@opencode-ai/cli-linux-x64
Advanced tools
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "F75E40ABD57C36A864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/get.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.get,\n Effect.fn(\"cli.service.get\")(function* (input) {\n process.stdout.write((yield* ServiceConfig.get(Option.getOrUndefined(input.key))) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";00BAAA,mBAAS,gBAMT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,SACnC,OAAO,QAAG,sBAAiB,OAAE,cAAU,MAAC,OAAO,MAC7C,aAAQ,YAAO,YAAO,WAAO,EAAc,IAAI,EAAO,eAAe,EAAM,GAAG,CAAC,GAAK,CAAG,EACxF,CACH", | ||
| "debugId": "0238A6B004869E8164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/logout.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.logout,\n Effect.fn(\"cli.mcp.logout\")(function* (input) {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n yield* Effect.forEach(\n credentials,\n (connection) => Effect.promise(() => client.credential.remove({ credentialID: connection.id, location })),\n { discard: true },\n )\n process.stdout.write(`Removed OAuth credentials for ${input.name}` + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";66BAAA,mBAAS,gBAST,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,YAC/B,OAAO,QAAG,qBAAgB,OAAE,cAAU,MAAC,OAAO,CAC5C,IAAM,EAAU,MAAO,EAAc,QAAQ,EAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EAAa,CAChB,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,IAAM,EAAc,EAAY,YAAY,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACnG,GAAI,EAAY,SAAW,EAAG,CAC5B,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,MAAO,EAAO,QACZ,EACA,CAAC,IAAe,EAAO,QAAQ,IAAM,EAAO,WAAW,OAAO,CAAE,aAAc,EAAW,GAAI,UAAS,CAAC,CAAC,EACxG,CAAE,QAAS,EAAK,CAClB,EACA,QAAQ,OAAO,MAAM,iCAAiC,EAAM,OAAS,CAAG,EACzE,CACH", | ||
| "debugId": "D55DC034FDF4FCEA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/azure.ts"], | ||
| "sourcesContent": [ | ||
| "import { Auth } from \"../route/auth\"\nimport { type AtLeastOne, type ProviderAuthOption } from \"../route/auth-options\"\nimport type { Route as RouteDef, RouteDefaultsInput } from \"../route/client\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { ProviderID, type ModelID } from \"../schema\"\nimport * as OpenAIChat from \"../protocols/openai-chat\"\nimport * as OpenAIResponses from \"../protocols/openai-responses\"\nimport { withOpenAIOptions, type OpenAIProviderOptionsInput } from \"./openai-options\"\n\nexport const id = ProviderID.make(\"azure\")\nconst routeAuth = Auth.remove(\"authorization\")\n\n// Azure needs the customer's resource URL; supply either `resourceName`\n// (helper builds the URL) or `baseURL` directly.\ntype AzureURL = AtLeastOne<{ readonly resourceName: string; readonly baseURL: string }>\n\nexport type ModelOptions = AzureURL &\n RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly apiVersion?: string\n readonly queryParams?: Record<string, string>\n readonly useCompletionUrls?: boolean\n readonly providerOptions?: OpenAIProviderOptionsInput\n }\nexport type Config = ModelOptions\n\nexport type Settings = ProviderPackage.Settings &\n AzureURL & {\n readonly apiKey?: string\n readonly apiVersion?: string\n readonly queryParams?: Readonly<Record<string, string>>\n readonly providerOptions?: OpenAIProviderOptionsInput\n }\n\nconst resourceBaseURL = (resourceName: string) => `https://${resourceName.trim()}.openai.azure.com/openai/v1`\n\nconst responsesRoute = OpenAIResponses.route.with({\n id: \"azure-openai-responses\",\n provider: id,\n auth: routeAuth,\n endpoint: {\n query: { \"api-version\": \"v1\" },\n },\n})\n\nconst chatRoute = OpenAIChat.route.with({\n id: \"azure-openai-chat\",\n provider: id,\n auth: routeAuth,\n endpoint: {\n query: { \"api-version\": \"v1\" },\n },\n})\n\nexport const routes = [responsesRoute, chatRoute]\n\nconst defaults = (input: Config) => {\n const {\n apiKey: _,\n apiVersion: _apiVersion,\n resourceName: _resourceName,\n useCompletionUrls: _useCompletionUrls,\n baseURL: _baseURL,\n queryParams: _queryParams,\n ...rest\n } = input\n if (\"auth\" in rest) {\n const { auth: _, ...withoutAuth } = rest\n return withoutAuth\n }\n return rest\n}\n\nconst auth = (input: Config) => {\n if (\"auth\" in input && input.auth) return input.auth\n return Auth.remove(\"authorization\").andThen(\n Auth.optional(\"apiKey\" in input ? input.apiKey : undefined, \"apiKey\")\n .orElse(Auth.config(\"AZURE_OPENAI_API_KEY\"))\n .pipe(Auth.header(\"api-key\")),\n )\n}\n\nconst configuredRoute = <Body, Prepared>(route: RouteDef<Body, Prepared>, input: Config) =>\n route.with({\n auth: auth(input),\n endpoint: {\n // AtLeastOne guarantees at least one is set; baseURL wins if both are.\n baseURL: input.baseURL ?? resourceBaseURL(input.resourceName!),\n query: {\n ...(input.apiVersion ? { \"api-version\": input.apiVersion } : {}),\n ...input.queryParams,\n },\n },\n })\n\nexport const configure = (input: Config) => {\n const configuredResponsesRoute = configuredRoute(responsesRoute, input)\n const configuredChatRoute = configuredRoute(chatRoute, input)\n const modelDefaults = defaults(input)\n\n const responses = (modelID: string | ModelID) =>\n configuredResponsesRoute.with(withOpenAIOptions(modelID, modelDefaults)).model({ id: modelID })\n\n const chat = (modelID: string | ModelID) =>\n configuredChatRoute.with(withOpenAIOptions(modelID, modelDefaults)).model({ id: modelID })\n\n return {\n id,\n model: (modelID: string | ModelID) => (input.useCompletionUrls === true ? chat(modelID) : responses(modelID)),\n responses,\n chat,\n configure,\n }\n}\n\nexport const provider = {\n id,\n configure,\n}\n\nconst config = (settings: Settings): Config => {\n const common = {\n apiKey: settings.apiKey,\n apiVersion: settings.apiVersion,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n providerOptions: settings.providerOptions,\n queryParams: settings.queryParams === undefined ? undefined : { ...settings.queryParams },\n }\n if (settings.baseURL !== undefined) return { ...common, baseURL: settings.baseURL }\n if (settings.resourceName !== undefined) return { ...common, resourceName: settings.resourceName }\n throw new Error(\"Azure requires resourceName or baseURL\")\n}\n\nexport const responsesModel: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure(config(settings)).responses(modelID)\nexport const chatModel: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure(config(settings)).chat(modelID)\nexport const model = responsesModel\n" | ||
| ], | ||
| "mappings": ";yMASO,SAAM,OAAK,OAAW,KAAK,OAAO,EACnC,EAAY,EAAK,OAAO,eAAe,EAwBvC,EAAkB,CAAC,IAAyB,WAAW,EAAa,KAAK,+BAEzE,EAAiC,EAAM,KAAK,CAChD,GAAI,yBACJ,SAAU,EACV,KAAM,EACN,SAAU,CACR,MAAO,CAAE,cAAe,IAAK,CAC/B,CACF,CAAC,EAEK,EAAuB,EAAM,KAAK,CACtC,GAAI,oBACJ,SAAU,EACV,KAAM,EACN,SAAU,CACR,MAAO,CAAE,cAAe,IAAK,CAC/B,CACF,CAAC,EAEY,EAAS,CAAC,EAAgB,CAAS,EAE1C,EAAW,CAAC,IAAkB,CAClC,IACE,OAAQ,EACR,WAAY,EACZ,aAAc,EACd,kBAAmB,EACnB,QAAS,EACT,YAAa,KACV,GACD,EACJ,GAAI,SAAU,EAAM,CAClB,IAAQ,KAAM,KAAM,GAAgB,EACpC,OAAO,EAET,OAAO,GAGH,EAAO,CAAC,IAAkB,CAC9B,GAAI,SAAU,GAAS,EAAM,KAAM,OAAO,EAAM,KAChD,OAAO,EAAK,OAAO,eAAe,EAAE,QAClC,EAAK,SAAS,WAAY,EAAQ,EAAM,OAAS,OAAW,QAAQ,EACjE,OAAO,EAAK,OAAO,sBAAsB,CAAC,EAC1C,KAAK,EAAK,OAAO,SAAS,CAAC,CAChC,GAGI,EAAkB,CAAiB,EAAiC,IACxE,EAAM,KAAK,CACT,KAAM,EAAK,CAAK,EAChB,S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AAK,CAAO,EAC7B,EAAQ", | ||
| "debugId": "9524E486B7D5CA8964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "2C526DF7842471A664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/anthropic-messages.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Framing } from \"../route/framing\"\nimport { Protocol } from \"../route/protocol\"\nimport {\n LLMError,\n LLMEvent,\n Usage,\n type CacheHint,\n type FinishReason,\n type JsonSchema,\n type LLMRequest,\n type MediaPart,\n type ProviderMetadata,\n type ToolCallPart,\n type ToolDefinition,\n type ToolContent,\n type ToolResultPart,\n} from \"../schema\"\nimport { JsonObject, optionalArray, optionalNull, ProviderShared } from \"./shared\"\nimport { classifyProviderFailure } from \"../provider-error\"\nimport * as Cache from \"./utils/cache\"\nimport { Lifecycle } from \"./utils/lifecycle\"\nimport { ToolSchemaProjection } from \"./utils/tool-schema\"\nimport { ToolStream } from \"./utils/tool-stream\"\n\nconst ADAPTER = \"anthropic-messages\"\nexport const DEFAULT_BASE_URL = \"https://api.anthropic.com/v1\"\nexport const PATH = \"/messages\"\n\n// =============================================================================\n// Request Body Schema\n// =============================================================================\nconst AnthropicCacheControl = Schema.Struct({\n type: Schema.tag(\"ephemeral\"),\n ttl: Schema.optional(Schema.Literals([\"5m\", \"1h\"])),\n})\n\nconst AnthropicTextBlock = Schema.Struct({\n type: Schema.tag(\"text\"),\n text: Schema.String,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicTextBlock = Schema.Schema.Type<typeof AnthropicTextBlock>\n\nconst AnthropicImageBlock = Schema.Struct({\n type: Schema.tag(\"image\"),\n source: Schema.Struct({\n type: Schema.tag(\"base64\"),\n media_type: Schema.String,\n data: Schema.String,\n }),\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicImageBlock = Schema.Schema.Type<typeof AnthropicImageBlock>\n\nconst AnthropicThinkingBlock = Schema.Struct({\n type: Schema.tag(\"thinking\"),\n thinking: Schema.String,\n signature: Schema.optional(Schema.String),\n cache_control: Schema.optional(AnthropicCacheControl),\n})\n\nconst AnthropicToolUseBlock = Schema.Struct({\n type: Schema.tag(\"tool_use\"),\n id: Schema.String,\n name: Schema.String,\n input: Schema.Unknown,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicToolUseBlock = Schema.Schema.Type<typeof AnthropicToolUseBlock>\n\nconst AnthropicServerToolUseBlock = Schema.Struct({\n type: Schema.tag(\"server_tool_use\"),\n id: Schema.String,\n name: Schema.String,\n input: Schema.Unknown,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicServerToolUseBlock = Schema.Schema.Type<typeof AnthropicServerToolUseBlock>\n\n// Server tool result blocks: web_search_tool_result, code_execution_tool_result,\n// and web_fetch_tool_result. The provider executes the tool and inlines the\n// structured result into the assistant turn — there is no client tool_result\n// round-trip. We round-trip the structured `content` payload as opaque JSON so\n// the next request can echo it back when continuing the conversation.\nconst AnthropicServerToolResultType = Schema.Literals([\n \"web_search_tool_result\",\n \"code_execution_tool_result\",\n \"web_fetch_tool_result\",\n])\ntype AnthropicServerToolResultType = Schema.Schema.Type<typeof AnthropicServerToolResultType>\n\nconst AnthropicServerToolResultBlock = Schema.Struct({\n type: AnthropicServerToolResultType,\n tool_use_id: Schema.String,\n content: Schema.Unknown,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicServerToolResultBlock = Schema.Schema.Type<typeof AnthropicServerToolResultBlock>\n\n// Anthropic accepts either a plain string or an ordered array of text/image\n// blocks inside `tool_result.content`. The array form is required when a tool\n// returns image bytes (screenshot, image search, etc.) so they can be passed\n// to the model as proper image inputs instead of being JSON-stringified into\n// the prompt — which silently inflates context by megabytes and can push the\n// conversation over the model's token limit.\nconst AnthropicToolResultContent = Schema.Union([AnthropicTextBlock, AnthropicImageBlock])\n\nconst AnthropicToolResultBlock = Schema.Struct({\n type: Schema.tag(\"tool_result\"),\n tool_use_id: Schema.String,\n content: Schema.Union([Schema.String, Schema.Array(AnthropicToolResultContent)]),\n is_error: Schema.optional(Schema.Boolean),\n cache_control: Schema.optional(AnthropicCacheControl),\n})\n\nconst AnthropicUserBlock = Schema.Union([AnthropicTextBlock, AnthropicImageBlock, AnthropicToolResultBlock])\ntype AnthropicUserBlock = Schema.Schema.Type<typeof AnthropicUserBlock>\nconst AnthropicAssistantBlock = Schema.Union([\n AnthropicTextBlock,\n AnthropicThinkingBlock,\n AnthropicToolUseBlock,\n AnthropicServerToolUseBlock,\n AnthropicServerToolResultBlock,\n])\ntype AnthropicAssistantBlock = Schema.Schema.Type<typeof AnthropicAssistantBlock>\ntype AnthropicToolResultBlock = Schema.Schema.Type<typeof AnthropicToolResultBlock>\n\nconst AnthropicMessage = Schema.Union([\n Schema.Struct({ role: Schema.Literal(\"user\"), content: Schema.Array(AnthropicUserBlock) }),\n Schema.Struct({ role: Schema.Literal(\"assistant\"), content: Schema.Array(AnthropicAssistantBlock) }),\n Schema.Struct({ role: Schema.Literal(\"system\"), content: Schema.Array(AnthropicTextBlock) }),\n]).pipe(Schema.toTaggedUnion(\"role\"))\ntype AnthropicMessage = Schema.Schema.Type<typeof AnthropicMessage>\n\nconst AnthropicTool = Schema.Struct({\n name: Schema.String,\n description: Schema.String,\n input_schema: JsonObject,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicTool = Schema.Schema.Type<typeof AnthropicTool>\n\nconst AnthropicToolChoice = Schema.Union([\n Schema.Struct({ type: Schema.Literals([\"auto\", \"any\"]) }),\n Schema.Struct({ type: Schema.tag(\"tool\"), name: Schema.String }),\n])\n\nconst AnthropicThinking = Schema.Union([\n Schema.Struct({\n type: Schema.tag(\"enabled\"),\n budget_tokens: Schema.Number,\n }),\n Schema.Struct({\n type: Schema.tag(\"adaptive\"),\n display: Schema.optional(Schema.Literals([\"summarized\", \"omitted\"])),\n }),\n Schema.Struct({\n type: Schema.tag(\"disabled\"),\n }),\n])\n\nconst AnthropicOutputConfig = Schema.Struct({\n effort: Schema.optional(Schema.String),\n})\n\nconst AnthropicBodyFields = {\n model: Schema.String,\n system: optionalArray(AnthropicTextBlock),\n messages: Schema.Array(AnthropicMessage),\n tools: optionalArray(AnthropicTool),\n tool_choice: Schema.optional(AnthropicToolChoice),\n stream: Schema.Literal(true),\n max_tokens: Schema.Number,\n temperature: Schema.optional(Schema.Number),\n top_p: Schema.optional(Schema.Number),\n top_k: Schema.optional(Schema.Number),\n stop_sequences: optionalArray(Schema.String),\n thinking: Schema.optional(AnthropicThinking),\n output_config: Schema.optional(AnthropicOutputConfig),\n}\nexport const AnthropicMessagesBody = Schema.Struct(AnthropicBodyFields)\nexport type AnthropicMessagesBody = Schema.Schema.Type<typeof AnthropicMessagesBody>\n\nconst AnthropicUsage = Schema.Struct({\n input_tokens: Schema.optional(Schema.Number),\n output_tokens: Schema.optional(Schema.Number),\n cache_creation_input_tokens: optionalNull(Schema.Number),\n cache_read_input_tokens: optionalNull(Schema.Number),\n})\ntype AnthropicUsage = Schema.Schema.Type<typeof AnthropicUsage>\n\nconst AnthropicStreamBlock = Schema.Struct({\n type: Schema.String,\n id: Schema.optional(Schema.String),\n name: Schema.optional(Schema.String),\n text: Schema.optional(Schema.String),\n thinking: Schema.optional(Schema.String),\n signature: Schema.optional(Schema.String),\n input: Schema.optional(Schema.Unknown),\n // *_tool_result blocks arrive whole as content_block_start (no streaming\n // delta) with the structured payload in `content` and the originating\n // server_tool_use id in `tool_use_id`.\n tool_use_id: Schema.optional(Schema.String),\n content: Schema.optional(Schema.Unknown),\n})\n\nconst AnthropicStreamDelta = Schema.Struct({\n type: Schema.optional(Schema.String),\n text: Schema.optional(Schema.String),\n thinking: Schema.optional(Schema.String),\n partial_json: Schema.optional(Schema.String),\n signature: Schema.optional(Schema.String),\n stop_reason: optionalNull(Schema.String),\n stop_sequence: optionalNull(Schema.String),\n})\n\nconst AnthropicEvent = Schema.Struct({\n type: Schema.String,\n index: Schema.optional(Schema.Number),\n message: Schema.optional(Schema.Struct({ usage: Schema.optional(AnthropicUsage) })),\n content_block: Schema.optional(AnthropicStreamBlock),\n delta: Schema.optional(AnthropicStreamDelta),\n usage: Schema.optional(AnthropicUsage),\n // `type` and `message` are both required per Anthropic's spec, but\n // OpenAI-compatible proxies and gateway translations occasionally drop one\n // or the other; mark them optional so a partial payload still parses and\n // the parser can fall back to whichever field is populated.\n error: Schema.optional(\n Schema.Struct({ type: Schema.optional(Schema.String), message: Schema.optional(Schema.String) }),\n ),\n})\ntype AnthropicEvent = Schema.Schema.Type<typeof AnthropicEvent>\n\ninterface ParserState {\n readonly tools: ToolStream.State<number>\n readonly usage?: Usage\n readonly lifecycle: Lifecycle.State\n}\n\nconst invalid = ProviderShared.invalidRequest\n\n// =============================================================================\n// Request Lowering\n// =============================================================================\n// Anthropic accepts at most 4 explicit cache_control breakpoints per request,\n// across `tools`, `system`, and `messages`. Beyond the cap the API returns a\n// 400 — so the lowering layer counts emitted markers and silently drops any\n// that exceed it.\nconst ANTHROPIC_BREAKPOINT_CAP = 4\n\nconst EPHEMERAL_5M = { type: \"ephemeral\" as const }\nconst EPHEMERAL_1H = { type: \"ephemeral\" as const, ttl: \"1h\" as const }\n\nconst cacheControl = (breakpoints: Cache.Breakpoints, cache: CacheHint | undefined) => {\n if (cache?.type !== \"ephemeral\" && cache?.type !== \"persistent\") return undefined\n if (breakpoints.remaining <= 0) {\n breakpoints.dropped += 1\n return undefined\n }\n breakpoints.remaining -= 1\n return Cache.ttlBucket(cache.ttlSeconds) === \"1h\" ? EPHEMERAL_1H : EPHEMERAL_5M\n}\n\nconst anthropicMetadata = (metadata: Record<string, unknown>): ProviderMetadata => ({ anthropic: metadata })\n\nconst signatureFromMetadata = (metadata: ProviderMetadata | undefined): string | undefined => {\n const anthropic = metadata?.anthropic\n if (!ProviderShared.isRecord(anthropic)) return undefined\n return typeof anthropic.signature === \"string\" ? anthropic.signature : undefined\n}\n\nconst lowerTool = (breakpoints: Cache.Breakpoints, tool: ToolDefinition, inputSchema: JsonSchema): AnthropicTool => ({\n name: tool.name,\n description: tool.description,\n input_schema: inputSchema,\n cache_control: cacheControl(breakpoints, tool.cache),\n})\n\nconst lowerToolChoice = (toolChoice: NonNullable<LLMRequest[\"toolChoice\"]>) =>\n ProviderShared.matchToolChoice(\"Anthropic Messages\", toolChoice, {\n auto: () => ({ type: \"auto\" as const }),\n none: () => undefined,\n required: () => ({ type: \"any\" as const }),\n tool: (name) => ({ type: \"tool\" as const, name }),\n })\n\nconst lowerToolCall = (part: ToolCallPart): AnthropicToolUseBlock => ({\n type: \"tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n})\n\nconst lowerServerToolCall = (part: ToolCallPart): AnthropicServerToolUseBlock => ({\n type: \"server_tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n})\n\n// Server tool result blocks are typed by name. Anthropic ships three today;\n// extend this list when new server tools land. The block content is the\n// structured payload returned by the provider, which we round-trip as-is.\nconst serverToolResultType = (name: string): AnthropicServerToolResultType | undefined => {\n if (name === \"web_search\") return \"web_search_tool_result\"\n if (name === \"code_execution\") return \"code_execution_tool_result\"\n if (name === \"web_fetch\") return \"web_fetch_tool_result\"\n return undefined\n}\n\nconst lowerServerToolResult = Effect.fn(\"AnthropicMessages.lowerServerToolResult\")(function* (part: ToolResultPart) {\n const wireType = serverToolResultType(part.name)\n if (!wireType)\n return yield* invalid(`Anthropic Messages does not know how to round-trip server tool result for ${part.name}`)\n return { type: wireType, tool_use_id: part.id, content: part.result.value } satisfies AnthropicServerToolResultBlock\n})\n\nconst lowerImage = Effect.fn(\"AnthropicMessages.lowerImage\")(function* (part: MediaPart) {\n const media = yield* ProviderShared.validateMedia(\n \"Anthropic Messages\",\n part,\n new Set<string>(ProviderShared.IMAGE_MIMES),\n )\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: media.mime,\n data: media.base64,\n },\n } satisfies AnthropicImageBlock\n})\n\n// Tool results may carry structured text/images. Keep media as provider-native\n// content instead of JSON-stringifying base64 into a prompt string.\nconst lowerToolResultContentItem = Effect.fn(\"AnthropicMessages.lowerToolResultContentItem\")(function* (\n item: ToolContent,\n) {\n if (item.type === \"text\") return { type: \"text\" as const, text: item.text } satisfies AnthropicTextBlock\n const media = yield* ProviderShared.validateToolFile(\n \"Anthropic Messages\",\n item,\n new Set<string>(ProviderShared.IMAGE_MIMES),\n )\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: media.mime,\n data: media.base64,\n },\n } satisfies AnthropicImageBlock\n})\n\nconst lowerToolResultContent = Effect.fn(\"AnthropicMessages.lowerToolResultContent\")(function* (part: ToolResultPart) {\n // Text / json / error results stay as a string for backward compatibility\n // with existing cassettes and provider expectations.\n if (part.result.type !== \"content\") return ProviderShared.toolResultText(part)\n // Preserve the narrowed array element type when compiled through a consumer package.\n const content: ReadonlyArray<ToolContent> = part.result.value\n return yield* Effect.forEach(content, lowerToolResultContentItem)\n})\n\n// Mid-conversation system messages are a native Claude API feature only for\n// Opus 4.8. Other Anthropic models intentionally use the same visible wrapped-\n// user fallback as non-Anthropic routes rather than sending a role they reject.\nconst supportsNativeSystemUpdates = (request: LLMRequest) => String(request.model.id) === \"claude-opus-4-8\"\n\nconst endsInServerToolUse = (message: LLMRequest[\"messages\"][number]) => {\n const last = message.content.at(-1)\n return message.role === \"assistant\" && last?.type === \"tool-call\" && last.providerExecuted === true\n}\n\nconst canUseNativeSystemUpdate = (messages: LLMRequest[\"messages\"], index: number) => {\n const previous = messages[index - 1]\n const next = messages[index + 1]\n return (\n previous !== undefined &&\n previous.role !== \"system\" &&\n (previous.role === \"user\" || previous.role === \"tool\" || endsInServerToolUse(previous)) &&\n next?.role !== \"system\" &&\n (next === undefined || next.role === \"assistant\")\n )\n}\n\nconst splitsLocalToolResults = (messages: LLMRequest[\"messages\"], index: number) => {\n const pending = new Set<string>()\n for (const message of messages.slice(0, index)) {\n for (const part of message.content) {\n if (message.role === \"assistant\" && part.type === \"tool-call\" && part.providerExecuted !== true)\n pending.add(part.id)\n if (message.role === \"tool\" && part.type === \"tool-result\") pending.delete(part.id)\n }\n }\n return pending.size > 0\n}\n\nconst lowerNativeSystemUpdate = Effect.fn(\"AnthropicMessages.lowerNativeSystemUpdate\")(function* (\n message: LLMRequest[\"messages\"][number],\n breakpoints: Cache.Breakpoints,\n) {\n const content = yield* ProviderShared.systemUpdateText(\"Anthropic Messages\", message)\n return {\n role: \"system\" as const,\n content: content.map((part) => ({\n type: \"text\" as const,\n text: part.text,\n cache_control: cacheControl(breakpoints, part.cache),\n })),\n }\n})\n\nconst lowerMessages = Effect.fn(\"AnthropicMessages.lowerMessages\")(function* (\n request: LLMRequest,\n breakpoints: Cache.Breakpoints,\n) {\n const messages: AnthropicMessage[] = []\n\n for (const [index, message] of request.messages.entries()) {\n if (message.role === \"system\") {\n if (splitsLocalToolResults(request.messages, index))\n return yield* invalid(\"Anthropic Messages system updates cannot split a local tool call from its tool result\")\n if (supportsNativeSystemUpdates(request) && canUseNativeSystemUpdate(request.messages, index)) {\n messages.push(yield* lowerNativeSystemUpdate(message, breakpoints))\n continue\n }\n const part = yield* ProviderShared.wrappedSystemUpdate(\"Anthropic Messages\", message)\n const block = { type: \"text\" as const, text: part.text, cache_control: cacheControl(breakpoints, part.cache) }\n const previous = messages.at(-1)\n if (previous?.role === \"user\")\n messages[messages.length - 1] = { role: \"user\", content: [...previous.content, block] }\n else messages.push({ role: \"user\", content: [block] })\n continue\n }\n\n if (message.role === \"user\") {\n const content: AnthropicUserBlock[] = []\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"text\", text: part.text, cache_control: cacheControl(breakpoints, part.cache) })\n continue\n }\n if (part.type === \"media\") {\n content.push(yield* lowerImage(part))\n continue\n }\n return yield* ProviderShared.unsupportedContent(\"Anthropic Messages\", \"user\", [\"text\", \"media\"])\n }\n messages.push({ role: \"user\", content })\n continue\n }\n\n if (message.role === \"assistant\") {\n const content: AnthropicAssistantBlock[] = []\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"text\", text: part.text, cache_control: cacheControl(breakpoints, part.cache) })\n continue\n }\n if (part.type === \"reasoning\") {\n content.push({\n type: \"thinking\",\n thinking: part.text,\n signature: part.encrypted ?? signatureFromMetadata(part.providerMetadata),\n })\n continue\n }\n if (part.type === \"tool-call\") {\n content.push(part.providerExecuted ? lowerServerToolCall(part) : lowerToolCall(part))\n continue\n }\n if (part.type === \"tool-result\" && part.providerExecuted) {\n content.push(yield* lowerServerToolResult(part))\n continue\n }\n return yield* invalid(\n `Anthropic Messages assistant messages only support text, reasoning, and tool-call content for now`,\n )\n }\n messages.push({ role: \"assistant\", content })\n continue\n }\n\n const content: AnthropicToolResultBlock[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"tool-result\"]))\n return yield* ProviderShared.unsupportedContent(\"Anthropic Messages\", \"tool\", [\"tool-result\"])\n content.push({\n type: \"tool_result\",\n tool_use_id: part.id,\n content: yield* lowerToolResultContent(part),\n is_error: part.result.type === \"error\" ? true : undefined,\n cache_control: cacheControl(breakpoints, part.cache),\n })\n }\n messages.push({ role: \"user\", content })\n }\n\n return messages\n})\n\nconst anthropicOptions = (request: LLMRequest) => request.providerOptions?.anthropic\n\nconst lowerThinking = Effect.fn(\"AnthropicMessages.lowerThinking\")(function* (request: LLMRequest) {\n const thinking = anthropicOptions(request)?.thinking\n if (!ProviderShared.isRecord(thinking)) return undefined\n if (thinking.type === \"adaptive\") {\n const display =\n thinking.display === \"summarized\"\n ? (\"summarized\" as const)\n : thinking.display === \"omitted\"\n ? (\"omitted\" as const)\n : undefined\n return { type: \"adaptive\" as const, ...(display === undefined ? {} : { display }) }\n }\n if (thinking.type === \"disabled\") return { type: \"disabled\" as const }\n if (thinking.type !== \"enabled\") return undefined\n const budget =\n typeof thinking.budgetTokens === \"number\"\n ? thinking.budgetTokens\n : typeof thinking.budget_tokens === \"number\"\n ? thinking.budget_tokens\n : undefined\n if (budget === undefined) return yield* invalid(\"Anthropic thinking provider option requires budgetTokens\")\n return { type: \"enabled\" as const, budget_tokens: budget }\n})\n\nconst outputConfig = (request: LLMRequest) => {\n const effort = anthropicOptions(request)?.effort\n return typeof effort === \"string\" ? { effort } : undefined\n}\n\nconst fromRequest = Effect.fn(\"AnthropicMessages.fromRequest\")(function* (request: LLMRequest) {\n const toolChoice = request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined\n const generation = request.generation\n const toolSchemaCompatibility = request.model.compatibility?.toolSchema\n const outputLimit = request.model.defaults?.limits?.output ?? request.model.route.defaults.limits?.output ?? 4096\n // Allocate the 4-breakpoint budget in invalidation order: tools → system →\n // messages. Tools live highest in the cache hierarchy, so when callers\n // over-mark we keep their tool hints and shed the message-tail ones first.\n const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP)\n const tools =\n request.tools.length === 0 || request.toolChoice?.type === \"none\"\n ? undefined\n : request.tools.map((tool) =>\n lowerTool(\n breakpoints,\n tool,\n ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility),\n ),\n )\n const system =\n request.system.length === 0\n ? undefined\n : request.system.map((part) => ({\n type: \"text\" as const,\n text: part.text,\n cache_control: cacheControl(breakpoints, part.cache),\n }))\n const messages = yield* lowerMessages(request, breakpoints)\n if (breakpoints.dropped > 0) {\n yield* Effect.logWarning(\n `Anthropic Messages: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${ANTHROPIC_BREAKPOINT_CAP} per request.`,\n )\n }\n return {\n model: request.model.id,\n system,\n messages,\n tools,\n tool_choice: toolChoice,\n stream: true as const,\n max_tokens: generation?.maxTokens ?? outputLimit,\n temperature: generation?.temperature,\n top_p: generation?.topP,\n top_k: generation?.topK,\n stop_sequences: generation?.stop,\n thinking: yield* lowerThinking(request),\n output_config: outputConfig(request),\n }\n})\n\n// =============================================================================\n// Stream Parsing\n// =============================================================================\nconst mapFinishReason = (reason: string | null | undefined): FinishReason => {\n if (reason === \"end_turn\" || reason === \"stop_sequence\" || reason === \"pause_turn\") return \"stop\"\n if (reason === \"max_tokens\") return \"length\"\n if (reason === \"tool_use\") return \"tool-calls\"\n if (reason === \"refusal\") return \"content-filter\"\n return \"unknown\"\n}\n\n// Anthropic reports the non-overlapping breakdown natively — its\n// `input_tokens` is the *non-cached* count per the Messages API docs, with\n// cache reads and writes as separate fields. We sum them to derive the\n// inclusive `inputTokens` the rest of the contract expects. Extended\n// thinking tokens are *not* broken out by Anthropic — they're billed as\n// part of `output_tokens`, so `reasoningTokens` stays `undefined` and\n// `outputTokens` carries the combined total.\nconst mapUsage = (usage: AnthropicUsage | undefined): Usage | undefined => {\n if (!usage) return undefined\n const nonCached = usage.input_tokens\n const cacheRead = usage.cache_read_input_tokens ?? undefined\n const cacheWrite = usage.cache_creation_input_tokens ?? undefined\n const inputTokens = ProviderShared.sumTokens(nonCached, cacheRead, cacheWrite)\n return new Usage({\n inputTokens,\n outputTokens: usage.output_tokens,\n nonCachedInputTokens: nonCached,\n cacheReadInputTokens: cacheRead,\n cacheWriteInputTokens: cacheWrite,\n totalTokens: ProviderShared.totalTokens(inputTokens, usage.output_tokens, undefined),\n providerMetadata: { anthropic: usage },\n })\n}\n\n// Anthropic emits usage on `message_start` and again on `message_delta` — the\n// final delta carries the authoritative totals. Right-biased merge: each\n// field prefers `right` when defined, falls back to `left`. `inputTokens` is\n// recomputed from the merged breakdown so the inclusive total stays\n// consistent with `nonCached + cacheRead + cacheWrite`.\nconst mergeUsage = (left: Usage | undefined, right: Usage | undefined) => {\n if (!left) return right\n if (!right) return left\n const nonCachedInputTokens = right.nonCachedInputTokens ?? left.nonCachedInputTokens\n const cacheReadInputTokens = right.cacheReadInputTokens ?? left.cacheReadInputTokens\n const cacheWriteInputTokens = right.cacheWriteInputTokens ?? left.cacheWriteInputTokens\n const inputTokens = ProviderShared.sumTokens(nonCachedInputTokens, cacheReadInputTokens, cacheWriteInputTokens)\n const outputTokens = right.outputTokens ?? left.outputTokens\n return new Usage({\n inputTokens,\n outputTokens,\n nonCachedInputTokens,\n cacheReadInputTokens,\n cacheWriteInputTokens,\n totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),\n providerMetadata: {\n anthropic: {\n ...left.providerMetadata?.[\"anthropic\"],\n ...right.providerMetadata?.[\"anthropic\"],\n },\n },\n })\n}\n\n// Server tool result blocks come whole in `content_block_start` (no streaming\n// delta sequence). We convert the payload to a `tool-result` event with\n// `providerExecuted: true`. The runtime appends it to the assistant message\n// for round-trip; downstream consumers can inspect `result.value` for the\n// structured payload.\nconst SERVER_TOOL_RESULT_NAMES: Record<AnthropicServerToolResultType, string> = {\n web_search_tool_result: \"web_search\",\n code_execution_tool_result: \"code_execution\",\n web_fetch_tool_result: \"web_fetch\",\n}\n\nconst isServerToolResultType = (type: string): type is AnthropicServerToolResultType => type in SERVER_TOOL_RESULT_NAMES\n\nconst serverToolResultEvent = (block: NonNullable<AnthropicEvent[\"content_block\"]>): LLMEvent | undefined => {\n if (!block.type || !isServerToolResultType(block.type)) return undefined\n const errorPayload =\n typeof block.content === \"object\" && block.content !== null && \"type\" in block.content\n ? String((block.content as Record<string, unknown>).type)\n : \"\"\n const isError = errorPayload.endsWith(\"_tool_result_error\")\n return LLMEvent.toolResult({\n id: block.tool_use_id ?? \"\",\n name: SERVER_TOOL_RESULT_NAMES[block.type],\n result: isError ? { type: \"error\", value: block.content } : { type: \"json\", value: block.content },\n providerExecuted: true,\n providerMetadata: anthropicMetadata({ blockType: block.type }),\n })\n}\n\ntype StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]\n\nconst NO_EVENTS: StepResult[\"1\"] = []\n\nconst onMessageStart = (state: ParserState, event: AnthropicEvent): StepResult => {\n const usage = mapUsage(event.message?.usage)\n return [usage ? { ...state, usage: mergeUsage(state.usage, usage) } : state, NO_EVENTS]\n}\n\nconst onContentBlockStart = (state: ParserState, event: AnthropicEvent): StepResult => {\n const block = event.content_block\n if (!block) return [state, NO_EVENTS]\n\n if ((block.type === \"tool_use\" || block.type === \"server_tool_use\") && event.index !== undefined) {\n const events: LLMEvent[] = []\n const lifecycle = Lifecycle.stepStart(state.lifecycle, events)\n return [\n {\n ...state,\n lifecycle,\n tools: ToolStream.start(state.tools, event.index, {\n id: block.id ?? String(event.index),\n name: block.name ?? \"\",\n providerExecuted: block.type === \"server_tool_use\",\n }),\n },\n [\n ...events,\n LLMEvent.toolInputStart({\n id: block.id ?? String(event.index),\n name: block.name ?? \"\",\n providerExecuted: block.type === \"server_tool_use\" ? true : undefined,\n }),\n ],\n ]\n }\n\n if (block.type === \"text\" && block.text) {\n const events: LLMEvent[] = []\n return [\n { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, `text-${event.index ?? 0}`, block.text) },\n events,\n ]\n }\n\n if (block.type === \"thinking\" && block.thinking) {\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${event.index ?? 0}`, block.thinking),\n },\n events,\n ]\n }\n\n const result = serverToolResultEvent(block)\n if (!result) return [state, NO_EVENTS]\n const events: LLMEvent[] = []\n return [{ ...state, lifecycle: Lifecycle.stepStart(state.lifecycle, events) }, [...events, result]]\n}\n\nconst onContentBlockDelta = Effect.fn(\"AnthropicMessages.onContentBlockDelta\")(function* (\n state: ParserState,\n event: AnthropicEvent,\n) {\n const delta = event.delta\n\n if (delta?.type === \"text_delta\" && delta.text) {\n const events: LLMEvent[] = []\n return [\n { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, `text-${event.index ?? 0}`, delta.text) },\n events,\n ] satisfies StepResult\n }\n\n if (delta?.type === \"thinking_delta\" && delta.thinking) {\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${event.index ?? 0}`, delta.thinking),\n },\n events,\n ] satisfies StepResult\n }\n\n if (delta?.type === \"signature_delta\" && delta.signature) {\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: Lifecycle.reasoningEnd(\n state.lifecycle,\n events,\n `reasoning-${event.index ?? 0}`,\n anthropicMetadata({ signature: delta.signature }),\n ),\n },\n events,\n ] satisfies StepResult\n }\n\n if (delta?.type === \"input_json_delta\" && event.index !== undefined) {\n if (!delta.partial_json) return [state, NO_EVENTS] satisfies StepResult\n const result = ToolStream.appendExisting(\n ADAPTER,\n state.tools,\n event.index,\n delta.partial_json,\n \"Anthropic Messages tool argument delta is missing its tool call\",\n )\n if (ToolStream.isError(result)) return yield* result\n const events: LLMEvent[] = []\n const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle\n events.push(...result.events)\n return [{ ...state, lifecycle, tools: result.tools }, events] satisfies StepResult\n }\n\n return [state, NO_EVENTS] satisfies StepResult\n})\n\nconst onContentBlockStop = Effect.fn(\"AnthropicMessages.onContentBlockStop\")(function* (\n state: ParserState,\n event: AnthropicEvent,\n) {\n if (event.index === undefined) return [state, NO_EVENTS] satisfies StepResult\n const result = yield* ToolStream.finish(ADAPTER, state.tools, event.index)\n const events: LLMEvent[] = []\n const resultEvents = result.events ?? []\n const lifecycle = resultEvents.length\n ? Lifecycle.stepStart(state.lifecycle, events)\n : Lifecycle.reasoningEnd(\n Lifecycle.textEnd(state.lifecycle, events, `text-${event.index}`),\n events,\n `reasoning-${event.index}`,\n )\n events.push(...resultEvents)\n return [{ ...state, lifecycle, tools: result.tools }, events] satisfies StepResult\n})\n\nconst onMessageDelta = (state: ParserState, event: AnthropicEvent): StepResult => {\n const usage = mergeUsage(state.usage, mapUsage(event.usage))\n const events: LLMEvent[] = []\n const lifecycle = Lifecycle.finish(state.lifecycle, events, {\n reason: mapFinishReason(event.delta?.stop_reason),\n usage,\n providerMetadata: event.delta?.stop_sequence\n ? anthropicMetadata({ stopSequence: event.delta.stop_sequence })\n : undefined,\n })\n return [{ ...state, lifecycle, usage }, events]\n}\n\n// Prefix `error.type` so overloads, rate limits, and quota errors are visible\n// even when the provider message is generic or empty.\nconst providerErrorMessage = (event: AnthropicEvent): string => {\n const type = event.error?.type\n const message = event.error?.message\n if (type && message) return `${type}: ${message}`\n return message || type || \"Anthropic Messages stream error\"\n}\n\nconst onError = (event: AnthropicEvent) =>\n new LLMError({\n module: ADAPTER,\n method: \"stream\",\n reason: classifyProviderFailure({ message: providerErrorMessage(event), code: event.error?.type }),\n })\n\nconst step = (state: ParserState, event: AnthropicEvent) => {\n if (event.type === \"message_start\") return Effect.succeed(onMessageStart(state, event))\n if (event.type === \"content_block_start\") return Effect.succeed(onContentBlockStart(state, event))\n if (event.type === \"content_block_delta\") return onContentBlockDelta(state, event)\n if (event.type === \"content_block_stop\") return onContentBlockStop(state, event)\n if (event.type === \"message_delta\") return Effect.succeed(onMessageDelta(state, event))\n if (event.type === \"error\") return onError(event)\n return Effect.succeed<StepResult>([state, NO_EVENTS])\n}\n\n// =============================================================================\n// Protocol And Anthropic Route\n// =============================================================================\n/**\n * The Anthropic Messages protocol — request body construction, body schema,\n * and the streaming-event state machine. Used by native Anthropic Cloud and\n * (once registered) Vertex Anthropic / Bedrock-hosted Anthropic passthrough.\n */\nexport const protocol = Protocol.make({\n id: ADAPTER,\n body: {\n schema: AnthropicMessagesBody,\n from: fromRequest,\n },\n stream: {\n event: Protocol.jsonEvent(AnthropicEvent),\n initial: () => ({ tools: ToolStream.empty<number>(), lifecycle: Lifecycle.initial() }),\n step,\n },\n})\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: \"anthropic\",\n providerMetadataKey: \"anthropic\",\n protocol,\n endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),\n auth: Auth.none,\n framing: Framing.sse,\n headers: () => ({ \"anthropic-version\": \"2023-06-01\" }),\n})\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Ac,EAAG,UAAW,EAAU,QAAQ,CAAE,GACpF,OACF,CACF,CAAC,EAEY,GAAQ,EAAM,KAAK,CAC9B,GAAI,EACJ,SAAU,YACV,oBAAqB,YACrB,WACA,SAAU,EAAS,KAAK,EAAM,CAAE,QAAS,CAAiB,CAAC,EAC3D,KAAM,EAAK,KACX,QAAS,EAAQ,IACjB,QAAS,KAAO,CAAE,oBAAqB,YAAa,EACtD,CAAC", | ||
| "debugId": "8D2297F7B60E58D864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "A885B1B43C09A4D264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/start.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.start,\n Effect.fn(\"cli.service.start\")(function* () {\n const transport = yield* Service.ensure(yield* ServiceConfig.options())\n process.stdout.write(transport.url + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+0BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,WACnC,OAAO,QAAG,wBAAmB,OAAE,cAAU,OAAG,MAC1C,SAAM,OAAY,WAAO,OAAQ,YAAO,MAAO,EAAc,QAAQ,CAAC,EACtE,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "882EDB8FFBBB07A964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@smithy+node-http-handler@4.9.7/node_modules/@smithy/node-http-handler/dist-cjs/index.js"], | ||
| "sourcesContent": [ | ||
| "const { buildQueryString, HttpResponse } = require(\"@smithy/core/protocols\");\nconst node_https = require(\"node:https\");\nconst { Readable } = require(\"node:stream\");\nconst http2 = require(\"node:http2\");\nconst { streamCollector } = require(\"@smithy/core/serde\");\nexports.streamCollector = streamCollector;\n\nfunction buildAbortError(abortSignal) {\n const reason = abortSignal && typeof abortSignal === \"object\" && \"reason\" in abortSignal\n ? abortSignal.reason\n : undefined;\n if (reason) {\n if (reason instanceof Error) {\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n abortError.cause = reason;\n return abortError;\n }\n const abortError = new Error(String(reason));\n abortError.name = \"AbortError\";\n return abortError;\n }\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n return abortError;\n}\n\nconst NODEJS_TIMEOUT_ERROR_CODES = [\"ECONNRESET\", \"EPIPE\", \"ETIMEDOUT\"];\n\nconst getTransformedHeaders = (headers) => {\n const transformedHeaders = {};\n for (const name in headers) {\n const headerValues = headers[name];\n transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(\",\") : headerValues;\n }\n return transformedHeaders;\n};\n\nconst timing = {\n setTimeout: (cb, ms) => setTimeout(cb, ms),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n};\n\nconst DEFER_EVENT_LISTENER_TIME$2 = 1000;\nconst setConnectionTimeout = (request, reject, timeoutInMs = 0) => {\n if (!timeoutInMs) {\n return -1;\n }\n const registerTimeout = (offset) => {\n const timeoutId = timing.setTimeout(() => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), {\n name: \"TimeoutError\",\n }));\n }, timeoutInMs - offset);\n const doWithSocket = (socket) => {\n if (socket?.connecting) {\n socket.on(\"connect\", () => {\n timing.clearTimeout(timeoutId);\n });\n }\n else {\n timing.clearTimeout(timeoutId);\n }\n };\n if (request.socket) {\n doWithSocket(request.socket);\n }\n else {\n request.on(\"socket\", doWithSocket);\n }\n };\n if (timeoutInMs < 2000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2);\n};\n\nconst setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => {\n if (timeoutInMs) {\n return timing.setTimeout(() => {\n let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? \"ERROR\" : \"WARN\"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;\n if (throwOnRequestTimeout) {\n const error = Object.assign(new Error(msg), {\n name: \"TimeoutError\",\n code: \"ETIMEDOUT\",\n });\n req.destroy(error);\n reject(error);\n }\n else {\n msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;\n logger?.warn?.(msg);\n }\n }, timeoutInMs);\n }\n return -1;\n};\n\nconst DEFER_EVENT_LISTENER_TIME$1 = 3000;\nconst setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => {\n if (keepAlive !== true) {\n return -1;\n }\n const registerListener = () => {\n if (request.socket) {\n request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n }\n else {\n request.on(\"socket\", (socket) => {\n socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n });\n }\n };\n if (deferTimeMs === 0) {\n registerListener();\n return 0;\n }\n return timing.setTimeout(registerListener, deferTimeMs);\n};\n\nconst DEFER_EVENT_LISTENER_TIME = 3000;\nconst setSocketTimeout = (request, reject, timeoutInMs = 0) => {\n const registerTimeout = (offset) => {\n const timeout = timeoutInMs - offset;\n const onTimeout = () => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: \"TimeoutError\" }));\n };\n if (request.socket) {\n request.socket.setTimeout(timeout, onTimeout);\n request.on(\"close\", () => request.socket?.removeListener(\"timeout\", onTimeout));\n }\n else {\n request.setTimeout(timeout, onTimeout);\n }\n };\n if (0 < timeoutInMs && timeoutInMs < 6000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);\n};\n\nconst MIN_WAIT_TIME = 6_000;\nasync function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {\n const headers = request.headers;\n const expect = headers ? headers.Expect || headers.expect : undefined;\n let timeoutId = -1;\n let sendBody = true;\n if (!externalAgent && expect === \"100-continue\") {\n sendBody = await Promise.race([\n new Promise((resolve) => {\n timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));\n }),\n new Promise((resolve) => {\n httpRequest.on(\"continue\", () => {\n timing.clearTimeout(timeoutId);\n resolve(true);\n });\n httpRequest.on(\"response\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n httpRequest.on(\"error\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n }),\n ]);\n }\n if (sendBody) {\n writeBody(httpRequest, request.body);\n }\n}\nfunction writeBody(httpRequest, body) {\n if (body instanceof Readable) {\n body.pipe(httpRequest);\n return;\n }\n if (body) {\n const isBuffer = Buffer.isBuffer(body);\n const isString = typeof body === \"string\";\n if (isBuffer || isString) {\n if (isBuffer && body.byteLength === 0) {\n httpRequest.end();\n }\n else {\n httpRequest.end(body);\n }\n return;\n }\n const uint8 = body;\n if (typeof uint8 === \"object\" &&\n uint8.buffer &&\n typeof uint8.byteOffset === \"number\" &&\n typeof uint8.byteLength === \"number\") {\n httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));\n return;\n }\n httpRequest.end(Buffer.from(body));\n return;\n }\n httpRequest.end();\n}\n\nconst DEFAULT_REQUEST_TIMEOUT = 0;\nlet hAgent = undefined;\nlet hRequest = undefined;\nclass NodeHttpHandler {\n config;\n configProvider;\n socketWarningTimestamp = 0;\n externalAgent = false;\n metadata = { handlerProtocol: \"http/1.1\" };\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttpHandler(instanceOrOptions);\n }\n static checkSocketUsage(agent, socketWarningTimestamp, logger = console) {\n const { sockets, requests, maxSockets } = agent;\n if (typeof maxSockets !== \"number\" || maxSockets === Infinity) {\n return socketWarningTimestamp;\n }\n const interval = 15_000;\n if (Date.now() - interval < socketWarningTimestamp) {\n return socketWarningTimestamp;\n }\n if (sockets && requests) {\n for (const origin in sockets) {\n const socketsInUse = sockets[origin]?.length ?? 0;\n const requestsEnqueued = requests[origin]?.length ?? 0;\n if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {\n logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.\nSee https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html\nor increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);\n return Date.now();\n }\n }\n }\n return socketWarningTimestamp;\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((_options) => {\n resolve(this.resolveDefaultConfig(_options));\n })\n .catch(reject);\n }\n else {\n resolve(this.resolveDefaultConfig(options));\n }\n });\n }\n destroy() {\n this.config?.httpAgent?.destroy();\n this.config?.httpsAgent?.destroy();\n }\n async handle(request, { abortSignal, requestTimeout } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n }\n const config = this.config;\n const isSSL = request.protocol === \"https:\";\n if (!isSSL && !this.config.httpAgent) {\n this.config.httpAgent = await this.config.httpAgentProvider();\n }\n return new Promise((_resolve, _reject) => {\n let writeRequestBodyPromise = undefined;\n let socketWarningTimeoutId = -1;\n let connectionTimeoutId = -1;\n let requestTimeoutId = -1;\n let socketTimeoutId = -1;\n let keepAliveTimeoutId = -1;\n const clearTimeouts = () => {\n timing.clearTimeout(socketWarningTimeoutId);\n timing.clearTimeout(connectionTimeoutId);\n timing.clearTimeout(requestTimeoutId);\n timing.clearTimeout(socketTimeoutId);\n timing.clearTimeout(keepAliveTimeoutId);\n };\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n clearTimeouts();\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n clearTimeouts();\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n return;\n }\n const headers = request.headers;\n const expectContinue = headers ? (headers.Expect ?? headers.expect) === \"100-continue\" : false;\n let agent = isSSL ? config.httpsAgent : config.httpAgent;\n if (expectContinue && !this.externalAgent) {\n agent = new (isSSL ? node_https.Agent : hAgent)({\n keepAlive: false,\n maxSockets: Infinity,\n });\n }\n socketWarningTimeoutId = timing.setTimeout(() => {\n this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config.logger);\n }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2000) + (config.connectionTimeout ?? 1000));\n const queryString = request.query ? buildQueryString(request.query) : \"\";\n let auth = undefined;\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}`;\n }\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n let hostname = request.hostname ?? \"\";\n if (hostname[0] === \"[\" && hostname.endsWith(\"]\")) {\n hostname = request.hostname.slice(1, -1);\n }\n else {\n hostname = request.hostname;\n }\n const nodeHttpsOptions = {\n headers: request.headers,\n host: hostname,\n method: request.method,\n path,\n port: request.port,\n agent,\n auth,\n };\n const requestFunc = isSSL ? node_https.request : hRequest;\n const req = requestFunc(nodeHttpsOptions, (res) => {\n const httpResponse = new HttpResponse({\n statusCode: res.statusCode || -1,\n reason: res.statusMessage,\n headers: getTransformedHeaders(res.headers),\n body: res,\n });\n resolve({ response: httpResponse });\n });\n req.on(\"error\", (err) => {\n if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {\n reject(Object.assign(err, { name: \"TimeoutError\" }));\n }\n else {\n reject(err);\n }\n });\n if (abortSignal) {\n const onAbort = () => {\n req.destroy();\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n req.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout;\n connectionTimeoutId = setConnectionTimeout(req, reject, config.connectionTimeout);\n requestTimeoutId = setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, config.logger ?? console);\n socketTimeoutId = setSocketTimeout(req, reject, config.socketTimeout);\n const httpAgent = nodeHttpsOptions.agent;\n if (typeof httpAgent === \"object\" && \"keepAlive\" in httpAgent) {\n keepAliveTimeoutId = setSocketKeepAlive(req, {\n keepAlive: httpAgent.keepAlive,\n keepAliveMsecs: httpAgent.keepAliveMsecs,\n });\n }\n writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => {\n clearTimeouts();\n return _reject(e);\n });\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n resolveDefaultConfig(options) {\n const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger, } = options || {};\n const keepAlive = true;\n const maxSockets = 50;\n return {\n connectionTimeout,\n requestTimeout,\n socketTimeout,\n socketAcquisitionWarningTimeout,\n throwOnRequestTimeout,\n httpAgentProvider: async () => {\n const node_http = require('node:http');\n const { Agent, request } = node_http.default ?? node_http;\n hRequest = request;\n hAgent = Agent;\n if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpAgent;\n }\n return new hAgent({ keepAlive, maxSockets, ...httpAgent });\n },\n httpsAgent: (() => {\n if (httpsAgent instanceof node_https.Agent || typeof httpsAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpsAgent;\n }\n return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent });\n })(),\n logger,\n };\n }\n}\n\nconst ids = new Uint16Array(1);\nclass ClientHttp2SessionRef {\n id = ids[0]++;\n total = 0;\n max = 0;\n session;\n refs = 0;\n constructor(session) {\n session.unref();\n this.session = session;\n }\n retain() {\n if (this.session.destroyed) {\n throw new Error(\"@smithy/node-http-handler - cannot acquire reference to destroyed session.\");\n }\n this.refs += 1;\n this.total += 1;\n this.max = Math.max(this.refs, this.max);\n this.session.ref();\n }\n free() {\n if (this.session.destroyed) {\n return;\n }\n this.refs -= 1;\n if (this.refs === 0) {\n this.session.unref();\n }\n if (this.refs < 0) {\n throw new Error(\"@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.\");\n }\n }\n deref() {\n return this.session;\n }\n close() {\n if (!this.session.closed) {\n this.session.close();\n }\n }\n destroy() {\n this.refs = 0;\n if (!this.session.destroyed) {\n this.session.destroy();\n }\n }\n useCount() {\n return this.refs;\n }\n}\n\nclass NodeHttp2ConnectionPool {\n sessions = [];\n maxConcurrency = 0;\n constructor(sessions) {\n this.sessions = (sessions ?? []).map((session) => new ClientHttp2SessionRef(session));\n }\n poll() {\n let cleanup = false;\n for (const session of this.sessions) {\n if (session.deref().destroyed) {\n cleanup = true;\n continue;\n }\n if (!this.maxConcurrency || session.useCount() < this.maxConcurrency) {\n return session;\n }\n }\n if (cleanup) {\n for (const session of this.sessions) {\n if (session.deref().destroyed) {\n this.remove(session);\n }\n }\n }\n }\n offerLast(ref) {\n this.sessions.push(ref);\n }\n remove(ref) {\n const ix = this.sessions.indexOf(ref);\n if (ix > -1) {\n this.sessions.splice(ix, 1);\n }\n }\n [Symbol.iterator]() {\n return this.sessions[Symbol.iterator]();\n }\n setMaxConcurrency(maxConcurrency) {\n this.maxConcurrency = maxConcurrency;\n }\n destroy(ref) {\n this.remove(ref);\n ref.destroy();\n }\n}\n\nclass NodeHttp2ConnectionManager {\n config;\n connectOptions;\n connectionPools = new Map();\n constructor(config) {\n this.config = config;\n if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {\n throw new RangeError(\"maxConcurrency must be greater than zero.\");\n }\n }\n lease(requestContext, connectionConfiguration) {\n const url = this.getUrlString(requestContext);\n const pool = this.getPool(url);\n if (!this.config.disableConcurrency && !connectionConfiguration.isEventStream) {\n const available = pool.poll();\n if (available) {\n available.retain();\n return available;\n }\n }\n const ref = new ClientHttp2SessionRef(this.connect(url));\n const session = ref.deref();\n if (this.config.maxConcurrency) {\n session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => {\n if (err) {\n throw new Error(\"Fail to set maxConcurrentStreams to \" +\n this.config.maxConcurrency +\n \"when creating new session for \" +\n requestContext.destination.toString());\n }\n });\n }\n const graceful = () => {\n this.removeFromPoolAndClose(url, ref);\n };\n const ensureDestroyed = () => {\n this.removeFromPoolAndCheckedDestroy(url, ref);\n };\n session.on(\"goaway\", graceful);\n session.on(\"error\", ensureDestroyed);\n session.on(\"frameError\", ensureDestroyed);\n session.on(\"close\", ensureDestroyed);\n if (connectionConfiguration.requestTimeout) {\n session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed);\n }\n pool.offerLast(ref);\n ref.retain();\n return ref;\n }\n release(_requestContext, ref) {\n ref.free();\n }\n createIsolatedSession(requestContext, connectionConfiguration) {\n const url = this.getUrlString(requestContext);\n const ref = new ClientHttp2SessionRef(this.connect(url));\n const session = ref.deref();\n session.settings({ maxConcurrentStreams: 1 });\n const ensureDestroyed = () => {\n ref.destroy();\n };\n session.on(\"error\", ensureDestroyed);\n session.on(\"frameError\", ensureDestroyed);\n session.on(\"close\", ensureDestroyed);\n if (connectionConfiguration.requestTimeout) {\n session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed);\n }\n ref.retain();\n return ref;\n }\n destroy() {\n for (const [url, connectionPool] of this.connectionPools) {\n for (const session of [...connectionPool]) {\n session.destroy();\n }\n this.connectionPools.delete(url);\n }\n }\n setMaxConcurrentStreams(maxConcurrentStreams) {\n if (maxConcurrentStreams && maxConcurrentStreams <= 0) {\n throw new RangeError(\"maxConcurrentStreams must be greater than zero.\");\n }\n this.config.maxConcurrency = maxConcurrentStreams;\n for (const pool of this.connectionPools.values()) {\n pool.setMaxConcurrency(maxConcurrentStreams);\n }\n }\n setDisableConcurrentStreams(disableConcurrentStreams) {\n this.config.disableConcurrency = disableConcurrentStreams;\n }\n setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions) {\n this.connectOptions = nodeHttp2ConnectOptions;\n }\n debug() {\n const pools = {};\n for (const [url, pool] of this.connectionPools) {\n const sessions = [];\n for (const ref of pool) {\n sessions.push({\n id: ref.id,\n active: ref.useCount(),\n maxConcurrent: ref.max,\n totalRequests: ref.total,\n });\n }\n pools[url] = { sessions };\n }\n return pools;\n }\n removeFromPoolAndClose(authority, ref) {\n this.connectionPools.get(authority)?.remove(ref);\n ref.close();\n }\n removeFromPoolAndCheckedDestroy(authority, ref) {\n this.connectionPools.get(authority)?.remove(ref);\n ref.destroy();\n }\n getPool(url) {\n if (!this.connectionPools.has(url)) {\n const pool = new NodeHttp2ConnectionPool();\n if (this.config.maxConcurrency) {\n pool.setMaxConcurrency(this.config.maxConcurrency);\n }\n this.connectionPools.set(url, pool);\n }\n return this.connectionPools.get(url);\n }\n getUrlString(request) {\n return request.destination.toString();\n }\n connect(url) {\n return this.connectOptions === undefined ? http2.connect(url) : http2.connect(url, this.connectOptions);\n }\n}\n\nconst { constants } = http2;\nclass NodeHttp2Handler {\n config;\n configProvider;\n metadata = { handlerProtocol: \"h2\" };\n connectionManager = new NodeHttp2ConnectionManager({});\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttp2Handler(instanceOrOptions);\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((opts) => {\n resolve(opts || {});\n })\n .catch(reject);\n }\n else {\n resolve(options || {});\n }\n });\n }\n destroy() {\n this.connectionManager.destroy();\n }\n async handle(request, { abortSignal, requestTimeout, isEventStream } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n const { disableConcurrentStreams, maxConcurrentStreams, nodeHttp2ConnectOptions } = this.config;\n this.connectionManager.setDisableConcurrentStreams(disableConcurrentStreams ?? false);\n if (maxConcurrentStreams) {\n this.connectionManager.setMaxConcurrentStreams(maxConcurrentStreams);\n }\n if (nodeHttp2ConnectOptions) {\n this.connectionManager.setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions);\n }\n }\n const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config;\n const useIsolatedSession = disableConcurrentStreams || isEventStream;\n const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout;\n return new Promise((_resolve, _reject) => {\n let fulfilled = false;\n let writeRequestBodyPromise = undefined;\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n fulfilled = true;\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n return;\n }\n const { hostname, method, port, protocol, query } = request;\n let auth = \"\";\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}@`;\n }\n const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : \"\"}`;\n const requestContext = { destination: new URL(authority) };\n const connectConfig = {\n requestTimeout: this.config?.sessionTimeout,\n isEventStream,\n };\n const ref = useIsolatedSession\n ? this.connectionManager.createIsolatedSession(requestContext, connectConfig)\n : this.connectionManager.lease(requestContext, connectConfig);\n const session = ref.deref();\n const rejectWithDestroy = (err) => {\n if (useIsolatedSession) {\n ref.destroy();\n }\n fulfilled = true;\n reject(err);\n };\n const queryString = query ? buildQueryString(query) : \"\";\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n const clientHttp2Stream = session.request({\n ...request.headers,\n [constants.HTTP2_HEADER_PATH]: path,\n [constants.HTTP2_HEADER_METHOD]: method,\n });\n if (effectiveRequestTimeout) {\n clientHttp2Stream.setTimeout(effectiveRequestTimeout, () => {\n clientHttp2Stream.close();\n const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`);\n timeoutError.name = \"TimeoutError\";\n rejectWithDestroy(timeoutError);\n });\n }\n if (abortSignal) {\n const onAbort = () => {\n clientHttp2Stream.close();\n const abortError = buildAbortError(abortSignal);\n rejectWithDestroy(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n clientHttp2Stream.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n clientHttp2Stream.on(\"frameError\", (type, code, id) => {\n rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));\n });\n clientHttp2Stream.on(\"error\", rejectWithDestroy);\n clientHttp2Stream.on(\"aborted\", () => {\n rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${clientHttp2Stream.rstCode}.`));\n });\n clientHttp2Stream.on(\"response\", (headers) => {\n const httpResponse = new HttpResponse({\n statusCode: headers[\":status\"] ?? -1,\n headers: getTransformedHeaders(headers),\n body: clientHttp2Stream,\n });\n fulfilled = true;\n resolve({ response: httpResponse });\n if (useIsolatedSession) {\n session.close();\n }\n });\n clientHttp2Stream.on(\"close\", () => {\n if (useIsolatedSession) {\n ref.destroy();\n }\n else {\n this.connectionManager.release(requestContext, ref);\n }\n if (!fulfilled) {\n rejectWithDestroy(new Error(\"Unexpected error: http2 request did not get a response\"));\n }\n });\n writeRequestBodyPromise = writeRequestBody(clientHttp2Stream, request, effectiveRequestTimeout);\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n}\n\nexports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT;\nexports.NodeHttp2Handler = NodeHttp2Handler;\nexports.NodeHttpHandler = NodeHttpHandler;\n" | ||
| ], | ||
| "mappings": ";2KAAA,SAAQ,wBAAkB,qBACpB,cACE,yBACF,cACE,wBACA,mBAAkB,GAE1B,SAAS,CAAe,CAAC,EAAa,CAClC,IAAM,EAAS,GAAe,OAAO,IAAgB,UAAY,WAAY,EACvE,EAAY,OACZ,OACN,GAAI,EAAQ,CACR,GAAI,aAAkB,MAAO,CACzB,IAAM,EAAiB,MAAM,iBAAiB,EAG9C,OAFA,EAAW,KAAO,aAClB,EAAW,MAAQ,EACZ,EAEX,IAAM,EAAiB,MAAM,OAAO,CAAM,CAAC,EAE3C,OADA,EAAW,KAAO,aACX,EAEX,IAAM,EAAiB,MAAM,iBAAiB,EAE9C,OADA,EAAW,KAAO,aACX,EAGX,IAAM,GAA6B,CAAC,aAAc,QAAS,WAAW,EAEhE,EAAwB,CAAC,IAAY,CACvC,IAAM,EAAqB,CAAC,EAC5B,QAAW,KAAQ,EAAS,CACxB,IAAM,EAAe,EAAQ,GAC7B,EAAmB,GAAQ,MAAM,QAAQ,CAAY,EAAI,EAAa,KAAK,GAAG,EAAI,EAEtF,OAAO,GAGL,EAAS,CACX,WAAY,CAAC,EAAI,IAAO,WAAW,EAAI,CAAE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,CAAC,EACzI,EACD,EAAkB,GAAG,WAAY,CAAC,IAAY,CAC1C,IAAM,EAAe,IAAI,EAAa,CAClC,WAAY,EAAQ,YAAc,GAClC,QAAS,EAAsB,CAAO,EACtC,KAAM,CACV,CAAC,EAGD,GAFA,EAAY,GACZ,EAAQ,CAAE,SAAU,CAAa,CAAC,EAC9B,EACA,EAAQ,MAAM,EAErB,EACD,EAAkB,GAAG,QAAS,IAAM,CAChC,GAAI,EACA,EAAI,QAAQ,EAGZ,UAAK,kBAAkB,QAAQ,EAAgB,CAAG,EAEtD,GAAI,CAAC,EACD,EAAsB,MAAM,wDAAwD,CAAC,EAE5F,EACD,EAA0B,EAAiB,EAAmB,EAAS,CAAuB,EACjG,EAEL,sBAAsB,CAAC,EAAK,EAAO,CAC/B,KAAK,OAAS,OACd,KAAK,eAAiB,KAAK,eAAe,KAAK,CAAC,IAAW,CACvD,MAAO,IACA,GACF,GAAM,CACX,EACH,EAEL,kBAAkB,EAAG,CACjB,OAAO,KAAK,QAAU,CAAC,EAE/B,CAEQ,2BAA0B,GAC1B,oBAAmB,EACnB,mBAAkB", | ||
| "debugId": "FC2987DD55BA02C364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.list,\n Effect.fn(\"cli.plugin.list\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.plugin.list({ location: { directory: process.cwd() } }))\n const plugins = response.data.toSorted((a, b) => a.id.localeCompare(b.id))\n if (plugins.length === 0) {\n process.stdout.write(\"No plugins loaded\" + EOL)\n return\n }\n process.stdout.write(plugins.map((plugin) => plugin.id).join(EOL) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";83BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,YAAO,cAAS,UAClC,OAAO,QAAG,sBAAiB,OAAE,cAAU,OAAG,MACxC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAClF,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzE,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,oBAAsB,CAAG,EAC9C,OAEF,QAAQ,OAAO,MAAM,EAAQ,IAAI,CAAC,IAAW,EAAO,EAAE,EAAE,KAAK,CAAG,EAAI,CAAG,EACxE,CACH", | ||
| "debugId": "A98FFAF5C52FCEBD64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/openai-images.ts", "../ai/src/providers/openai.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Encoding, Schema } from \"effect\"\nimport { Headers, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\"\nimport {\n ImageModel,\n GeneratedImage,\n ImageResponse,\n type ImageInput,\n type ImageRequestFor,\n type ImageRoute,\n} from \"../image\"\nimport { Auth, type Definition as AuthDefinition } from \"../route/auth\"\nimport {\n InvalidProviderOutputReason,\n LLMError,\n Usage,\n mergeHttpOptions,\n mergeJsonRecords,\n type HttpOptions,\n} from \"../schema\"\nimport { ProviderShared } from \"./shared\"\nimport { ImageInputs } from \"./utils/image-input\"\nimport { OpenAIImage } from \"./utils/openai-image\"\n\nconst ADAPTER = \"openai-images\"\nexport const DEFAULT_BASE_URL = \"https://api.openai.com/v1\"\nexport const PATH = \"/images/generations\"\nexport const EDIT_PATH = \"/images/edits\"\n\nexport type OpenAIImageString<Known extends string> = Known | (string & {})\n\nexport type OpenAIImageOptions = {\n readonly mask?: ImageInput\n readonly n?: number\n readonly size?: OpenAIImageString<\n \"auto\" | \"256x256\" | \"512x512\" | \"1024x1024\" | \"1536x1024\" | \"1024x1536\" | \"1792x1024\" | \"1024x1792\"\n >\n readonly quality?: OpenAIImageString<\"auto\" | \"low\" | \"medium\" | \"high\" | \"standard\" | \"hd\">\n readonly background?: OpenAIImageString<\"auto\" | \"opaque\" | \"transparent\">\n readonly moderation?: OpenAIImageString<\"auto\" | \"low\">\n readonly outputFormat?: OpenAIImageString<\"png\" | \"jpeg\" | \"webp\">\n readonly outputCompression?: number\n} & Record<string, unknown>\n\nexport type OpenAIImageBody = Record<string, unknown> & {\n readonly model: string\n readonly prompt: string\n}\n\nconst OpenAIImageResponse = Schema.Struct({\n data: Schema.Array(\n Schema.Struct({\n b64_json: Schema.optional(Schema.String),\n url: Schema.optional(Schema.String),\n revised_prompt: Schema.optional(Schema.String),\n }),\n ),\n output_format: Schema.optional(Schema.String),\n usage: Schema.optional(\n Schema.Struct({\n input_tokens: Schema.optional(Schema.Number),\n output_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n input_tokens_details: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n output_tokens_details: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n }),\n ),\n})\n\nexport interface ModelInput {\n readonly id: string\n readonly auth: AuthDefinition\n readonly baseURL?: string\n readonly headers?: Record<string, string>\n readonly http?: HttpOptions\n}\n\nconst nativeOptions = (options: OpenAIImageOptions | undefined) => {\n if (!options) return undefined\n const { mask: _, outputFormat, outputCompression, ...native } = options\n return {\n output_format: outputFormat,\n output_compression: outputCompression,\n ...native,\n }\n}\n\nconst invalidOutput = (message: string) =>\n new LLMError({\n module: ADAPTER,\n method: \"generate\",\n reason: new InvalidProviderOutputReason({ message, route: ADAPTER }),\n })\n\nconst applyQuery = (url: string, query: Record<string, string> | undefined) => {\n if (!query) return url\n const next = new URL(url)\n Object.entries(query).forEach(([key, value]) => next.searchParams.set(key, value))\n return next.toString()\n}\n\nexport const model = (input: ModelInput) => {\n const route: ImageRoute<OpenAIImageOptions> = {\n id: ADAPTER,\n generate: Effect.fn(\"OpenAIImages.generate\")(function* (request: ImageRequestFor<OpenAIImageOptions>, execute) {\n const mask = request.options?.mask\n if (mask !== undefined && (request.images?.length ?? 0) === 0)\n return yield* ImageInputs.invalid(ADAPTER, \"An OpenAI image mask requires at least one input image\")\n const http = mergeHttpOptions(request.model.http, request.http)\n const sourceImages = request.images ?? []\n const multipartImages = yield* Effect.forEach(sourceImages, (image) => {\n if (image.type === \"bytes\") return Effect.succeed({ data: image.data, mediaType: image.mediaType })\n if (image.type === \"url\") return ImageInputs.decodeDataUrl(image.url, ADAPTER)\n return Effect.succeed(undefined)\n })\n const multipartMask =\n mask === undefined\n ? undefined\n : mask.type === \"bytes\"\n ? { data: mask.data, mediaType: mask.mediaType }\n : mask.type === \"url\"\n ? yield* ImageInputs.decodeDataUrl(mask.url, ADAPTER)\n : undefined\n const useMultipart =\n sourceImages.length > 0 &&\n multipartImages.every((image) => image !== undefined) &&\n (mask === undefined || multipartMask !== undefined)\n const path = sourceImages.length === 0 ? PATH : EDIT_PATH\n const url = applyQuery(`${(input.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\")}${path}`, http?.query)\n\n if (useMultipart) {\n const form = new FormData()\n form.append(\"model\", request.model.id)\n form.append(\"prompt\", request.prompt)\n Object.entries(mergeJsonRecords(nativeOptions(request.options), http?.body) ?? {}).forEach(([key, value]) => {\n if ([\"model\", \"prompt\", \"image\", \"image[]\", \"images\", \"mask\"].includes(key)) return\n form.append(key, typeof value === \"string\" ? value : ProviderShared.encodeJson(value))\n })\n multipartImages.forEach((image, index) => {\n if (image === undefined) return\n form.append(\"image[]\", imageBlob(image.data, image.mediaType), `image-${index}`)\n })\n if (multipartMask !== undefined)\n form.append(\"mask\", imageBlob(multipartMask.data, multipartMask.mediaType), \"mask\")\n const headers = yield* Auth.toEffect(input.auth)({\n request,\n method: \"POST\",\n url,\n body: \"[multipart/form-data]\",\n headers: Headers.remove(Headers.fromInput({ ...input.headers, ...http?.headers }), \"content-type\"),\n })\n const response = yield* execute(\n HttpClientRequest.post(url).pipe(HttpClientRequest.setHeaders(headers), HttpClientRequest.bodyFormData(form)),\n )\n return yield* parseResponse(response, request.options, http?.body)\n }\n\n const references = sourceImages.map((image) => {\n if (image.type === \"bytes\") return { image_url: ImageInputs.dataUrl(image) }\n if (image.type === \"url\") return { image_url: image.url }\n if (image.type === \"file-id\") return { file_id: image.id }\n return undefined\n })\n if (references.some((image) => image === undefined))\n return yield* ImageInputs.invalid(ADAPTER, \"OpenAI Images accepts image URLs, data URLs, bytes, and file IDs\")\n const maskReference =\n mask === undefined\n ? undefined\n : mask.type === \"bytes\"\n ? { image_url: ImageInputs.dataUrl(mask) }\n : mask.type === \"url\"\n ? { image_url: mask.url }\n : mask.type === \"file-id\"\n ? { file_id: mask.id }\n : undefined\n if (mask !== undefined && maskReference === undefined)\n return yield* ImageInputs.invalid(ADAPTER, \"OpenAI Images accepts masks as URLs, data URLs, bytes, or file IDs\")\n const requestBody = mergeJsonRecords(\n {\n model: request.model.id,\n prompt: request.prompt,\n images: references.length === 0 ? undefined : references,\n mask: maskReference,\n },\n nativeOptions(request.options),\n http?.body,\n ) as OpenAIImageBody\n const text = ProviderShared.encodeJson(requestBody)\n const headers = yield* Auth.toEffect(input.auth)({\n request,\n method: \"POST\",\n url,\n body: text,\n headers: Headers.fromInput({ ...input.headers, ...http?.headers }),\n })\n const response = yield* execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(text, \"application/json\"),\n ),\n )\n return yield* parseResponse(response, request.options, http?.body)\n }),\n }\n return ImageModel.make<OpenAIImageOptions>({ id: input.id, provider: \"openai\", route, http: input.http })\n}\n\nconst parseResponse = Effect.fn(\"OpenAIImages.parseResponse\")(function* (\n response: HttpClientResponse.HttpClientResponse,\n options: OpenAIImageOptions | undefined,\n overlay: Record<string, unknown> | undefined,\n) {\n const payload = yield* response.json.pipe(\n Effect.mapError(() => invalidOutput(\"Failed to read the OpenAI Images response\")),\n )\n const decoded = yield* Schema.decodeUnknownEffect(OpenAIImageResponse)(payload).pipe(\n Effect.mapError(() => invalidOutput(\"OpenAI Images returned an invalid response\")),\n )\n const requestBody = mergeJsonRecords(nativeOptions(options), overlay)\n const format =\n decoded.output_format ?? (typeof requestBody?.output_format === \"string\" ? requestBody.output_format : \"png\")\n const images = yield* Effect.forEach(decoded.data, (item, index) => {\n if (item.b64_json)\n return Effect.fromResult(Encoding.decodeBase64(item.b64_json)).pipe(\n Effect.mapError(() => invalidOutput(`OpenAI Images result ${index} contains invalid base64 data`)),\n Effect.map(\n (data) =>\n new GeneratedImage({\n mediaType: `image/${format}`,\n data,\n providerMetadata:\n item.revised_prompt === undefined ? undefined : { openai: { revisedPrompt: item.revised_prompt } },\n }),\n ),\n )\n if (item.url)\n return Effect.succeed(\n new GeneratedImage({\n mediaType: `image/${format}`,\n data: item.url,\n providerMetadata:\n item.revised_prompt === undefined ? undefined : { openai: { revisedPrompt: item.revised_prompt } },\n }),\n )\n return Effect.fail(invalidOutput(`OpenAI Images result ${index} has neither image data nor a URL`))\n })\n if (images.length === 0) return yield* invalidOutput(\"OpenAI Images returned no images\")\n return new ImageResponse({\n images,\n usage:\n decoded.usage === undefined\n ? undefined\n : new Usage({\n inputTokens: decoded.usage.input_tokens,\n outputTokens: decoded.usage.output_tokens,\n totalTokens: decoded.usage.total_tokens,\n providerMetadata: { openai: decoded.usage },\n }),\n providerMetadata: { openai: { outputFormat: format } },\n })\n})\n\nconst imageBlob = (data: Uint8Array, mediaType: string) => {\n const buffer = new ArrayBuffer(data.byteLength)\n new Uint8Array(buffer).set(data)\n return new Blob([buffer], { type: mediaType })\n}\n\nexport const OpenAIImages = {\n model,\n} as const\n", | ||
| "import { AuthOptions, type ProviderAuthOption } from \"../route/auth-options\"\nimport type { Route, RouteDefaultsInput } from \"../route/client\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { HttpOptions, ProviderID, ToolDefinition, mergeHttpOptions, type ModelID } from \"../schema\"\nimport * as OpenAIChat from \"../protocols/openai-chat\"\nimport * as OpenAIResponses from \"../protocols/openai-responses\"\nimport { withOpenAIOptions, type OpenAIProviderOptionsInput } from \"./openai-options\"\nimport { OpenAIImages, type OpenAIImageString } from \"../protocols/openai-images\"\n\nexport type { OpenAIOptionsInput, OpenAIResponseIncludable } from \"./openai-options\"\nexport type { OpenAIImageOptions } from \"../protocols/openai-images\"\n\nexport const id = ProviderID.make(\"openai\")\n\nexport const routes = [OpenAIResponses.route, OpenAIResponses.webSocketRoute, OpenAIChat.route]\n\n// This provider facade wraps the lower-level Responses and Chat model factories\n// with OpenAI-specific conveniences: typed options, API-key sugar, env fallback,\n// and default option normalization.\nexport type Config = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n readonly queryParams?: Record<string, string>\n readonly providerOptions?: OpenAIProviderOptionsInput\n }\n\nexport interface ImageGenerationOptions {\n readonly action?: OpenAIImageString<\"auto\" | \"generate\" | \"edit\">\n readonly background?: OpenAIImageString<\"auto\" | \"opaque\" | \"transparent\">\n readonly inputFidelity?: OpenAIImageString<\"low\" | \"high\">\n readonly outputCompression?: number\n readonly outputFormat?: OpenAIImageString<\"png\" | \"jpeg\" | \"webp\">\n readonly partialImages?: number\n readonly quality?: OpenAIImageString<\"auto\" | \"low\" | \"medium\" | \"high\" | \"standard\" | \"hd\">\n readonly size?: OpenAIImageString<\n \"auto\" | \"256x256\" | \"512x512\" | \"1024x1024\" | \"1536x1024\" | \"1024x1536\" | \"1792x1024\" | \"1024x1792\"\n >\n}\n\nexport const imageGeneration = (options: ImageGenerationOptions = {}) =>\n ToolDefinition.make({\n name: \"image_generation\",\n description: \"Generate or edit an image using OpenAI's hosted image generation tool.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n native: {\n openai: {\n type: \"image_generation\",\n action: options.action,\n background: options.background,\n input_fidelity: options.inputFidelity,\n output_compression: options.outputCompression,\n output_format: options.outputFormat,\n partial_images: options.partialImages,\n quality: options.quality,\n size: options.size,\n },\n },\n })\n\nexport interface Settings extends ProviderPackage.Settings {\n readonly apiKey?: string\n readonly baseURL?: string\n readonly organization?: string\n readonly project?: string\n readonly queryParams?: Readonly<Record<string, string>>\n readonly transport?: \"http\" | \"websocket\"\n readonly providerOptions?: OpenAIProviderOptionsInput\n}\n\nconst auth = (options: ProviderAuthOption<\"optional\">) => AuthOptions.bearer(options, \"OPENAI_API_KEY\")\n\nconst defaults = (input: Config) => {\n const { apiKey: _, auth: _auth, baseURL: _baseURL, queryParams: _queryParams, ...rest } = input\n return rest\n}\n\nconst configuredRoute = <Body, Prepared>(route: Route<Body, Prepared>, input: Config) =>\n route.with({\n auth: auth(input),\n endpoint: { baseURL: input.baseURL, query: input.queryParams },\n })\n\nexport const configure = (input: Config = {}) => {\n const responsesRoute = configuredRoute(OpenAIResponses.route, input)\n const responsesWebSocketRoute = configuredRoute(OpenAIResponses.webSocketRoute, input)\n const chatRoute = configuredRoute(OpenAIChat.route, input)\n const modelDefaults = defaults(input)\n const responses = (id: string | ModelID) =>\n responsesRoute.with(withOpenAIOptions(id, modelDefaults, { textVerbosity: true })).model({ id })\n const responsesWebSocket = (id: string | ModelID) =>\n responsesWebSocketRoute.with(withOpenAIOptions(id, modelDefaults, { textVerbosity: true })).model({ id })\n const chat = (id: string | ModelID) => chatRoute.with(withOpenAIOptions(id, modelDefaults)).model({ id })\n const image = (modelID: string | ModelID) =>\n OpenAIImages.model({\n id: modelID,\n auth: auth(input),\n baseURL: input.baseURL,\n headers: input.headers,\n http: mergeHttpOptions(\n input.http === undefined ? undefined : HttpOptions.make(input.http),\n input.queryParams === undefined ? undefined : new HttpOptions({ query: input.queryParams }),\n ),\n })\n\n return {\n id,\n model: responses,\n responses,\n responsesWebSocket,\n chat,\n image,\n configure,\n }\n}\n\nexport const provider = configure()\n\nconst config = (settings: Settings): Config => {\n const headers = {\n ...(settings.organization === undefined ? {} : { \"OpenAI-Organization\": settings.organization }),\n ...(settings.project === undefined ? {} : { \"OpenAI-Project\": settings.project }),\n ...settings.headers,\n }\n return {\n apiKey: settings.apiKey,\n baseURL: settings.baseURL,\n headers: Object.keys(headers).length === 0 ? undefined : headers,\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n providerOptions: settings.providerOptions,\n queryParams: settings.queryParams === undefined ? undefined : { ...settings.queryParams },\n }\n}\n\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) => {\n const configured = configure(config(settings))\n if (settings.transport === undefined || settings.transport === \"http\") return configured.responses(modelID)\n if (settings.transport === \"websocket\") return configured.responsesWebSocket(modelID)\n throw new Error(`Unsupported OpenAI Responses transport: ${String(settings.transport)}`)\n}\n\nexport const chatModel: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure(config(settings)).chat(modelID)\nexport const responses = provider.responses\nexport const responsesWebSocket = provider.responsesWebSocket\nexport const chat = provider.chat\nexport const image = provider.image\n" | ||
| ], | ||
| "mappings": ";oiBAuBA,SAAM,OAAU,qBACH,QAAmB,iCACnB,QAAO,2BACP,QAAY,gBAsBnB,GAAsB,EAAO,OAAO,CACxC,KAAM,EAAO,MACX,EAAO,OAAO,CACZ,SAAU,EAAO,SAAS,EAAO,MAAM,EACvC,IAA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ACL,OAAQ,EAAS,OACjB,QAAS,EAAS,QAClB,QAAS,OAAO,KAAK,CAAO,EAAE,SAAW,EAAI,OAAY,EACzD,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,OACjB,gBAAiB,EAAS,gBAC1B,YAAa,EAAS,cAAgB,OAAY,OAAY,IAAK,EAAS,WAAY,CAC1F,GAGW,GAAuD,CAAC,EAAS,IAAa,CACzF,IAAM,EAAa,EAAU,EAAO,CAAQ,CAAC,EAC7C,GAAI,EAAS,YAAc,QAAa,EAAS,YAAc,OAAQ,OAAO,EAAW,UAAU,CAAO,EAC1G,GAAI,EAAS,YAAc,YAAa,OAAO,EAAW,mBAAmB,CAAO,EACpF,MAAU,MAAM,2CAA2C,OAAO,EAAS,SAAS,GAAG,GAG5E,GAA2D,CAAC,EAAS,IAChF,EAAU,EAAO,CAAQ,CAAC,EAAE,KAAK,CAAO,EAC7B,GAAY,EAAS,UACrB,GAAqB,EAAS,mBAC9B,GAAO,EAAS,KAChB,GAAQ,EAAS", | ||
| "debugId": "C8E7C636D5F0103664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "875F80385A090D7264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/connect.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type IntegrationCommandStatusOutput, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.connect,\n Effect.fn(\"cli.auth.connect\")(function* (input) {\n process.stdout.write(\"Connecting...\" + EOL + EOL)\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n yield* request(() => client.integration.wellknown.add({ url: input.url, location }))\n const integrationID = input.url.replace(/\\/+$/, \"\")\n const started = yield* request(() =>\n client.integration.command.connect({ integrationID, methodID: \"login\", location }),\n )\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.command.cancel({ integrationID, attemptID: started.data.attemptID, location }),\n ).pipe(Effect.ignore),\n )\n\n const status = yield* wait(client, integrationID, started.data.attemptID)\n if (status.status === \"failed\") return yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") return yield* Effect.fail(new Error(\"Authentication expired\"))\n process.stdout.write(\"Connected\" + EOL)\n }),\n)\n\nconst wait = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n shown = false,\n): Effect.Effect<Exclude<IntegrationCommandStatusOutput[\"data\"], { status: \"pending\" }>, unknown> =>\n Effect.gen(function* () {\n const response = yield* request(() => client.integration.command.status({ integrationID, attemptID, location }))\n if (response.data.status !== \"pending\") return response.data\n const output = response.data.message?.trim()\n if (!shown && output) process.stdout.write(output + EOL + EOL)\n yield* Effect.sleep(500)\n return yield* wait(client, integrationID, attemptID, shown || !!output)\n })\n\nfunction request<A>(task: () => Promise<A>) {\n return Effect.tryPromise({ try: task, catch: (cause) => cause })\n}\n" | ||
| ], | ||
| "mappings": ";83BAAA,mBAAS,gBAQT,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,UAAK,cAAS,aAChC,OAAO,QAAG,uBAAkB,OAAE,cAAU,MAAC,EAAO,CAC9C,QAAQ,OAAO,MAAM,gBAAkB,EAAM,CAAG,EAChD,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QA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,CAAC,IAAU,CAAM,CAAC", | ||
| "debugId": "CF85AFB46ACAAA8664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+deepinfra@2.0.41+d6123d32214422cb/node_modules/@ai-sdk/deepinfra/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/deepinfra-provider.ts\nimport {\n OpenAICompatibleCompletionLanguageModel,\n OpenAICompatibleEmbeddingModel\n} from \"@ai-sdk/openai-compatible\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/deepinfra-image-model.ts\nimport {\n combineHeaders,\n convertBase64ToUint8Array,\n convertToFormData,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n downloadBlob,\n postFormDataToApi,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\nvar DeepInfraImageModel = class {\n constructor(modelId, config) {\n this.modelId = modelId;\n this.config = config;\n this.specificationVersion = \"v3\";\n this.maxImagesPerCall = 1;\n }\n get provider() {\n return this.config.provider;\n }\n async doGenerate({\n prompt,\n n,\n size,\n aspectRatio,\n seed,\n providerOptions,\n headers,\n abortSignal,\n files,\n mask\n }) {\n var _a, _b, _c, _d, _e;\n const warnings = [];\n const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();\n if (files != null && files.length > 0) {\n const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi({\n url: this.getEditUrl(),\n headers: combineHeaders(this.config.headers(), headers),\n formData: convertToFormData(\n {\n model: this.modelId,\n prompt,\n image: await Promise.all(files.map((file) => fileToBlob(file))),\n mask: mask != null ? await fileToBlob(mask) : void 0,\n n,\n size,\n ...(_d = providerOptions.deepinfra) != null ? _d : {}\n },\n { useArrayBrackets: false }\n ),\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: deepInfraEditErrorSchema,\n errorToMessage: (error) => {\n var _a2, _b2;\n return (_b2 = (_a2 = error.error) == null ? void 0 : _a2.message) != null ? _b2 : \"Unknown error\";\n }\n }),\n successfulResponseHandler: createJsonResponseHandler(\n deepInfraEditResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n images: response2.data.map((item) => item.b64_json),\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders2\n }\n };\n }\n const splitSize = size == null ? void 0 : size.split(\"x\");\n const { value: response, responseHeaders } = await postJsonToApi({\n url: `${this.config.baseURL}/${this.modelId}`,\n headers: combineHeaders(this.config.headers(), headers),\n body: {\n prompt,\n num_images: n,\n ...aspectRatio && { aspect_ratio: aspectRatio },\n ...splitSize && { width: splitSize[0], height: splitSize[1] },\n ...seed != null && { seed },\n ...(_e = providerOptions.deepinfra) != null ? _e : {}\n },\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: deepInfraErrorSchema,\n errorToMessage: (error) => error.detail.error\n }),\n successfulResponseHandler: createJsonResponseHandler(\n deepInfraImageResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n images: response.images.map(\n (image) => image.replace(/^data:image\\/\\w+;base64,/, \"\")\n ),\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders\n }\n };\n }\n getEditUrl() {\n const baseUrl = this.config.baseURL.replace(\"/inference\", \"/openai\");\n return `${baseUrl}/images/edits`;\n }\n};\nvar deepInfraErrorSchema = z.object({\n detail: z.object({\n error: z.string()\n })\n});\nvar deepInfraImageResponseSchema = z.object({\n images: z.array(z.string())\n});\nvar deepInfraEditErrorSchema = z.object({\n error: z.object({\n message: z.string()\n }).optional()\n});\nvar deepInfraEditResponseSchema = z.object({\n data: z.array(z.object({ b64_json: z.string() }))\n});\nasync function fileToBlob(file) {\n if (file.type === \"url\") {\n return downloadBlob(file.url);\n }\n const data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array(file.data);\n return new Blob([data], { type: file.mediaType });\n}\n\n// src/deepinfra-chat-language-model.ts\nimport { OpenAICompatibleChatLanguageModel } from \"@ai-sdk/openai-compatible\";\nvar DeepInfraChatLanguageModel = class extends OpenAICompatibleChatLanguageModel {\n constructor(modelId, config) {\n super(modelId, config);\n }\n /**\n * Fixes incorrect token usage for Gemini/Gemma models from DeepInfra.\n *\n * DeepInfra's API returns completion_tokens that don't include reasoning_tokens\n * for Gemini/Gemma models, which violates the OpenAI-compatible spec.\n * According to the spec, completion_tokens should include reasoning_tokens.\n *\n * Example of incorrect data from DeepInfra:\n * {\n * \"completion_tokens\": 84, // text-only tokens\n * \"completion_tokens_details\": {\n * \"reasoning_tokens\": 1081 // reasoning tokens not included above\n * }\n * }\n *\n * This would result in negative text tokens: 84 - 1081 = -997\n *\n * The fix: If reasoning_tokens > completion_tokens, add reasoning_tokens\n * to completion_tokens: 84 + 1081 = 1165\n */\n fixUsageForGeminiModels(usage) {\n var _a, _b;\n if (!usage || !((_a = usage.completion_tokens_details) == null ? void 0 : _a.reasoning_tokens)) {\n return usage;\n }\n const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;\n const reasoningTokens = usage.completion_tokens_details.reasoning_tokens;\n if (reasoningTokens > completionTokens) {\n const correctedCompletionTokens = completionTokens + reasoningTokens;\n return {\n ...usage,\n // Add reasoning_tokens to completion_tokens to get the correct total\n completion_tokens: correctedCompletionTokens,\n // Update total_tokens if present\n total_tokens: usage.total_tokens != null ? usage.total_tokens + reasoningTokens : void 0\n };\n }\n return usage;\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g;\n const result = await super.doGenerate(options);\n if ((_a = result.usage) == null ? void 0 : _a.raw) {\n const fixedRawUsage = this.fixUsageForGeminiModels(result.usage.raw);\n if (fixedRawUsage !== result.usage.raw) {\n const promptTokens = (_b = fixedRawUsage.prompt_tokens) != null ? _b : 0;\n const completionTokens = (_c = fixedRawUsage.completion_tokens) != null ? _c : 0;\n const cacheReadTokens = (_e = (_d = fixedRawUsage.prompt_tokens_details) == null ? void 0 : _d.cached_tokens) != null ? _e : 0;\n const reasoningTokens = (_g = (_f = fixedRawUsage.completion_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : 0;\n return {\n ...result,\n usage: {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens - reasoningTokens,\n reasoning: reasoningTokens\n },\n raw: fixedRawUsage\n }\n };\n }\n }\n return result;\n }\n async doStream(options) {\n const result = await super.doStream(options);\n const originalStream = result.stream;\n const fixUsage = this.fixUsageForGeminiModels.bind(this);\n const transformedStream = new ReadableStream({\n async start(controller) {\n var _a, _b, _c, _d, _e, _f, _g;\n const reader = originalStream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value.type === \"finish\" && ((_a = value.usage) == null ? void 0 : _a.raw)) {\n const fixedRawUsage = fixUsage(value.usage.raw);\n if (fixedRawUsage !== value.usage.raw) {\n const promptTokens = (_b = fixedRawUsage.prompt_tokens) != null ? _b : 0;\n const completionTokens = (_c = fixedRawUsage.completion_tokens) != null ? _c : 0;\n const cacheReadTokens = (_e = (_d = fixedRawUsage.prompt_tokens_details) == null ? void 0 : _d.cached_tokens) != null ? _e : 0;\n const reasoningTokens = (_g = (_f = fixedRawUsage.completion_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : 0;\n controller.enqueue({\n ...value,\n usage: {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens - reasoningTokens,\n reasoning: reasoningTokens\n },\n raw: fixedRawUsage\n }\n });\n } else {\n controller.enqueue(value);\n }\n } else {\n controller.enqueue(value);\n }\n }\n controller.close();\n } catch (error) {\n controller.error(error);\n }\n }\n });\n return {\n ...result,\n stream: transformedStream\n };\n }\n};\n\n// src/version.ts\nvar VERSION = true ? \"2.0.41\" : \"0.0.0-test\";\n\n// src/deepinfra-provider.ts\nfunction createDeepInfra(options = {}) {\n var _a;\n const baseURL = withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.deepinfra.com/v1\"\n );\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"DEEPINFRA_API_KEY\",\n description: \"DeepInfra's API key\"\n })}`,\n ...options.headers\n },\n `ai-sdk/deepinfra/${VERSION}`\n );\n const getCommonModelConfig = (modelType) => ({\n provider: `deepinfra.${modelType}`,\n url: ({ path }) => `${baseURL}/openai${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createChatModel = (modelId) => {\n return new DeepInfraChatLanguageModel(\n modelId,\n getCommonModelConfig(\"chat\")\n );\n };\n const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(\n modelId,\n getCommonModelConfig(\"completion\")\n );\n const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(\n modelId,\n getCommonModelConfig(\"embedding\")\n );\n const createImageModel = (modelId) => new DeepInfraImageModel(modelId, {\n ...getCommonModelConfig(\"image\"),\n baseURL: baseURL ? `${baseURL}/inference` : \"https://api.deepinfra.com/v1/inference\"\n });\n const provider = (modelId) => createChatModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.completionModel = createCompletionModel;\n provider.chatModel = createChatModel;\n provider.image = createImageModel;\n provider.imageModel = createImageModel;\n provider.languageModel = createChatModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n return provider;\n}\nvar deepinfra = createDeepInfra();\nexport {\n VERSION,\n createDeepInfra,\n deepinfra\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";4ZAuBA,SAAI,OAAsB,UAAM,MAC9B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AK,EAAQ,UAAY,KAAO,EAAK,8BACxC,EACM,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,oBACzB,YAAa,qBACf,CAAC,OACE,EAAQ,OACb,EACA,oBAAoB,GACtB,EACM,EAAuB,CAAC,KAAe,CAC3C,SAAU,aAAa,IACvB,IAAK,EAAG,UAAW,GAAG,WAAiB,IACvC,QAAS,EACT,MAAO,EAAQ,KACjB,GACM,EAAkB,CAAC,IAAY,CACnC,OAAO,IAAI,EACT,EACA,EAAqB,MAAM,CAC7B,GAEI,EAAwB,CAAC,IAAY,IAAI,EAC7C,EACA,EAAqB,YAAY,CACnC,EACM,EAAuB,CAAC,IAAY,IAAI,EAC5C,EACA,EAAqB,WAAW,CAClC,EACM,EAAmB,CAAC,IAAY,IAAI,EAAoB,EAAS,IAClE,EAAqB,OAAO,EAC/B,QAAS,EAAU,GAAG,cAAsB,wCAC9C,CAAC,EACK,EAAW,CAAC,IAAY,EAAgB,CAAO,EASrD,OARA,EAAS,qBAAuB,KAChC,EAAS,gBAAkB,EAC3B,EAAS,UAAY,EACrB,EAAS,MAAQ,EACjB,EAAS,WAAa,EACtB,EAAS,cAAgB,EACzB,EAAS,eAAiB,EAC1B,EAAS,mBAAqB,EACvB,EAET,IAAI,GAAY,EAAgB", | ||
| "debugId": "1F1C56ADBDECFB6A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/utils/image-input.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Encoding } from \"effect\"\nimport type { ImageInput } from \"../../image\"\nimport { InvalidRequestReason, LLMError } from \"../../schema\"\n\nconst invalid = (module: string, message: string) =>\n new LLMError({\n module,\n method: \"generate\",\n reason: new InvalidRequestReason({ message }),\n })\n\nexport const dataUrl = (input: Extract<ImageInput, { readonly type: \"bytes\" }>) =>\n `data:${input.mediaType};base64,${Encoding.encodeBase64(input.data)}`\n\nexport const decodeDataUrl = (\n url: string,\n module: string,\n): Effect.Effect<{ readonly mediaType: string; readonly data: Uint8Array } | undefined, LLMError> => {\n if (!url.startsWith(\"data:\")) return Effect.succeed(undefined)\n const match = /^data:([^;,]+);base64,(.*)$/s.exec(url)\n if (!match) return Effect.fail(invalid(module, \"Image data URLs must contain a MIME type and base64 data\"))\n return Effect.fromResult(Encoding.decodeBase64(match[2])).pipe(\n Effect.mapError(() => invalid(module, \"Image data URL contains invalid base64 data\")),\n Effect.map((data) => ({ mediaType: match[1], data })),\n )\n}\n\nexport const invalidImageInput = invalid\n\nexport const ImageInputs = {\n dataUrl,\n decodeDataUrl,\n invalid: invalidImageInput,\n} as const\n" | ||
| ], | ||
| "mappings": ";mHAIA,SAAM,EAAU,CAAC,EAAgB,IAC/B,IAAI,EAAS,CACX,SACA,OAAQ,WACR,OAAQ,IAAI,EAAqB,CAAE,SAAQ,CAAC,CAC9C,CAAC,EAEU,EAAU,CAAC,IACtB,QAAQ,EAAM,oBAAoB,EAAS,aAAa,EAAM,IAAI,IAEvD,EAAgB,CAC3B,EACA,IACmG,CACnG,GAAI,CAAC,EAAI,WAAW,OAAO,EAAG,OAAO,EAAO,QAAQ,MAAS,EAC7D,IAAM,EAAQ,+BAA+B,KAAK,CAAG,EACrD,GAAI,CAAC,EAAO,OAAO,EAAO,KAAK,EAAQ,EAAQ,0DAA0D,CAAC,EAC1G,OAAO,EAAO,WAAW,EAAS,aAAa,EAAM,EAAE,CAAC,EAAE,KACxD,EAAO,SAAS,IAAM,EAAQ,EAAQ,6CAA6C,CAAC,EACpF,EAAO,IAAI,CAAC,KAAU,CAAE,UAAW,EAAM,GAAI,MAAK,EAAE,CACtD,GAGW,EAAoB,EAEpB,EAAc,CACzB,UACA,gBACA,QAAS,CACX", | ||
| "debugId": "BC9991F4B3A9AFFB64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "1DB8266BE0353A8164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "5C90F02A2BA402F464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/node-http.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js"], | ||
| "sourcesContent": [ | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { retry } from \"./remoteProvider/retry\";\nexport const ENV_CMDS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nexport const ENV_CMDS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nexport const ENV_CMDS_AUTH_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromContainerMetadata = (init = {}) => {\n const { timeout, maxRetries } = providerConfigFromInit(init);\n return () => retry(async () => {\n const requestOptions = await getCmdsUri({ logger: init.logger });\n const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));\n if (!isImdsCredentials(credsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credsResponse);\n }, maxRetries);\n};\nconst requestFromEcsImds = async (timeout, options) => {\n if (process.env[ENV_CMDS_AUTH_TOKEN]) {\n options.headers = {\n ...options.headers,\n Authorization: process.env[ENV_CMDS_AUTH_TOKEN],\n };\n }\n const buffer = await httpRequest({\n ...options,\n timeout,\n });\n return buffer.toString();\n};\nconst CMDS_IP = \"169.254.170.2\";\nconst GREENGRASS_HOSTS = new Set([\"localhost\", \"127.0.0.1\"]);\nconst GREENGRASS_PROTOCOLS = new Set([\"http:\", \"https:\"]);\nconst getCmdsUri = async ({ logger }) => {\n if (process.env[ENV_CMDS_RELATIVE_URI]) {\n return {\n hostname: CMDS_IP,\n path: process.env[ENV_CMDS_RELATIVE_URI],\n };\n }\n if (process.env[ENV_CMDS_FULL_URI]) {\n let parsed;\n try {\n parsed = new URL(process.env[ENV_CMDS_FULL_URI]);\n }\n catch {\n throw new CredentialsProviderError(`${process.env[ENV_CMDS_FULL_URI]} is not a valid container metadata service URL`, { tryNextLink: false, logger });\n }\n if (!parsed.hostname || !GREENGRASS_HOSTS.has(parsed.hostname)) {\n throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {\n tryNextLink: false,\n logger,\n });\n }\n if (!parsed.protocol || !GREENGRASS_PROTOCOLS.has(parsed.protocol)) {\n throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {\n tryNextLink: false,\n logger,\n });\n }\n return {\n protocol: parsed.protocol,\n hostname: parsed.hostname,\n path: parsed.pathname + parsed.search,\n port: parsed.port ? parseInt(parsed.port, 10) : undefined,\n };\n }\n throw new CredentialsProviderError(\"The container metadata credential provider cannot be used unless\" +\n ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` +\n \" variable is set\", {\n tryNextLink: false,\n logger,\n });\n};\n", | ||
| "export const isImdsCredentials = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.AccessKeyId === \"string\" &&\n typeof arg.SecretAccessKey === \"string\" &&\n typeof arg.Token === \"string\" &&\n typeof arg.Expiration === \"string\";\nexport const fromImdsCredentials = (creds) => ({\n accessKeyId: creds.AccessKeyId,\n secretAccessKey: creds.SecretAccessKey,\n sessionToken: creds.Token,\n expiration: new Date(creds.Expiration),\n ...(creds.AccountId && { accountId: creds.AccountId }),\n});\n", | ||
| "export const DEFAULT_TIMEOUT = 1000;\nexport const DEFAULT_MAX_RETRIES = 0;\nexport const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout });\n", | ||
| "import { ProviderError } from \"@smithy/core/config\";\nimport { node_http } from \"./node-http\";\nexport function httpRequest(options) {\n return new Promise((resolve, reject) => {\n const req = node_http.request({\n method: \"GET\",\n ...options,\n hostname: options.hostname?.replace(/^\\[(.+)\\]$/, \"$1\"),\n });\n req.on(\"error\", (err) => {\n reject(Object.assign(new ProviderError(\"Unable to connect to instance metadata service\"), err));\n req.destroy();\n });\n req.on(\"timeout\", () => {\n reject(new ProviderError(\"TimeoutError from instance metadata service\"));\n req.destroy();\n });\n req.on(\"response\", (res) => {\n const { statusCode = 400 } = res;\n if (statusCode < 200 || 300 <= statusCode) {\n reject(Object.assign(new ProviderError(\"Error response received from instance metadata service\"), { statusCode }));\n req.destroy();\n }\n const chunks = [];\n res.on(\"data\", (chunk) => {\n chunks.push(chunk);\n });\n res.on(\"end\", () => {\n resolve(Buffer.concat(chunks));\n req.destroy();\n });\n });\n req.end();\n });\n}\n", | ||
| "import node_http from \"node:http\";\nexport { node_http };\n", | ||
| "export const retry = (toRetry, maxRetries) => {\n let promise = toRetry();\n for (let i = 0; i < maxRetries; i++) {\n promise = promise.catch(toRetry);\n }\n return promise;\n};\n", | ||
| "import { CredentialsProviderError, loadConfig } from \"@smithy/core/config\";\nimport { InstanceMetadataV1FallbackError } from \"./error/InstanceMetadataV1FallbackError\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { retry } from \"./remoteProvider/retry\";\nimport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nimport { staticStabilityProvider } from \"./utils/staticStabilityProvider\";\nconst IMDS_PATH = \"/latest/meta-data/iam/security-credentials/\";\nconst IMDS_TOKEN_PATH = \"/latest/api/token\";\nconst AWS_EC2_METADATA_V1_DISABLED = \"AWS_EC2_METADATA_V1_DISABLED\";\nconst PROFILE_AWS_EC2_METADATA_V1_DISABLED = \"ec2_metadata_v1_disabled\";\nconst X_AWS_EC2_METADATA_TOKEN = \"x-aws-ec2-metadata-token\";\nexport const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger });\nconst getInstanceMetadataProvider = (init = {}) => {\n let disableFetchToken = false;\n const { logger, profile } = init;\n const { timeout, maxRetries } = providerConfigFromInit(init);\n const getCredentials = async (maxRetries, options) => {\n const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;\n if (isImdsV1Fallback) {\n let fallbackBlockedFromProfile = false;\n let fallbackBlockedFromProcessEnv = false;\n const configValue = await loadConfig({\n environmentVariableSelector: (env) => {\n const envValue = env[AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProcessEnv = !!envValue && envValue !== \"false\";\n if (envValue === undefined) {\n throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger });\n }\n return fallbackBlockedFromProcessEnv;\n },\n configFileSelector: (profile) => {\n const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProfile = !!profileValue && profileValue !== \"false\";\n return fallbackBlockedFromProfile;\n },\n default: false,\n }, {\n profile,\n })();\n if (init.ec2MetadataV1Disabled || configValue) {\n const causes = [];\n if (init.ec2MetadataV1Disabled)\n causes.push(\"credential provider initialization (runtime option ec2MetadataV1Disabled)\");\n if (fallbackBlockedFromProfile)\n causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);\n if (fallbackBlockedFromProcessEnv)\n causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);\n throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(\", \")}].`);\n }\n }\n const imdsProfile = (await retry(async () => {\n let profile;\n try {\n profile = await getProfile(options);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return profile;\n }, maxRetries)).trim();\n return retry(async () => {\n let creds;\n try {\n creds = await getCredentialsFromProfile(imdsProfile, options, init);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return creds;\n }, maxRetries);\n };\n return async () => {\n const endpoint = await getInstanceMetadataEndpoint();\n if (disableFetchToken) {\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (no token fetch)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n else {\n let token;\n try {\n token = (await getMetadataToken({ ...endpoint, timeout })).toString();\n }\n catch (error) {\n if (error?.statusCode === 400) {\n throw Object.assign(error, {\n message: \"EC2 Metadata token request returned error\",\n });\n }\n else if (error.message === \"TimeoutError\" || [403, 404, 405].includes(error.statusCode)) {\n disableFetchToken = true;\n }\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (initial)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n return getCredentials(maxRetries, {\n ...endpoint,\n headers: {\n [X_AWS_EC2_METADATA_TOKEN]: token,\n },\n timeout,\n });\n }\n };\n};\nconst getMetadataToken = async (options) => httpRequest({\n ...options,\n path: IMDS_TOKEN_PATH,\n method: \"PUT\",\n headers: {\n \"x-aws-ec2-metadata-token-ttl-seconds\": \"21600\",\n },\n});\nconst getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString();\nconst getCredentialsFromProfile = async (profile, options, init) => {\n const credentialsResponse = JSON.parse((await httpRequest({\n ...options,\n path: IMDS_PATH + profile,\n })).toString());\n if (!isImdsCredentials(credentialsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credentialsResponse);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nexport class InstanceMetadataV1FallbackError extends CredentialsProviderError {\n tryNextLink;\n name = \"InstanceMetadataV1FallbackError\";\n constructor(message, tryNextLink = true) {\n super(message, tryNextLink);\n this.tryNextLink = tryNextLink;\n Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype);\n }\n}\n", | ||
| "import { loadConfig } from \"@smithy/core/config\";\nimport { parseUrl } from \"@smithy/core/protocols\";\nimport { Endpoint as InstanceMetadataEndpoint } from \"../config/Endpoint\";\nimport { ENDPOINT_CONFIG_OPTIONS } from \"../config/EndpointConfigOptions\";\nimport { EndpointMode } from \"../config/EndpointMode\";\nimport { ENDPOINT_MODE_CONFIG_OPTIONS, } from \"../config/EndpointModeConfigOptions\";\nexport const getInstanceMetadataEndpoint = async () => parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig()));\nconst getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)();\nconst getFromEndpointModeConfig = async () => {\n const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();\n switch (endpointMode) {\n case EndpointMode.IPv4:\n return InstanceMetadataEndpoint.IPv4;\n case EndpointMode.IPv6:\n return InstanceMetadataEndpoint.IPv6;\n default:\n throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`);\n }\n};\n", | ||
| "export var Endpoint;\n(function (Endpoint) {\n Endpoint[\"IPv4\"] = \"http://169.254.169.254\";\n Endpoint[\"IPv6\"] = \"http://[fd00:ec2::254]\";\n})(Endpoint || (Endpoint = {}));\n", | ||
| "export const ENV_ENDPOINT_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT\";\nexport const CONFIG_ENDPOINT_NAME = \"ec2_metadata_service_endpoint\";\nexport const ENDPOINT_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],\n default: undefined,\n};\n", | ||
| "export var EndpointMode;\n(function (EndpointMode) {\n EndpointMode[\"IPv4\"] = \"IPv4\";\n EndpointMode[\"IPv6\"] = \"IPv6\";\n})(EndpointMode || (EndpointMode = {}));\n", | ||
| "import { EndpointMode } from \"./EndpointMode\";\nexport const ENV_ENDPOINT_MODE_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE\";\nexport const CONFIG_ENDPOINT_MODE_NAME = \"ec2_metadata_service_endpoint_mode\";\nexport const ENDPOINT_MODE_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],\n default: EndpointMode.IPv4,\n};\n", | ||
| "const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;\nconst STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;\nconst STATIC_STABILITY_DOC_URL = \"https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html\";\nexport const getExtendedInstanceMetadataCredentials = (credentials, logger) => {\n const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS +\n Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);\n const newExpiration = new Date(Date.now() + refreshInterval * 1000);\n logger.warn(\"Attempting credential expiration extension due to a credential service availability issue. A refresh of these \" +\n `credentials will be attempted after ${new Date(newExpiration)}.\\nFor more information, please visit: ` +\n STATIC_STABILITY_DOC_URL);\n const originalExpiration = credentials.originalExpiration ?? credentials.expiration;\n return {\n ...credentials,\n ...(originalExpiration ? { originalExpiration } : {}),\n expiration: newExpiration,\n };\n};\n", | ||
| "import { getExtendedInstanceMetadataCredentials } from \"./getExtendedInstanceMetadataCredentials\";\nexport const staticStabilityProvider = (provider, options = {}) => {\n const logger = options?.logger || console;\n let pastCredentials;\n return async () => {\n let credentials;\n try {\n credentials = await provider();\n if (credentials.expiration && credentials.expiration.getTime() < Date.now()) {\n credentials = getExtendedInstanceMetadataCredentials(credentials, logger);\n }\n }\n catch (e) {\n if (pastCredentials) {\n logger.warn(\"Credential renew failed: \", e);\n credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger);\n }\n else {\n throw e;\n }\n }\n pastCredentials = credentials;\n return credentials;\n };\n};\n" | ||
| ], | ||
| "mappings": ";mJAAA,oBCAO,SAAM,EAAoB,CAAC,IAAQ,QAAQ,CAAG,GACjD,OAAO,IAAQ,UACf,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,kBAAoB,UAC/B,OAAO,EAAI,QAAU,UACrB,OAAO,EAAI,aAAe,SACjB,EAAsB,CAAC,KAAW,CAC3C,YAAa,EAAM,YACnB,gBAAiB,EAAM,gBACvB,aAAc,EAAM,MACpB,WAAY,IAAI,KAAK,EAAM,UAAU,KACjC,EAAM,WAAa,CAAE,UAAW,EAAM,SAAU,CACxD,GCZO,IAAM,EAAkB,KAClB,EAAsB,EACtB,EAAyB,EAAG,aADN,EACwC,UAF5C,SAE8E,CAAE,aAAY,SAAQ,GCFnI,eCAA,oBDEO,SAAS,CAAW,CAAC,EAAS,CACjC,OAAO,IAAI,QAAQ,CAAC,EAAS,IAAW,CACpC,IAAM,EAAM,EAAU,QAAQ,CAC1B,OAAQ,SACL,EACH,SAAU,EAAQ,UAAU,QAAQ,aAAc,IAAI,CAC1D,CAAC,EACD,EAAI,GAAG,QAAS,CAAC,IAAQ,CACrB,EAAO,OAAO,OAAO,IAAI,gBAAc,gDAAgD,EAAG,CAAG,CAAC,EAC9F,EAAI,QAAQ,EACf,EACD,EAAI,GAAG,UAAW,IAAM,CACpB,EAAO,IAAI,gBAAc,6CAA6C,CAAC,EACvE,EAAI,QAAQ,EACf,EACD,EAAI,GAAG,WAAY,CAAC,IAAQ,CACxB,IAAQ,aAAa,KAAQ,EAC7B,GAAI,EAAa,KAAO,KAAO,EAC3B,EAAO,OAAO,OAAO,IAAI,gBAAc,wDA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B,MAAM,EAEV,OAAO,GACR,CAAU,GAEjB,MAAO,UAAY,CACf,IAAM,EAAW,MAAM,EAA4B,EACnD,GAAI,EAEA,OADA,GAAQ,MAAM,4BAA6B,oCAAoC,EACxE,EAAe,EAAY,IAAK,EAAU,SAAQ,CAAC,EAEzD,KACD,IAAI,EACJ,GAAI,CACA,GAAS,MAAM,GAAiB,IAAK,EAAU,SAAQ,CAAC,GAAG,SAAS,EAExE,MAAO,EAAO,CACV,GAAI,GAAO,aAAe,IACtB,MAAM,OAAO,OAAO,EAAO,CACvB,QAAS,2CACb,CAAC,EAEA,QAAI,EAAM,UAAY,gBAAkB,CAAC,IAAK,IAAK,GAAG,EAAE,SAAS,EAAM,UAAU,EAClF,EAAoB,GAGxB,OADA,GAAQ,MAAM,4BAA6B,6BAA6B,EACjE,EAAe,EAAY,IAAK,EAAU,SAAQ,CAAC,EAE9D,OAAO,EAAe,EAAY,IAC3B,EACH,QAAS,EACJ,GAA2B,CAChC,EACA,SACJ,CAAC,KAIP,GAAmB,MAAO,IAAY,EAAY,IACjD,EACH,KAAM,GACN,OAAQ,MACR,QAAS,CACL,uCAAwC,OAC5C,CACJ,CAAC,EACK,GAAa,MAAO,KAAa,MAAM,EAAY,IAAK,EAAS,KAAM,CAAU,CAAC,GAAG,SAAS,EAC9F,GAA4B,MAAO,EAAS,EAAS,IAAS,CAChE,IAAM,EAAsB,KAAK,OAAO,MAAM,EAAY,IACnD,EACH,KAAM,EAAY,CACtB,CAAC,GAAG,SAAS,CAAC,EACd,GAAI,CAAC,EAAkB,CAAmB,EACtC,MAAM,IAAI,2BAAyB,4DAA6D,CAC5F,OAAQ,EAAK,MACjB,CAAC,EAEL,OAAO,EAAoB,CAAmB", | ||
| "debugId": "AC9C3BD25D2368A664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/run.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(Commands.commands.run, (input) =>\n Effect.gen(function* () {\n const { runNonInteractive } = yield* Effect.promise(() => import(\"../../run/run\"))\n const separator = process.argv.indexOf(\"--\", 2)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n yield* Effect.promise(() =>\n runNonInteractive({\n server,\n message: [...input.message, ...(separator === -1 ? [] : process.argv.slice(separator + 1))],\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n format: input.format,\n file: [...input.file],\n title: Option.getOrUndefined(input.title),\n thinking: input.thinking,\n auto: input.auto || input.yolo,\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+9BAKA,SAAe,SAAQ,aAAQ,OAAS,cAAS,SAAK,MAAC,SACrD,OAAO,SAAI,cAAU,OAAG,MACtB,SAAQ,0BAAsB,WAAO,OAAO,aAAQ,SAAa,wCAAgB,OAC3E,OAAY,aAAQ,UAAK,aAAQ,UAAM,MAAC,EACxC,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACD,MAAO,EAAO,QAAQ,IACpB,EAAkB,CAChB,SACA,QAAS,CAAC,GAAG,EAAM,QAAS,GAAI,IAAc,GAAK,CAAC,EAAI,QAAQ,KAAK,MAAM,EAAY,CAAC,CAAE,EAC1F,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAM,OACd,KAAM,CAAC,GAAG,EAAM,IAAI,EACpB,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,SAAU,EAAM,SAChB,KAAM,EAAM,MAAQ,EAAM,IAC5B,CAAC,CACH,EACD,CACH", | ||
| "debugId": "B07C05B3FE06C7B764756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/api.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nconst methods = new Set([\"delete\", \"get\", \"head\", \"options\", \"patch\", \"post\", \"put\"])\n\ntype Operation = {\n operationId?: string\n}\n\ntype OpenApi = {\n paths?: Record<string, Record<string, Operation>>\n}\n\nexport default Runtime.handler(\n Commands.commands.api,\n Effect.fn(\"cli.api\")(function* (input) {\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n mismatch: \"ignore\",\n })\n const endpoint = server.endpoint\n const params = Option.getOrElse(input.param, () => ({}))\n const request = yield* resolveRequest(endpoint, input.request, params)\n const headers = new Headers(Service.headers(endpoint))\n for (const header of input.header) {\n const index = header.indexOf(\":\")\n if (index < 1) return yield* Effect.fail(new Error(`Invalid header, expected name:value: ${header}`))\n headers.set(header.slice(0, index).trim(), header.slice(index + 1).trim())\n }\n const body = Option.getOrUndefined(input.data)\n if (body !== undefined && !headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n\n const response = yield* Effect.tryPromise(() =>\n fetch(new URL(request.path, endpoint.url), {\n method: request.method,\n headers,\n body,\n }),\n )\n const output = yield* Effect.promise(() => response.text())\n if (output) process.stdout.write(output + (output.endsWith(EOL) ? \"\" : EOL))\n }),\n)\n\nexport function resolveOperation(spec: OpenApi, operationID: string, params: Record<string, string>) {\n for (const [path, operations] of Object.entries(spec.paths ?? {})) {\n for (const [method, operation] of Object.entries(operations)) {\n if (!methods.has(method) || operation.operationId !== operationID) continue\n return { method: method.toUpperCase(), path: interpolate(path, params) }\n }\n }\n throw new Error(`Operation not found: ${operationID}`)\n}\n\nexport function rawRequest(input: readonly string[]) {\n if (input.length !== 2 || !methods.has(input[0].toLowerCase()) || !input[1].startsWith(\"/\")) return\n return { method: input[0].toUpperCase(), path: input[1] }\n}\n\nfunction resolveRequest(endpoint: Endpoint, input: readonly string[], params: Record<string, string>) {\n const raw = rawRequest(input)\n if (raw) return Effect.succeed(raw)\n if (input.length !== 1) return Effect.fail(new Error(\"Expected an operation name or an HTTP method and path\"))\n return Effect.tryPromise(async () => {\n const response = await fetch(new URL(\"/openapi.json\", endpoint.url), { headers: Service.headers(endpoint) })\n if (!response.ok) throw new Error(`Failed to load OpenAPI document: HTTP ${response.status}`)\n return resolveOperation((await response.json()) as OpenApi, input[0], params)\n })\n}\n\nfunction interpolate(path: string, params: Record<string, string>) {\n const used = new Set<string>()\n const pathname = path.replaceAll(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = params[name]\n if (value === undefined) throw new Error(`Missing path parameter: ${name}`)\n used.add(name)\n return encodeURIComponent(value)\n })\n const query = new URLSearchParams(Object.entries(params).filter(([name]) => !used.has(name))).toString()\n return query ? `${pathname}?${query}` : pathname\n}\n" | ||
| ], | ||
| "mappings": ";+9BAAA,mBAAS,gBAOT,SAAM,OAAU,SAAI,SAAI,MAAC,cAAU,WAAO,YAAQ,eAAW,aAAS,YAAQ,UAAK,MAAC,OAUrE,SAAQ,aACrB,OAAS,cAAS,SAClB,OAAO,QAAG,cAAS,OAAE,cAAU,CAAC,EAAO,CAMrC,IAAM,GALS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,WAClB,SAAU,QACZ,CAAC,GACuB,SAClB,EAAS,EAAO,UAAU,EAAM,MAAO,KAAO,CAAC,EAAE,EACjD,EAA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EAAG,OAC7F,MAAO,CAAE,OAAQ,EAAM,GAAG,YAAY,EAAG,KAAM,EAAM,EAAG,EAG1D,SAAS,CAAc,CAAC,EAAoB,EAA0B,EAAgC,CACpG,IAAM,EAAM,EAAW,CAAK,EAC5B,GAAI,EAAK,OAAO,EAAO,QAAQ,CAAG,EAClC,GAAI,EAAM,SAAW,EAAG,OAAO,EAAO,KAAS,MAAM,uDAAuD,CAAC,EAC7G,OAAO,EAAO,WAAW,SAAY,CACnC,IAAM,EAAW,MAAM,MAAM,IAAI,IAAI,gBAAiB,EAAS,GAAG,EAAG,CAAE,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAC3G,GAAI,CAAC,EAAS,GAAI,MAAU,MAAM,yCAAyC,EAAS,QAAQ,EAC5F,OAAO,EAAkB,MAAM,EAAS,KAAK,EAAe,EAAM,GAAI,CAAM,EAC7E,EAGH,SAAS,CAAW,CAAC,EAAc,EAAgC,CACjE,IAAM,EAAO,IAAI,IACX,EAAW,EAAK,WAAW,eAAgB,CAAC,EAAG,IAAiB,CACpE,IAAM,EAAQ,EAAO,GACrB,GAAI,IAAU,OAAW,MAAU,MAAM,2BAA2B,GAAM,EAE1E,OADA,EAAK,IAAI,CAAI,EACN,mBAAmB,CAAK,EAChC,EACK,EAAQ,IAAI,gBAAgB,OAAO,QAAQ,CAAM,EAAE,OAAO,EAAE,KAAU,CAAC,EAAK,IAAI,CAAI,CAAC,CAAC,EAAE,SAAS,EACvG,OAAO,EAAQ,GAAG,KAAY,IAAU", | ||
| "debugId": "E0CE0AF1CF9C51D464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/route/auth-options.ts"], | ||
| "sourcesContent": [ | ||
| "import type { Config, Redacted } from \"effect\"\nimport { Auth } from \"./auth\"\n\nexport type ApiKeyMode = \"optional\" | \"required\"\n\nexport type AuthOverride = {\n readonly auth: Auth.Definition\n readonly apiKey?: never\n}\n\nexport type OptionalApiKeyAuth = {\n readonly apiKey?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>>\n readonly auth?: never\n}\n\nexport type RequiredApiKeyAuth = {\n readonly apiKey: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>>\n readonly auth?: never\n}\n\nexport type ProviderAuthOption<Mode extends ApiKeyMode> =\n | AuthOverride\n | (Mode extends \"optional\" ? OptionalApiKeyAuth : RequiredApiKeyAuth)\n\nexport type ModelOptions<Base, Mode extends ApiKeyMode> = Omit<Base, \"apiKey\" | \"auth\"> & ProviderAuthOption<Mode>\n\nexport type ModelArgs<Base, Mode extends ApiKeyMode> = Mode extends \"optional\"\n ? readonly [options?: ModelOptions<Base, Mode>]\n : readonly [options: ModelOptions<Base, Mode>]\n\nexport type ModelFactory<Base, Mode extends ApiKeyMode, Model> = (id: string, ...args: ModelArgs<Base, Mode>) => Model\n\n/**\n * Require at least one of the keys in `T`. Use for option shapes where any\n * subset of fields is acceptable but at least one must be present (e.g. Azure\n * accepts `resourceName` or `baseURL`).\n */\nexport type AtLeastOne<T> = {\n [K in keyof T]: Required<Pick<T, K>> & Partial<Omit<T, K>>\n}[keyof T]\n\n/**\n * Standard bearer-auth resolution for providers: honor an explicit `auth`\n * override, otherwise resolve `apiKey` (option > config var) and apply it as\n * a bearer token.\n */\nexport const bearer = (\n options: ProviderAuthOption<\"optional\">,\n envVar: string | ReadonlyArray<string>,\n): Auth.Definition => {\n if (\"auth\" in options && options.auth) return options.auth\n return (Array.isArray(envVar) ? envVar : [envVar])\n .reduce(\n (auth, name) => auth.orElse(Auth.config(name)),\n Auth.optional(\"apiKey\" in options ? options.apiKey : undefined, \"apiKey\"),\n )\n .bearer()\n}\n\nexport * as AuthOptions from \"./auth-options\"\n" | ||
| ], | ||
| "mappings": ";kJA8CO,SAAM,EAAS,CACpB,EACA,IACoB,CACpB,GAAI,SAAU,GAAW,EAAQ,KAAM,OAAO,EAAQ,KACtD,OAAQ,MAAM,QAAQ,CAAM,EAAI,EAAS,CAAC,CAAM,GAC7C,OACC,CAAC,EAAM,IAAS,EAAK,OAAO,EAAK,OAAO,CAAI,CAAC,EAC7C,EAAK,SAAS,WAAY,EAAU,EAAQ,OAAS,OAAW,QAAQ,CAC1E,EACC,OAAO", | ||
| "debugId": "1455D6473AF7893664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.33/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsJson1_1Protocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultCognitoIdentityHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"cognito-identity\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetCredentialsForIdentity\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n case \"GetId\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"cognito-identity\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.32\";\nvar packageInfo = {\n\tversion: version};\n\nconst m = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = \"stringEquals\", h = { [m]: \"Endpoint\" }, i = { [m]: d }, j = { [m]: \"Region\" }, k = {}, l = [j];\nconst _data = {\n conditions: [\n [c, [h]],\n [c, l],\n [\"aws.partition\", l, d],\n [e, [{ [m]: \"UseFIPS\" }, b]],\n [e, [{ fn: f, argv: [i, \"supportsFIPS\"] }, b]],\n [e, [{ [m]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [i, \"supportsDualStack\"] }, b]],\n [g, [{ fn: f, argv: [i, \"name\"] }, \"aws\"]],\n [g, [j, \"us-east-1\"]],\n [g, [j, \"us-east-2\"]],\n [g, [j, \"us-west-1\"]],\n [g, [j, \"us-west-2\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [h, k],\n [\"https://cognito-identity-fips.us-east-1.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-east-2.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-west-1.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-west-2.amazonaws.com\", k],\n [\"https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", k],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}\", k],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://cognito-identity.{Region}.amazonaws.com\", k],\n [\"https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}\", k],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}\", k],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 17, 3,\n 1, 4, r + 16,\n 2, 5, r + 16,\n 3, 9, 6,\n 5, 7, r + 15,\n 6, 8, r + 14,\n 7, r + 12, r + 13,\n 4, 11, 10,\n 5, r + 9, r + 11,\n 5, 12, r + 10,\n 6, 13, r + 9,\n 8, r + 4, 14,\n 9, r + 5, 15,\n 10, r + 6, 16,\n 11, r + 7, r + 8,\n 3, r + 1, 18,\n 5, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass CognitoIdentityServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, CognitoIdentityServiceException.prototype);\n }\n}\n\nclass ExternalServiceException extends CognitoIdentityServiceException {\n name = \"ExternalServiceException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ExternalServiceException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExternalServiceException.prototype);\n }\n}\nclass InternalErrorException extends CognitoIdentityServiceException {\n name = \"InternalErrorException\";\n $fault = \"server\";\n constructor(opts) {\n super({\n name: \"InternalErrorException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalErrorException.prototype);\n }\n}\nclass InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException {\n name = \"InvalidIdentityPoolConfigurationException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidIdentityPoolConfigurationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidIdentityPoolConfigurationException.prototype);\n }\n}\nclass InvalidParameterException extends CognitoIdentityServiceException {\n name = \"InvalidParameterException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidParameterException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidParameterException.prototype);\n }\n}\nclass NotAuthorizedException extends CognitoIdentityServiceException {\n name = \"NotAuthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"NotAuthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, NotAuthorizedException.prototype);\n }\n}\nclass ResourceConflictException extends CognitoIdentityServiceException {\n name = \"ResourceConflictException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceConflictException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceConflictException.prototype);\n }\n}\nclass ResourceNotFoundException extends CognitoIdentityServiceException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nclass TooManyRequestsException extends CognitoIdentityServiceException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nclass LimitExceededException extends CognitoIdentityServiceException {\n name = \"LimitExceededException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"LimitExceededException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, LimitExceededException.prototype);\n }\n}\n\nconst _AI = \"AccountId\";\nconst _AKI = \"AccessKeyId\";\nconst _C = \"Credentials\";\nconst _CRA = \"CustomRoleArn\";\nconst _E = \"Expiration\";\nconst _ESE = \"ExternalServiceException\";\nconst _GCFI = \"GetCredentialsForIdentity\";\nconst _GCFII = \"GetCredentialsForIdentityInput\";\nconst _GCFIR = \"GetCredentialsForIdentityResponse\";\nconst _GI = \"GetId\";\nconst _GII = \"GetIdInput\";\nconst _GIR = \"GetIdResponse\";\nconst _IEE = \"InternalErrorException\";\nconst _II = \"IdentityId\";\nconst _IIPCE = \"InvalidIdentityPoolConfigurationException\";\nconst _IPE = \"InvalidParameterException\";\nconst _IPI = \"IdentityPoolId\";\nconst _IPT = \"IdentityProviderToken\";\nconst _L = \"Logins\";\nconst _LEE = \"LimitExceededException\";\nconst _LM = \"LoginsMap\";\nconst _NAE = \"NotAuthorizedException\";\nconst _RCE = \"ResourceConflictException\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SK = \"SecretKey\";\nconst _SKS = \"SecretKeyString\";\nconst _ST = \"SessionToken\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _hE = \"httpError\";\nconst _m = \"message\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentity\";\nconst _se = \"server\";\nconst n0 = \"com.amazonaws.cognitoidentity\";\nconst _s_registry = TypeRegistry.for(_s);\nvar CognitoIdentityServiceException$ = [-3, _s, \"CognitoIdentityServiceException\", 0, [], []];\n_s_registry.registerError(CognitoIdentityServiceException$, CognitoIdentityServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar ExternalServiceException$ = [-3, n0, _ESE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(ExternalServiceException$, ExternalServiceException);\nvar InternalErrorException$ = [-3, n0, _IEE,\n { [_e]: _se },\n [_m],\n [0]\n];\nn0_registry.registerError(InternalErrorException$, InternalErrorException);\nvar InvalidIdentityPoolConfigurationException$ = [-3, n0, _IIPCE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidIdentityPoolConfigurationException$, InvalidIdentityPoolConfigurationException);\nvar InvalidParameterException$ = [-3, n0, _IPE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidParameterException$, InvalidParameterException);\nvar LimitExceededException$ = [-3, n0, _LEE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(LimitExceededException$, LimitExceededException);\nvar NotAuthorizedException$ = [-3, n0, _NAE,\n { [_e]: _c, [_hE]: 403 },\n [_m],\n [0]\n];\nn0_registry.registerError(NotAuthorizedException$, NotAuthorizedException);\nvar ResourceConflictException$ = [-3, n0, _RCE,\n { [_e]: _c, [_hE]: 409 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceConflictException$, ResourceConflictException);\nvar ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);\nvar TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nn0_registry.registerError(TooManyRequestsException$, TooManyRequestsException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar IdentityProviderToken = [0, n0, _IPT, 8, 0];\nvar SecretKeyString = [0, n0, _SKS, 8, 0];\nvar Credentials$ = [3, n0, _C,\n 0,\n [_AKI, _SK, _ST, _E],\n [0, [() => SecretKeyString, 0], 0, 4]\n];\nvar GetCredentialsForIdentityInput$ = [3, n0, _GCFII,\n 0,\n [_II, _L, _CRA],\n [0, [() => LoginsMap, 0], 0], 1\n];\nvar GetCredentialsForIdentityResponse$ = [3, n0, _GCFIR,\n 0,\n [_II, _C],\n [0, [() => Credentials$, 0]]\n];\nvar GetIdInput$ = [3, n0, _GII,\n 0,\n [_IPI, _AI, _L],\n [0, 0, [() => LoginsMap, 0]], 1\n];\nvar GetIdResponse$ = [3, n0, _GIR,\n 0,\n [_II],\n [0]\n];\nvar LoginsMap = [2, n0, _LM,\n 0, [0,\n 0],\n [() => IdentityProviderToken,\n 0]\n];\nvar GetCredentialsForIdentity$ = [9, n0, _GCFI,\n 0, () => GetCredentialsForIdentityInput$, () => GetCredentialsForIdentityResponse$\n];\nvar GetId$ = [9, n0, _GI,\n 0, () => GetIdInput$, () => GetIdResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2014-06-30\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultCognitoIdentityHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsJson1_1Protocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.cognitoidentity\",\n errorTypeRegistries,\n xmlNamespace: \"http://cognito-identity.amazonaws.com/doc/2014-06-30/\",\n version: \"2014-06-30\",\n serviceTarget: \"AWSCognitoIdentityService\",\n },\n serviceId: config?.serviceId ?? \"Cognito Identity\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass CognitoIdentityClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultCognitoIdentityHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"AWSCognitoIdentityService\", \"CognitoIdentityClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass GetCredentialsForIdentityCommand extends command(_ep0, _mw0, \"GetCredentialsForIdentity\", GetCredentialsForIdentity$) {\n}\n\nclass GetIdCommand extends command(_ep0, _mw0, \"GetId\", GetId$) {\n}\n\nconst commands = {\n GetCredentialsForIdentityCommand,\n GetIdCommand,\n};\nclass CognitoIdentity extends CognitoIdentityClient {\n}\ncreateAggregatedClient(commands, CognitoIdentity);\n\nexports.CognitoIdentity = CognitoIdentity;\nexports.CognitoIdentityClient = CognitoIdentityClient;\nexports.CognitoIdentityServiceException = CognitoIdentityServiceException;\nexports.CognitoIdentityServiceException$ = CognitoIdentityServiceException$;\nexports.Credentials$ = Credentials$;\nexports.ExternalServiceException = ExternalServiceException;\nexports.ExternalServiceException$ = ExternalServiceException$;\nexports.GetCredentialsForIdentity$ = GetCredentialsForIdentity$;\nexports.GetCredentialsForIdentityCommand = GetCredentialsForIdentityCommand;\nexports.GetCredentialsForIdentityInput$ = GetCredentialsForIdentityInput$;\nexports.GetCredentialsForIdentityResponse$ = GetCredentialsForIdentityResponse$;\nexports.GetId$ = GetId$;\nexports.GetIdCommand = GetIdCommand;\nexports.GetIdInput$ = GetIdInput$;\nexports.GetIdResponse$ = GetIdResponse$;\nexports.InternalErrorException = InternalErrorException;\nexports.InternalErrorException$ = InternalErrorException$;\nexports.InvalidIdentityPoolConfigurationException = InvalidIdentityPoolConfigurationException;\nexports.InvalidIdentityPoolConfigurationException$ = InvalidIdentityPoolConfigurationException$;\nexports.InvalidParameterException = InvalidParameterException;\nexports.InvalidParameterException$ = InvalidParameterException$;\nexports.LimitExceededException = LimitExceededException;\nexports.LimitExceededException$ = LimitExceededException$;\nexports.NotAuthorizedException = NotAuthorizedException;\nexports.NotAuthorizedException$ = NotAuthorizedException$;\nexports.ResourceConflictException = ResourceConflictException;\nexports.ResourceConflictException$ = ResourceConflictException$;\nexports.ResourceNotFoundException = ResourceNotFoundException;\nexports.ResourceNotFoundException$ = ResourceNotFoundException$;\nexports.TooManyRequestsException = TooManyRequestsException;\nexports.TooManyRequestsException$ = TooManyRequestsException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";8VAAA,SAAQ,6BAAsB,qCAAiC,QAAmC,uCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cA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AAgB,IAAI,GAAqB,KAAK,MAAM,CAAC,EAC1D,KAAK,gBAAgB,IAAI,GAAmB,KAAK,MAAM,CAAC,EACxD,KAAK,gBAAgB,IAAI,GAAe,KAAK,MAAM,CAAC,EACpD,KAAK,gBAAgB,IAAI,GAAuB,KAAK,MAAM,CAAC,EAC5D,KAAK,gBAAgB,IAAI,GAAoB,KAAK,MAAM,CAAC,EACzD,KAAK,gBAAgB,IAAI,GAAgB,KAAK,MAAM,CAAC,EACrD,KAAK,gBAAgB,IAAI,GAA4B,KAAK,MAAM,CAAC,EACjE,KAAK,gBAAgB,IAAI,GAAuC,KAAK,OAAQ,CACzE,iCAAkC,GAClC,+BAAgC,MAAO,KAAW,IAAI,GAA8B,CAChF,iBAAkB,GAAO,WAC7B,CAAC,CACL,CAAC,CAAC,EACF,KAAK,gBAAgB,IAAI,GAAqB,KAAK,MAAM,CAAC,EAE9D,OAAO,EAAG,CACN,MAAM,QAAQ,EAEtB,CAEA,IAAM,EAAU,GAAY,GAAc,4BAA6B,wBAAyB,EAAiB,EAC3G,EAAO,CAAC,EACR,GAAO,CAAC,EAAS,EAAI,EAAQ,IAAM,CAAC,EAE1C,MAAM,UAAyC,EAAQ,EAAM,GAAM,4BAA6B,EAA0B,CAAE,CAC5H,CAEA,MAAM,UAAqB,EAAQ,EAAM,GAAM,QAAS,EAAM,CAAE,CAChE,CAEA,IAAM,GAAW,CACb,mCACA,cACJ,EACA,MAAM,WAAwB,CAAsB,CACpD,CACA,GAAuB,GAAU,EAAe,EAGhD,IAAQ,GAAwB,EAOhC,IAAQ,GAAmC,EAI3C,IAAQ,GAAe", | ||
| "debugId": "A7B7D250584743F964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/ui/timeline.tsx", "src/commands/handlers/console/login.ts"], | ||
| "sourcesContent": [ | ||
| "import { createComponent as _$createComponent } from \"@opentui/solid\";\nimport { effect as _$effect } from \"@opentui/solid\";\nimport { createTextNode as _$createTextNode } from \"@opentui/solid\";\nimport { insertNode as _$insertNode } from \"@opentui/solid\";\nimport { insert as _$insert } from \"@opentui/solid\";\nimport { setProp as _$setProp } from \"@opentui/solid\";\nimport { createElement as _$createElement } from \"@opentui/solid\";\n/** @jsxImportSource @opentui/solid */\nimport { createCliRenderer, RGBA } from \"@opentui/core\";\nimport { createScrollbackWriter, render, useKeyboard } from \"@opentui/solid\";\nimport { registerOpencodeSpinner } from \"@opencode-ai/tui/component/register-spinner\";\nimport { Show, createSignal } from \"solid-js\";\nregisterOpencodeSpinner();\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst IDLE_TIMEOUT = 1_000;\nconst COLORS = {\n accent: RGBA.fromIndex(6),\n error: RGBA.fromIndex(1),\n foreground: RGBA.defaultForeground(),\n muted: RGBA.fromIndex(8),\n success: RGBA.fromIndex(2)\n};\nconst ROWS = {\n intro: {\n marker: \"┌\",\n color: COLORS.muted,\n connector: true\n },\n item: {\n marker: \"●\",\n color: COLORS.accent,\n connector: true\n },\n success: {\n marker: \"◇\",\n color: COLORS.success,\n connector: true\n },\n failure: {\n marker: \"■\",\n color: COLORS.error,\n connector: false\n },\n outro: {\n marker: \"└\",\n color: COLORS.muted,\n connector: false\n }\n};\nfunction row(kind, value) {\n const style = ROWS[kind];\n return createScrollbackWriter(() => (() => {\n var _el$ = _$createElement(\"box\"),\n _el$2 = _$createElement(\"box\"),\n _el$3 = _$createElement(\"text\"),\n _el$4 = _$createElement(\"text\");\n _$insertNode(_el$, _el$2);\n _$setProp(_el$, \"width\", \"100%\");\n _$setProp(_el$, \"minHeight\", 1);\n _$setProp(_el$, \"flexDirection\", \"column\");\n _$insertNode(_el$2, _el$3);\n _$insertNode(_el$2, _el$4);\n _$setProp(_el$2, \"width\", \"100%\");\n _$setProp(_el$2, \"minHeight\", 1);\n _$setProp(_el$2, \"flexDirection\", \"row\");\n _$setProp(_el$2, \"gap\", 1);\n _$setProp(_el$3, \"flexShrink\", 0);\n _$insert(_el$3, () => style.marker);\n _$setProp(_el$4, \"wrapMode\", \"word\");\n _$insert(_el$4, value);\n _$insert(_el$, _$createComponent(Show, {\n get when() {\n return style.connector;\n },\n get children() {\n var _el$5 = _$createElement(\"text\");\n _$insertNode(_el$5, _$createTextNode(`│`));\n _$effect(_$p => _$setProp(_el$5, \"fg\", COLORS.muted, _$p));\n return _el$5;\n }\n }), null);\n _$effect(_p$ => {\n var _v$ = style.color,\n _v$2 = COLORS.foreground;\n _v$ !== _p$.e && (_p$.e = _$setProp(_el$3, \"fg\", _v$, _p$.e));\n _v$2 !== _p$.t && (_p$.t = _$setProp(_el$4, \"fg\", _v$2, _p$.t));\n return _p$;\n }, {\n e: undefined,\n t: undefined\n });\n return _el$;\n })(), {\n startOnNewLine: true,\n trailingNewline: !style.connector\n });\n}\nfunction TimelineFooter(props) {\n useKeyboard(event => {\n if (event.name !== \"escape\" && !(event.ctrl && event.name === \"c\")) return;\n event.preventDefault();\n props.cancel();\n });\n return (() => {\n var _el$7 = _$createElement(\"box\");\n _$setProp(_el$7, \"width\", \"100%\");\n _$setProp(_el$7, \"height\", 1);\n _$setProp(_el$7, \"flexDirection\", \"row\");\n _$setProp(_el$7, \"gap\", 1);\n _$insert(_el$7, _$createComponent(Show, {\n get when() {\n return props.pending();\n },\n children: text => [(() => {\n var _el$8 = _$createElement(\"spinner\");\n _$setProp(_el$8, \"frames\", SPINNER_FRAMES);\n _$setProp(_el$8, \"interval\", 80);\n _$effect(_$p => _$setProp(_el$8, \"color\", COLORS.accent, _$p));\n return _el$8;\n })(), (() => {\n var _el$9 = _$createElement(\"text\");\n _$setProp(_el$9, \"wrapMode\", \"none\");\n _$setProp(_el$9, \"truncate\", true);\n _$insert(_el$9, text);\n _$effect(_$p => _$setProp(_el$9, \"fg\", COLORS.foreground, _$p));\n return _el$9;\n })()]\n }));\n return _el$7;\n })();\n}\nfunction bounded(task) {\n return new Promise(resolve => {\n const timer = setTimeout(resolve, IDLE_TIMEOUT);\n timer.unref();\n const finish = () => {\n clearTimeout(timer);\n resolve();\n };\n void task.then(finish, finish);\n });\n}\nasync function shutdown(renderer) {\n await bounded(renderer.idle());\n try {\n renderer.externalOutputMode = \"passthrough\";\n } finally {\n try {\n renderer.screenMode = \"main-screen\";\n } finally {\n if (!renderer.isDestroyed) renderer.destroy();\n }\n }\n}\nexport async function createTimelineHost() {\n const stdout = process.stdout;\n const controller = new AbortController();\n const signals = [\"SIGINT\", \"SIGHUP\", \"SIGQUIT\"];\n const cancel = () => {\n if (!controller.signal.aborted) controller.abort();\n };\n signals.forEach(signal => process.on(signal, cancel));\n if (!stdout.isTTY || !process.stdin.isTTY) {\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = async (kind, text) => {\n if (closed) throw new Error(\"timeline closed\");\n if (writing) throw new Error(\"timeline write already in progress\");\n writing = true;\n try {\n const style = kind === \"pending\" ? undefined : ROWS[kind];\n const marker = kind === \"pending\" ? \".\" : ROWS[kind].marker;\n const connector = style?.connector ? \"│\\n\" : \"\";\n active = new Promise((resolve, reject) => {\n stdout.write(`${marker} ${text}\\n${connector}`, error => error ? reject(error) : resolve());\n });\n await active;\n } finally {\n writing = false;\n active = undefined;\n }\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n signals.forEach(signal => process.off(signal, cancel));\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n }\n let renderer;\n try {\n // Start on a fresh row so delayed SSH cursor reports cannot make\n // split-footer overwrite the shell command.\n process.stdout.write(\"\\n\");\n renderer = await createCliRenderer({\n stdin: process.stdin,\n useMouse: false,\n autoFocus: false,\n openConsoleOnError: false,\n exitOnCtrlC: false,\n exitSignals: [],\n screenMode: \"split-footer\",\n footerHeight: 1,\n externalOutputMode: \"capture-stdout\",\n consoleMode: \"disabled\",\n clearOnShutdown: false\n });\n const activeRenderer = renderer;\n const [pending, setPending] = createSignal();\n const renderTask = render(() => _$createComponent(TimelineFooter, {\n pending: pending,\n cancel: cancel\n }), activeRenderer);\n void renderTask.catch(cancel);\n await bounded(activeRenderer.idle());\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = (kind, text) => {\n if (closed) return Promise.reject(new Error(\"timeline closed\"));\n if (writing) return Promise.reject(new Error(\"timeline write already in progress\"));\n writing = true;\n active = (async () => {\n if (kind === \"pending\") {\n setPending(text);\n activeRenderer.requestRender();\n } else {\n if (kind === \"success\" || kind === \"failure\" || kind === \"outro\") setPending(undefined);\n activeRenderer.writeToScrollback(row(kind, text));\n activeRenderer.requestRender();\n }\n await bounded(activeRenderer.idle());\n })().finally(() => {\n writing = false;\n active = undefined;\n });\n return active;\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n try {\n await shutdown(activeRenderer);\n await bounded(renderTask);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n } catch (error) {\n try {\n if (renderer) await shutdown(renderer);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n throw error;\n }\n}", | ||
| "import { Cause, Effect, Exit, Option } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { AppProcess } from \"@opencode-ai/util/process\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { createTimelineHost, type TimelineHost } from \"../../../ui/timeline\"\n\nconst integrationID = \"opencode\"\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.console.commands.login,\n Effect.fn(\"cli.console.login\")(function* (input) {\n const timeline = yield* Effect.acquireRelease(\n Effect.promise(() => createTimelineHost()),\n (value) => request(() => value.close()).pipe(Effect.ignore),\n )\n const exit = yield* login(timeline, Option.getOrUndefined(input.url)).pipe(\n Effect.raceFirst(AppProcess.waitForAbort(timeline.signal)),\n Effect.exit,\n )\n if (Exit.isSuccess(exit)) return\n\n const cancelled = timeline.signal.aborted\n yield* request(() => timeline.failure(cancelled ? \"Authorization cancelled\" : errorMessage(exit.cause))).pipe(\n Effect.ignore,\n )\n process.exitCode = cancelled ? 130 : 1\n }),\n)\n\nconst login = Effect.fn(\"cli.console.login.run\")(function* (timeline: TimelineHost, server?: string) {\n yield* request(() => timeline.intro(\"Log in\"))\n yield* request(() => timeline.pending(\"Connecting to OpenCode...\"))\n\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const found = yield* request((signal) => client.integration.get({ integrationID, location }, { signal }))\n const integration = yield* required(found.data, \"OpenCode Console integration is unavailable\")\n const method = yield* required(\n integration.methods.find((candidate) => candidate.type === \"oauth\"),\n \"OpenCode Console login is unavailable\",\n )\n\n yield* request(() => timeline.pending(\"Starting authorization...\"))\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n {\n integrationID,\n methodID: method.id,\n inputs: server ? { server } : {},\n location,\n },\n { signal },\n ),\n )\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n if (attempt.mode !== \"auto\") yield* Effect.fail(new Error(\"OpenCode Console requires a device login\"))\n\n yield* request(() => timeline.item(`Go to: ${attempt.url}`))\n yield* request(() => timeline.item(attempt.instructions))\n yield* request(async () => {\n const { default: open } = await import(\"open\")\n await open(attempt.url)\n }).pipe(Effect.ignore)\n yield* request(() => timeline.pending(\"Waiting for authorization...\"))\n\n const status = yield* waitForConsoleLogin(client, integrationID, attempt.attemptID)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") yield* Effect.fail(new Error(\"Device code expired\"))\n\n yield* request(() => timeline.success(\"Connected to OpenCode Console\"))\n yield* request(() => timeline.outro(\"Done\"))\n})\n\nconst waitForConsoleLogin = Effect.fn(\"cli.console.login.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.oauth.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n yield* Effect.sleep(500)\n }\n})\n\nfunction request<A>(task: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: task,\n catch: (cause) => cause,\n })\n}\n\nfunction required<A>(value: A | null | undefined, message: string) {\n return value === null || value === undefined ? Effect.fail(new Error(message)) : Effect.succeed(value)\n}\n\nfunction errorMessage(cause: Cause.Cause<unknown>) {\n const error = Cause.squash(cause)\n if (error instanceof Error) return error.message\n if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\") {\n return error.message\n }\n return String(error)\n}\n" | ||
| ], | ||
| "mappings": ";0lCAYA,OAAwB,OACxB,SAAM,OAAiB,MAAC,cAAI,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,aAAG,OACjE,QAAe,UACf,OAAS,MACb,YAAQ,OAAK,eAAU,MAAC,EACxB,MAAO,EAAK,UAAU,CAAC,EACvB,WAAY,EAAK,kBAAkB,EACnC,MAAO,EAAK,UAAU,CAAC,EACvB,QAAS,EAAK,UAAU,CAAC,CAC3B,EACM,EAAO,CACX,MAAO,CACL,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,EACA,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ources": ["src/commands/handlers/mcp/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode, type McpServer } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.list,\n Effect.fn(\"cli.mcp.list\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.mcp.list({ location: { directory: process.cwd() } }))\n const servers = response.data.toSorted((a, b) => a.name.localeCompare(b.name))\n if (servers.length === 0) {\n process.stdout.write(\"No MCP servers configured\" + EOL)\n return\n }\n const width = Math.max(...servers.map((server) => server.name.length))\n const lines = servers.map(\n (server) => `${icon(server.status)} ${server.name.padEnd(width)} ${describe(server.status)}`,\n )\n process.stdout.write(lines.join(EOL) + EOL)\n }),\n)\n\nfunction icon(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"connected\":\n return \"✓\"\n case \"needs_auth\":\n return \"⚠\"\n case \"failed\":\n case \"needs_client_registration\":\n return \"✗\"\n default:\n return \"○\"\n }\n}\n\nfunction describe(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"needs_auth\":\n return \"needs authentication\"\n case \"needs_client_registration\":\n return `needs client registration: ${status.error}`\n case \"failed\":\n return `failed: ${status.error}`\n default:\n return status.status\n }\n}\n" | ||
| ], | ||
| "mappings": ";83BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,UAC/B,OAAO,QAAG,mBAAc,OAAE,cAAU,OAAG,MACrC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,IAAI,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAC/E,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC,EAC7E,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,4BAA8B,CAAG,EACtD,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAQ,IAAI,CAAC,IAAW,EAAO,KAAK,MAAM,CAAC,EAC/D,EAAQ,EAAQ,IACpB,CAAC,IAAW,GAAG,EAAK,EAAO,MAAM,KAAK,EAAO,KAAK,OAAO,CAAK,MAAM,EAAS,EAAO,MAAM,GAC5F,EACA,QAAQ,OAAO,MAAM,EAAM,KAAK,CAAG,EAAI,CAAG,EAC3C,CACH,EAEA,SAAS,CAAI,CAAC,EAA6B,CACzC,OAAQ,EAAO,YACR,YACH,MAAO,aACJ,aACH,MAAO,aACJ,aACA,4BACH,MAAO,iBAEP,MAAO,UAIb,SAAS,CAAQ,CAAC,EAA6B,CAC7C,OAAQ,EAAO,YACR,aACH,MAAO,2BACJ,4BACH,MAAO,8BAA8B,EAAO,YACzC,SACH,MAAO,WAAW,EAAO,gBAEzB,OAAO,EAAO", | ||
| "debugId": "31632EC4E9C311F864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/version.ts"], | ||
| "sourcesContent": [ | ||
| "declare const OPENCODE_VERSION: string\ndeclare const OPENCODE_CHANNEL: string\n\nconst version = typeof OPENCODE_VERSION === \"string\" ? OPENCODE_VERSION : \"local\"\nconst channel = typeof OPENCODE_CHANNEL === \"string\" ? OPENCODE_CHANNEL : \"local\"\n\nexport { version as OPENCODE_VERSION, channel as OPENCODE_CHANNEL }\nexport const OPENCODE_LOCAL = channel === \"local\"\n" | ||
| ], | ||
| "mappings": ";AAGA,IAAM,EAAiD,mBACjD,EAAiD,OAGhD,IAAM,EAAiB", | ||
| "debugId": "BA1623A5D09EA80B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/ai-gateway-provider@3.1.2+a6631614dda8d488/node_modules/ai-gateway-provider/dist/providers/unified.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/providers/unified.ts\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nvar createUnified = (arg) => {\n return createOpenAICompatible({\n baseURL: \"https://gateway.ai.cloudflare.com/v1/compat\",\n // intercepted and replaced with actual base URL later\n name: \"Unified\",\n ...arg || {}\n });\n};\nvar unified = createUnified();\nexport {\n createUnified,\n unified\n};\n//# sourceMappingURL=unified.mjs.map" | ||
| ], | ||
| "mappings": ";kSAEA,SAAI,OAAgB,MAAC,SAAQ,MAC3B,YAAO,OAAuB,CAC5B,QAAS,8CAET,KAAM,aACH,GAAO,CAAC,CACb,CAAC,GAEC,EAAU,EAAc", | ||
| "debugId": "A1979C1743C8067964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.33/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"awsssoportal\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSSOHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetRoleCredentials\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"awsssoportal\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.32\";\nvar packageInfo = {\n\tversion: version};\n\nconst k = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = { [k]: \"Endpoint\" }, h = { [k]: d }, i = {}, j = [{ [k]: \"Region\" }];\nconst _data = {\n conditions: [\n [c, [g]],\n [c, j],\n [\"aws.partition\", j, d],\n [e, [{ [k]: \"UseFIPS\" }, b]],\n [e, [{ [k]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [h, \"supportsDualStack\"] }, b]],\n [e, [{ fn: f, argv: [h, \"supportsFIPS\"] }, b]],\n [\"stringEquals\", [{ fn: f, argv: [h, \"name\"] }, \"aws-us-gov\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [g, i],\n [\"https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://portal.sso.{Region}.amazonaws.com\", i],\n [\"https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://portal.sso.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 13, 3,\n 1, 4, r + 12,\n 2, 5, r + 12,\n 3, 8, 6,\n 4, 7, r + 11,\n 5, r + 9, r + 10,\n 4, 11, 9,\n 6, 10, r + 8,\n 7, r + 6, r + 7,\n 5, 12, r + 5,\n 6, r + 4, r + 5,\n 3, r + 1, 14,\n 4, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SSOServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOServiceException.prototype);\n }\n}\n\nclass InvalidRequestException extends SSOServiceException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n }\n}\nclass ResourceNotFoundException extends SSOServiceException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nclass TooManyRequestsException extends SSOServiceException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nclass UnauthorizedException extends SSOServiceException {\n name = \"UnauthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"UnauthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedException.prototype);\n }\n}\n\nconst _ATT = \"AccessTokenType\";\nconst _GRC = \"GetRoleCredentials\";\nconst _GRCR = \"GetRoleCredentialsRequest\";\nconst _GRCRe = \"GetRoleCredentialsResponse\";\nconst _IRE = \"InvalidRequestException\";\nconst _RC = \"RoleCredentials\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SAKT = \"SecretAccessKeyType\";\nconst _STT = \"SessionTokenType\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _UE = \"UnauthorizedException\";\nconst _aI = \"accountId\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _ai = \"account_id\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _ex = \"expiration\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _hH = \"httpHeader\";\nconst _hQ = \"httpQuery\";\nconst _m = \"message\";\nconst _rC = \"roleCredentials\";\nconst _rN = \"roleName\";\nconst _rn = \"role_name\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.sso\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _xasbt = \"x-amz-sso_bearer_token\";\nconst n0 = \"com.amazonaws.sso\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SSOServiceException$ = [-3, _s, \"SSOServiceException\", 0, [], []];\n_s_registry.registerError(SSOServiceException$, SSOServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidRequestException$, InvalidRequestException);\nvar ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);\nvar TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nn0_registry.registerError(TooManyRequestsException$, TooManyRequestsException);\nvar UnauthorizedException$ = [-3, n0, _UE,\n { [_e]: _c, [_hE]: 401 },\n [_m],\n [0]\n];\nn0_registry.registerError(UnauthorizedException$, UnauthorizedException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar AccessTokenType = [0, n0, _ATT, 8, 0];\nvar SecretAccessKeyType = [0, n0, _SAKT, 8, 0];\nvar SessionTokenType = [0, n0, _STT, 8, 0];\nvar GetRoleCredentialsRequest$ = [3, n0, _GRCR,\n 0,\n [_rN, _aI, _aT],\n [[0, { [_hQ]: _rn }], [0, { [_hQ]: _ai }], [() => AccessTokenType, { [_hH]: _xasbt }]], 3\n];\nvar GetRoleCredentialsResponse$ = [3, n0, _GRCRe,\n 0,\n [_rC],\n [[() => RoleCredentials$, 0]]\n];\nvar RoleCredentials$ = [3, n0, _RC,\n 0,\n [_aKI, _sAK, _sT, _ex],\n [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1]\n];\nvar GetRoleCredentials$ = [9, n0, _GRC,\n { [_h]: [\"GET\", \"/federation/credentials\", 200] }, () => GetRoleCredentialsRequest$, () => GetRoleCredentialsResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.sso\",\n errorTypeRegistries,\n version: \"2019-06-10\",\n serviceTarget: \"SWBPortalService\",\n },\n serviceId: config?.serviceId ?? \"SSO\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SSOClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"SWBPortalService\", \"SSOClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass GetRoleCredentialsCommand extends command(_ep0, _mw0, \"GetRoleCredentials\", GetRoleCredentials$) {\n}\n\nconst commands = {\n GetRoleCredentialsCommand,\n};\nclass SSO extends SSOClient {\n}\ncreateAggregatedClient(commands, SSO);\n\nexports.GetRoleCredentials$ = GetRoleCredentials$;\nexports.GetRoleCredentialsCommand = GetRoleCredentialsCommand;\nexports.GetRoleCredentialsRequest$ = GetRoleCredentialsRequest$;\nexports.GetRoleCredentialsResponse$ = GetRoleCredentialsResponse$;\nexports.InvalidRequestException = InvalidRequestException;\nexports.InvalidRequestException$ = InvalidRequestException$;\nexports.ResourceNotFoundException = ResourceNotFoundException;\nexports.ResourceNotFoundException$ = ResourceNotFoundException$;\nexports.RoleCredentials$ = RoleCredentials$;\nexports.SSO = SSO;\nexports.SSOClient = SSOClient;\nexports.SSOServiceException = SSOServiceException;\nexports.SSOServiceException$ = SSOServiceException$;\nexports.TooManyRequestsException = TooManyRequestsException;\nexports.TooManyRequestsException$ = TooManyRequestsException$;\nexports.UnauthorizedException = UnauthorizedException;\nexports.UnauthorizedException$ = UnauthorizedException$;\nexports.errorTypeReg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sB,EAAmB,CAAE,CACvG,CAEA,IAAM,GAAW,CACb,2BACJ,EACA,MAAM,UAAY,CAAU,CAC5B,CACA,GAAuB,GAAU,CAAG,EAGpC,IAAQ,EAA4B,EASpC,IAAQ,EAAY", | ||
| "debugId": "8B496C2D9D764D6164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "C63480F88842C89164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token.js"], | ||
| "sourcesContent": [ | ||
| "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_exports = {};\n__export(token_exports, {\n refreshToken: () => refreshToken\n});\nmodule.exports = __toCommonJS(token_exports);\nvar import_token_error = require(\"./token-error\");\nvar import_token_util = require(\"./token-util\");\nasync function refreshToken(options) {\n let projectId = options?.project;\n let teamId = options?.team;\n if (!projectId && !teamId) {\n const projectInfo = (0, import_token_util.findProjectInfo)();\n projectId = projectInfo.projectId;\n teamId = projectInfo.teamId;\n } else if (!projectId || !teamId) {\n const projectInfo = (0, import_token_util.findProjectInfo)();\n projectId = projectId ?? projectInfo.projectId;\n teamId = teamId ?? projectInfo.teamId;\n }\n if (!projectId) {\n throw new import_token_error.VercelOidcTokenError(\n \"Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`\"\n );\n }\n let maybeToken = (0, import_token_util.loadToken)(projectId);\n if (!maybeToken || (0, import_token_util.isExpired)((0, import_token_util.getTokenPayload)(maybeToken.token), options?.expirationBufferMs)) {\n const authToken = await (0, import_token_util.getVercelToken)({\n expirationBufferMs: options?.expirationBufferMs\n });\n maybeToken = await (0, import_token_util.getVercelOidcToken)(authToken, projectId, teamId);\n if (!maybeToken) {\n throw new import_token_error.VercelOidcTokenError(\"Failed to refresh OIDC token\");\n }\n (0, import_token_util.saveToken)(maybeToken, projectId);\n }\n process.env.VERCEL_OIDC_TOKEN = maybeToken.token;\n return;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n refreshToken\n});\n" | ||
| ], | ||
| "mappings": ";2HACA,SAAuB,eAAnB,EAC0B,yBAA1B,EAC2B,oBAA3B,GADmB,OAEnB,EAAe,OAAO,UAAU,eAChC,EAAW,CAAC,EAAQ,IAAQ,CAC9B,QAAS,KAAQ,EACf,EAAU,EAAQ,EAAM,CAAE,IAAK,EAAI,GAAO,WAAY,EAAK,CAAC,GAE5D,EAAc,CAAC,EAAI,EAAM,EAAQ,IAAS,CAC5C,GAAI,GAAQ,OAAO,IAAS,UAAY,OAAO,IAAS,YACtD,QAAS,KAAO,EAAkB,CAAI,EACpC,GAAI,CAAC,EAAa,KAAK,EAAI,CAAG,GAAK,IAAQ,EACzC,EAAU,EAAI,EAAK,CAAE,IAAK,IAAM,EAAK,GAAM,WAAY,EAAE,EAAO,EAAiB,EAAM,CAAG,IAAM,EAAK,UAAW,CAAC,EAEvH,OAAO,GAEL,EAAe,CAAC,IAAQ,EAAY,EAAU,CAAC,EAAG,aAAc,CAAE,MAAO,EAAK,CAAC,EAAG,CAAG,EACrF,EAAgB,CAAC,EACrB,EAAS,EAAe,CACtB,aAAc,IAAM,CACtB,CAAC,EACD,EAAO,QAAU,EAAa,CAAa,EAC3C,IAAI,MACA,MACJ,eAAe,CAAY,CAAC,EAAS,CACnC,IAAI,EAAY,GAAS,QACrB,EAAS,GAAS,KACtB,GAAI,CAAC,GAAa,CAAC,EAAQ,CACzB,IAAM,GAAe,EAAG,EAAkB,iBAAiB,EAC3D,EAAY,EAAY,UACxB,EAAS,EAAY,OAChB,QAAI,CAAC,GAAa,CAAC,EAAQ,CAChC,IAAM,GAAe,EAAG,EAAkB,iBAAiB,EAC3D,EAAY,GAAa,EAAY,UACrC,EAAS,GAAU,EAAY,OAEjC,GAAI,CAAC,EACH,MAAM,IAAI,EAAmB,qBAC3B,gGACF,EAEF,IAAI,GAAc,EAAG,EAAkB,WAAW,CAAS,EAC3D,GAAI,CAAC,IAAe,EAAG,EAAkB,YAAY,EAAG,EAAkB,iBAAiB,EAAW,KAAK,EAAG,GAAS,kBAAkB,EAAG,CAC1I,IAAM,EAAY,MAAO,EAAG,EAAkB,gBAAgB,CAC5D,mBAAoB,GAAS,kBAC/B,CAAC,EAED,GADA,EAAa,MAAO,EAAG,EAAkB,oBAAoB,EAAW,EAAW,CAAM,EACrF,CAAC,EACH,MAAM,IAAI,EAAmB,qBAAqB,8BAA8B,GAEjF,EAAG,EAAkB,WAAW,EAAY,CAAS,EAExD,QAAQ,IAAI,kBAAoB,EAAW,MAC3C", | ||
| "debugId": "2A56C9E4CAF25DFF64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+cerebras@2.0.41+d6123d32214422cb/node_modules/@ai-sdk/cerebras/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/cerebras-provider.ts\nimport { OpenAICompatibleChatLanguageModel } from \"@ai-sdk/openai-compatible\";\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\n\n// src/version.ts\nvar VERSION = true ? \"2.0.41\" : \"0.0.0-test\";\n\n// src/cerebras-provider.ts\nvar cerebrasErrorSchema = z.object({\n message: z.string(),\n type: z.string(),\n param: z.string(),\n code: z.string()\n});\nvar cerebrasErrorStructure = {\n errorSchema: cerebrasErrorSchema,\n errorToMessage: (data) => data.message\n};\nfunction createCerebras(options = {}) {\n var _a;\n const baseURL = withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.cerebras.ai/v1\"\n );\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"CEREBRAS_API_KEY\",\n description: \"Cerebras API key\"\n })}`,\n ...options.headers\n },\n `ai-sdk/cerebras/${VERSION}`\n );\n const createLanguageModel = (modelId) => {\n return new OpenAICompatibleChatLanguageModel(modelId, {\n provider: `cerebras.chat`,\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch,\n errorStructure: cerebrasErrorStructure,\n supportsStructuredOutputs: true\n });\n };\n const provider = (modelId) => createLanguageModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.languageModel = createLanguageModel;\n provider.chat = createLanguageModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar cerebras = createCerebras();\nexport {\n VERSION,\n cerebras,\n createCerebras\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";yVAaA,SAAI,OAAiB,cAGjB,OAAsB,OAAE,YAAO,MACjC,QAAS,EAAE,OAAO,EAClB,KAAM,EAAE,OAAO,EACf,MAAO,EAAE,OAAO,EAChB,KAAM,EAAE,OAAO,CACjB,CAAC,EACG,EAAyB,CAC3B,YAAa,EACb,eAAgB,CAAC,IAAS,EAAK,OACjC,EACA,SAAS,CAAc,CAAC,EAAU,CAAC,EAAG,CACpC,IAAI,EACJ,IAAM,EAAU,GACb,EAAK,EAAQ,UAAY,KAAO,EAAK,4BACxC,EACM,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,mBACzB,YAAa,kBACf,CAAC,OACE,EAAQ,OACb,EACA,mBAAmB,GACrB,EACM,EAAsB,CAAC,IAAY,CACvC,OAAO,IAAI,EAAkC,EAAS,CACpD,SAAU,gBACV,IAAK,EAAG,UAAW,GAAG,IAAU,IAChC,QAAS,EACT,MAAO,EAAQ,MACf,eAAgB,EAChB,0BAA2B,EAC7B,CAAC,GAEG,EAAW,CAAC,IAAY,EAAoB,CAAO,EAWzD,OAVA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,KAAO,EAChB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,EAAW,EAAe", | ||
| "debugId": "B2E82BC0134DFDB064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-web-identity@3.972.65/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-web-identity@3.972.65/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, externalDataInterceptor } from \"@smithy/core/config\";\nimport { readFileSync } from \"node:fs\";\nimport { fromWebToken } from \"./fromWebToken\";\nconst ENV_TOKEN_FILE = \"AWS_WEB_IDENTITY_TOKEN_FILE\";\nconst ENV_ROLE_ARN = \"AWS_ROLE_ARN\";\nconst ENV_ROLE_SESSION_NAME = \"AWS_ROLE_SESSION_NAME\";\nexport const fromTokenFile = (init = {}) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromTokenFile\");\n const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];\n const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN];\n const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];\n if (!webIdentityTokenFile || !roleArn) {\n throw new CredentialsProviderError(\"Web identity configuration not specified\", {\n logger: init.logger,\n });\n }\n const credentials = await fromWebToken({\n ...init,\n webIdentityToken: externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ??\n readFileSync(webIdentityTokenFile, { encoding: \"ascii\" }),\n roleArn,\n roleSessionName,\n })(awsIdentityProperties);\n if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN\", \"h\");\n }\n return credentials;\n};\n", | ||
| "export const fromWebToken = (init) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromWebToken\");\n const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init;\n let { roleAssumerWithWebIdentity } = init;\n if (!roleAssumerWithWebIdentity) {\n const { getDefaultRoleAssumerWithWebIdentity } = await import(\"@aws-sdk/nested-clients/sts\");\n roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({\n ...init.clientConfig,\n credentialProviderLogger: init.logger,\n parentClientConfig: {\n ...awsIdentityProperties?.callerClientConfig,\n ...init.parentClientConfig,\n },\n }, init.clientPlugins);\n }\n return roleAssumerWithWebIdentity({\n RoleArn: roleArn,\n RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,\n WebIdentityToken: webIdentityToken,\n ProviderId: providerId,\n PolicyArns: policyArns,\n Policy: policy,\n DurationSeconds: durationSeconds,\n });\n};\n" | ||
| ], | ||
| "mappings": ";kJAAA,oBACA,gBACA,uBAAS,WCFF,IAAM,EAAe,CAAC,IAAS,MAAO,IAA0B,CACnE,EAAK,QAAQ,MAAM,0DAA0D,EAC7E,IAAQ,UAAS,kBAAiB,mBAAkB,aAAY,aAAY,SAAQ,mBAAoB,GAClG,8BAA+B,EACrC,GAAI,CAAC,EAA4B,CAC7B,IAAQ,wCAAyC,KAAa,0CAC9D,EAA6B,EAAqC,IAC3D,EAAK,aACR,yBAA0B,EAAK,OAC/B,mBAAoB,IACb,GAAuB,sBACvB,EAAK,kBACZ,CACJ,EAAG,EAAK,aAAa,EAEzB,OAAO,EAA2B,CAC9B,QAAS,EACT,gBAAiB,GAAmB,sBAAsB,KAAK,IAAI,IACnE,iBAAkB,EAClB,WAAY,EACZ,WAAY,EACZ,OAAQ,EACR,gBAAiB,CACrB,CAAC,GDnBL,IAAM,EAAiB,8BACjB,EAAe,eACf,EAAwB,wBACjB,EAAgB,CAAC,EAAO,CAAC,IAAM,MAAO,IAA0B,CACzE,EAAK,QAAQ,MAAM,2DAA2D,EAC9E,IAAM,EAAuB,GAAM,sBAAwB,QAAQ,IAAI,GACjE,EAAU,GAAM,SAAW,QAAQ,IAAI,GACvC,EAAkB,GAAM,iBAAmB,QAAQ,IAAI,GAC7D,GAAI,CAAC,GAAwB,CAAC,EAC1B,MAAM,IAAI,2BAAyB,2CAA4C,CAC3E,OAAQ,EAAK,MACjB,CAAC,EAEL,IAAM,EAAc,MAAM,EAAa,IAChC,EACH,iBAAkB,2BAAyB,iBAAiB,EAAE,IAC1D,EAAa,EAAsB,CAAE,SAAU,OAAQ,CAAC,EAC5D,UACA,iBACJ,CAAC,EAAE,CAAqB,EACxB,GAAI,IAAyB,QAAQ,IAAI,GACrC,uBAAqB,EAAa,wCAAyC,GAAG,EAElF,OAAO", | ||
| "debugId": "392445BAA8BD455864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/openrouter.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route, type RouteDefaultsInput } from \"../route/client\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Framing } from \"../route/framing\"\nimport { Protocol } from \"../route/protocol\"\nimport { AuthOptions, type ProviderAuthOption } from \"../route/auth-options\"\nimport { ProviderID, type ModelID, type ProviderOptions } from \"../schema\"\nimport * as OpenAICompatibleProfiles from \"./openai-compatible-profile\"\nimport * as OpenAIChat from \"../protocols/openai-chat\"\nimport { isRecord } from \"../protocols/shared\"\n\nexport const profile = OpenAICompatibleProfiles.profiles.openrouter\nexport const id = ProviderID.make(profile.provider)\nconst ADAPTER = \"openrouter\"\n\nexport interface OpenRouterOptions {\n readonly [key: string]: unknown\n readonly usage?: boolean | Record<string, unknown>\n readonly reasoning?: Record<string, unknown>\n readonly promptCacheKey?: string\n}\n\nexport type OpenRouterProviderOptionsInput = ProviderOptions & {\n readonly openrouter?: OpenRouterOptions\n}\n\nexport type ModelOptions = Omit<RouteDefaultsInput, \"providerOptions\"> &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n readonly providerOptions?: OpenRouterProviderOptionsInput\n }\n\nconst OpenRouterBody = Schema.StructWithRest(Schema.Struct(OpenAIChat.bodyFields), [\n Schema.Record(Schema.String, Schema.Any),\n])\nexport type OpenRouterBody = Schema.Schema.Type<typeof OpenRouterBody>\n\nexport const protocol = Protocol.make({\n id: \"openrouter-chat\",\n body: {\n schema: OpenRouterBody,\n from: (request) =>\n OpenAIChat.protocol.body.from(request).pipe(\n Effect.map((body) => {\n const sourceAssistants = request.messages.filter((message) => message.role === \"assistant\")\n let assistantIndex = 0\n const messages = body.messages.map((message) => {\n if (message.role !== \"assistant\") return message\n const source = sourceAssistants[assistantIndex++]\n const reasoning = source?.content\n .filter((part) => part.type === \"reasoning\")\n .map((part) => part.text)\n .join(\"\")\n const reasoningDetails = Array.isArray(message.reasoning_details) ? message.reasoning_details : undefined\n return {\n ...message,\n reasoning_content: undefined,\n reasoning_text: undefined,\n reasoning: reasoning && reasoningDetails && reasoningDetails.length > 0 ? reasoning : undefined,\n reasoning_details: reasoningDetails,\n }\n })\n return {\n ...body,\n messages,\n ...bodyOptions(request.providerOptions?.openrouter),\n } as OpenRouterBody\n }),\n ),\n },\n stream: OpenAIChat.protocol.stream,\n})\n\nconst bodyOptions = (input: unknown) => {\n const openrouter = isRecord(input) ? input : {}\n return {\n ...(openrouter.usage === true\n ? { usage: { include: true } }\n : isRecord(openrouter.usage)\n ? { usage: openrouter.usage }\n : {}),\n ...(isRecord(openrouter.reasoning) ? { reasoning: openrouter.reasoning } : {}),\n ...(typeof openrouter.promptCacheKey === \"string\" ? { prompt_cache_key: openrouter.promptCacheKey } : {}),\n }\n}\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: profile.provider,\n protocol,\n endpoint: Endpoint.path(\"/chat/completions\", { baseURL: profile.baseURL }),\n framing: Framing.sse,\n})\n\nexport const routes = [route]\n\nconst configuredRoute = (input: ModelOptions) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n return route.with({\n ...rest,\n endpoint: { baseURL: baseURL ?? profile.baseURL },\n auth: AuthOptions.bearer(input, \"OPENROUTER_API_KEY\"),\n })\n}\n\nexport const configure = (input: ModelOptions = {}) => {\n const route = configuredRoute(input)\n return {\n id,\n model: (modelID: string | ModelID) => route.model({ id: modelID }),\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model = provider.model\n" | ||
| ], | ||
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AW,CAAE,iBAAkB,EAAW,cAAe,EAAI,CAAC,CACzG,GAGW,EAAQ,EAAM,KAAK,CAC9B,GAAI,EACJ,SAAU,EAAQ,SAClB,WACA,SAAU,EAAS,KAAK,oBAAqB,CAAE,QAAS,EAAQ,OAAQ,CAAC,EACzE,QAAS,EAAQ,GACnB,CAAC,EAEY,EAAS,CAAC,CAAK,EAEtB,EAAkB,CAAC,IAAwB,CAC/C,IAAQ,OAAQ,EAAG,KAAM,EAAO,aAAY,GAAS,EACrD,OAAO,EAAM,KAAK,IACb,EACH,SAAU,CAAE,QAAS,GAAW,EAAQ,OAAQ,EAChD,KAAM,EAAY,OAAO,EAAO,oBAAoB,CACtD,CAAC,GAGU,EAAY,CAAC,EAAsB,CAAC,IAAM,CACrD,IAAM,EAAQ,EAAgB,CAAK,EACnC,MAAO,CACL,KACA,MAAO,CAAC,IAA8B,EAAM,MAAM,CAAE,GAAI,CAAQ,CAAC,EACjE,WACF,GAGW,EAAW,EAAU,EACrB,EAAQ,EAAS", | ||
| "debugId": "E887C7A8CA449E7464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/createCredentialChain.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/resolveLogins.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/IndexedDbStorage.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/InMemoryStorage.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/localStorage.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentity.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentityPool.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromContainerMetadata.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromEnv.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromIni.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromInstanceMetadata.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.70/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.70/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.70/node_modules/@aws-sdk/credential-provider-node/dist-es/runtime/memoize-chain.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromNodeProviderChain.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromProcess.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromSSO.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.base.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTokenFile.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromWebToken.js"], | ||
| "sourcesContent": [ | ||
| "import { ProviderError } from \"@smithy/core/config\";\nexport const createCredentialChain = (...credentialProviders) => {\n let expireAfter = -1;\n const baseFunction = async (awsIdentityProperties) => {\n const credentials = await propertyProviderChain(...credentialProviders)(awsIdentityProperties);\n if (!credentials.expiration && expireAfter !== -1) {\n credentials.expiration = new Date(Date.now() + expireAfter);\n }\n return credentials;\n };\n const withOptions = Object.assign(baseFunction, {\n expireAfter(milliseconds) {\n if (milliseconds < 5 * 60_000) {\n throw new Error(\"@aws-sdk/credential-providers - createCredentialChain(...).expireAfter(ms) may not be called with a duration lower than five minutes.\");\n }\n expireAfter = milliseconds;\n return withOptions;\n },\n });\n return withOptions;\n};\nexport const propertyProviderChain = (...providers) => async (awsIdentityProperties) => {\n if (providers.length === 0) {\n throw new ProviderError(\"No providers in chain\", { tryNextLink: false });\n }\n let lastProviderError;\n for (const provider of providers) {\n try {\n return await provider(awsIdentityProperties);\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { resolveLogins } from \"./resolveLogins\";\nexport function fromCognitoIdentity(parameters) {\n return async (awsIdentityProperties) => {\n parameters.logger?.debug(\"@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity\");\n const { GetCredentialsForIdentityCommand, CognitoIdentityClient } = await import(\"./loadCognitoIdentity.js\");\n const fromConfigs = (property) => parameters.clientConfig?.[property] ??\n parameters.parentClientConfig?.[property] ??\n awsIdentityProperties?.callerClientConfig?.[property];\n const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken, } = throwOnMissingCredentials(parameters.logger), } = await (parameters.client ??\n new CognitoIdentityClient(Object.assign({}, parameters.clientConfig ?? {}, {\n region: fromConfigs(\"region\"),\n profile: fromConfigs(\"profile\"),\n userAgentAppId: fromConfigs(\"userAgentAppId\"),\n }))).send(new GetCredentialsForIdentityCommand({\n CustomRoleArn: parameters.customRoleArn,\n IdentityId: parameters.identityId,\n Logins: parameters.logins ? await resolveLogins(parameters.logins) : undefined,\n }));\n return {\n identityId: parameters.identityId,\n accessKeyId: AccessKeyId,\n secretAccessKey: SecretKey,\n sessionToken: SessionToken,\n expiration: Expiration,\n };\n };\n}\nfunction throwOnMissingAccessKeyId(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no access key ID\", { logger });\n}\nfunction throwOnMissingCredentials(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no credentials\", { logger });\n}\nfunction throwOnMissingSecretKey(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no secret key\", { logger });\n}\n", | ||
| "export function resolveLogins(logins) {\n return Promise.all(Object.keys(logins).reduce((arr, name) => {\n const tokenOrProvider = logins[name];\n if (typeof tokenOrProvider === \"string\") {\n arr.push([name, tokenOrProvider]);\n }\n else {\n arr.push(tokenOrProvider().then((token) => [name, token]));\n }\n return arr;\n }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins, [key, value]) => {\n logins[key] = value;\n return logins;\n }, {}));\n}\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { fromCognitoIdentity } from \"./fromCognitoIdentity\";\nimport { localStorage } from \"./localStorage\";\nimport { resolveLogins } from \"./resolveLogins\";\nexport function fromCognitoIdentityPool({ accountId, cache = localStorage(), client, clientConfig, customRoleArn, identityPoolId, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? \"ANONYMOUS\" : undefined, logger, parentClientConfig, }) {\n logger?.debug(\"@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity\");\n const cacheKey = userIdentifier\n ? `aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}`\n : undefined;\n let provider = async (awsIdentityProperties) => {\n const { GetIdCommand, CognitoIdentityClient } = await import(\"./loadCognitoIdentity.js\");\n const fromConfigs = (property) => clientConfig?.[property] ??\n parentClientConfig?.[property] ??\n awsIdentityProperties?.callerClientConfig?.[property];\n const _client = client ??\n new CognitoIdentityClient(Object.assign({}, clientConfig ?? {}, {\n region: fromConfigs(\"region\"),\n profile: fromConfigs(\"profile\"),\n userAgentAppId: fromConfigs(\"userAgentAppId\"),\n }));\n let identityId = (cacheKey && (await cache.getItem(cacheKey)));\n if (!identityId) {\n const { IdentityId = throwOnMissingId(logger) } = await _client.send(new GetIdCommand({\n AccountId: accountId,\n IdentityPoolId: identityPoolId,\n Logins: logins ? await resolveLogins(logins) : undefined,\n }));\n identityId = IdentityId;\n if (cacheKey) {\n Promise.resolve(cache.setItem(cacheKey, identityId)).catch(() => { });\n }\n }\n provider = fromCognitoIdentity({\n client: _client,\n customRoleArn,\n logins,\n identityId,\n });\n return provider(awsIdentityProperties);\n };\n return (awsIdentityProperties) => provider(awsIdentityProperties).catch(async (err) => {\n if (cacheKey) {\n Promise.resolve(cache.removeItem(cacheKey)).catch(() => { });\n }\n throw err;\n });\n}\nfunction throwOnMissingId(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no identity ID\", { logger });\n}\n", | ||
| "const STORE_NAME = \"IdentityIds\";\nexport class IndexedDbStorage {\n dbName;\n constructor(dbName = \"aws:cognito-identity-ids\") {\n this.dbName = dbName;\n }\n getItem(key) {\n return this.withObjectStore(\"readonly\", (store) => {\n const req = store.get(key);\n return new Promise((resolve) => {\n req.onerror = () => resolve(null);\n req.onsuccess = () => resolve(req.result ? req.result.value : null);\n });\n }).catch(() => null);\n }\n removeItem(key) {\n return this.withObjectStore(\"readwrite\", (store) => {\n const req = store.delete(key);\n return new Promise((resolve, reject) => {\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve();\n });\n });\n }\n setItem(id, value) {\n return this.withObjectStore(\"readwrite\", (store) => {\n const req = store.put({ id, value });\n return new Promise((resolve, reject) => {\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve();\n });\n });\n }\n getDb() {\n const openDbRequest = self.indexedDB.open(this.dbName, 1);\n return new Promise((resolve, reject) => {\n openDbRequest.onsuccess = () => {\n resolve(openDbRequest.result);\n };\n openDbRequest.onerror = () => {\n reject(openDbRequest.error);\n };\n openDbRequest.onblocked = () => {\n reject(new Error(\"Unable to access DB\"));\n };\n openDbRequest.onupgradeneeded = () => {\n const db = openDbRequest.result;\n db.onerror = () => {\n reject(new Error(\"Failed to create object store\"));\n };\n db.createObjectStore(STORE_NAME, { keyPath: \"id\" });\n };\n });\n }\n withObjectStore(mode, action) {\n return this.getDb().then((db) => {\n const tx = db.transaction(STORE_NAME, mode);\n tx.oncomplete = () => db.close();\n return new Promise((resolve, reject) => {\n tx.onerror = () => reject(tx.error);\n resolve(action(tx.objectStore(STORE_NAME)));\n }).catch((err) => {\n db.close();\n throw err;\n });\n });\n }\n}\n", | ||
| "export class InMemoryStorage {\n store;\n constructor(store = {}) {\n this.store = store;\n }\n getItem(key) {\n if (key in this.store) {\n return this.store[key];\n }\n return null;\n }\n removeItem(key) {\n delete this.store[key];\n }\n setItem(key, value) {\n this.store[key] = value;\n }\n}\n", | ||
| "import { IndexedDbStorage } from \"./IndexedDbStorage\";\nimport { InMemoryStorage } from \"./InMemoryStorage\";\nconst inMemoryStorage = new InMemoryStorage();\nexport function localStorage() {\n if (typeof self === \"object\" && self.indexedDB) {\n return new IndexedDbStorage();\n }\n if (typeof window === \"object\" && window.localStorage) {\n return window.localStorage;\n }\n return inMemoryStorage;\n}\n", | ||
| "import { fromCognitoIdentity as _fromCognitoIdentity } from \"@aws-sdk/credential-provider-cognito-identity\";\nexport const fromCognitoIdentity = (options) => _fromCognitoIdentity({\n ...options,\n});\n", | ||
| "import { fromCognitoIdentityPool as _fromCognitoIdentityPool } from \"@aws-sdk/credential-provider-cognito-identity\";\nexport const fromCognitoIdentityPool = (options) => _fromCognitoIdentityPool({\n ...options,\n});\n", | ||
| "import { fromContainerMetadata as _fromContainerMetadata } from \"@smithy/credential-provider-imds\";\nexport const fromContainerMetadata = (init) => {\n init?.logger?.debug(\"@smithy/credential-provider-imds\", \"fromContainerMetadata\");\n return _fromContainerMetadata(init);\n};\n", | ||
| "import { fromEnv as _fromEnv } from \"@aws-sdk/credential-provider-env\";\nexport const fromEnv = (init) => _fromEnv(init);\n", | ||
| "import { fromIni as _fromIni } from \"@aws-sdk/credential-provider-ini\";\nexport const fromIni = (init = {}) => _fromIni({\n ...init,\n});\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromInstanceMetadata as _fromInstanceMetadata } from \"@smithy/credential-provider-imds\";\nexport const fromInstanceMetadata = (init) => {\n init?.logger?.debug(\"@smithy/credential-provider-imds\", \"fromInstanceMetadata\");\n return async () => _fromInstanceMetadata(init)().then((creds) => setCredentialFeature(creds, \"CREDENTIALS_IMDS\", \"0\"));\n};\n", | ||
| "import { fromLoginCredentials as _fromLoginCredentials, } from \"@aws-sdk/credential-provider-login\";\nexport const fromLoginCredentials = (init) => _fromLoginCredentials({\n ...init,\n});\n", | ||
| "import { ENV_KEY, ENV_SECRET, fromEnv } from \"@aws-sdk/credential-provider-env\";\nimport { CredentialsProviderError, ENV_PROFILE } from \"@smithy/core/config\";\nimport { remoteProvider } from \"./remoteProvider\";\nimport { memoizeChain } from \"./runtime/memoize-chain\";\nlet multipleCredentialSourceWarningEmitted = false;\nexport const defaultProvider = (init = {}) => memoizeChain([\n async () => {\n const profile = init.profile ?? process.env[ENV_PROFILE];\n if (profile) {\n const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET];\n if (envStaticCredentialsAreSet) {\n if (!multipleCredentialSourceWarningEmitted) {\n const warnFn = init.logger?.warn && init.logger?.constructor?.name !== \"NoOpLogger\"\n ? init.logger.warn.bind(init.logger)\n : console.warn;\n warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:\n Multiple credential sources detected: \n Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.\n This SDK will proceed with the AWS_PROFILE value.\n \n However, a future version may change this behavior to prefer the ENV static credentials.\n Please ensure that your environment only sets either the AWS_PROFILE or the\n AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.\n`);\n multipleCredentialSourceWarningEmitted = true;\n }\n }\n throw new CredentialsProviderError(\"AWS_PROFILE is set, skipping fromEnv provider.\", {\n logger: init.logger,\n tryNextLink: true,\n });\n }\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromEnv\");\n return fromEnv(init)();\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n throw new CredentialsProviderError(\"Skipping SSO provider in default chain (inputs do not include SSO fields).\", { logger: init.logger });\n }\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromIni\");\n const { fromIni } = await import(\"@aws-sdk/credential-provider-ini\");\n return fromIni(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromProcess\");\n const { fromProcess } = await import(\"@aws-sdk/credential-provider-process\");\n return fromProcess(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile\");\n const { fromTokenFile } = await import(\"@aws-sdk/credential-provider-web-identity\");\n return fromTokenFile(init)(awsIdentityProperties);\n },\n async () => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::remoteProvider\");\n return (await remoteProvider(init))();\n },\n async () => {\n throw new CredentialsProviderError(\"Could not load credentials from any providers\", {\n tryNextLink: false,\n logger: init.logger,\n });\n },\n], credentialsTreatedAsExpired);\nexport const credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined;\nexport const credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000;\n", | ||
| "import { chain, CredentialsProviderError } from \"@smithy/core/config\";\nexport const ENV_IMDS_DISABLED = \"AWS_EC2_METADATA_DISABLED\";\nexport const remoteProvider = async (init) => {\n const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata\");\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n return chain(fromHttp(init), fromContainerMetadata(init));\n }\n if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== \"false\") {\n return async () => {\n throw new CredentialsProviderError(\"EC2 Instance Metadata Service access disabled\", { logger: init.logger });\n };\n }\n init.logger?.debug(\"@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata\");\n return fromInstanceMetadata(init);\n};\n", | ||
| "export function memoizeChain(providers, treatAsExpired) {\n const chain = internalCreateChain(providers);\n let activeLock;\n let passiveLock;\n let credentials;\n let forceRefreshLock;\n const provider = async (options) => {\n if (options?.forceRefresh) {\n if (!forceRefreshLock) {\n forceRefreshLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n forceRefreshLock = undefined;\n });\n }\n await forceRefreshLock;\n return credentials;\n }\n if (credentials?.expiration) {\n if (credentials?.expiration?.getTime() < Date.now()) {\n credentials = undefined;\n }\n }\n if (activeLock) {\n await activeLock;\n }\n else if (!credentials || treatAsExpired?.(credentials)) {\n if (credentials) {\n if (!passiveLock) {\n passiveLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n passiveLock = undefined;\n });\n }\n }\n else {\n activeLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n activeLock = undefined;\n });\n return provider(options);\n }\n }\n return credentials;\n };\n return provider;\n}\nexport const internalCreateChain = (providers) => async (awsIdentityProperties) => {\n let lastProviderError;\n for (const provider of providers) {\n try {\n return await provider(awsIdentityProperties);\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n", | ||
| "import { defaultProvider } from \"@aws-sdk/credential-provider-node\";\nexport const fromNodeProviderChain = (init = {}) => defaultProvider({\n ...init,\n});\n", | ||
| "import { fromProcess as _fromProcess } from \"@aws-sdk/credential-provider-process\";\nexport const fromProcess = (init) => _fromProcess(init);\n", | ||
| "import { fromSSO as _fromSSO } from \"@aws-sdk/credential-provider-sso\";\nexport const fromSSO = (init = {}) => {\n return _fromSSO({ ...init });\n};\n", | ||
| "import { loadConfig, NODE_REGION_CONFIG_FILE_OPTIONS } from \"@smithy/core/config\";\nimport { fromNodeProviderChain } from \"./fromNodeProviderChain\";\nimport { fromTemporaryCredentials as fromTemporaryCredentialsBase } from \"./fromTemporaryCredentials.base\";\nexport const fromTemporaryCredentials = (options) => {\n return fromTemporaryCredentialsBase(options, fromNodeProviderChain, async ({ profile = process.env.AWS_PROFILE }) => loadConfig({\n environmentVariableSelector: (env) => env.AWS_REGION,\n configFileSelector: (profileData) => {\n return profileData.region;\n },\n default: () => undefined,\n }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, profile })());\n};\n", | ||
| "import { normalizeProvider } from \"@smithy/core\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nconst ASSUME_ROLE_DEFAULT_REGION = \"us-east-1\";\nexport const fromTemporaryCredentials = (options, credentialDefaultProvider, regionProvider) => {\n let stsClient;\n return async (awsIdentityProperties = {}) => {\n const { callerClientConfig } = awsIdentityProperties;\n const profile = options.clientConfig?.profile ?? callerClientConfig?.profile;\n const logger = options.logger ?? callerClientConfig?.logger;\n logger?.debug(\"@aws-sdk/credential-providers - fromTemporaryCredentials (STS)\");\n const params = { ...options.params, RoleSessionName: options.params.RoleSessionName ?? \"aws-sdk-js-\" + Date.now() };\n if (params?.SerialNumber) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Temporary credential requires multi-factor authentication, but no MFA code callback was provided.`, {\n tryNextLink: false,\n logger,\n });\n }\n params.TokenCode = await options.mfaCodeProvider(params?.SerialNumber);\n }\n const { AssumeRoleCommand, STSClient } = await import(\"./loadSts.js\");\n if (!stsClient) {\n const defaultCredentialsOrError = typeof credentialDefaultProvider === \"function\" ? credentialDefaultProvider() : undefined;\n const credentialSources = [\n options.masterCredentials,\n options.clientConfig?.credentials,\n void callerClientConfig?.credentials,\n callerClientConfig?.credentialDefaultProvider?.(),\n defaultCredentialsOrError,\n ];\n let credentialSource = \"STS client default credentials\";\n if (credentialSources[0]) {\n credentialSource = \"options.masterCredentials\";\n }\n else if (credentialSources[1]) {\n credentialSource = \"options.clientConfig.credentials\";\n }\n else if (credentialSources[2]) {\n credentialSource = \"caller client's credentials\";\n throw new Error(\"fromTemporaryCredentials recursion in callerClientConfig.credentials\");\n }\n else if (credentialSources[3]) {\n credentialSource = \"caller client's credentialDefaultProvider\";\n }\n else if (credentialSources[4]) {\n credentialSource = \"AWS SDK default credentials\";\n }\n const regionSources = [\n options.clientConfig?.region,\n callerClientConfig?.region,\n await regionProvider?.({\n profile,\n }),\n ASSUME_ROLE_DEFAULT_REGION,\n ];\n let regionSource = \"default partition's default region\";\n if (regionSources[0]) {\n regionSource = \"options.clientConfig.region\";\n }\n else if (regionSources[1]) {\n regionSource = \"caller client's region\";\n }\n else if (regionSources[2]) {\n regionSource = \"file or env region\";\n }\n const requestHandlerSources = [\n filterRequestHandler(options.clientConfig?.requestHandler),\n filterRequestHandler(callerClientConfig?.requestHandler),\n ];\n let requestHandlerSource = \"STS default requestHandler\";\n if (requestHandlerSources[0]) {\n requestHandlerSource = \"options.clientConfig.requestHandler\";\n }\n else if (requestHandlerSources[1]) {\n requestHandlerSource = \"caller client's requestHandler\";\n }\n logger?.debug?.(`@aws-sdk/credential-providers - fromTemporaryCredentials STS client init with ` +\n `${regionSource}=${await normalizeProvider(coalesce(regionSources))()}, ${credentialSource}, ${requestHandlerSource}.`);\n stsClient = new STSClient({\n userAgentAppId: callerClientConfig?.userAgentAppId,\n ...options.clientConfig,\n credentials: coalesce(credentialSources),\n logger,\n profile,\n region: coalesce(regionSources),\n requestHandler: coalesce(requestHandlerSources),\n });\n }\n if (options.clientPlugins) {\n for (const plugin of options.clientPlugins) {\n stsClient.middlewareStack.use(plugin);\n }\n }\n const { Credentials } = await stsClient.send(new AssumeRoleCommand(params));\n if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {\n throw new CredentialsProviderError(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`, {\n logger,\n });\n }\n return {\n accessKeyId: Credentials.AccessKeyId,\n secretAccessKey: Credentials.SecretAccessKey,\n sessionToken: Credentials.SessionToken,\n expiration: Credentials.Expiration,\n credentialScope: Credentials.CredentialScope,\n };\n };\n};\nconst filterRequestHandler = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\" ? undefined : requestHandler;\n};\nconst coalesce = (args) => {\n for (const item of args) {\n if (item !== undefined) {\n return item;\n }\n }\n};\n", | ||
| "import { fromTokenFile as _fromTokenFile } from \"@aws-sdk/credential-provider-web-identity\";\nexport const fromTokenFile = (init = {}) => _fromTokenFile({\n ...init,\n});\n", | ||
| "import { fromWebToken as _fromWebToken } from \"@aws-sdk/credential-provider-web-identity\";\nexport const fromWebToken = (init) => _fromWebToken({\n ...init,\n});\n" | ||
| ], | ||
| "mappings": ";moBAAA,oBACa,QAAwB,SAAI,SAAwB,MAC7D,SAAI,OAAc,QAQZ,OAAc,YAAO,YAPN,WAAO,IAA0B,CAClD,IAAM,EAAc,MAAM,GAAsB,GAAG,CAAmB,EAAE,CAAqB,EAC7F,GAAI,CAAC,EAAY,YAAc,IAAgB,GAC3C,EAAY,WAAa,IAAI,KAAK,KAAK,IAAI,EAAI,CAAW,EAE9D,OAAO,GAEqC,CAC5C,WAAW,CAAC,EAAc,CACtB,GAAI,EAAe,OACf,MAAU,MAAM,uIAAuI,EAG3J,OADA,EAAc,EACP,EAEf,CAAC,EACD,OAAO,GAEE,GAAwB,IAAI,IAAc,MAAO,IAA0B,CACpF,GAAI,EAAU,SAAW,EACrB,MAAM,IAAI,gBAAc,wBAAyB,CAAE,YAAa,EAAM,CAAC,EAE3E,IAAI,EACJ,QAAW,KAAY,EACnB,GAAI,CACA,OAAO,MAAM,EAAS,CAAqB,EAE/C,MAAO,EAAK,CAER,GADA,EAAoB,EAChB,GAAK,YACL,SAEJ,MAAM,EAGd,MAAM,GCtCV,eCAO,SAAS,CAAa,CAAC,EAAQ,CAClC,OAAO,QAAQ,IAAI,OAAO,KAAK,CAAM,EAAE,OAAO,CAAC,EAAK,IAAS,CACzD,IAAM,EAAkB,EAAO,GAC/B,GAAI,OAAO,IAAoB,SAC3B,EAAI,KAAK,CAAC,EAAM,CAAe,CAAC,EAGhC,OAAI,KAAK,EAAgB,EAAE,KAAK,CAAC,IAAU,CAAC,EAAM,CAAK,CAAC,CAAC,EAE7D,OAAO,GACR,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,IAAkB,EAAc,OAAO,CAAC,GAAS,EAAK,KAAW,CAE3E,OADA,EAA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uB,CAAC,IAAmB,CAC7C,OAAO,GAAgB,UAAU,kBAAoB,KAAO,OAAY,GAEtE,EAAW,CAAC,IAAS,CACvB,QAAW,KAAQ,EACf,GAAI,IAAS,OACT,OAAO,GD/GZ,IAAM,GAA2B,CAAC,IAAY,CACjD,OAAO,GAA6B,EAAS,EAAuB,OAAS,UAAU,QAAQ,IAAI,eAAkB,aAAW,CAC5H,4BAA6B,CAAC,IAAQ,EAAI,WAC1C,mBAAoB,CAAC,IAAgB,CACjC,OAAO,EAAY,QAEvB,QAAS,IAAG,CAAG,OACnB,EAAG,IAAK,kCAAiC,SAAQ,CAAC,EAAE,CAAC,GETlD,IAAM,GAAgB,CAAC,EAAO,CAAC,IAAM,GAAe,IACpD,CACP,CAAC,ECFM,IAAM,GAAe,CAAC,IAAS,GAAc,IAC7C,CACP,CAAC", | ||
| "debugId": "9AD3E414B8A23DFD64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/agents.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.agents,\n Effect.fn(\"cli.debug.agents\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.agent.list({ location: { directory: process.cwd() } }))\n process.stdout.write(\n JSON.stringify(\n response.data.toSorted((a, b) => a.id.localeCompare(b.id)),\n null,\n 2,\n ) + EOL,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";83BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,WAAM,cAAS,YACjC,OAAO,QAAG,uBAAkB,OAAE,cAAU,OAAG,MACzC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EAC1G,QAAQ,OAAO,MACb,KAAK,UACH,EAAS,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzD,KACA,CACF,EAAI,CACN,EACD,CACH", | ||
| "debugId": "97096986A07B4DC964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/openai-compatible-chat.ts"], | ||
| "sourcesContent": [ | ||
| "import { Route, type RouteRoutedModelInput } from \"../route/client\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Framing } from \"../route/framing\"\nimport * as OpenAIChat from \"./openai-chat\"\n\nconst ADAPTER = \"openai-compatible-chat\"\n\nexport type OpenAICompatibleChatModelInput = RouteRoutedModelInput\n\n/**\n * Route for non-OpenAI providers that expose an OpenAI Chat-compatible\n * `/chat/completions` endpoint. Reuses `OpenAIChat.protocol` end-to-end and\n * overrides only the route id so providers can be resolved per-family without\n * colliding with native OpenAI. Provider helpers configure the route endpoint\n * before model selection.\n */\nexport const route = Route.make({\n id: ADAPTER,\n providerMetadataKey: \"openai\",\n protocol: OpenAIChat.protocol,\n endpoint: Endpoint.path(\"/chat/completions\"),\n framing: Framing.sse,\n})\n\nexport * as OpenAICompatibleChat from \"./openai-compatible-chat\"\n" | ||
| ], | ||
| "mappings": ";mHAKA,SAAM,EAAU,yBAWH,EAAQ,EAAM,KAAK,CAC9B,GAAI,EACJ,oBAAqB,SACrB,SAAqB,EACrB,SAAU,EAAS,KAAK,mBAAmB,EAC3C,QAAS,EAAQ,GACnB,CAAC", | ||
| "debugId": "DAAFF133E6C5614A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/xai-images.ts", "../ai/src/providers/xai.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Encoding, Schema } from \"effect\"\nimport { Headers, HttpClientRequest } from \"effect/unstable/http\"\nimport { GeneratedImage, ImageModel, ImageResponse, type ImageRequestFor, type ImageRoute } from \"../image\"\nimport { Auth, type Definition as AuthDefinition } from \"../route/auth\"\nimport {\n InvalidProviderOutputReason,\n LLMError,\n Usage,\n mergeHttpOptions,\n mergeJsonRecords,\n type HttpOptions,\n} from \"../schema\"\nimport { ProviderShared, optionalNull } from \"./shared\"\nimport { ImageInputs } from \"./utils/image-input\"\n\nconst ADAPTER = \"xai-images\"\nexport const DEFAULT_BASE_URL = \"https://api.x.ai/v1\"\nexport const PATH = \"/images/generations\"\nexport const EDIT_PATH = \"/images/edits\"\n\nexport type XAIImageString<Known extends string> = Known | (string & {})\n\nexport type XAIImageOptions = {\n readonly n?: number\n readonly aspectRatio?: XAIImageString<\n | \"1:1\"\n | \"3:4\"\n | \"4:3\"\n | \"9:16\"\n | \"16:9\"\n | \"2:3\"\n | \"3:2\"\n | \"9:19.5\"\n | \"19.5:9\"\n | \"9:20\"\n | \"20:9\"\n | \"1:2\"\n | \"2:1\"\n | \"auto\"\n >\n readonly aspect_ratio?: XAIImageString<\n | \"1:1\"\n | \"3:4\"\n | \"4:3\"\n | \"9:16\"\n | \"16:9\"\n | \"2:3\"\n | \"3:2\"\n | \"9:19.5\"\n | \"19.5:9\"\n | \"9:20\"\n | \"20:9\"\n | \"1:2\"\n | \"2:1\"\n | \"auto\"\n >\n readonly resolution?: XAIImageString<\"1k\" | \"2k\">\n readonly responseFormat?: XAIImageString<\"url\" | \"b64_json\">\n readonly response_format?: XAIImageString<\"url\" | \"b64_json\">\n} & Record<string, unknown>\n\ntype XAIImageBody = Record<string, unknown> & {\n readonly model: string\n readonly prompt: string\n}\n\nconst XAIImageResponse = Schema.Struct({\n data: Schema.Array(\n Schema.Struct({\n b64_json: optionalNull(Schema.String),\n url: optionalNull(Schema.String),\n revised_prompt: optionalNull(Schema.String),\n mime_type: optionalNull(Schema.String),\n }),\n ),\n usage: Schema.optional(Schema.Unknown),\n})\n\nexport interface ModelInput {\n readonly id: string\n readonly auth: AuthDefinition\n readonly baseURL?: string\n readonly headers?: Record<string, string>\n readonly http?: HttpOptions\n}\n\nconst nativeOptions = (options: XAIImageOptions | undefined) => {\n if (!options) return undefined\n const { aspectRatio, responseFormat, ...native } = options\n return {\n aspect_ratio: aspectRatio,\n response_format: responseFormat,\n ...native,\n }\n}\n\nconst invalidOutput = (message: string) =>\n new LLMError({\n module: ADAPTER,\n method: \"generate\",\n reason: new InvalidProviderOutputReason({ message, route: ADAPTER }),\n })\n\nconst applyQuery = (url: string, query: Record<string, string> | undefined) => {\n if (!query) return url\n const next = new URL(url)\n Object.entries(query).forEach(([key, value]) => next.searchParams.set(key, value))\n return next.toString()\n}\n\nexport const model = (input: ModelInput) => {\n const route: ImageRoute<XAIImageOptions> = {\n id: ADAPTER,\n generate: Effect.fn(\"XAIImages.generate\")(function* (request: ImageRequestFor<XAIImageOptions>, execute) {\n const http = mergeHttpOptions(request.model.http, request.http)\n const imageReferences = (request.images ?? []).map((image) => {\n if (image.type === \"bytes\") return { url: ImageInputs.dataUrl(image), type: \"image_url\" as const }\n if (image.type === \"url\") return { url: image.url, type: \"image_url\" as const }\n if (image.type === \"file-id\") return { file_id: image.id }\n return undefined\n })\n if (imageReferences.some((image) => image === undefined))\n return yield* ImageInputs.invalid(ADAPTER, \"xAI Images accepts image URLs, data URLs, bytes, and file IDs\")\n const requestBody = mergeJsonRecords(\n {\n model: request.model.id,\n prompt: request.prompt,\n image: imageReferences.length === 1 ? imageReferences[0] : undefined,\n images: imageReferences.length > 1 ? imageReferences : undefined,\n },\n nativeOptions(request.options),\n http?.body,\n ) as XAIImageBody\n const text = ProviderShared.encodeJson(requestBody)\n const url = applyQuery(\n `${(input.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\")}${imageReferences.length === 0 ? PATH : EDIT_PATH}`,\n http?.query,\n )\n const headers = yield* Auth.toEffect(input.auth)({\n request,\n method: \"POST\",\n url,\n body: text,\n headers: Headers.fromInput({ ...input.headers, ...http?.headers }),\n })\n const response = yield* execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(text, \"application/json\"),\n ),\n )\n const payload = yield* response.json.pipe(\n Effect.mapError(() => invalidOutput(\"Failed to read the xAI Images response\")),\n )\n const decoded = yield* Schema.decodeUnknownEffect(XAIImageResponse)(payload).pipe(\n Effect.mapError(() => invalidOutput(\"xAI Images returned an invalid response\")),\n )\n const images = yield* Effect.forEach(decoded.data, (item, index) => {\n const mediaType = item.mime_type ?? \"application/octet-stream\"\n if (item.b64_json)\n return Effect.fromResult(Encoding.decodeBase64(item.b64_json)).pipe(\n Effect.mapError(() => invalidOutput(`xAI Images result ${index} contains invalid base64 data`)),\n Effect.map(\n (data) =>\n new GeneratedImage({\n mediaType,\n data,\n providerMetadata:\n item.revised_prompt === undefined || item.revised_prompt === null\n ? undefined\n : { xai: { revisedPrompt: item.revised_prompt } },\n }),\n ),\n )\n if (item.url)\n return Effect.succeed(\n new GeneratedImage({\n mediaType,\n data: item.url,\n providerMetadata:\n item.revised_prompt === undefined || item.revised_prompt === null\n ? undefined\n : { xai: { revisedPrompt: item.revised_prompt } },\n }),\n )\n return Effect.fail(invalidOutput(`xAI Images result ${index} has neither image data nor a URL`))\n })\n if (images.length === 0) return yield* invalidOutput(\"xAI Images returned no images\")\n const usage = ProviderShared.isRecord(decoded.usage) ? decoded.usage : undefined\n return new ImageResponse({\n images,\n usage: usage === undefined ? undefined : new Usage({ providerMetadata: { xai: usage } }),\n providerMetadata: usage === undefined ? undefined : { xai: { usage } },\n })\n }),\n }\n return ImageModel.make<XAIImageOptions>({ id: input.id, provider: \"xai\", route, http: input.http })\n}\n\nexport const XAIImages = {\n model,\n} as const\n", | ||
| "import { AuthOptions, type ProviderAuthOption } from \"../route/auth-options\"\nimport type { RouteDefaultsInput } from \"../route/client\"\nimport { HttpOptions, ProviderID, type ModelID } from \"../schema\"\nimport * as OpenAICompatibleProfiles from \"./openai-compatible-profile\"\nimport * as OpenAICompatibleChat from \"../protocols/openai-compatible-chat\"\nimport * as OpenAIResponses from \"../protocols/openai-responses\"\nimport { XAIImages } from \"../protocols/xai-images\"\n\nexport const id = ProviderID.make(\"xai\")\n\nexport type ModelOptions = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n }\n\nexport type { XAIImageOptions } from \"../protocols/xai-images\"\n\nexport const routes = [OpenAIResponses.route, OpenAICompatibleChat.route]\n\nconst auth = (options: ProviderAuthOption<\"optional\">) => AuthOptions.bearer(options, \"XAI_API_KEY\")\n\nconst configuredResponsesRoute = (input: ModelOptions) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n return OpenAIResponses.route.with({\n ...rest,\n provider: id,\n endpoint: { baseURL: baseURL ?? OpenAICompatibleProfiles.profiles.xai.baseURL },\n auth: auth(input),\n })\n}\n\nconst configuredChatRoute = (input: ModelOptions) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n return OpenAICompatibleChat.route.with({\n ...rest,\n provider: id,\n endpoint: { baseURL: baseURL ?? OpenAICompatibleProfiles.profiles.xai.baseURL },\n auth: auth(input),\n })\n}\n\nexport const configure = (input: ModelOptions = {}) => {\n const responsesRoute = configuredResponsesRoute(input)\n const chatRoute = configuredChatRoute(input)\n const responses = (modelID: string | ModelID) => responsesRoute.model({ id: modelID })\n const chat = (modelID: string | ModelID) => chatRoute.model({ id: modelID })\n const image = (modelID: string | ModelID) =>\n XAIImages.model({\n id: modelID,\n auth: auth(input),\n baseURL: input.baseURL ?? OpenAICompatibleProfiles.profiles.xai.baseURL,\n headers: input.headers,\n http: input.http === undefined ? undefined : HttpOptions.make(input.http),\n })\n return {\n id,\n model: responses,\n responses,\n chat,\n image,\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model = provider.model\nexport const responses = provider.responses\nexport const chat = provider.chat\nexport const image = provider.image\n" | ||
| ], | ||
| "mappings": ";4yBAeA,SAAM,OAAU,kBACH,OAAmB,2BACnB,OAAO,2BACP,OAAY,qBAgDnB,OAAmB,OAAO,YAAO,MACrC,UAAM,OAAO,WACX,EAAO,OAAO,CACZ,SAAU,EAAa,EAAO,MAAM,EACpC,IAAK,EAAa,EAAO,MAAM,EAC/B,eAAgB,EAAa,EAAO,MAAM,EAC1C,UAAW,EAAa,EAAO,MAAM,CACvC,CAAC,CACH,EACA,MAAO,EAAO,SAAS,EAAO,OAAO,CACvC,CAAC,EAUK,EAAgB,CAAC,IAAyC,CAC9D,GAAI,CAAC,EAAS,OACd,IAAQ,cAAa,oBAAmB,GAAW,EACnD,MAAO,CACL,aAAc,EACd,gBAAiB,KACd,CACL,GAGI,EAAgB,CAAC,IACrB,IAAI,EAAS,CACX,OAAQ,EACR,OAAQ,WACR,OAAQ,IAAI,EAA4B,CAAE,UAAS,MAAO,CAAQ,CAAC,CACrE,CAAC,EAEG,EAAa,CAAC,EAAa,IAA8C,CAC7E,GAAI,CAAC,EAAO,OAAO,EACnB,IAAM,EAAO,IAAI,IAAI,CAAG,EAExB,OADA,OAAO,QAAQ,CAAK,EAAE,QAAQ,EAAE,EAAK,KAAW,EAAK,aAAa,IAAI,EAAK,CAAK,CAAC,EAC1E,EAAK,SAAS,GAGV,GAAQ,CAAC,IAAsB,CAC1C,IAAM,EAAqC,CACzC,GAAI,EACJ,SAAU,EAAO,GAAG,oBAAoB,EAAE,SAAU,CAAC,EAA2C,EAAS,CACvG,IAAM,EAAO,EAAiB,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,KAAM,EAAO,aAAY,GAAS,EACrD,OAAuB,EAAM,KAAK,IAC7B,EACH,SAAU,EACV,SAAU,CAAE,QAAS,GAAoC,EAAS,IAAI,OAAQ,EAC9E,KAAM,EAAK,CAAK,CAClB,CAAC,GAGG,GAAsB,CAAC,IAAwB,CACnD,IAAQ,OAAQ,EAAG,KAAM,EAAO,aAAY,GAAS,EACrD,OAA4B,EAAM,KAAK,IAClC,EACH,SAAU,EACV,SAAU,CAAE,QAAS,GAAoC,EAAS,IAAI,OAAQ,EAC9E,KAAM,EAAK,CAAK,CAClB,CAAC,GAGU,EAAY,CAAC,EAAsB,CAAC,IAAM,CACrD,IAAM,EAAiB,GAAyB,CAAK,EAC/C,EAAY,GAAoB,CAAK,EACrC,EAAY,CAAC,IAA8B,EAAe,MAAM,CAAE,GAAI,CAAQ,CAAC,EAUrF,MAAO,CACL,KACA,MAAO,EACP,YACA,KAbW,CAAC,IAA8B,EAAU,MAAM,CAAE,GAAI,CAAQ,CAAC,EAczE,MAbY,CAAC,IACb,EAAU,MAAM,CACd,GAAI,EACJ,KAAM,EAAK,CAAK,EAChB,QAAS,EAAM,SAAoC,EAAS,IAAI,QAChE,QAAS,EAAM,QACf,KAAM,EAAM,OAAS,OAAY,OAAY,EAAY,KAAK,EAAM,IAAI,CAC1E,CAAC,EAOD,WACF,GAGW,EAAW,EAAU,EACrB,GAAQ,EAAS,MACjB,GAAY,EAAS,UACrB,GAAO,EAAS,KAChB,GAAQ,EAAS", | ||
| "debugId": "322AAA3035C260A364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-login@3.972.66/node_modules/@aws-sdk/credential-provider-login/dist-es/fromLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-login@3.972.66/node_modules/@aws-sdk/credential-provider-login/dist-es/LoginCredentialsFetcher.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { LoginCredentialsFetcher } from \"./LoginCredentialsFetcher\";\nexport const fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => {\n init?.logger?.debug?.(\"@aws-sdk/credential-providers - fromLoginCredentials\");\n const profiles = await parseKnownFiles(init || {});\n const profileName = getProfileName({\n profile: init?.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile?.login_session) {\n throw new CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, {\n tryNextLink: true,\n logger: init?.logger,\n });\n }\n const fetcher = new LoginCredentialsFetcher(profile, init, callerClientConfig);\n const credentials = await fetcher.loadCredentials();\n return setCredentialFeature(credentials, \"CREDENTIALS_LOGIN\", \"AD\");\n};\n", | ||
| "import { CredentialsProviderError, readFile } from \"@smithy/core/config\";\nimport { HttpRequest } from \"@smithy/core/protocols\";\nimport { createHash, createPrivateKey, createPublicKey, sign } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nexport class LoginCredentialsFetcher {\n profileData;\n init;\n callerClientConfig;\n static REFRESH_THRESHOLD = 5 * 60 * 1000;\n constructor(profileData, init, callerClientConfig) {\n this.profileData = profileData;\n this.init = init;\n this.callerClientConfig = callerClientConfig;\n }\n async loadCredentials() {\n const token = await this.loadToken();\n if (!token) {\n throw new CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger });\n }\n const accessToken = token.accessToken;\n const now = Date.now();\n const expiryTime = new Date(accessToken.expiresAt).getTime();\n const timeUntilExpiry = expiryTime - now;\n if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) {\n return this.refresh(token);\n }\n return {\n accessKeyId: accessToken.accessKeyId,\n secretAccessKey: accessToken.secretAccessKey,\n sessionToken: accessToken.sessionToken,\n accountId: accessToken.accountId,\n expiration: new Date(accessToken.expiresAt),\n };\n }\n get logger() {\n return this.init?.logger;\n }\n get loginSession() {\n return this.profileData.login_session;\n }\n async refresh(token) {\n const { SigninClient, CreateOAuth2TokenCommand } = await import(\"@aws-sdk/nested-clients/signin\");\n const { logger, userAgentAppId } = this.callerClientConfig ?? {};\n const isH2 = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\";\n };\n const requestHandler = isH2(this.callerClientConfig?.requestHandler)\n ? undefined\n : this.callerClientConfig?.requestHandler;\n const region = this.profileData.region ?? (await this.callerClientConfig?.region?.()) ?? process.env.AWS_REGION;\n const client = new SigninClient({\n credentials: {\n accessKeyId: \"\",\n secretAccessKey: \"\",\n },\n region,\n requestHandler,\n logger,\n userAgentAppId,\n ...this.init?.clientConfig,\n });\n this.createDPoPInterceptor(client.middlewareStack);\n const commandInput = {\n tokenInput: {\n clientId: token.clientId,\n refreshToken: token.refreshToken,\n grantType: \"refresh_token\",\n },\n };\n try {\n const response = await client.send(new CreateOAuth2TokenCommand(commandInput));\n const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {};\n const { refreshToken, expiresIn } = response.tokenOutput ?? {};\n if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) {\n throw new CredentialsProviderError(\"Token refresh response missing required fields\", {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n const expiresInMs = (expiresIn ?? 900) * 1000;\n const expiration = new Date(Date.now() + expiresInMs);\n const updatedToken = {\n ...token,\n accessToken: {\n ...token.accessToken,\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiresAt: expiration.toISOString(),\n },\n refreshToken,\n };\n await this.saveToken(updatedToken);\n const newAccessToken = updatedToken.accessToken;\n return {\n accessKeyId: newAccessToken.accessKeyId,\n secretAccessKey: newAccessToken.secretAccessKey,\n sessionToken: newAccessToken.sessionToken,\n accountId: newAccessToken.accountId,\n expiration,\n };\n }\n catch (error) {\n if (error.name === \"AccessDeniedException\") {\n const errorType = error.error;\n let message;\n switch (errorType) {\n case \"TOKEN_EXPIRED\":\n message = \"Your session has expired. Please reauthenticate.\";\n break;\n case \"USER_CREDENTIALS_CHANGED\":\n message =\n \"Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.\";\n break;\n case \"INSUFFICIENT_PERMISSIONS\":\n message =\n \"Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.\";\n break;\n default:\n message = `Failed to refresh token: ${String(error)}. Please re-authenticate using \\`aws login\\``;\n }\n throw new CredentialsProviderError(message, { logger: this.logger, tryNextLink: false });\n }\n throw new CredentialsProviderError(`Failed to refresh token: ${String(error)}. Please re-authenticate using aws login`, { logger: this.logger });\n }\n }\n async loadToken() {\n const tokenFilePath = this.getTokenFilePath();\n try {\n let tokenData;\n try {\n tokenData = await readFile(tokenFilePath, { ignoreCache: this.init?.ignoreCache });\n }\n catch {\n tokenData = await fs.readFile(tokenFilePath, \"utf8\");\n }\n const token = JSON.parse(tokenData);\n const missingFields = [\"accessToken\", \"clientId\", \"refreshToken\", \"dpopKey\"].filter((k) => !token[k]);\n if (!token.accessToken?.accountId) {\n missingFields.push(\"accountId\");\n }\n if (missingFields.length > 0) {\n throw new CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(\", \")}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n return token;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error)}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n }\n async saveToken(token) {\n const tokenFilePath = this.getTokenFilePath();\n const directory = dirname(tokenFilePath);\n try {\n await fs.mkdir(directory, { recursive: true });\n }\n catch (error) {\n }\n await fs.writeFile(tokenFilePath, JSON.stringify(token, null, 2), \"utf8\");\n }\n getTokenFilePath() {\n const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join(homedir(), \".aws\", \"login\", \"cache\");\n const loginSessionBytes = Buffer.from(this.loginSession, \"utf8\");\n const loginSessionSha256 = createHash(\"sha256\").update(loginSessionBytes).digest(\"hex\");\n return join(directory, `${loginSessionSha256}.json`);\n }\n derToRawSignature(derSignature) {\n let offset = 2;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const rLength = derSignature[offset++];\n let r = derSignature.subarray(offset, offset + rLength);\n offset += rLength;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const sLength = derSignature[offset++];\n let s = derSignature.subarray(offset, offset + sLength);\n r = r[0] === 0x00 ? r.subarray(1) : r;\n s = s[0] === 0x00 ? s.subarray(1) : s;\n const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]);\n const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]);\n return Buffer.concat([rPadded, sPadded]);\n }\n createDPoPInterceptor(middlewareStack) {\n middlewareStack.add((next) => async (args) => {\n if (HttpRequest.isInstance(args.request)) {\n const request = args.request;\n const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : \"\"}${request.path}`;\n const dpop = await this.generateDpop(request.method, actualEndpoint);\n request.headers = {\n ...request.headers,\n DPoP: dpop,\n };\n }\n return next(args);\n }, {\n step: \"finalizeRequest\",\n name: \"dpopInterceptor\",\n override: true,\n });\n }\n async generateDpop(method = \"POST\", endpoint) {\n const token = await this.loadToken();\n try {\n const privateKey = createPrivateKey({\n key: token.dpopKey,\n format: \"pem\",\n type: \"sec1\",\n });\n const publicKey = createPublicKey(privateKey);\n const publicDer = publicKey.export({ format: \"der\", type: \"spki\" });\n let pointStart = -1;\n for (let i = 0; i < publicDer.length; i++) {\n if (publicDer[i] === 0x04) {\n pointStart = i;\n break;\n }\n }\n const x = publicDer.slice(pointStart + 1, pointStart + 33);\n const y = publicDer.slice(pointStart + 33, pointStart + 65);\n const header = {\n alg: \"ES256\",\n typ: \"dpop+jwt\",\n jwk: {\n kty: \"EC\",\n crv: \"P-256\",\n x: x.toString(\"base64url\"),\n y: y.toString(\"base64url\"),\n },\n };\n const payload = {\n jti: crypto.randomUUID(),\n htm: method,\n htu: endpoint,\n iat: Math.floor(Date.now() / 1000),\n };\n const headerB64 = Buffer.from(JSON.stringify(header)).toString(\"base64url\");\n const payloadB64 = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const message = `${headerB64}.${payloadB64}`;\n const asn1Signature = sign(\"sha256\", Buffer.from(message), privateKey);\n const rawSignature = this.derToRawSignature(asn1Signature);\n const signatureB64 = rawSignature.toString(\"base64url\");\n return `${message}.${signatureB64}`;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to generate Dpop proof: ${error instanceof Error ? error.message : String(error)}`, { logger: this.logger, tryNextLink: false });\n }\n }\n}\n" | ||
| ], | ||
| "mappings": ";iMAAA,oBACA,gBCDA,oBACA,WACA,qBAAS,sBAAY,qBAAkB,UAAiB,eACxD,mBAAS,WACT,kBAAS,WACT,kBAAS,UAAS,aACX,MAAM,CAAwB,CACjC,YACA,KACA,yBACO,mBAAoB,OAC3B,WAAW,CAAC,EAAa,EAAM,EAAoB,CAC/C,KAAK,YAAc,EACnB,KAAK,KAAO,EACZ,KAAK,mBAAqB,OAExB,gBAAe,EAAG,CACpB,IAAM,EAAQ,MAAM,KAAK,UAAU,EACnC,GAAI,CAAC,EACD,MAAM,IAAI,2BAAyB,sCAAsC,KAAK,uDAAwD,CAAE,YAAa,GAAO,OAAQ,KAAK,MAAO,CAAC,EAErL,IAAM,EAAc,EAAM,YACpB,EAAM,KAAK,IAAI,EAGrB,GAFmB,IAAI,KAAK,EAAY,SAAS,EAAE,QAAQ,EACtB,GACd,EAAwB,kBAC3C,OAAO,KAAK,QAAQ,CAAK,EAE7B,MAAO,CACH,YAAa,EAAY,YACzB,gBAAiB,EAAY,gBAC7B,aAAc,EAAY,aAC1B,UAAW,EAAY,UACvB,WAAY,IAAI,KAAK,EAAY,SAAS,CAC9C,KAEA,OAAM,EAAG,CACT,OAAO,KAAK,MAAM,UAElB,aAAY,EAAG,CACf,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M,EAAW,MAAM,kBAAgB,GAAQ,CAAC,CAAC,EAC3C,EAAc,iBAAe,CAC/B,QAAS,GAAM,SAAW,GAAoB,OAClD,CAAC,EACK,EAAU,EAAS,GACzB,GAAI,CAAC,GAAS,cACV,MAAM,IAAI,2BAAyB,WAAW,oCAA+C,CACzF,YAAa,GACb,OAAQ,GAAM,MAClB,CAAC,EAGL,IAAM,EAAc,MADJ,IAAI,EAAwB,EAAS,EAAM,CAAkB,EAC3C,gBAAgB,EAClD,OAAO,uBAAqB,EAAa,oBAAqB,IAAI", | ||
| "debugId": "54BB6C4E806A7D3864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/stop.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.stop,\n Effect.fn(\"cli.service.stop\")(function* () {\n yield* Service.stop(yield* ServiceConfig.options())\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+0BAMA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,UACnC,OAAO,QAAG,uBAAkB,OAAE,cAAU,OAAG,MACzC,WAAO,OAAQ,UAAK,WAAO,OAAc,aAAQ,MAAC,EACnD,CACH", | ||
| "debugId": "C8258D95CE88312564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "963995FD2543E48564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/gemini.ts", "../ai/src/protocols/google-images.ts", "../ai/src/providers/google.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Framing } from \"../route/framing\"\nimport { Protocol } from \"../route/protocol\"\nimport {\n LLMEvent,\n Usage,\n type FinishReason,\n type JsonSchema,\n type LLMRequest,\n type MediaPart,\n type ProviderMetadata,\n type TextPart,\n type ToolCallPart,\n type ToolDefinition,\n type ToolContent,\n} from \"../schema\"\nimport { JsonObject, optionalArray, ProviderShared } from \"./shared\"\nimport { GeminiToolSchema } from \"./utils/gemini-tool-schema\"\nimport { Lifecycle } from \"./utils/lifecycle\"\nimport { ToolSchemaProjection } from \"./utils/tool-schema\"\n\nconst ADAPTER = \"gemini\"\nconst MEDIA_MIMES = new Set<string>(ProviderShared.MEDIA_MIMES)\nexport const DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com/v1beta\"\n\n// =============================================================================\n// Request Body Schema\n// =============================================================================\nconst GeminiTextPart = Schema.Struct({\n text: Schema.String,\n thought: Schema.optional(Schema.Boolean),\n thoughtSignature: Schema.optional(Schema.String),\n})\n\nconst GeminiInlineDataPart = Schema.Struct({\n inlineData: Schema.Struct({\n mimeType: Schema.String,\n data: Schema.String,\n }),\n})\n\nconst GeminiFunctionCallPart = Schema.Struct({\n functionCall: Schema.Struct({\n name: Schema.String,\n args: Schema.Unknown,\n }),\n thoughtSignature: Schema.optional(Schema.String),\n})\n\nconst GeminiFunctionResponsePart = Schema.Struct({\n functionResponse: Schema.Struct({\n name: Schema.String,\n response: Schema.Unknown,\n }),\n})\n\nconst GeminiContentPart = Schema.Union([\n GeminiTextPart,\n GeminiInlineDataPart,\n GeminiFunctionCallPart,\n GeminiFunctionResponsePart,\n])\n\nconst GeminiContent = Schema.Struct({\n role: Schema.Literals([\"user\", \"model\"]),\n parts: Schema.Array(GeminiContentPart),\n})\ntype GeminiContent = Schema.Schema.Type<typeof GeminiContent>\n\nconst GeminiSystemInstruction = Schema.Struct({\n parts: Schema.Array(Schema.Struct({ text: Schema.String })),\n})\n\nconst GeminiFunctionDeclaration = Schema.Struct({\n name: Schema.String,\n description: Schema.String,\n parameters: Schema.optional(JsonObject),\n})\n\nconst GeminiTool = Schema.Struct({\n functionDeclarations: Schema.Array(GeminiFunctionDeclaration),\n})\n\nconst GeminiToolConfig = Schema.Struct({\n functionCallingConfig: Schema.Struct({\n mode: Schema.Literals([\"AUTO\", \"NONE\", \"ANY\"]),\n allowedFunctionNames: optionalArray(Schema.String),\n }),\n})\n\nconst GeminiThinkingConfig = Schema.Struct({\n thinkingBudget: Schema.optional(Schema.Number),\n includeThoughts: Schema.optional(Schema.Boolean),\n})\n\nconst GeminiGenerationConfig = Schema.Struct({\n maxOutputTokens: Schema.optional(Schema.Number),\n temperature: Schema.optional(Schema.Number),\n topP: Schema.optional(Schema.Number),\n topK: Schema.optional(Schema.Number),\n stopSequences: optionalArray(Schema.String),\n thinkingConfig: Schema.optional(GeminiThinkingConfig),\n})\n\nconst GeminiBodyFields = {\n contents: Schema.Array(GeminiContent),\n systemInstruction: Schema.optional(GeminiSystemInstruction),\n tools: optionalArray(GeminiTool),\n toolConfig: Schema.optional(GeminiToolConfig),\n generationConfig: Schema.optional(GeminiGenerationConfig),\n}\nconst GeminiBody = Schema.Struct(GeminiBodyFields)\nexport type GeminiBody = Schema.Schema.Type<typeof GeminiBody>\n\nconst GeminiUsage = Schema.Struct({\n cachedContentTokenCount: Schema.optional(Schema.Number),\n thoughtsTokenCount: Schema.optional(Schema.Number),\n promptTokenCount: Schema.optional(Schema.Number),\n candidatesTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n})\ntype GeminiUsage = Schema.Schema.Type<typeof GeminiUsage>\n\nconst GeminiCandidate = Schema.Struct({\n content: Schema.optional(GeminiContent),\n finishReason: Schema.optional(Schema.String),\n})\n\nconst GeminiEvent = Schema.Struct({\n candidates: optionalArray(GeminiCandidate),\n usageMetadata: Schema.optional(GeminiUsage),\n})\ntype GeminiEvent = Schema.Schema.Type<typeof GeminiEvent>\n\ninterface ParserState {\n readonly finishReason?: string\n readonly hasToolCalls: boolean\n readonly nextToolCallId: number\n readonly usage?: Usage\n readonly lifecycle: Lifecycle.State\n readonly reasoningSignature?: string\n}\n\n// =============================================================================\n// Tool Schema Conversion\n// =============================================================================\n// Tool-schema conversion has two distinct concerns:\n//\n// 1. Sanitize — fix common authoring mistakes Gemini rejects: integer/number\n// enums (must be strings), `required` entries that don't match a property,\n// untyped arrays (`items` must be present), and `properties`/`required`\n// keys on non-object scalars. Mirrors OpenCode's historical Gemini rules.\n//\n// 2. Project — lossy mapping from JSON Schema to Gemini's schema dialect:\n// drop empty objects, derive `nullable: true` from `type: [..., \"null\"]`,\n// coerce `const` to `[const]` enum, recurse properties/items, propagate\n// only an allowlisted set of keys (description, required, format, type,\n// properties, items, allOf, anyOf, oneOf, minLength). Anything outside the\n// allowlist (e.g. `additionalProperties`, `$ref`) is silently dropped.\n//\n// Sanitize runs first, then project. The implementation lives in\n// `utils/gemini-tool-schema` so this protocol keeps the same shape as the other\n// provider protocols.\n\n// =============================================================================\n// Request Lowering\n// =============================================================================\nconst lowerTool = (tool: ToolDefinition, inputSchema: JsonSchema) => ({\n name: tool.name,\n description: tool.description,\n parameters: GeminiToolSchema.convert(inputSchema),\n})\n\nconst lowerToolConfig = (toolChoice: NonNullable<LLMRequest[\"toolChoice\"]>) =>\n ProviderShared.matchToolChoice(\"Gemini\", toolChoice, {\n auto: () => ({ functionCallingConfig: { mode: \"AUTO\" as const } }),\n none: () => ({ functionCallingConfig: { mode: \"NONE\" as const } }),\n required: () => ({ functionCallingConfig: { mode: \"ANY\" as const } }),\n tool: (name) => ({ functionCallingConfig: { mode: \"ANY\" as const, allowedFunctionNames: [name] } }),\n })\n\nconst lowerUserPart = Effect.fn(\"Gemini.lowerUserPart\")(function* (part: TextPart | MediaPart) {\n if (part.type === \"text\") return { text: part.text }\n const media = yield* ProviderShared.validateMedia(\"Gemini\", part, MEDIA_MIMES)\n return { inlineData: { mimeType: media.mime, data: media.base64 } }\n})\n\nconst googleMetadata = (metadata: Record<string, unknown>): ProviderMetadata => ({ google: metadata })\n\nconst thoughtSignature = (providerMetadata: ProviderMetadata | undefined) => {\n const google = providerMetadata?.google\n return ProviderShared.isRecord(google) && typeof google.thoughtSignature === \"string\"\n ? google.thoughtSignature\n : undefined\n}\n\nconst lowerToolCall = (part: ToolCallPart) => ({\n functionCall: { name: part.name, args: part.input },\n thoughtSignature: thoughtSignature(part.providerMetadata),\n})\n\nconst lowerMessages = Effect.fn(\"Gemini.lowerMessages\")(function* (request: LLMRequest) {\n const contents: GeminiContent[] = []\n\n for (const message of request.messages) {\n if (message.role === \"system\") {\n const part = yield* ProviderShared.wrappedSystemUpdate(\"Gemini\", message)\n const previous = contents.at(-1)\n if (previous?.role === \"user\")\n contents[contents.length - 1] = { role: \"user\", parts: [...previous.parts, { text: part.text }] }\n else contents.push({ role: \"user\", parts: [{ text: part.text }] })\n continue\n }\n\n if (message.role === \"user\") {\n const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"media\"]))\n return yield* ProviderShared.unsupportedContent(\"Gemini\", \"user\", [\"text\", \"media\"])\n parts.push(yield* lowerUserPart(part))\n }\n contents.push({ role: \"user\", parts })\n continue\n }\n\n if (message.role === \"assistant\") {\n const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"reasoning\", \"tool-call\"]))\n return yield* ProviderShared.unsupportedContent(\"Gemini\", \"assistant\", [\"text\", \"reasoning\", \"tool-call\"])\n if (part.type === \"text\") {\n parts.push({ text: part.text })\n continue\n }\n if (part.type === \"reasoning\") {\n parts.push({ text: part.text, thought: true, thoughtSignature: thoughtSignature(part.providerMetadata) })\n continue\n }\n if (part.type === \"tool-call\") {\n parts.push(lowerToolCall(part))\n continue\n }\n }\n contents.push({ role: \"model\", parts })\n continue\n }\n\n const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"tool-result\"]))\n return yield* ProviderShared.unsupportedContent(\"Gemini\", \"tool\", [\"tool-result\"])\n if (part.result.type !== \"content\") {\n parts.push({\n functionResponse: {\n name: part.name,\n response: {\n name: part.name,\n content: ProviderShared.toolResultText(part),\n },\n },\n })\n continue\n }\n const content: ReadonlyArray<ToolContent> = part.result.value\n const text = content.filter((item) => item.type === \"text\").map((item) => item.text)\n parts.push({\n functionResponse: {\n name: part.name,\n response: {\n name: part.name,\n content: text.join(\"\\n\"),\n },\n },\n })\n for (const item of content) {\n if (item.type === \"text\") continue\n const media = yield* ProviderShared.validateToolFile(\"Gemini\", item, MEDIA_MIMES)\n parts.push({ inlineData: { mimeType: media.mime, data: media.base64 } })\n }\n }\n contents.push({ role: \"user\", parts })\n }\n\n return contents\n})\n\nconst geminiOptions = (request: LLMRequest) => request.providerOptions?.gemini\n\nconst thinkingConfig = (request: LLMRequest) => {\n const value = geminiOptions(request)?.thinkingConfig\n if (!ProviderShared.isRecord(value)) return undefined\n const result = {\n thinkingBudget: typeof value.thinkingBudget === \"number\" ? value.thinkingBudget : undefined,\n includeThoughts: typeof value.includeThoughts === \"boolean\" ? value.includeThoughts : undefined,\n }\n return Object.values(result).some((item) => item !== undefined) ? result : undefined\n}\n\nconst fromRequest = Effect.fn(\"Gemini.fromRequest\")(function* (request: LLMRequest) {\n const toolsEnabled = request.tools.length > 0 && request.toolChoice?.type !== \"none\"\n const generation = request.generation\n const toolSchemaCompatibility = request.model.compatibility?.toolSchema\n const generationConfig = {\n maxOutputTokens: generation?.maxTokens,\n temperature: generation?.temperature,\n topP: generation?.topP,\n topK: generation?.topK,\n stopSequences: generation?.stop,\n thinkingConfig: thinkingConfig(request),\n }\n\n return {\n contents: yield* lowerMessages(request),\n systemInstruction:\n request.system.length === 0 ? undefined : { parts: [{ text: ProviderShared.joinText(request.system) }] },\n tools: toolsEnabled\n ? [\n {\n functionDeclarations: request.tools.map((tool) =>\n lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),\n ),\n },\n ]\n : undefined,\n toolConfig: toolsEnabled && request.toolChoice ? yield* lowerToolConfig(request.toolChoice) : undefined,\n generationConfig: Object.values(generationConfig).some((value) => value !== undefined)\n ? generationConfig\n : undefined,\n }\n})\n\n// =============================================================================\n// Stream Parsing\n// =============================================================================\n// Gemini reports `promptTokenCount` (inclusive total) with a\n// `cachedContentTokenCount` subset. `candidatesTokenCount` is *exclusive*\n// of `thoughtsTokenCount` — visible-only, not a total — so we sum the two\n// to produce the inclusive `outputTokens` the rest of the contract expects.\nconst mapUsage = (usage: GeminiUsage | undefined) => {\n if (!usage) return undefined\n const cached = usage.cachedContentTokenCount\n const nonCached = ProviderShared.subtractTokens(usage.promptTokenCount, cached)\n // `candidatesTokenCount` is visible-only; sum with thoughts to produce the\n // inclusive `outputTokens` the contract expects. Only compute the total\n // when the visible component is reported — otherwise we'd fabricate an\n // inclusive number from a partial breakdown.\n const outputTokens =\n usage.candidatesTokenCount !== undefined ? usage.candidatesTokenCount + (usage.thoughtsTokenCount ?? 0) : undefined\n return new Usage({\n inputTokens: usage.promptTokenCount,\n outputTokens,\n nonCachedInputTokens: nonCached,\n cacheReadInputTokens: cached,\n reasoningTokens: usage.thoughtsTokenCount,\n totalTokens: ProviderShared.totalTokens(usage.promptTokenCount, outputTokens, usage.totalTokenCount),\n providerMetadata: { google: usage },\n })\n}\n\nconst mapFinishReason = (finishReason: string | undefined, hasToolCalls: boolean): FinishReason => {\n if (finishReason === \"STOP\") return hasToolCalls ? \"tool-calls\" : \"stop\"\n if (finishReason === \"MAX_TOKENS\") return \"length\"\n if (\n finishReason === \"IMAGE_SAFETY\" ||\n finishReason === \"RECITATION\" ||\n finishReason === \"SAFETY\" ||\n finishReason === \"BLOCKLIST\" ||\n finishReason === \"PROHIBITED_CONTENT\" ||\n finishReason === \"SPII\"\n )\n return \"content-filter\"\n if (finishReason === \"MALFORMED_FUNCTION_CALL\") return \"error\"\n return \"unknown\"\n}\n\nconst finish = (state: ParserState): ReadonlyArray<LLMEvent> =>\n state.finishReason || state.usage\n ? (() => {\n const events: LLMEvent[] = []\n const lifecycle = state.reasoningSignature\n ? Lifecycle.reasoningEnd(\n state.lifecycle,\n events,\n \"reasoning-0\",\n googleMetadata({ thoughtSignature: state.reasoningSignature }),\n )\n : state.lifecycle\n Lifecycle.finish(lifecycle, events, {\n reason: mapFinishReason(state.finishReason, state.hasToolCalls),\n usage: state.usage,\n })\n return events\n })()\n : []\n\nconst step = (state: ParserState, event: GeminiEvent) => {\n const nextState = {\n ...state,\n usage: event.usageMetadata ? (mapUsage(event.usageMetadata) ?? state.usage) : state.usage,\n }\n const candidate = event.candidates?.[0]\n if (!candidate?.content)\n return Effect.succeed([\n { ...nextState, finishReason: candidate?.finishReason ?? nextState.finishReason },\n [],\n ] as const)\n\n const events: LLMEvent[] = []\n let hasToolCalls = nextState.hasToolCalls\n let lifecycle = nextState.lifecycle\n let nextToolCallId = nextState.nextToolCallId\n let reasoningSignature = nextState.reasoningSignature\n\n for (const part of candidate.content.parts) {\n if (\"thoughtSignature\" in part && part.thoughtSignature && \"thought\" in part && part.thought)\n reasoningSignature = part.thoughtSignature\n if (\"text\" in part && part.text.length > 0) {\n if (part.thought) {\n lifecycle = Lifecycle.reasoningDelta(\n lifecycle,\n events,\n \"reasoning-0\",\n part.text,\n part.thoughtSignature ? googleMetadata({ thoughtSignature: part.thoughtSignature }) : undefined,\n )\n continue\n }\n lifecycle = Lifecycle.reasoningEnd(\n lifecycle,\n events,\n \"reasoning-0\",\n reasoningSignature ? googleMetadata({ thoughtSignature: reasoningSignature }) : undefined,\n )\n lifecycle = Lifecycle.textDelta(lifecycle, events, \"text-0\", part.text)\n continue\n }\n\n if (\"functionCall\" in part) {\n const input = part.functionCall.args\n const id = `tool_${nextToolCallId++}`\n lifecycle = Lifecycle.reasoningEnd(\n lifecycle,\n events,\n \"reasoning-0\",\n reasoningSignature ? googleMetadata({ thoughtSignature: reasoningSignature }) : undefined,\n )\n lifecycle = Lifecycle.stepStart(lifecycle, events)\n events.push(\n LLMEvent.toolCall({\n id,\n name: part.functionCall.name,\n input,\n providerMetadata: part.thoughtSignature\n ? googleMetadata({ thoughtSignature: part.thoughtSignature })\n : undefined,\n }),\n )\n hasToolCalls = true\n }\n }\n\n return Effect.succeed([\n {\n ...nextState,\n hasToolCalls,\n lifecycle,\n nextToolCallId,\n reasoningSignature,\n finishReason: candidate.finishReason ?? nextState.finishReason,\n },\n events,\n ] as const)\n}\n\n// =============================================================================\n// Protocol And Gemini Route\n// =============================================================================\n/**\n * The Gemini protocol — request body construction, body schema, and the\n * streaming-event state machine. Used by Google AI Studio Gemini and (once\n * registered) Vertex Gemini.\n */\nexport const protocol = Protocol.make({\n id: ADAPTER,\n body: {\n schema: GeminiBody,\n from: fromRequest,\n },\n stream: {\n event: Protocol.jsonEvent(GeminiEvent),\n initial: () => ({ hasToolCalls: false, nextToolCallId: 0, lifecycle: Lifecycle.initial() }),\n step,\n onHalt: finish,\n },\n})\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: \"google\",\n providerMetadataKey: \"google\",\n protocol,\n // Gemini's path embeds the model id and pins SSE framing at the URL level.\n endpoint: Endpoint.path(({ request }) => `/models/${request.model.id}:streamGenerateContent?alt=sse`, {\n baseURL: DEFAULT_BASE_URL,\n }),\n auth: Auth.none,\n framing: Framing.sse,\n})\n\nexport * as Gemini from \"./gemini\"\n", | ||
| "import { Effect, Encoding, Schema } from \"effect\"\nimport { Headers, HttpClientRequest } from \"effect/unstable/http\"\nimport {\n GeneratedImage,\n ImageModel,\n ImageResponse,\n type ImageInput,\n type ImageRequestFor,\n type ImageRoute,\n} from \"../image\"\nimport { Auth, type Definition as AuthDefinition } from \"../route/auth\"\nimport {\n InvalidProviderOutputReason,\n LLMError,\n Usage,\n mergeHttpOptions,\n mergeJsonRecords,\n type HttpOptions,\n type ProviderMetadata,\n} from \"../schema\"\nimport { ProviderShared } from \"./shared\"\nimport { ImageInputs } from \"./utils/image-input\"\n\nconst ADAPTER = \"google-images\"\nexport const DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com/v1beta\"\n\nexport type GoogleImageString<Known extends string> = Known | (string & {})\n\nexport type GoogleImageOptions = {\n readonly aspectRatio?: GoogleImageString<\n \"1:1\" | \"2:3\" | \"3:2\" | \"3:4\" | \"4:3\" | \"4:5\" | \"5:4\" | \"9:16\" | \"16:9\" | \"21:9\"\n >\n readonly imageSize?: GoogleImageString<\"1K\" | \"2K\" | \"4K\">\n readonly seed?: number\n readonly thinkingLevel?: GoogleImageString<\"MINIMAL\" | \"LOW\" | \"MEDIUM\" | \"HIGH\">\n readonly includeThoughts?: boolean\n} & Record<string, unknown>\n\nexport type GoogleImageBody = Record<string, unknown> & {\n readonly contents: ReadonlyArray<{\n readonly role: \"user\"\n readonly parts: ReadonlyArray<Record<string, unknown>>\n }>\n readonly generationConfig: Record<string, unknown>\n}\n\nconst GoogleUsage = Schema.StructWithRest(\n Schema.Struct({\n cachedContentTokenCount: Schema.optional(Schema.Number),\n thoughtsTokenCount: Schema.optional(Schema.Number),\n promptTokenCount: Schema.optional(Schema.Number),\n candidatesTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n promptTokensDetails: Schema.optional(Schema.Unknown),\n candidatesTokensDetails: Schema.optional(Schema.Unknown),\n }),\n [Schema.Record(Schema.String, Schema.Unknown)],\n)\n\nconst GoogleImageResponse = Schema.Struct({\n candidates: Schema.optional(\n Schema.Array(\n Schema.Struct({\n index: Schema.optional(Schema.Number),\n content: Schema.optional(\n Schema.Struct({\n parts: Schema.Array(\n Schema.Struct({\n text: Schema.optional(Schema.String),\n thought: Schema.optional(Schema.Boolean),\n thoughtSignature: Schema.optional(Schema.String),\n inlineData: Schema.optional(\n Schema.Struct({\n mimeType: Schema.String,\n data: Schema.String,\n }),\n ),\n }),\n ),\n }),\n ),\n finishReason: Schema.optional(Schema.String),\n finishMessage: Schema.optional(Schema.String),\n safetyRatings: Schema.optional(Schema.Unknown),\n citationMetadata: Schema.optional(Schema.Unknown),\n groundingMetadata: Schema.optional(Schema.Unknown),\n }),\n ),\n ),\n usageMetadata: Schema.optional(GoogleUsage),\n modelVersion: Schema.optional(Schema.String),\n responseId: Schema.optional(Schema.String),\n promptFeedback: Schema.optional(Schema.Unknown),\n})\n\nexport interface ModelInput {\n readonly id: string\n readonly auth: AuthDefinition\n readonly baseURL?: string\n readonly headers?: Record<string, string>\n readonly http?: HttpOptions\n}\n\nconst nativeOptions = (options: GoogleImageOptions | undefined) => {\n const { aspectRatio, imageSize, seed, thinkingLevel, includeThoughts, ...native } = options ?? {}\n const image = {\n aspectRatio,\n imageSize,\n }\n const thinkingConfig = {\n thinkingLevel,\n includeThoughts,\n }\n return (\n mergeJsonRecords(\n {\n responseModalities: [\"IMAGE\"],\n imageConfig: Object.values(image).some((value) => value !== undefined) ? image : undefined,\n seed,\n thinkingConfig: Object.values(thinkingConfig).some((value) => value !== undefined) ? thinkingConfig : undefined,\n },\n native,\n ) ?? { responseModalities: [\"IMAGE\"] }\n )\n}\n\nconst invalidOutput = (message: string, providerMetadata?: ProviderMetadata) =>\n new LLMError({\n module: ADAPTER,\n method: \"generate\",\n reason: new InvalidProviderOutputReason({ message, route: ADAPTER, providerMetadata }),\n })\n\nconst applyQuery = (url: string, query: Record<string, string> | undefined) => {\n if (!query) return url\n const next = new URL(url)\n Object.entries(query).forEach(([key, value]) => next.searchParams.set(key, value))\n return next.toString()\n}\n\nexport const model = (input: ModelInput) => {\n const route: ImageRoute<GoogleImageOptions> = {\n id: ADAPTER,\n generate: Effect.fn(\"GoogleImages.generate\")(function* (request: ImageRequestFor<GoogleImageOptions>, execute) {\n const imageParts = yield* Effect.forEach(request.images ?? [], googleImagePart)\n const http = mergeHttpOptions(request.model.http, request.http)\n const requestBody = mergeJsonRecords(\n {\n contents: [{ role: \"user\", parts: [{ text: request.prompt }, ...imageParts] }],\n generationConfig: nativeOptions(request.options),\n },\n http?.body,\n ) as GoogleImageBody\n const text = ProviderShared.encodeJson(requestBody)\n const url = applyQuery(\n `${(input.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\")}/models/${request.model.id}:generateContent`,\n http?.query,\n )\n const headers = yield* Auth.toEffect(input.auth)({\n request,\n method: \"POST\",\n url,\n body: text,\n headers: Headers.fromInput({ ...input.headers, ...http?.headers }),\n })\n const response = yield* execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(text, \"application/json\"),\n ),\n )\n const payload = yield* response.json.pipe(\n Effect.mapError(() => invalidOutput(\"Failed to read the Google Images response\")),\n )\n const decoded = yield* Schema.decodeUnknownEffect(GoogleImageResponse)(payload).pipe(\n Effect.mapError(() => invalidOutput(\"Google Images returned an invalid response\")),\n )\n const candidates = decoded.candidates ?? []\n const candidateMetadata = candidates.map((candidate, candidateIndex) => ({\n index: candidate.index ?? candidateIndex,\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n citationMetadata: candidate.citationMetadata,\n groundingMetadata: candidate.groundingMetadata,\n parts: (candidate.content?.parts ?? []).map((part) =>\n part.inlineData === undefined\n ? {\n type: \"text\",\n text: part.text,\n thought: part.thought,\n thoughtSignature: part.thoughtSignature,\n }\n : {\n type: \"inlineData\",\n mediaType: part.inlineData.mimeType,\n thought: part.thought,\n thoughtSignature: part.thoughtSignature,\n },\n ),\n }))\n const encoded = candidates.flatMap((candidate, candidateIndex) =>\n (candidate.content?.parts ?? []).flatMap((part, partIndex) =>\n part.inlineData === undefined || part.thought === true\n ? []\n : [{ candidate, candidateIndex, partIndex, inlineData: part.inlineData }],\n ),\n )\n const images = yield* Effect.forEach(encoded, (item) =>\n Effect.fromResult(Encoding.decodeBase64(item.inlineData.data)).pipe(\n Effect.mapError(() =>\n invalidOutput(\n `Google Images candidate ${item.candidateIndex} part ${item.partIndex} contains invalid base64 data`,\n ),\n ),\n Effect.map(\n (data) =>\n new GeneratedImage({\n mediaType: item.inlineData.mimeType,\n data,\n providerMetadata: {\n google: {\n candidateIndex: item.candidate.index ?? item.candidateIndex,\n partIndex: item.partIndex,\n finishReason: item.candidate.finishReason,\n safetyRatings: item.candidate.safetyRatings,\n citationMetadata: item.candidate.citationMetadata,\n groundingMetadata: item.candidate.groundingMetadata,\n thoughtSignature: item.candidate.content?.parts[item.partIndex]?.thoughtSignature,\n },\n },\n }),\n ),\n ),\n )\n if (images.length === 0) {\n const finishReasons = candidates.flatMap((candidate) =>\n candidate.finishReason === undefined ? [] : [candidate.finishReason],\n )\n return yield* invalidOutput(\n `Google Images returned no final images${\n finishReasons.length === 0 ? \"\" : ` (finish reasons: ${finishReasons.join(\", \")})`\n }; inspect reason.providerMetadata.google for prompt feedback and candidate details`,\n {\n google: {\n promptFeedback: decoded.promptFeedback,\n candidates: candidateMetadata,\n },\n },\n )\n }\n const usage = decoded.usageMetadata\n const outputTokens =\n usage?.candidatesTokenCount === undefined\n ? undefined\n : usage.candidatesTokenCount + (usage.thoughtsTokenCount ?? 0)\n return new ImageResponse({\n images,\n usage:\n usage === undefined\n ? undefined\n : new Usage({\n inputTokens: usage.promptTokenCount,\n outputTokens,\n nonCachedInputTokens: ProviderShared.subtractTokens(\n usage.promptTokenCount,\n usage.cachedContentTokenCount,\n ),\n cacheReadInputTokens: usage.cachedContentTokenCount,\n reasoningTokens: usage.thoughtsTokenCount,\n totalTokens: ProviderShared.totalTokens(usage.promptTokenCount, outputTokens, usage.totalTokenCount),\n providerMetadata: { google: usage },\n }),\n providerMetadata: {\n google: {\n modelVersion: decoded.modelVersion,\n responseId: decoded.responseId,\n promptFeedback: decoded.promptFeedback,\n candidates: candidateMetadata,\n },\n },\n })\n }),\n }\n return ImageModel.make<GoogleImageOptions>({ id: input.id, provider: \"google\", route, http: input.http })\n}\n\nconst googleImagePart = (image: ImageInput): Effect.Effect<Record<string, unknown>, LLMError> => {\n if (image.type === \"bytes\")\n return Effect.succeed({ inlineData: { mimeType: image.mediaType, data: Encoding.encodeBase64(image.data) } })\n if (image.type === \"file-uri\") return Effect.succeed({ fileData: { mimeType: image.mediaType, fileUri: image.uri } })\n if (image.type === \"url\")\n return ImageInputs.decodeDataUrl(image.url, ADAPTER).pipe(\n Effect.flatMap((decoded) => {\n if (decoded === undefined)\n return Effect.fail(\n ImageInputs.invalid(\n ADAPTER,\n \"Google generateContent does not fetch public image URLs; use bytes, a data URL, or a Gemini file URI\",\n ),\n )\n return Effect.succeed({\n inlineData: { mimeType: decoded.mediaType, data: Encoding.encodeBase64(decoded.data) },\n })\n }),\n )\n return Effect.fail(\n ImageInputs.invalid(ADAPTER, \"Google generateContent requires Gemini file URIs rather than provider file IDs\"),\n )\n}\n\nexport const GoogleImages = {\n model,\n} as const\n", | ||
| "import type { RouteDefaultsInput } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport type { ProviderAuthOption } from \"../route/auth-options\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { HttpOptions, ProviderID, mergeHttpOptions, type ModelID, type ProviderOptions } from \"../schema\"\nimport { Gemini } from \"../protocols/gemini\"\nimport { GoogleImages } from \"../protocols/google-images\"\n\nexport type { GoogleImageOptions } from \"../protocols/google-images\"\n\nexport const id = ProviderID.make(\"google\")\n\nexport const routes = [Gemini.route]\n\nexport type Config = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n }\n\nexport interface Settings extends ProviderPackage.Settings {\n readonly apiKey?: string\n readonly baseURL?: string\n readonly providerOptions?: ProviderOptions\n}\n\nconst auth = (options: ProviderAuthOption<\"optional\">) => {\n if (\"auth\" in options && options.auth) return options.auth\n return Auth.optional(\"apiKey\" in options ? options.apiKey : undefined, \"apiKey\")\n .orElse(Auth.config(\"GOOGLE_GENERATIVE_AI_API_KEY\"))\n .pipe(Auth.header(\"x-goog-api-key\"))\n}\n\nconst configuredRoute = (input: Config) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n return Gemini.route.with({ ...rest, endpoint: { baseURL }, auth: auth(input) })\n}\n\nexport const configure = (input: Config = {}) => {\n const route = configuredRoute(input)\n const image = (modelID: string | ModelID) =>\n GoogleImages.model({\n id: modelID,\n auth: auth(input),\n baseURL: input.baseURL,\n headers: input.headers,\n http: mergeHttpOptions(input.http === undefined ? undefined : HttpOptions.make(input.http)),\n })\n return {\n id,\n model: (modelID: string | ModelID) => route.model({ id: modelID }),\n image,\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure({\n apiKey: settings.apiKey,\n baseURL: settings.baseURL,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n providerOptions: settings.providerOptions,\n }).model(modelID)\n\nexport const image = provider.image\n" | ||
| ], | ||
| "mappings": ";ytBAwBA,SAAM,OAAU,cACV,OAAc,SAAI,SAAY,OAAe,gBAAW,OACjD,OAAmB,mDAK1B,GAAiB,EAAO,OAAO,CACnC,KAAM,EAAO,OACb,QAAS,EAAO,SAAS,EAAO,OAAO,EACvC,iBAAkB,EAAO,SAAS,EAAO,MAAM,CACjD,CAAC,EAEK,GAAuB,EAAO,OAAO,CACzC,WAAY,EAAO,OAAO,CACxB,SAAU,EAAO,OACjB,KAAM,EAAO,MACf,CAAC,CACH,CAAC,EAEK,GAAyB,EAAO,OAAO,CAC3C,aAAc,EAAO,OAAO,CAC1B,KAAM,EAAO,OACb,KAAM,EAAO,OACf,CAAC,EACD,iBAAkB,EAAO,SAAS,EAAO,MAAM,CACjD,CAAC,EAEK,GAA6B,EAAO,OAAO,CAC/C,iBAAkB,EAAO,OAAO,CAC9B,KAAM,EAAO,OACb,SAAU,EAAO,OACnB,CAAC,CACH,CAAC,EAEK,GAAoB,EAAO,MAAM,CACrC,GACA,GACA,GACA,EACF,CAAC,EA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AAE,CAAC,GAGnE,EAAY,CAAC,EAAgB,CAAC,IAAM,CAC/C,IAAM,EAAQ,GAAgB,CAAK,EASnC,MAAO,CACL,MACA,MAAO,CAAC,IAA8B,EAAM,MAAM,CAAE,GAAI,CAAQ,CAAC,EACjE,MAXY,CAAC,IACb,GAAa,MAAM,CACjB,GAAI,EACJ,KAAM,GAAK,CAAK,EAChB,QAAS,EAAM,QACf,QAAS,EAAM,QACf,KAAM,EAAiB,EAAM,OAAS,OAAY,OAAY,GAAY,KAAK,EAAM,IAAI,CAAC,CAC5F,CAAC,EAKD,WACF,GAGW,GAAW,EAAU,EACrB,GAAuD,CAAC,EAAS,IAC5E,EAAU,CACR,OAAQ,EAAS,OACjB,QAAS,EAAS,QAClB,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,OACjB,gBAAiB,EAAS,eAC5B,CAAC,EAAE,MAAM,CAAO,EAEL,GAAQ,GAAS", | ||
| "debugId": "E9FD687BAA44B3B664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/set.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.set,\n Effect.fn(\"cli.service.set\")(function* (input) {\n yield* ServiceConfig.set(input.key, input.value)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";k0BAKA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,SACnC,OAAO,QAAG,sBAAiB,OAAE,cAAU,MAAC,OAAO,MAC7C,WAAO,OAAc,SAAI,OAAM,SAAK,OAAM,KAAK,EAChD,CACH", | ||
| "debugId": "217B0F21A34BBE0E64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name: name14,\n message,\n cause\n }) {\n super(message);\n this[_a] = true;\n this.name = name14;\n this.cause = cause;\n }\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error) {\n return _AISDKError.hasMarker(error, marker);\n }\n static hasMarker(error, marker15) {\n const markerSymbol = Symbol.for(marker15);\n return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500),\n // server error\n data\n }) {\n super({ name, message, cause });\n this[_a2] = true;\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker2);\n }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n // used in isInstance\n constructor({ message = \"Empty response body\" } = {}) {\n super({ name: name2, message });\n this[_a3] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker3);\n }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n constructor({\n message,\n cause,\n argument\n }) {\n super({ name: name3, message, cause });\n this[_a4] = true;\n this.argument = argument;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker4);\n }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n constructor({\n prompt,\n message,\n cause\n }) {\n super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n this[_a5] = true;\n this.prompt = prompt;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker5);\n }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`\n }) {\n super({ name: name5, message });\n this[_a6] = true;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker6);\n }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n constructor({ text, cause }) {\n super({\n name: name6,\n message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a7] = true;\n this.text = text;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker7);\n }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name7, message });\n this[_a8] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker8);\n }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name8, message });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker9);\n }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n // used in isInstance\n constructor({\n message = \"No content generated.\"\n } = {}) {\n super({ name: name9, message });\n this[_a10] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker10);\n }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n constructor({\n errorName = name10,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`\n }) {\n super({ name: errorName, message });\n this[_a11] = true;\n this.modelId = modelId;\n this.modelType = modelType;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker11);\n }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n constructor(options) {\n super({\n name: name11,\n message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n });\n this[_a12] = true;\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker12);\n }\n};\n\n// src/errors/type-validation-error.ts\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n constructor({\n value,\n cause,\n context\n }) {\n let contextPrefix = \"Type validation failed\";\n if (context == null ? void 0 : context.field) {\n contextPrefix += ` for ${context.field}`;\n }\n if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n contextPrefix += \" (\";\n const parts = [];\n if (context.entityName) {\n parts.push(context.entityName);\n }\n if (context.entityId) {\n parts.push(`id: \"${context.entityId}\"`);\n }\n contextPrefix += parts.join(\", \");\n contextPrefix += \")\";\n }\n super({\n name: name12,\n message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\n this.context = context;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker13);\n }\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n context\n }) {\n var _a15, _b15, _c;\n if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {\n return cause;\n }\n return new _TypeValidationError({ value, cause, context });\n }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`\n }) {\n super({ name: name13, message });\n this[_a14] = true;\n this.functionality = functionality;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker14);\n }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n if (typeof value === \"object\") {\n return Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n }\n return false;\n}\nfunction isJSONArray(value) {\n return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n return value != null && typeof value === \"object\" && Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n}\nexport {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidArgumentError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n getErrorMessage,\n isJSONArray,\n isJSONObject,\n isJSONValue\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";AACA,IAAI,EAAS,kBACT,GAAS,OAAO,IAAI,CAAM,EAC1B,EAAI,EACJ,EAAa,MAAM,UAAqB,EAAK,MAAO,EAAK,GAAQ,EAAI,CASvE,WAAW,EACT,KAAM,EACN,UACA,SACC,CACD,MAAM,CAAO,EACb,KAAK,GAAM,GACX,KAAK,KAAO,EACZ,KAAK,MAAQ,QAOR,WAAU,CAAC,EAAO,CACvB,OAAO,EAAY,UAAU,EAAO,CAAM,QAErC,UAAS,CAAC,EAAO,EAAU,CAChC,IAAM,EAAe,OAAO,IAAI,CAAQ,EACxC,OAAO,GAAS,MAAQ,OAAO,IAAU,UAAY,KAAgB,GAAS,OAAO,EAAM,KAAkB,WAAa,EAAM,KAAkB,GAEtJ,EAGI,EAAO,kBACP,EAAU,mBAAmB,IAC7B,GAAU,OAAO,IAAI,CAAO,EAC5B,EAAK,EACL,GAAe,cAAe,EAAM,EAAY,EAAM,G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,EAET,OAAO,IAAI,EAAqB,CAAE,QAAO,QAAO,SAAQ,CAAC,EAE7D,EAGI,GAAS,mCACT,GAAW,mBAAmB,KAC9B,GAAW,OAAO,IAAI,EAAQ,EAC9B,EAAM,EACN,GAAgC,cAAe,EAAO,EAAY,EAAO,GAAU,EAAM,CAC3F,WAAW,EACT,gBACA,UAAU,IAAI,mCACb,CACD,MAAM,CAAE,KAAM,GAAQ,SAAQ,CAAC,EAC/B,KAAK,GAAQ,GACb,KAAK,cAAgB,QAEhB,WAAU,CAAC,EAAO,CACvB,OAAO,EAAW,UAAU,EAAO,EAAQ,EAE/C", | ||
| "debugId": "E63BC2D296E57CD464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.33/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSigninHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"signin\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSigninHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateOAuth2Token\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"signin\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.32\";\nvar packageInfo = {\n\tversion: version};\n\nconst s = \"ref\";\nconst a = -1, b = false, c = true, d = \"isSet\", e = \"booleanEquals\", f = \"coalesce\", g = \"PartitionResult\", h = \"stringEquals\", i = \"getAttr\", j = \"https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}\", k = { [s]: \"Endpoint\" }, l = { \"fn\": i, \"argv\": [{ [s]: g }, \"name\"] }, m = { [s]: \"Region\" }, n = { [s]: g }, o = { \"authSchemes\": [{ \"name\": \"sigv4\", \"signingName\": \"signin\", \"signingRegion\": \"{Region}\" }] }, p = {}, q = [m];\nconst _data = {\n conditions: [\n [d, q],\n [e, [{ fn: f, argv: [{ [s]: \"IsControlPlane\" }, b] }, c]],\n [d, [k]],\n [\"aws.partition\", q, g],\n [e, [{ [s]: \"UseFIPS\" }, c]],\n [h, [l, \"aws\"]],\n [e, [{ fn: f, argv: [{ [s]: \"IsOAuthEndpoint\" }, b] }, c]],\n [e, [{ [s]: \"UseDualStack\" }, c]],\n [h, [l, \"aws-cn\"]],\n [h, [m, \"us-gov-west-1\"]],\n [h, [l, \"aws-us-gov\"]],\n [e, [{ fn: i, argv: [n, \"supportsFIPS\"] }, c]],\n [h, [l, \"aws-iso\"]],\n [h, [l, \"aws-iso-b\"]],\n [h, [l, \"aws-iso-f\"]],\n [h, [l, \"aws-iso-e\"]],\n [h, [l, \"aws-eusc\"]],\n [e, [{ fn: i, argv: [n, \"supportsDualStack\"] }, c]]\n ],\n results: [\n [a],\n [\"https://signin.{Region}.api.aws\", o],\n [\"https://signin.{Region}.api.amazonwebservices.com.cn\", o],\n [j, o],\n [a, \"FIPS endpoints are not supported for OAuth operations. Disable FIPS or use a non-OAuth operation.\"],\n [\"https://{Region}.oauth.signin.aws\", o],\n [\"https://{Region}.signin.aws.amazon.com\", p],\n [\"https://{Region}.signin.amazonaws.cn\", p],\n [\"https://{Region}.signin.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin.c2shome.ic.gov\", p],\n [\"https://{Region}.signin.sc2shome.sgov.gov\", p],\n [\"https://{Region}.signin.csphome.hci.ic.gov\", p],\n [\"https://{Region}.signin.csphome.adc-e.uk\", p],\n [\"https://{Region}.signin.amazonaws-eusc.eu\", p],\n [\"https://signin-fips.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin-fips.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin.{PartitionResult#dnsSuffix}\", p],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [k, p],\n [\"https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", p],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://signin-fips.{Region}.{PartitionResult#dnsSuffix}\", p],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [j, p],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://signin.{Region}.{PartitionResult#dnsSuffix}\", p],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 6, 3,\n 2, 36, 4,\n 4, 5, r + 27,\n 6, r + 4, r + 27,\n 1, 29, 7,\n 2, 36, 8,\n 3, 9, 31,\n 4, 22, 10,\n 5, 19, 11,\n 7, 21, 12,\n 8, r + 7, 13,\n 10, r + 8, 14,\n 12, r + 9, 15,\n 13, r + 10, 16,\n 14, r + 11, 17,\n 15, r + 12, 18,\n 16, r + 13, r + 16,\n 6, r + 5, 20,\n 7, 21, r + 6,\n 17, r + 24, r + 25,\n 6, r + 4, 23,\n 7, 27, 24,\n 9, r + 14, 25,\n 10, r + 15, 26,\n 11, r + 22, r + 23,\n 11, 28, r + 21,\n 17, r + 20, r + 21,\n 2, 35, 30,\n 3, 39, 31,\n 4, 32, r + 27,\n 6, r + 4, 33,\n 7, r + 27, 34,\n 9, r + 14, r + 27,\n 3, 39, 36,\n 4, 38, 37,\n 7, r + 18, r + 19,\n 6, r + 4, r + 17,\n 5, r + 1, 40,\n 8, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"IsControlPlane\", \"IsOAuthEndpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SigninServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SigninServiceException.prototype);\n }\n}\n\nclass AccessDeniedException extends SigninServiceException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n }\n}\nclass InternalServerException extends SigninServiceException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n }\n}\nclass TooManyRequestsError extends SigninServiceException {\n name = \"TooManyRequestsError\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"TooManyRequestsError\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n this.error = opts.error;\n }\n}\nclass ValidationException extends SigninServiceException {\n name = \"ValidationException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"ValidationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ValidationException.prototype);\n this.error = opts.error;\n }\n}\n\nconst _ADE = \"AccessDeniedException\";\nconst _AT = \"AccessToken\";\nconst _COAT = \"CreateOAuth2Token\";\nconst _COATR = \"CreateOAuth2TokenRequest\";\nconst _COATRB = \"CreateOAuth2TokenRequestBody\";\nconst _COATRBr = \"CreateOAuth2TokenResponseBody\";\nconst _COATRr = \"CreateOAuth2TokenResponse\";\nconst _COATWIAM = \"CreateOAuth2TokenWithIAM\";\nconst _COATWIAMR = \"CreateOAuth2TokenWithIAMRequest\";\nconst _COATWIAMRr = \"CreateOAuth2TokenWithIAMResponse\";\nconst _ISE = \"InternalServerException\";\nconst _OAAT = \"OAuthAccessToken\";\nconst _RT = \"RefreshToken\";\nconst _TMRE = \"TooManyRequestsError\";\nconst _VE = \"ValidationException\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _at = \"access_token\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ei = \"expires_in\";\nconst _gT = \"grantType\";\nconst _gt = \"grant_type\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _jN = \"jsonName\";\nconst _m = \"message\";\nconst _r = \"resource\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.signin\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _se = \"server\";\nconst _tI = \"tokenInput\";\nconst _tO = \"tokenOutput\";\nconst _tT = \"tokenType\";\nconst _tt = \"token_type\";\nconst n0 = \"com.amazonaws.signin\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SigninServiceException$ = [-3, _s, \"SigninServiceException\", 0, [], []];\n_s_registry.registerError(SigninServiceException$, SigninServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar AccessDeniedException$ = [-3, n0, _ADE,\n { [_e]: _c },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(AccessDeniedException$, AccessDeniedException);\nvar InternalServerException$ = [-3, n0, _ISE,\n { [_e]: _se, [_hE]: 500 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(InternalServerException$, InternalServerException);\nvar TooManyRequestsError$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(TooManyRequestsError$, TooManyRequestsError);\nvar ValidationException$ = [-3, n0, _VE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(ValidationException$, ValidationException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar OAuthAccessToken = [0, n0, _OAAT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nvar AccessToken$ = [3, n0, _AT,\n 8,\n [_aKI, _sAK, _sT],\n [[0, { [_jN]: _aKI }], [0, { [_jN]: _sAK }], [0, { [_jN]: _sT }]], 3\n];\nvar CreateOAuth2TokenRequest$ = [3, n0, _COATR,\n 0,\n [_tI],\n [[() => CreateOAuth2TokenRequestBody$, 16]], 1\n];\nvar CreateOAuth2TokenRequestBody$ = [3, n0, _COATRB,\n 0,\n [_cI, _gT, _co, _rU, _cV, _rT],\n [[0, { [_jN]: _cI }], [0, { [_jN]: _gT }], 0, [0, { [_jN]: _rU }], [0, { [_jN]: _cV }], [() => RefreshToken, { [_jN]: _rT }]], 2\n];\nvar CreateOAuth2TokenResponse$ = [3, n0, _COATRr,\n 0,\n [_tO],\n [[() => CreateOAuth2TokenResponseBody$, 16]], 1\n];\nvar CreateOAuth2TokenResponseBody$ = [3, n0, _COATRBr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken$, { [_jN]: _aT }], [0, { [_jN]: _tT }], [1, { [_jN]: _eI }], [() => RefreshToken, { [_jN]: _rT }], [0, { [_jN]: _iT }]], 4\n];\nvar CreateOAuth2TokenWithIAMRequest$ = [3, n0, _COATWIAMR,\n 0,\n [_gT, _r],\n [[0, { [_jN]: _gt }], 0], 2\n];\nvar CreateOAuth2TokenWithIAMResponse$ = [3, n0, _COATWIAMRr,\n 0,\n [_aT, _tT, _eI],\n [[() => OAuthAccessToken, { [_jN]: _at }], [0, { [_jN]: _tt }], [1, { [_jN]: _ei }]], 3\n];\nvar CreateOAuth2Token$ = [9, n0, _COAT,\n { [_h]: [\"POST\", \"/v1/token\", 200] }, () => CreateOAuth2TokenRequest$, () => CreateOAuth2TokenResponse$\n];\nvar CreateOAuth2TokenWithIAM$ = [9, n0, _COATWIAM,\n { [_h]: [\"POST\", \"/v1/token?x-amz-client-auth-method=iam\", 200] }, () => CreateOAuth2TokenWithIAMRequest$, () => CreateOAuth2TokenWithIAMResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2023-01-01\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSigninHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.signin\",\n errorTypeRegistries,\n version: \"2023-01-01\",\n serviceTarget: \"Signin\",\n },\n serviceId: config?.serviceId ?? \"Signin\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SigninClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSigninHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"Signin\", \"SigninClient\", getEndpointPlugin);\nconst _ep0 = {\n IsControlPlane: { type: \"staticContextParams\", value: false },\n};\nconst _ep1 = {\n IsOAuthEndpoint: { type: \"staticContextParams\", value: true },\n};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass CreateOAuth2TokenCommand extends command(_ep0, _mw0, \"CreateOAuth2Token\", CreateOAuth2Token$) {\n}\n\nclass CreateOAuth2TokenWithIAMCommand extends command(_ep1, _mw0, \"CreateOAuth2TokenWithIAM\", CreateOAuth2TokenWithIAM$) {\n}\n\nconst commands = {\n CreateOAuth2TokenCommand,\n CreateOAuth2TokenWithIAMCommand,\n};\nclass Signin extends SigninClient {\n}\ncreateAggregatedClient(commands, Signin);\n\nconst OAuth2ErrorCode = {\n AUTHCODE_EXPIRED: \"AUTHCODE_EXPIRED\",\n CONFLICT: \"CONFLICT\",\n INSUFFICIENT_PERMISSIONS: \"INSUFFICIENT_PERMISSIONS\",\n INVALID_REQUEST: \"INVALID_REQUEST\",\n RESOURCE_NOT_FOUND: \"RESOURCE_NOT_FOUND\",\n SERVER_ERROR: \"server_error\",\n SERVICE_QUOTA_EXCEEDED: \"SERVICE_QUOTA_EXCEEDED\",\n TOKEN_EXPIRED: \"TOKEN_EXPIRED\",\n USER_CREDENTIALS_CHANGED: \"USER_CREDENTIALS_CHANGED\",\n};\n\nexports.AccessDeniedException = AccessDeniedException;\nexports.AccessDeniedException$ = AccessDeniedException$;\nexports.AccessToken$ = AccessToken$;\nexports.CreateOAuth2Token$ = CreateOAuth2Token$;\nexports.CreateOAuth2TokenCommand = CreateOAuth2TokenCommand;\nexports.CreateOAuth2TokenRequest$ = CreateOAuth2TokenRequest$;\nexports.CreateOAuth2TokenRequestBody$ = CreateOAuth2TokenRequestBody$;\nexports.CreateOAuth2TokenResponse$ = CreateOAuth2TokenResponse$;\nexports.CreateOAuth2TokenResponseBody$ = CreateOAuth2TokenResponseBody$;\nexports.CreateOAuth2TokenWithIAM$ = CreateOAuth2TokenWithIAM$;\nexports.CreateOAuth2TokenWithIAMCommand = CreateOAuth2TokenWithIAMCommand;\nexports.CreateOAuth2TokenWithIAMRequest$ = CreateOAuth2TokenWithIAMRequest$;\nexports.CreateOAuth2TokenWithIAMResponse$ = CreateOAuth2TokenWithIAMResponse$;\nexports.InternalServerException = InternalServerException;\nexports.InternalServerException$ = InternalServerException$;\nexports.OAuth2ErrorCode = OAuth2ErrorCode;\nexports.Signin = Signin;\nexports.SigninClient = SigninClient;\nexports.SigninServiceException = SigninServiceException;\nexports.SigninServiceException$ = SigninServiceException$;\nexports.TooManyRequestsError = TooManyRequestsError;\nexports.TooManyRequestsError$ = TooManyRequestsError$;\nexports.ValidationException = ValidationException;\nexports.ValidationException$ = ValidationException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";+VAAA,SAAQ,6BAAsB,qCAAiC,QAAmC,uCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,qBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,UAAQ,eAAa,iCACnN,QAAS,SACjB,IAAQ,GAAW,GACX,GAAW,GACnB,IAAQ,6BAA2B,aAAY,yCAAuC,8CAA4C,8BAA4B,mCAAiC,8BACvL,yBAAuB,iBAAe,kBAAgB,2BAAyB,yBAAuB,4BACtG,YAAU,wCAAsC,mCAAiC,iCACjF,sBAAoB,kCAAgC,mCAAiC,sBAAoB,yBACzG,gBAAc,+BACd,4BAA0B,qBAAmB,8CAC7C,UAAQ,YAAU,YAAU,cAAY,8BACxC,mBAAiB,0BACjB,8BACA,gBAEF,GAAgD,MAAO,EAAQ,EAAS,IAAU,CACpF,MAAO,CACH,UAAW,GAAiB,CAAO,EAAE,UACrC,OAAQ,MAAM,GAAkB,EAAO,MAAM,EAAE,IAAM,IAAM,CACvD,M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B,EAAkB,CAAE,CACpG,CAEA,MAAM,UAAwC,GAAQ,GAAM,GAAM,2BAA4B,EAAyB,CAAE,CACzH,CAEA,IAAM,GAAW,CACb,2BACA,iCACJ,EACA,MAAM,UAAe,CAAa,CAClC,CACA,GAAuB,GAAU,CAAM,EAEvC,IAAM,GAAkB,CACpB,iBAAkB,mBAClB,SAAU,WACV,yBAA0B,2BAC1B,gBAAiB,kBACjB,mBAAoB,qBACpB,aAAc,eACd,uBAAwB,yBACxB,cAAe,gBACf,yBAA0B,0BAC9B,EAEA,IAAQ,GAAwB,EACxB,GAAyB,GACzB,GAAe,GACf,GAAqB,GACrB,GAA2B,EAC3B,GAA4B,GAC5B,GAAgC,GAChC,GAA6B,GAC7B,GAAiC,GACjC,GAA4B,GAC5B,GAAkC,EAClC,GAAmC,GACnC,GAAoC,GACpC,GAA0B,EAC1B,GAA2B,GAC3B,GAAkB,GAClB,GAAS,EACT,GAAe,EACf,GAAyB,EACzB,GAA0B,GAC1B,GAAuB,EACvB,GAAwB,GACxB,GAAsB,EACtB,GAAuB,GACvB,GAAsB", | ||
| "debugId": "DE00E40CFAAA44EA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "5AF8BF55D2FC6BA964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.61/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.61/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.61/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.61/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nimport { NodeHttpHandler } from \"@smithy/node-http-handler\";\nimport fs from \"node:fs/promises\";\nimport { checkUrl } from \"./checkUrl\";\nimport { createGetRequest, getCredentials } from \"./requestHelpers\";\nimport { retryWrapper } from \"./retry-wrapper\";\nconst AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nconst DEFAULT_LINK_LOCAL_HOST = \"http://169.254.170.2\";\nconst AWS_CONTAINER_CREDENTIALS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = \"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromHttp = (options = {}) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-http - fromHttp\");\n let host;\n const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];\n const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];\n const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];\n const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];\n const warn = options.logger?.constructor?.name === \"NoOpLogger\" || !options.logger?.warn\n ? console.warn\n : options.logger.warn.bind(options.logger);\n if (relative && full) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.\");\n warn(\"awsContainerCredentialsRelativeUri will take precedence.\");\n }\n if (token && tokenFile) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.\");\n warn(\"awsContainerAuthorizationTokenFile will take precedence.\");\n }\n if (relative) {\n host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;\n }\n else if (full) {\n host = full;\n }\n else {\n throw new CredentialsProviderError(`No HTTP credential provider host provided.\nSet AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });\n }\n const url = new URL(host);\n checkUrl(url, options.logger);\n const requestHandler = NodeHttpHandler.create({ connectionTimeout: options.timeout ?? 1000 });\n const requestTimeout = options.timeout ?? 1000;\n const provider = retryWrapper(async () => {\n const request = createGetRequest(url);\n if (tokenFile) {\n request.headers.Authorization = validateToken((await fs.readFile(tokenFile)).toString());\n }\n else if (token) {\n request.headers.Authorization = validateToken(token);\n }\n try {\n const result = await requestHandler.handle(request, { requestTimeout });\n return getCredentials(result.response).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_HTTP\", \"z\"));\n }\n catch (e) {\n throw new CredentialsProviderError(String(e), { logger: options.logger });\n }\n }, options.maxRetries ?? 3, options.timeout ?? 1000);\n return async () => {\n try {\n return await provider();\n }\n finally {\n requestHandler.destroy?.();\n }\n };\n};\nconst validateToken = (token) => {\n if (token.includes(\"\\r\\n\")) {\n throw new CredentialsProviderError(\"Authorization token contains invalid \\\\r\\\\n sequence.\");\n }\n return token;\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nconst LOOPBACK_CIDR_IPv4 = \"127.0.0.0/8\";\nconst LOOPBACK_CIDR_IPv6 = \"::1/128\";\nconst ECS_CONTAINER_HOST = \"169.254.170.2\";\nconst EKS_CONTAINER_HOST_IPv4 = \"169.254.170.23\";\nconst EKS_CONTAINER_HOST_IPv6 = \"[fd00:ec2::23]\";\nexport const checkUrl = (url, logger) => {\n if (url.protocol === \"https:\") {\n return;\n }\n if (url.hostname === ECS_CONTAINER_HOST ||\n url.hostname === EKS_CONTAINER_HOST_IPv4 ||\n url.hostname === EKS_CONTAINER_HOST_IPv6) {\n return;\n }\n if (url.hostname.includes(\"[\")) {\n if (url.hostname === \"[::1]\" || url.hostname === \"[0000:0000:0000:0000:0000:0000:0000:0001]\") {\n return;\n }\n }\n else {\n if (url.hostname === \"localhost\") {\n return;\n }\n const ipComponents = url.hostname.split(\".\");\n const inRange = (component) => {\n const num = parseInt(component, 10);\n return 0 <= num && num <= 255;\n };\n if (ipComponents[0] === \"127\" &&\n inRange(ipComponents[1]) &&\n inRange(ipComponents[2]) &&\n inRange(ipComponents[3]) &&\n ipComponents.length === 4) {\n return;\n }\n }\n throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:\n - loopback CIDR 127.0.0.0/8 or [::1/128]\n - ECS container host 169.254.170.2\n - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger });\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { HttpRequest } from \"@smithy/core/protocols\";\nimport { parseRfc3339DateTime } from \"@smithy/core/serde\";\nimport { sdkStreamMixin } from \"@smithy/core/serde\";\nexport function createGetRequest(url) {\n return new HttpRequest({\n protocol: url.protocol,\n hostname: url.hostname,\n port: Number(url.port),\n path: url.pathname,\n query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => {\n acc[k] = v;\n return acc;\n }, {}),\n fragment: url.hash,\n });\n}\nexport async function getCredentials(response, logger) {\n const stream = sdkStreamMixin(response.body);\n const str = await stream.transformToString();\n if (response.statusCode === 200) {\n const parsed = JSON.parse(str);\n if (typeof parsed.AccessKeyId !== \"string\" ||\n typeof parsed.SecretAccessKey !== \"string\" ||\n typeof parsed.Token !== \"string\" ||\n typeof parsed.Expiration !== \"string\") {\n throw new CredentialsProviderError(\"HTTP credential provider response not of the required format, an object matching: \" +\n \"{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }\", { logger });\n }\n return {\n accessKeyId: parsed.AccessKeyId,\n secretAccessKey: parsed.SecretAccessKey,\n sessionToken: parsed.Token,\n expiration: parseRfc3339DateTime(parsed.Expiration),\n };\n }\n if (response.statusCode >= 400 && response.statusCode < 500) {\n let parsedBody = {};\n try {\n parsedBody = JSON.parse(str);\n }\n catch (e) { }\n throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), {\n Code: parsedBody.Code,\n Message: parsedBody.Message,\n });\n }\n throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger });\n}\n", | ||
| "export const retryWrapper = (toRetry, maxRetries, delayMs) => {\n return async () => {\n for (let i = 0; i < maxRetries; ++i) {\n try {\n return await toRetry();\n }\n catch (e) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n return await toRetry();\n };\n};\n" | ||
| ], | ||
| "mappings": ";wPAAA,oBACA,gBACA,gBACA,gCCHA,eAGA,IAAM,EAAqB,gBACrB,EAA0B,iBAC1B,EAA0B,iBACnB,EAAW,CAAC,EAAK,IAAW,CACrC,GAAI,EAAI,WAAa,SACjB,OAEJ,GAAI,EAAI,WAAa,GACjB,EAAI,WAAa,GACjB,EAAI,WAAa,EACjB,OAEJ,GAAI,EAAI,SAAS,SAAS,GAAG,GACzB,GAAI,EAAI,WAAa,SAAW,EAAI,WAAa,4CAC7C,OAGH,KACD,GAAI,EAAI,WAAa,YACjB,OAEJ,IAAM,EAAe,EAAI,SAAS,MAAM,GAAG,EACrC,EAAU,CAAC,IAAc,CAC3B,IAAM,EAAM,SAAS,EAAW,EAAE,EAClC,MAAO,IAAK,GAAO,GAAO,KAE9B,GAAI,EAAa,KAAO,OACpB,EAAQ,EAAa,EAAE,GACvB,EAAQ,EAAa,EAAE,GACvB,EAAQ,EAAa,EAAE,GACvB,EAAa,SAAW,EACxB,OAGR,MAAM,IAAI,2BAAyB;AAAA;AAAA;AAAA,yDAGmB,CAAE,QAAO,CAAC,GCxCpE,eACA,WACA,WACA,WACO,SAAS,CAAgB,CAAC,EAAK,CAClC,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U,uBAAqB,EAAO,mBAAoB,GAAG,CAAC,EAE/G,MAAO,EAAG,CACN,MAAM,IAAI,2BAAyB,OAAO,CAAC,EAAG,CAAE,OAAQ,EAAQ,MAAO,CAAC,IAE7E,EAAQ,YAAc,EAAG,EAAQ,SAAW,IAAI,EACnD,MAAO,UAAY,CACf,GAAI,CACA,OAAO,MAAM,EAAS,SAE1B,CACI,EAAe,UAAU,KAI/B,EAAgB,CAAC,IAAU,CAC7B,GAAI,EAAM,SAAS;AAAA,CAAM,EACrB,MAAM,IAAI,2BAAyB,uDAAuD,EAE9F,OAAO", | ||
| "debugId": "4490416A1AD1E6F664756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/server-process.ts", "src/commands/handlers/serve.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ServerProcess from \"./server-process\"\n\nimport { NodeServices } from \"@effect/platform-node\"\nimport { Service, type DiscoverOptions, type Info } from \"@opencode-ai/client/effect/service\"\nimport { LayerNode } from \"@opencode-ai/util/effect/layer-node\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { OPENCODE_CHANNEL, OPENCODE_VERSION } from \"./version\"\nimport { AppProcess } from \"@opencode-ai/util/process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport path from \"node:path\"\nimport { Effect, FileSystem, Logger, Option, Redacted, Schedule, Schema } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { Env } from \"./env\"\nimport { ServiceConfig } from \"./services/service-config\"\nimport { Updater } from \"./services/updater\"\n\nexport type Mode = \"default\" | \"service\" | \"stdio\"\n\nexport type Options = {\n readonly mode: Mode\n readonly hostname?: string\n readonly port?: number\n}\n\n// The process effect lives until server shutdown; tracing it would parent every request to one process-lifetime trace.\nexport const run = Effect.fnUntraced(function* (options: Options) {\n return yield* processEffect(options).pipe(\n Effect.provide(Updater.layer),\n Effect.provide(\n LayerNode.compile(LayerNode.group([Global.node, AppProcess.node]), [\n [\n Global.node,\n Global.layerWith(process.env.OPENCODE_CONFIG_DIR ? { config: process.env.OPENCODE_CONFIG_DIR } : {}),\n ],\n ]),\n ),\n Effect.provide(NodeServices.layer),\n )\n})\n\nconst processEffect = Effect.fnUntraced(function* (options: Options) {\n if (options.mode === \"service\") yield* Effect.sync(() => process.chdir(Global.Path.home))\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const serviceOptions = options.mode === \"service\" ? yield* ServiceConfig.options() : undefined\n const config = options.mode === \"service\" ? yield* ServiceConfig.read() : {}\n const hostname = options.hostname ?? config.hostname ?? \"127.0.0.1\"\n const port = options.port ?? config.port ?? (options.mode === \"service\" ? ServiceConfig.defaultPort() : undefined)\n if (\n serviceOptions !== undefined &&\n port !== undefined &&\n (yield* Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })) !== undefined\n )\n return\n const { start } = yield* Effect.promise(() => import(\"@opencode-ai/server/process\"))\n const environmentPassword = yield* Env.password\n // Keep the lease credential out of the environment inherited by tools.\n if (options.mode === \"stdio\") {\n delete process.env.OPENCODE_PASSWORD\n delete process.env.OPENCODE_SERVER_PASSWORD\n }\n const password =\n options.mode === \"service\"\n ? config.password || randomBytes(32).toString(\"base64url\")\n : environmentPassword\n ? Redacted.value(environmentPassword)\n : randomBytes(32).toString(\"base64url\")\n if (!password) return yield* Effect.fail(new Error(\"Missing server password\"))\n const instanceID = randomUUID()\n const server = yield* start(\n {\n app: {\n name: process.env.OPENCODE_CLIENT ?? \"cli\",\n version: OPENCODE_VERSION,\n channel: OPENCODE_CHANNEL,\n },\n hostname,\n port,\n password,\n simulation: truthy(process.env.OPENCODE_SIMULATE),\n database: {\n path:\n process.env.OPENCODE_DB ??\n ([\"latest\", \"beta\", \"prod\"].includes(OPENCODE_CHANNEL) ||\n process.env.OPENCODE_DISABLE_CHANNEL_DB === \"1\" ||\n process.env.OPENCODE_DISABLE_CHANNEL_DB === \"true\"\n ? \"opencode.db\"\n : `opencode-${OPENCODE_CHANNEL.replace(/[^a-zA-Z0-9._-]/g, \"-\")}.db`),\n },\n models: {\n url: process.env.OPENCODE_MODELS_URL,\n file: process.env.OPENCODE_MODELS_PATH,\n fetch: !truthy(process.env.OPENCODE_DISABLE_MODELS_FETCH),\n },\n observability: {\n endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,\n headers: process.env.OTEL_EXPORTER_OTLP_HEADERS,\n },\n config: {\n directory: process.env.OPENCODE_CONFIG_DIR,\n project: !truthy(\n process.env.OPENCODE_CONFIG_PROJECT_DISABLE ?? process.env.OPENCODE_DISABLE_PROJECT_CONFIG,\n ),\n file: process.env.OPENCODE_CONFIG,\n content: process.env.OPENCODE_CONFIG_CONTENT,\n },\n windows: {\n gitbash: process.env.OPENCODE_GIT_BASH_PATH,\n },\n fs: {\n filewatcher: !truthy(\n process.env.OPENCODE_FILEWATCHER_DISABLE ?? process.env.OPENCODE_DISABLE_FILEWATCHER,\n ),\n fff:\n process.env.OPENCODE_DISABLE_FFF === undefined\n ? process.platform !== \"win32\"\n : !truthy(process.env.OPENCODE_DISABLE_FFF),\n },\n },\n serviceOptions === undefined\n ? undefined\n : {\n instanceID,\n onListen: (address, shutdown) =>\n Effect.gen(function* () {\n if (!config.password) yield* ServiceConfig.password(password)\n return yield* register(address, password, instanceID, serviceOptions.file, shutdown)\n }),\n },\n ).pipe(\n Effect.provide(Logger.layer([], { mergeWithExisting: false })),\n Effect.catch((error) => {\n if (serviceOptions === undefined || port === undefined || !addressInUse(error)) return Effect.fail(error)\n return recognizeIncumbent(serviceOptions, hostname, port).pipe(\n Effect.flatMap((found) =>\n found\n ? Effect.void\n : Effect.fail(\n new Error(\n `Managed service port ${port} on ${hostname} is already in use by another process. ` +\n \"Configure another port with `opencode service set port <port>` and start the service again.\",\n { cause: error },\n ),\n ),\n ),\n )\n }),\n )\n if (server === undefined) return\n const url = HttpServer.formatAddress(server.address)\n console.log(options.mode === \"stdio\" ? JSON.stringify({ url }) : `server listening on ${url}`)\n if (options.mode === \"default\" && !environmentPassword) console.log(`server password ${password}`)\n const updater = yield* Updater.Service\n yield* updater.check().pipe(Effect.schedule(Schedule.spaced(\"10 minutes\")), Effect.forkScoped)\n return yield* options.mode === \"service\"\n ? server.shutdown\n : options.mode === \"stdio\"\n ? waitForStdinClose()\n : Effect.never\n }).pipe(Effect.annotateLogs({ role: \"server\" })),\n )\n})\n\nconst infoJson = Schema.fromJsonString(Service.Info)\nconst encodeInfo = Schema.encodeEffect(infoJson)\nconst decodeInfo = Schema.decodeUnknownEffect(infoJson)\n\nconst register = Effect.fnUntraced(function* (\n address: HttpServer.Address,\n password: string,\n id: string,\n file: string,\n shutdown: Effect.Effect<void>,\n) {\n const fs = yield* FileSystem.FileSystem\n const temp = file + \".\" + id + \".tmp\"\n yield* fs.makeDirectory(path.dirname(file), { recursive: true })\n const info = {\n id,\n version: OPENCODE_VERSION,\n url: HttpServer.formatAddress(address),\n pid: process.pid,\n password,\n }\n const encoded = yield* encodeInfo(info)\n const current = fs.readFileString(file).pipe(\n Effect.flatMap(decodeInfo),\n Effect.orElseSucceed(() => undefined),\n )\n const owns = (found: Info | undefined) =>\n found?.id === info.id &&\n found.version === info.version &&\n found.url === info.url &&\n found.pid === info.pid &&\n found.password === info.password\n yield* fs.writeFileString(temp, encoded, { mode: 0o600 }).pipe(Effect.andThen(fs.rename(temp, file)))\n yield* current.pipe(\n Effect.filterOrFail(owns),\n Effect.repeat(Schedule.spaced(\"5 seconds\")),\n Effect.ignore,\n Effect.andThen(shutdown),\n Effect.forkScoped,\n )\n return current.pipe(\n Effect.flatMap((found) => (owns(found) ? fs.remove(file) : Effect.void)),\n Effect.ignore,\n )\n})\n\nconst recognizeIncumbent = Effect.fnUntraced(function* (options: DiscoverOptions, hostname: string, port: number) {\n const found = yield* Service.incumbent({ ...options, url: serviceURL(hostname, port) }).pipe(\n Effect.filterOrFail((value) => value !== undefined),\n Effect.retry(Schedule.spaced(\"100 millis\")),\n Effect.timeoutOption(\"15 seconds\"),\n )\n return Option.isSome(found)\n})\n\nfunction serviceURL(hostname: string, port: number) {\n return `http://${hostname.includes(\":\") ? `[${hostname}]` : hostname}:${port}`\n}\n\nfunction truthy(value?: string) {\n return value === \"1\" || value?.toLowerCase() === \"true\"\n}\n\nfunction addressInUse(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false\n if (\"code\" in error && error.code === \"EADDRINUSE\") return true\n return \"cause\" in error && addressInUse(error.cause)\n}\n\nfunction waitForStdinClose() {\n return Effect.callback<void>((resume) => {\n const close = () => resume(Effect.void)\n process.stdin.once(\"end\", close)\n process.stdin.once(\"close\", close)\n process.stdin.resume()\n if (process.stdin.readableEnded || process.stdin.destroyed) close()\n return Effect.sync(() => {\n process.stdin.off(\"end\", close)\n process.stdin.off(\"close\", close)\n process.stdin.pause()\n })\n })\n}\n", | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerProcess } from \"../../server-process\"\n\nexport default Runtime.handler(\n Commands.commands.serve,\n Effect.fnUntraced(function* (input) {\n if (input.service && input.stdio) return yield* Effect.fail(new Error(\"--service and --stdio cannot be combined\"))\n return yield* ServerProcess.run({\n mode: input.service ? \"service\" : input.stdio ? \"stdio\" : \"default\",\n hostname: Option.getOrUndefined(input.hostname),\n port: Option.getOrUndefined(input.port),\n })\n }),\n)\n" | ||
| ], | ||
| "mappings": ";0kCAQA,2BAAS,qBAAa,oBACtB,yBAgBO,SAAM,OAAM,OAAO,gBAAW,cAAU,MAAC,OAAkB,MAChE,YAAO,WAAO,OAAc,MAAO,OAAE,UACnC,OAAO,aAAQ,OAAQ,UAAK,OAC5B,EAAO,QACL,EAAU,QAAQ,EAAU,MAAM,CAAC,EAAO,KAAM,EAAW,IAAI,CAAC,EAAG,CACjE,CACE,EAAO,KACP,EAAO,UAAU,QAAQ,IAAI,oBAAsB,CAAE,OAAQ,QAAQ,IAAI,mBAAoB,EAAI,CAAC,C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AM,UAAW,EAAM,EAClE,OAAO,EAAO,KAAK,IAAM,CACvB,QAAQ,MAAM,IAAI,MAAO,CAAK,EAC9B,QAAQ,MAAM,IAAI,QAAS,CAAK,EAChC,QAAQ,MAAM,MAAM,EACrB,EACF,EC/OH,IAAe,KAAQ,QACrB,EAAS,SAAS,MAClB,EAAO,WAAW,SAAU,CAAC,EAAO,CAClC,GAAI,EAAM,SAAW,EAAM,MAAO,OAAO,MAAO,EAAO,KAAS,MAAM,0CAA0C,CAAC,EACjH,OAAO,MAAO,EAAc,IAAI,CAC9B,KAAM,EAAM,QAAU,UAAY,EAAM,MAAQ,QAAU,UAC1D,SAAU,EAAO,eAAe,EAAM,QAAQ,EAC9C,KAAM,EAAO,eAAe,EAAM,IAAI,CACxC,CAAC,EACF,CACH", | ||
| "debugId": "0F18A970B4CBC59064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/services/server-connection.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint, type EnsureOptions } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, isUnauthorizedError, OpenCode } from \"@opencode-ai/client/promise\"\nimport { OPENCODE_VERSION } from \"../version\"\nimport { Effect, Redacted } from \"effect\"\nimport { Env } from \"../env\"\nimport { ServiceConfig } from \"./service-config\"\nimport { Standalone } from \"./standalone\"\n\nexport type Args = {\n readonly server?: string\n readonly standalone?: boolean\n readonly mismatch?: \"replace\" | \"ignore\" | \"error\"\n readonly onStart?: EnsureOptions[\"onStart\"]\n}\n\nexport type Resolved = {\n readonly endpoint: Endpoint\n readonly service?: ReturnType<typeof managedService>\n}\n\nexport const resolve = Effect.fn(\"cli.server-connection.resolve\")(function* (args: Args) {\n if (args.server !== undefined && args.standalone)\n return yield* Effect.fail(new Error(\"--server and --standalone cannot be combined\"))\n if (args.server !== undefined) {\n const password = yield* Env.password\n const endpoint = {\n url: args.server,\n auth: password ? { type: \"basic\" as const, username: \"opencode\", password: Redacted.value(password) } : undefined,\n } satisfies Endpoint\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const health = yield* Effect.tryPromise({\n try: () => client.health.get({ signal: AbortSignal.timeout(5_000) }),\n catch: (cause) => connectError(endpoint, cause),\n })\n if (health.version !== OPENCODE_VERSION)\n process.stderr.write(\n `Warning: Server at ${endpoint.url} has version ${health.version}; this client is ${OPENCODE_VERSION}. Continuing anyway.\\n`,\n )\n return { endpoint } satisfies Resolved\n }\n if (args.standalone) {\n return { endpoint: yield* Standalone.start() } satisfies Resolved\n }\n\n const options = yield* ServiceConfig.options()\n return {\n endpoint: yield* resolveManaged({ ...options, onStart: args.onStart }, args.mismatch ?? \"replace\"),\n service: managedService(options),\n } satisfies Resolved\n})\n\nfunction managedService(options: EnsureOptions) {\n const reconnectOptions = { ...options, version: undefined }\n return {\n reconnect: () => Service.ensure(reconnectOptions),\n restart: () =>\n Effect.gen(function* () {\n yield* Service.stop(options)\n yield* Service.ensure(reconnectOptions)\n }),\n }\n}\n\nconst resolveManaged = Effect.fnUntraced(function* (\n options: EnsureOptions,\n mismatch: NonNullable<Args[\"mismatch\"]>,\n) {\n if (mismatch === \"replace\") return yield* Service.ensure(options)\n if (mismatch === \"ignore\") return yield* Service.ensure({ ...options, version: undefined })\n\n const compatible = yield* Service.discover(options)\n if (compatible !== undefined) return compatible\n const existing = yield* Service.discover({ ...options, version: undefined })\n if (existing !== undefined)\n return yield* Effect.fail(new Error(\"Background server version does not match this client\"))\n return yield* Service.ensure(options)\n})\n\nfunction connectError(endpoint: Endpoint, cause: unknown) {\n if (isUnauthorizedError(cause)) {\n return new Error(\n endpoint.auth === undefined\n ? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`\n : `Server at ${endpoint.url} rejected the password`,\n { cause },\n )\n }\n if (cause instanceof ClientError && cause.reason === \"Transport\")\n return new Error(`Could not reach server at ${endpoint.url}`, { cause })\n return new Error(`Server at ${endpoint.url} did not provide a compatible V2 health response`, { cause })\n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L,EAGF,IAAM,EAAiB,EAAO,WAAW,SAAU,CACjD,EACA,EACA,CACA,GAAI,IAAa,UAAW,OAAO,MAAO,EAAQ,OAAO,CAAO,EAChE,GAAI,IAAa,SAAU,OAAO,MAAO,EAAQ,OAAO,IAAK,EAAS,QAAS,MAAU,CAAC,EAE1F,IAAM,EAAa,MAAO,EAAQ,SAAS,CAAO,EAClD,GAAI,IAAe,OAAW,OAAO,EAErC,IADiB,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,KAC1D,OACf,OAAO,MAAO,EAAO,KAAS,MAAM,sDAAsD,CAAC,EAC7F,OAAO,MAAO,EAAQ,OAAO,CAAO,EACrC,EAED,SAAS,CAAY,CAAC,EAAoB,EAAgB,CACxD,GAAI,EAAoB,CAAK,EAC3B,OAAW,MACT,EAAS,OAAS,OACd,aAAa,EAAS,iDACtB,aAAa,EAAS,4BAC1B,CAAE,OAAM,CACV,EAEF,GAAI,aAAiB,GAAe,EAAM,SAAW,YACnD,OAAW,MAAM,6BAA6B,EAAS,MAAO,CAAE,OAAM,CAAC,EACzE,OAAW,MAAM,aAAa,EAAS,sDAAuD,CAAE,OAAM,CAAC", | ||
| "debugId": "9CED01F2E9A5836864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/utils/cache.ts"], | ||
| "sourcesContent": [ | ||
| "// Shared helpers for provider cache-marker lowering. Anthropic and Bedrock\n// both enforce a 4-breakpoint cap per request and accept the same `5m`/`1h`\n// TTL buckets, so the counter and TTL mapping live here.\n\nexport interface Breakpoints {\n remaining: number\n dropped: number\n}\n\nexport const newBreakpoints = (cap: number): Breakpoints => ({ remaining: cap, dropped: 0 })\n\n// Returns `\"1h\"` for any `ttlSeconds >= 3600`, otherwise `undefined` (the\n// provider default 5m). Anthropic & Bedrock both treat anything shorter than\n// an hour as 5m.\nexport const ttlBucket = (ttlSeconds: number | undefined): \"1h\" | undefined =>\n ttlSeconds !== undefined && ttlSeconds >= 3600 ? \"1h\" : undefined\n" | ||
| ], | ||
| "mappings": ";AASO,IAAM,EAAiB,CAAC,KAA8B,CAAE,UAAW,EAAK,QAAS,CAAE,GAK7E,EAAY,CAAC,IACxB,IAAe,QAAa,GAAc,KAAO,KAAO", | ||
| "debugId": "D269F74C97CFE94364756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/utils/openai-options.ts", "../ai/src/protocols/openai-chat.ts"], | ||
| "sourcesContent": [ | ||
| "import { Schema } from \"effect\"\nimport type { LLMRequest, TextVerbosity as TextVerbosityValue } from \"../../schema\"\nimport { ReasoningEfforts, TextVerbosity } from \"../../schema\"\n\nexport const OpenAIReasoningEfforts = ReasoningEfforts\nexport type OpenAIReasoningEffort = string\n\n// Mirrors OpenAI's `ResponseIncludable` union from the official SDK. Keep this\n// in lockstep with `openai-node/src/resources/responses/responses.ts`.\nexport const OpenAIResponseIncludables = [\n \"file_search_call.results\",\n \"web_search_call.results\",\n \"web_search_call.action.sources\",\n \"message.input_image.image_url\",\n \"computer_call_output.output.image_url\",\n \"code_interpreter_call.outputs\",\n \"reasoning.encrypted_content\",\n \"message.output_text.logprobs\",\n] as const\nexport type OpenAIResponseIncludable = (typeof OpenAIResponseIncludables)[number]\nexport const OpenAIServiceTiers = [\"auto\", \"default\", \"flex\", \"priority\"] as const\nexport type OpenAIServiceTier = (typeof OpenAIServiceTiers)[number]\n\nconst TEXT_VERBOSITY = new Set<string>([\"low\", \"medium\", \"high\"])\nconst INCLUDABLES = new Set<string>(OpenAIResponseIncludables)\nconst SERVICE_TIERS = new Set<string>(OpenAIServiceTiers)\n\nexport const OpenAIReasoningEffort = Schema.String\nexport const OpenAITextVerbosity = TextVerbosity\nexport const OpenAIResponseIncludable = Schema.Literals(OpenAIResponseIncludables)\nexport const OpenAIServiceTier = Schema.Literals(OpenAIServiceTiers)\n\nexport const isReasoningEffort = (effort: unknown): effort is OpenAIReasoningEffort => typeof effort === \"string\"\n\nconst isTextVerbosity = (value: unknown): value is TextVerbosityValue =>\n typeof value === \"string\" && TEXT_VERBOSITY.has(value)\n\nconst options = (request: LLMRequest) => request.providerOptions?.openai\n\nexport const store = (request: LLMRequest): boolean | undefined => {\n const value = options(request)?.store\n return typeof value === \"boolean\" ? value : undefined\n}\n\nexport const reasoningEffort = (request: LLMRequest): string | undefined => {\n const value = options(request)?.reasoningEffort\n return typeof value === \"string\" ? value : undefined\n}\n\nexport const reasoningSummary = (request: LLMRequest): \"auto\" | undefined =>\n options(request)?.reasoningSummary === \"auto\" ? \"auto\" : undefined\n\n// Resolve the OpenAI Responses `include` field. Filters out unknown\n// includable values defensively so a typo in upstream config drops the\n// invalid entry instead of poisoning the wire body. An empty array (either\n// passed directly or produced by filtering) is treated as \"no include\" and\n// returns undefined so the request body omits the field entirely.\nexport const include = (request: LLMRequest): ReadonlyArray<OpenAIResponseIncludable> | undefined => {\n const value = options(request)?.include\n if (!Array.isArray(value)) return undefined\n const filtered = value.filter((entry): entry is OpenAIResponseIncludable => INCLUDABLES.has(entry))\n return filtered.length > 0 ? filtered : undefined\n}\n\nexport const promptCacheKey = (request: LLMRequest) => {\n const value = options(request)?.promptCacheKey\n return typeof value === \"string\" ? value : undefined\n}\n\nexport const textVerbosity = (request: LLMRequest) => {\n const value = options(request)?.textVerbosity\n return isTextVerbosity(value) ? value : undefined\n}\n\nexport const serviceTier = (request: LLMRequest) => {\n const value = options(request)?.serviceTier\n return typeof value === \"string\" && SERVICE_TIERS.has(value) ? (value as OpenAIServiceTier) : undefined\n}\n\nexport const instructions = (request: LLMRequest) => {\n const value = options(request)?.instructions\n return typeof value === \"string\" ? value : undefined\n}\n\nexport * as OpenAIOptions from \"./openai-options\"\n", | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { HttpTransport } from \"../route/transport\"\nimport { Protocol } from \"../route/protocol\"\nimport {\n LLMEvent,\n Usage,\n type FinishReason,\n type JsonSchema,\n type LLMRequest,\n type MediaPart,\n type ReasoningPart,\n type TextPart,\n type ToolCallPart,\n type ToolDefinition,\n type ToolContent,\n} from \"../schema\"\nimport { isRecord, JsonObject, optionalArray, optionalNull, ProviderShared } from \"./shared\"\nimport { OpenAIOptions } from \"./utils/openai-options\"\nimport { Lifecycle } from \"./utils/lifecycle\"\nimport { ToolSchemaProjection } from \"./utils/tool-schema\"\nimport { ToolStream } from \"./utils/tool-stream\"\n\nconst ADAPTER = \"openai-chat\"\nconst IMAGE_MIMES = new Set<string>(ProviderShared.IMAGE_MIMES)\nconst RESERVED_REASONING_FIELDS = new Set([\"role\", \"content\", \"tool_calls\"])\nexport const DEFAULT_BASE_URL = \"https://api.openai.com/v1\"\nexport const PATH = \"/chat/completions\"\n\n// =============================================================================\n// Request Body Schema\n// =============================================================================\n// The body schema is the provider-native JSON body. `fromRequest` below builds\n// this shape from the common `LLMRequest`, then `Route.make` validates and\n// JSON-encodes it before transport.\nconst OpenAIChatFunction = Schema.Struct({\n name: Schema.String,\n description: Schema.String,\n parameters: JsonObject,\n})\n\nconst OpenAIChatTool = Schema.Struct({\n type: Schema.tag(\"function\"),\n function: OpenAIChatFunction,\n})\ntype OpenAIChatTool = Schema.Schema.Type<typeof OpenAIChatTool>\n\nconst OpenAIChatAssistantToolCall = Schema.Struct({\n id: Schema.String,\n type: Schema.tag(\"function\"),\n function: Schema.Struct({\n name: Schema.String,\n arguments: Schema.String,\n }),\n})\ntype OpenAIChatAssistantToolCall = Schema.Schema.Type<typeof OpenAIChatAssistantToolCall>\n\nconst OpenAIChatUserContent = Schema.Union([\n Schema.Struct({ type: Schema.Literal(\"text\"), text: Schema.String }),\n Schema.Struct({\n type: Schema.Literal(\"image_url\"),\n image_url: Schema.Struct({ url: Schema.String }),\n }),\n])\n\nconst OpenAIChatMessage = Schema.Union([\n Schema.Struct({ role: Schema.Literal(\"system\"), content: Schema.String }),\n Schema.Struct({\n role: Schema.Literal(\"user\"),\n content: Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContent)]),\n }),\n Schema.StructWithRest(\n Schema.Struct({\n role: Schema.Literal(\"assistant\"),\n content: Schema.NullOr(Schema.String),\n tool_calls: optionalArray(OpenAIChatAssistantToolCall),\n reasoning_content: Schema.optional(Schema.String),\n reasoning: Schema.optional(Schema.String),\n reasoning_text: Schema.optional(Schema.String),\n reasoning_details: Schema.optional(Schema.Unknown),\n }),\n [Schema.Record(Schema.String, Schema.Unknown)],\n ),\n Schema.Struct({ role: Schema.Literal(\"tool\"), tool_call_id: Schema.String, content: Schema.String }),\n]).pipe(Schema.toTaggedUnion(\"role\"))\ntype OpenAIChatMessage = Schema.Schema.Type<typeof OpenAIChatMessage>\n\nconst OpenAIChatToolChoice = Schema.Union([\n Schema.Literals([\"auto\", \"none\", \"required\"]),\n Schema.Struct({\n type: Schema.tag(\"function\"),\n function: Schema.Struct({ name: Schema.String }),\n }),\n])\n\nexport const bodyFields = {\n model: Schema.String,\n messages: Schema.Array(OpenAIChatMessage),\n tools: optionalArray(OpenAIChatTool),\n tool_choice: Schema.optional(OpenAIChatToolChoice),\n stream: Schema.Literal(true),\n stream_options: Schema.optional(Schema.Struct({ include_usage: Schema.Boolean })),\n store: Schema.optional(Schema.Boolean),\n reasoning_effort: Schema.optional(OpenAIOptions.OpenAIReasoningEffort),\n max_tokens: Schema.optional(Schema.Number),\n temperature: Schema.optional(Schema.Number),\n top_p: Schema.optional(Schema.Number),\n frequency_penalty: Schema.optional(Schema.Number),\n presence_penalty: Schema.optional(Schema.Number),\n seed: Schema.optional(Schema.Number),\n stop: optionalArray(Schema.String),\n}\nconst OpenAIChatBody = Schema.Struct(bodyFields)\nexport type OpenAIChatBody = Schema.Schema.Type<typeof OpenAIChatBody>\n\n// =============================================================================\n// Streaming Event Schema\n// =============================================================================\n// The event schema is one decoded SSE `data:` payload. `Framing.sse` splits the\n// byte stream into strings, then `Protocol.jsonEvent` decodes each string into\n// this provider-native event shape.\nconst OpenAIChatUsage = Schema.Struct({\n prompt_tokens: Schema.optional(Schema.Number),\n completion_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n prompt_tokens_details: optionalNull(\n Schema.Struct({\n cached_tokens: Schema.optional(Schema.Number),\n }),\n ),\n completion_tokens_details: optionalNull(\n Schema.Struct({\n reasoning_tokens: Schema.optional(Schema.Number),\n }),\n ),\n})\n\nconst OpenAIChatToolCallDeltaFunction = Schema.Struct({\n name: optionalNull(Schema.String),\n arguments: optionalNull(Schema.String),\n})\n\nconst OpenAIChatToolCallDelta = Schema.Struct({\n index: Schema.Number,\n id: optionalNull(Schema.String),\n function: optionalNull(OpenAIChatToolCallDeltaFunction),\n})\ntype OpenAIChatToolCallDelta = Schema.Schema.Type<typeof OpenAIChatToolCallDelta>\n\nconst OpenAIChatDelta = Schema.StructWithRest(\n Schema.Struct({\n content: optionalNull(Schema.String),\n reasoning_content: optionalNull(Schema.String),\n reasoning: optionalNull(Schema.String),\n reasoning_text: optionalNull(Schema.String),\n reasoning_details: optionalNull(Schema.Unknown),\n tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),\n }),\n [Schema.Record(Schema.String, Schema.Unknown)],\n)\n\nconst OpenAIChatChoice = Schema.Struct({\n delta: optionalNull(OpenAIChatDelta),\n finish_reason: optionalNull(Schema.String),\n})\n\nexport const OpenAIChatEvent = Schema.Struct({\n choices: Schema.Array(OpenAIChatChoice),\n usage: optionalNull(OpenAIChatUsage),\n})\nexport type OpenAIChatEvent = Schema.Schema.Type<typeof OpenAIChatEvent>\ntype OpenAIChatRequestMessage = LLMRequest[\"messages\"][number]\n\ninterface PendingToolDelta {\n readonly id?: string\n readonly name?: string\n readonly input: string\n}\n\nexport interface ParserState {\n readonly tools: ToolStream.State<number>\n readonly pendingTools: Partial<Record<number, PendingToolDelta>>\n readonly toolCallEvents: ReadonlyArray<LLMEvent>\n readonly usage?: Usage\n readonly finishReason?: FinishReason\n readonly lifecycle: Lifecycle.State\n readonly reasoningField?: string\n readonly reasoningDetails: Array<unknown>\n readonly reasoningDetailsObserved: boolean\n readonly reasoningEmitted: boolean\n}\n\n// =============================================================================\n// Request Lowering\n// =============================================================================\n// Lowering is the only place that knows how common LLM messages map onto the\n// OpenAI Chat wire format. Keep provider quirks here instead of leaking native\n// fields into `LLMRequest`.\nconst lowerTool = (tool: ToolDefinition, inputSchema: JsonSchema): OpenAIChatTool => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: ToolSchemaProjection.openAI(inputSchema),\n },\n})\n\nconst lowerToolChoice = (toolChoice: NonNullable<LLMRequest[\"toolChoice\"]>) =>\n ProviderShared.matchToolChoice(\"OpenAI Chat\", toolChoice, {\n auto: () => \"auto\" as const,\n none: () => \"none\" as const,\n required: () => \"required\" as const,\n tool: (name) => ({ type: \"function\" as const, function: { name } }),\n })\n\nconst lowerToolCall = (part: ToolCallPart): OpenAIChatAssistantToolCall => ({\n id: part.id,\n type: \"function\",\n function: {\n name: part.name,\n arguments: ProviderShared.encodeJson(part.input),\n },\n})\n\nconst lowerMedia = Effect.fn(\"OpenAIChat.lowerMedia\")(function* (part: MediaPart) {\n const media = yield* ProviderShared.validateMedia(\"OpenAI Chat\", part, IMAGE_MIMES)\n return { type: \"image_url\" as const, image_url: { url: media.dataUrl } }\n})\n\nconst openAICompatibleReasoningContent = (native: unknown) =>\n isRecord(native) && typeof native.reasoning_content === \"string\" ? native.reasoning_content : undefined\n\nconst reasoningField = (part: ReasoningPart) => {\n const field = part.providerMetadata?.openai?.reasoningField\n return typeof field === \"string\" ? field : undefined\n}\n\nconst reasoningDetails = (parts: ReadonlyArray<ReasoningPart>, native: unknown) => {\n const observed = parts.flatMap((part) => {\n const details = part.providerMetadata?.openai?.reasoningDetails\n return Array.isArray(details) ? details : []\n })\n if (parts.some((part) => Array.isArray(part.providerMetadata?.openai?.reasoningDetails))) return observed\n if (isRecord(native) && Array.isArray(native.reasoning_details)) return native.reasoning_details\n}\n\nconst lowerUserMessage = Effect.fn(\"OpenAIChat.lowerUserMessage\")(function* (message: OpenAIChatRequestMessage) {\n const content: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"text\", text: part.text })\n continue\n }\n if (part.type === \"media\") {\n content.push(yield* lowerMedia(part))\n continue\n }\n return yield* ProviderShared.unsupportedContent(\"OpenAI Chat\", \"user\", [\"text\", \"media\"])\n }\n if (content.every((part) => part.type === \"text\"))\n return { role: \"user\" as const, content: content.map((part) => part.text).join(\"\") }\n return { role: \"user\" as const, content }\n})\n\nconst lowerAssistantMessage = Effect.fn(\"OpenAIChat.lowerAssistantMessage\")(function* (\n message: OpenAIChatRequestMessage,\n configuredField?: string,\n) {\n const content: TextPart[] = []\n const reasoning: ReasoningPart[] = []\n const toolCalls: OpenAIChatAssistantToolCall[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"reasoning\", \"tool-call\"]))\n return yield* ProviderShared.unsupportedContent(\"OpenAI Chat\", \"assistant\", [\"text\", \"reasoning\", \"tool-call\"])\n if (part.type === \"text\") {\n content.push(part)\n continue\n }\n if (part.type === \"reasoning\") {\n reasoning.push(part)\n continue\n }\n if (part.type === \"tool-call\") {\n toolCalls.push(lowerToolCall(part))\n continue\n }\n }\n const text = reasoning.map((part) => part.text).join(\"\")\n const details = reasoningDetails(reasoning, message.native?.openaiCompatible)\n const observedField = reasoning.map(reasoningField).find((value) => value !== undefined)\n const nativeReasoning = openAICompatibleReasoningContent(message.native?.openaiCompatible)\n const fullyStructured = reasoning.every((part) => Array.isArray(part.providerMetadata?.openai?.reasoningDetails))\n const field = (() => {\n if (configuredField !== undefined) return configuredField\n if (reasoning.length === 0) return undefined\n if (observedField !== undefined) return observedField\n if (nativeReasoning !== undefined) return \"reasoning_content\"\n if (!fullyStructured) return \"reasoning_content\"\n })()\n const reasoningText = (() => {\n if (configuredField !== undefined) return reasoning.length === 0 ? (nativeReasoning ?? \"\") : text\n if (reasoning.length === 0) return nativeReasoning\n return text\n })()\n const result = {\n role: \"assistant\" as const,\n content: content.length === 0 ? null : ProviderShared.joinText(content),\n tool_calls: toolCalls.length === 0 ? undefined : toolCalls,\n reasoning_details: details,\n }\n if (field === undefined || reasoningText === undefined) return result\n return { ...result, [field]: reasoningText }\n})\n\nconst lowerToolMessages = Effect.fn(\"OpenAIChat.lowerToolMessages\")(function* (message: OpenAIChatRequestMessage) {\n const messages: OpenAIChatMessage[] = []\n const images: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"tool-result\"]))\n return yield* ProviderShared.unsupportedContent(\"OpenAI Chat\", \"tool\", [\"tool-result\"])\n if (part.result.type !== \"content\") {\n messages.push({ role: \"tool\", tool_call_id: part.id, content: ProviderShared.toolResultText(part) })\n continue\n }\n const content: ReadonlyArray<ToolContent> = part.result.value\n const text = content.filter((item) => item.type === \"text\").map((item) => item.text)\n messages.push({ role: \"tool\", tool_call_id: part.id, content: text.join(\"\\n\") })\n const files = content.filter((item) => item.type === \"file\")\n images.push(\n ...(yield* Effect.forEach(files, (item) =>\n lowerMedia({ type: \"media\", mediaType: item.mime, data: item.uri, filename: item.name }),\n )),\n )\n }\n return { messages, images }\n})\n\nconst lowerMessage = Effect.fn(\"OpenAIChat.lowerMessage\")(function* (\n message: OpenAIChatRequestMessage,\n reasoningField?: string,\n) {\n if (message.role === \"user\") return [yield* lowerUserMessage(message)]\n if (message.role === \"assistant\") return [yield* lowerAssistantMessage(message, reasoningField)]\n return (yield* lowerToolMessages(message)).messages\n})\n\nconst lowerMessages = Effect.fn(\"OpenAIChat.lowerMessages\")(function* (request: LLMRequest) {\n const system: OpenAIChatMessage[] =\n request.system.length === 0 ? [] : [{ role: \"system\", content: ProviderShared.joinText(request.system) }]\n const messages = [...system]\n const pendingImages: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []\n const flushImages = () => {\n if (pendingImages.length === 0) return\n messages.push({ role: \"user\", content: pendingImages.splice(0) })\n }\n for (const message of request.messages) {\n if (message.role === \"system\") {\n const part = yield* ProviderShared.wrappedSystemUpdate(\"OpenAI Chat\", message)\n if (pendingImages.length > 0) {\n messages.push({ role: \"user\", content: [...pendingImages.splice(0), { type: \"text\", text: part.text }] })\n continue\n }\n const previous = messages.at(-1)\n if (previous?.role === \"user\" && typeof previous.content === \"string\")\n messages[messages.length - 1] = { role: \"user\", content: `${previous.content}\\n${part.text}` }\n else if (previous?.role === \"user\" && Array.isArray(previous.content))\n messages[messages.length - 1] = {\n role: \"user\",\n content: [...previous.content, { type: \"text\", text: part.text }],\n }\n else messages.push({ role: \"user\", content: part.text })\n continue\n }\n if (message.role === \"tool\") {\n const lowered = yield* lowerToolMessages(message)\n messages.push(...lowered.messages)\n pendingImages.push(...lowered.images)\n continue\n }\n flushImages()\n messages.push(...(yield* lowerMessage(message, request.model.compatibility?.reasoningField)))\n }\n flushImages()\n return messages\n})\n\nconst lowerOptions = Effect.fn(\"OpenAIChat.lowerOptions\")(function* (request: LLMRequest) {\n const store = OpenAIOptions.store(request)\n const reasoningEffort = OpenAIOptions.reasoningEffort(request)\n return {\n ...(store !== undefined ? { store } : {}),\n ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),\n }\n})\n\nconst fromRequest = Effect.fn(\"OpenAIChat.fromRequest\")(function* (request: LLMRequest) {\n // `fromRequest` returns the provider body only. Endpoint, auth, framing,\n // validation, and HTTP execution are composed by `Route.make`.\n const reasoningField = request.model.compatibility?.reasoningField\n if (reasoningField && RESERVED_REASONING_FIELDS.has(reasoningField))\n return yield* ProviderShared.invalidRequest(\n `OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`,\n )\n const generation = request.generation\n const toolSchemaCompatibility = request.model.compatibility?.toolSchema\n return {\n model: request.model.id,\n messages: yield* lowerMessages(request),\n tools:\n request.tools.length === 0\n ? undefined\n : request.tools.map((tool) =>\n lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),\n ),\n tool_choice: request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,\n stream: true as const,\n stream_options: { include_usage: true },\n max_tokens: generation?.maxTokens,\n temperature: generation?.temperature,\n top_p: generation?.topP,\n frequency_penalty: generation?.frequencyPenalty,\n presence_penalty: generation?.presencePenalty,\n seed: generation?.seed,\n stop: generation?.stop,\n ...(yield* lowerOptions(request)),\n }\n})\n\n// =============================================================================\n// Stream Parsing\n// =============================================================================\n// Streaming parsers are small state machines: every event returns a new state\n// plus the common `LLMEvent`s produced by that event. Tool calls are accumulated\n// because OpenAI streams JSON arguments across multiple deltas.\nconst mapFinishReason = (reason: string | null | undefined): FinishReason => {\n if (reason === \"stop\") return \"stop\"\n if (reason === \"length\") return \"length\"\n if (reason === \"content_filter\") return \"content-filter\"\n if (reason === \"function_call\" || reason === \"tool_calls\") return \"tool-calls\"\n return \"unknown\"\n}\n\n// OpenAI Chat reports `prompt_tokens` (inclusive total) with a\n// `cached_tokens` subset, and `completion_tokens` (inclusive total) with\n// a `reasoning_tokens` subset. We pass the inclusive totals through and\n// derive the non-cached breakdown so the `LLM.Usage` contract is\n// satisfied on both sides.\nconst mapUsage = (usage: OpenAIChatEvent[\"usage\"]): Usage | undefined => {\n if (!usage) return undefined\n const cached = usage.prompt_tokens_details?.cached_tokens\n const reasoning = usage.completion_tokens_details?.reasoning_tokens\n const nonCached = ProviderShared.subtractTokens(usage.prompt_tokens, cached)\n return new Usage({\n inputTokens: usage.prompt_tokens,\n outputTokens: usage.completion_tokens,\n nonCachedInputTokens: nonCached,\n cacheReadInputTokens: cached,\n reasoningTokens: reasoning,\n totalTokens: ProviderShared.totalTokens(usage.prompt_tokens, usage.completion_tokens, usage.total_tokens),\n providerMetadata: { openai: usage },\n })\n}\n\nconst reasoningDelta = (\n delta: Schema.Schema.Type<typeof OpenAIChatDelta> | null | undefined,\n configuredField?: string,\n) => {\n if (!delta) return undefined\n const fields = new Set([configuredField, \"reasoning_content\", \"reasoning\", \"reasoning_text\"])\n for (const field of fields) {\n if (field === undefined) continue\n const text = delta[field]\n if (typeof text === \"string\" && text.length > 0) return { field, text }\n }\n return undefined\n}\n\nconst detailText = (details: ReadonlyArray<unknown>) => {\n const text = details.flatMap((detail) => {\n if (!isRecord(detail)) return []\n if (detail.type === \"reasoning.text\" && typeof detail.text === \"string\" && detail.text) return [detail.text]\n if (detail.type === \"reasoning.summary\" && typeof detail.summary === \"string\" && detail.summary)\n return [detail.summary]\n return []\n })\n if (text.length > 0) return text.join(\"\")\n}\n\nconst appendReasoningDetails = (result: Array<unknown>, details: ReadonlyArray<unknown>) => {\n for (const detail of details) {\n const previous = result.at(-1)\n if (\n !isRecord(previous) ||\n previous.type !== \"reasoning.text\" ||\n !isRecord(detail) ||\n detail.type !== \"reasoning.text\" ||\n conflictingReasoningTextDetails(previous, detail)\n ) {\n result.push(detail)\n continue\n }\n result[result.length - 1] = {\n ...previous,\n ...Object.fromEntries(Object.entries(detail).filter((entry) => entry[1] !== undefined)),\n text: `${typeof previous.text === \"string\" ? previous.text : \"\"}${typeof detail.text === \"string\" ? detail.text : \"\"}`,\n signature: mergeDetailValue(previous.signature, detail.signature),\n format: mergeDetailValue(previous.format, detail.format),\n }\n }\n}\n\nconst mergeDetailValue = (previous: unknown, current: unknown) =>\n previous || current || (previous !== undefined ? previous : current)\n\nconst conflictingReasoningTextDetails = (previous: Record<string, unknown>, current: Record<string, unknown>) =>\n conflictingDetailValue(previous.id, current.id) ||\n conflictingDetailValue(previous.index, current.index) ||\n conflictingDetailValue(previous.format, current.format) ||\n (Boolean(previous.signature) && Boolean(current.signature) && previous.signature !== current.signature)\n\nconst conflictingDetailValue = (previous: unknown, current: unknown) =>\n previous !== undefined && previous !== null && current !== undefined && current !== null && previous !== current\n\nconst reasoningMetadata = (field: ParserState[\"reasoningField\"], details?: ReadonlyArray<unknown>) => ({\n openai: {\n ...(field ? { reasoningField: field } : {}),\n ...(details ? { reasoningDetails: details } : {}),\n },\n})\n\nconst step = (state: ParserState, event: OpenAIChatEvent) =>\n Effect.gen(function* () {\n const events: LLMEvent[] = []\n const usage = mapUsage(event.usage) ?? state.usage\n const choice = event.choices[0]\n const finishReason = choice?.finish_reason ? mapFinishReason(choice.finish_reason) : state.finishReason\n const delta = choice?.delta\n const toolDeltas = delta?.tool_calls ?? []\n let tools = state.tools\n let pendingTools = state.pendingTools\n\n let lifecycle = state.lifecycle\n\n const reasoning = reasoningDelta(delta, state.reasoningField)\n const reasoningField = state.reasoningField ?? (!state.lifecycle.text.has(\"text-0\") ? reasoning?.field : undefined)\n const detailDelta = Array.isArray(delta?.reasoning_details) ? delta.reasoning_details : undefined\n if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)\n const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined\n const deltaMetadata = reasoningMetadata(reasoningField)\n const text = detailDelta?.length ? (detailText(detailDelta) ?? reasoning?.text) : reasoning?.text\n if (!state.lifecycle.text.has(\"text-0\") && text !== undefined)\n lifecycle = Lifecycle.reasoningDelta(lifecycle, events, \"reasoning-0\", text, deltaMetadata)\n else if (\n reasoningDetailsObserved &&\n !lifecycle.reasoning.has(\"reasoning-0\") &&\n (Boolean(delta?.content) || toolDeltas.length > 0)\n )\n lifecycle = Lifecycle.reasoningStart(lifecycle, events, \"reasoning-0\", deltaMetadata)\n const reasoningEmitted = state.reasoningEmitted || lifecycle.reasoning.has(\"reasoning-0\")\n\n if (delta?.content) {\n lifecycle = Lifecycle.reasoningEnd(\n lifecycle,\n events,\n \"reasoning-0\",\n reasoningMetadata(reasoningField, reasoningDetailsObserved ? state.reasoningDetails : undefined),\n )\n lifecycle = Lifecycle.textDelta(lifecycle, events, \"text-0\", delta.content)\n }\n\n for (const tool of toolDeltas) {\n const current = tools[tool.index]\n const pending = pendingTools[tool.index]\n const id = current?.id ?? pending?.id ?? (tool.id || undefined)\n const name = current?.name ?? pending?.name ?? (tool.function?.name || undefined)\n const text = `${pending?.input ?? \"\"}${tool.function?.arguments ?? \"\"}`\n if (!current && (!id || !name)) {\n pendingTools = { ...pendingTools, [tool.index]: { id: id || undefined, name: name || undefined, input: text } }\n continue\n }\n if (pending) {\n pendingTools = { ...pendingTools }\n delete pendingTools[tool.index]\n }\n const result = ToolStream.appendOrStart(\n ADAPTER,\n tools,\n tool.index,\n { id: id || undefined, name: name || undefined, text },\n \"OpenAI Chat tool call delta is missing id or name\",\n )\n if (ToolStream.isError(result)) return yield* result\n tools = result.tools\n if (result.events.length) lifecycle = Lifecycle.stepStart(lifecycle, events)\n events.push(...result.events)\n }\n\n if (finishReason !== undefined && state.finishReason === undefined && Object.keys(pendingTools).length > 0)\n return yield* ProviderShared.eventError(ADAPTER, \"OpenAI Chat tool call delta is missing id or name\")\n\n // Finalize accumulated tool inputs eagerly when finish_reason arrives so\n // valid calls and malformed local calls settle independently.\n const finished =\n finishReason !== undefined && state.finishReason === undefined && Object.keys(tools).length > 0\n ? yield* ToolStream.finishAll(ADAPTER, tools)\n : undefined\n\n return [\n {\n tools: finished?.tools ?? tools,\n pendingTools,\n toolCallEvents: finished?.events ?? state.toolCallEvents,\n usage,\n finishReason,\n lifecycle,\n reasoningField,\n reasoningDetails: state.reasoningDetails,\n reasoningDetailsObserved,\n reasoningEmitted,\n },\n events,\n ] as const\n })\n\nconst finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {\n const events: LLMEvent[] = []\n const hasToolCalls = state.toolCallEvents.length > 0\n const reason = state.finishReason === \"stop\" && hasToolCalls ? \"tool-calls\" : state.finishReason\n const metadata = reasoningMetadata(\n state.reasoningField,\n state.reasoningDetailsObserved ? state.reasoningDetails : undefined,\n )\n const started =\n state.reasoningDetailsObserved && !state.reasoningEmitted\n ? Lifecycle.reasoningStart(state.lifecycle, events, \"reasoning-0\", reasoningMetadata(state.reasoningField))\n : state.lifecycle\n const ended = Lifecycle.reasoningEnd(started, events, \"reasoning-0\", metadata)\n const lifecycle = state.toolCallEvents.length ? Lifecycle.stepStart(ended, events) : ended\n events.push(...state.toolCallEvents)\n if (reason) Lifecycle.finish(lifecycle, events, { reason, usage: state.usage })\n return events\n}\n\n// =============================================================================\n// Protocol And OpenAI Route\n// =============================================================================\n/**\n * The OpenAI Chat protocol — request body construction, body schema, and the\n * streaming-event state machine. Reused by every route that speaks OpenAI Chat\n * over HTTP+SSE: native OpenAI, DeepSeek, TogetherAI, Cerebras, Baseten,\n * Fireworks, DeepInfra, and (once added) Azure OpenAI Chat.\n */\nexport const protocol = Protocol.make({\n id: ADAPTER,\n body: {\n schema: OpenAIChatBody,\n from: fromRequest,\n },\n stream: {\n event: Protocol.jsonEvent(OpenAIChatEvent),\n initial: (request) => ({\n tools: ToolStream.empty<number>(),\n pendingTools: {},\n toolCallEvents: [],\n lifecycle: Lifecycle.initial(),\n reasoningField: request.model.compatibility?.reasoningField,\n reasoningDetails: [],\n reasoningDetailsObserved: false,\n reasoningEmitted: false,\n }),\n step,\n onHalt: finishEvents,\n },\n})\n\nexport const httpTransport = HttpTransport.sseJson.with<OpenAIChatBody>()\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: \"openai\",\n providerMetadataKey: \"openai\",\n protocol,\n endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),\n auth: Auth.none,\n transport: httpTransport,\n})\n\nexport * as OpenAIChat from \"./openai-chat\"\n" | ||
| ], | ||
| "mappings": ";6tBAIO,SAAM,QAAyB,OAKzB,EAA4B,CACvC,2BACA,0BACA,iCACA,gCACA,wCACA,gCACA,8BACA,8BACF,EAEa,EAAqB,CAAC,OAAQ,UAAW,OAAQ,UAAU,EAGlE,GAAiB,IAAI,IAAY,CAAC,MAAO,SAAU,MAAM,CAAC,EAC1D,GAAc,IAAI,IAAY,CAAyB,EACvD,GAAgB,IAAI,IAAY,CAAkB,EAE3C,GAAwB,EAAO,OAC/B,GAAsB,EACtB,GAA2B,EAAO,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ACpC,GAAI,EACJ,KAAM,CACJ,OAAQ,GACR,KAAM,EACR,EACA,OAAQ,CACN,MAAO,EAAS,UAAU,EAAe,EACzC,QAAS,CAAC,KAAa,CACrB,MAAO,EAAW,MAAc,EAChC,aAAc,CAAC,EACf,eAAgB,CAAC,EACjB,UAAW,EAAU,QAAQ,EAC7B,eAAgB,EAAQ,MAAM,eAAe,eAC7C,iBAAkB,CAAC,EACnB,yBAA0B,GAC1B,iBAAkB,EACpB,GACA,QACA,OAAQ,EACV,CACF,CAAC,EAEY,GAAgB,EAAc,QAAQ,KAAqB,EAE3D,GAAQ,EAAM,KAAK,CAC9B,GAAI,EACJ,SAAU,SACV,oBAAqB,SACrB,YACA,SAAU,EAAS,KAAK,GAAM,CAAE,QAAS,EAAiB,CAAC,EAC3D,KAAM,EAAK,KACX,UAAW,EACb,CAAC", | ||
| "debugId": "59EC0446E859A52964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/openai-compatible-profile.ts"], | ||
| "sourcesContent": [ | ||
| "export interface OpenAICompatibleProfile {\n readonly provider: string\n readonly baseURL: string\n}\n\nexport const profiles = {\n baseten: { provider: \"baseten\", baseURL: \"https://inference.baseten.co/v1\" },\n cerebras: { provider: \"cerebras\", baseURL: \"https://api.cerebras.ai/v1\" },\n deepinfra: { provider: \"deepinfra\", baseURL: \"https://api.deepinfra.com/v1/openai\" },\n deepseek: { provider: \"deepseek\", baseURL: \"https://api.deepseek.com/v1\" },\n fireworks: { provider: \"fireworks\", baseURL: \"https://api.fireworks.ai/inference/v1\" },\n groq: { provider: \"groq\", baseURL: \"https://api.groq.com/openai/v1\" },\n openrouter: { provider: \"openrouter\", baseURL: \"https://openrouter.ai/api/v1\" },\n togetherai: { provider: \"togetherai\", baseURL: \"https://api.together.xyz/v1\" },\n xai: { provider: \"xai\", baseURL: \"https://api.x.ai/v1\" },\n} as const satisfies Record<string, OpenAICompatibleProfile>\n\nexport const byProvider: Record<string, OpenAICompatibleProfile> = Object.fromEntries(\n Object.values(profiles).map((profile) => [profile.provider, profile]),\n)\n" | ||
| ], | ||
| "mappings": ";AAKO,IAAM,EAAW,CACtB,QAAS,CAAE,SAAU,UAAW,QAAS,iCAAkC,EAC3E,SAAU,CAAE,SAAU,WAAY,QAAS,4BAA6B,EACxE,UAAW,CAAE,SAAU,YAAa,QAAS,qCAAsC,EACnF,SAAU,CAAE,SAAU,WAAY,QAAS,6BAA8B,EACzE,UAAW,CAAE,SAAU,YAAa,QAAS,uCAAwC,EACrF,KAAM,CAAE,SAAU,OAAQ,QAAS,gCAAiC,EACpE,WAAY,CAAE,SAAU,aAAc,QAAS,8BAA+B,EAC9E,WAAY,CAAE,SAAU,aAAc,QAAS,6BAA8B,EAC7E,IAAK,CAAE,SAAU,MAAO,QAAS,qBAAsB,CACzD,EAEa,EAAsD,OAAO,YACxE,OAAO,OAAO,CAAQ,EAAE,IAAI,CAAC,IAAY,CAAC,EAAQ,SAAU,CAAO,CAAC,CACtE", | ||
| "debugId": "21C2B34943584DBF64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "A1DB45508CE6096C64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/openai-options.ts"], | ||
| "sourcesContent": [ | ||
| "import type { ProviderOptions, ReasoningEffort, TextVerbosity } from \"../schema\"\nimport { mergeProviderOptions } from \"../schema\"\nimport type { OpenAIResponseIncludable, OpenAIServiceTier } from \"../protocols/utils/openai-options\"\n\nexport type { OpenAIResponseIncludable, OpenAIServiceTier } from \"../protocols/utils/openai-options\"\n\nexport interface OpenAIOptionsInput {\n readonly [key: string]: unknown\n readonly store?: boolean\n readonly promptCacheKey?: string\n readonly reasoningEffort?: ReasoningEffort\n readonly reasoningSummary?: \"auto\"\n // OpenAI Responses `include` wire field. Mirrors the official SDK's\n // `ResponseIncludable[]` union exactly so AI SDK callers and direct\n // native-SDK callers share one shape and no translation is required.\n readonly include?: ReadonlyArray<OpenAIResponseIncludable>\n readonly textVerbosity?: TextVerbosity\n readonly serviceTier?: OpenAIServiceTier\n}\n\nexport type OpenAIProviderOptionsInput = ProviderOptions & {\n readonly openai?: OpenAIOptionsInput\n}\n\nconst definedEntries = (input: Record<string, unknown>) =>\n Object.entries(input).filter((entry) => entry[1] !== undefined)\n\nconst openAIProviderOptions = (options: OpenAIOptionsInput | undefined): ProviderOptions | undefined => {\n const openai = Object.fromEntries(\n definedEntries({\n store: options?.store,\n promptCacheKey: options?.promptCacheKey,\n reasoningEffort: options?.reasoningEffort,\n reasoningSummary: options?.reasoningSummary,\n include: options?.include,\n textVerbosity: options?.textVerbosity,\n serviceTier: options?.serviceTier,\n }),\n )\n if (Object.keys(openai).length === 0) return undefined\n return { openai }\n}\n\nexport const gpt5DefaultOptions = (\n modelID: string,\n options: { readonly textVerbosity?: boolean } = {},\n): ProviderOptions | undefined => {\n const id = modelID.toLowerCase()\n if (!id.includes(\"gpt-5\") || id.includes(\"gpt-5-chat\") || id.includes(\"gpt-5-pro\")) return undefined\n return openAIProviderOptions({\n reasoningEffort: \"medium\",\n reasoningSummary: \"auto\",\n // GPT-5 reasoning models are configured stateless (`store: false`) by\n // `openAIDefaultOptions` below, so the only way a follow-up turn can\n // carry reasoning state is via the encrypted reasoning include. Without\n // this, callers using the default model facade get reasoning summaries\n // they cannot replay statelessly.\n include: [\"reasoning.encrypted_content\"],\n textVerbosity:\n options.textVerbosity === true && id.includes(\"gpt-5.\") && !id.includes(\"codex\") && !id.includes(\"-chat\")\n ? \"low\"\n : undefined,\n })\n}\n\nexport const openAIDefaultOptions = (\n modelID: string,\n options: { readonly textVerbosity?: boolean } = {},\n): ProviderOptions | undefined =>\n mergeProviderOptions(openAIProviderOptions({ store: false }), gpt5DefaultOptions(modelID, options))\n\nexport const withOpenAIOptions = <Options extends { readonly providerOptions?: OpenAIProviderOptionsInput }>(\n modelID: string,\n options: Options,\n defaults: { readonly textVerbosity?: boolean } = {},\n): Omit<Options, \"providerOptions\"> & { readonly providerOptions?: ProviderOptions } => {\n return {\n ...options,\n providerOptions: mergeProviderOptions(openAIDefaultOptions(modelID, defaults), options.providerOptions),\n }\n}\n\nexport * as OpenAIProviderOptions from \"./openai-options\"\n" | ||
| ], | ||
| "mappings": ";oDAwBA,IAAM,EAAiB,CAAC,IACtB,OAAO,QAAQ,CAAK,EAAE,OAAO,CAAC,IAAU,EAAM,KAAO,MAAS,EAE1D,EAAwB,CAAC,IAAyE,CACtG,IAAM,EAAS,OAAO,YACpB,EAAe,CACb,MAAO,GAAS,MAChB,eAAgB,GAAS,eACzB,gBAAiB,GAAS,gBAC1B,iBAAkB,GAAS,iBAC3B,QAAS,GAAS,QAClB,cAAe,GAAS,cACxB,YAAa,GAAS,WACxB,CAAC,CACH,EACA,GAAI,OAAO,KAAK,CAAM,EAAE,SAAW,EAAG,OACtC,MAAO,CAAE,QAAO,GAGL,EAAqB,CAChC,EACA,EAAgD,CAAC,IACjB,CAChC,IAAM,EAAK,EAAQ,YAAY,EAC/B,GAAI,CAAC,EAAG,SAAS,OAAO,GAAK,EAAG,SAAS,YAAY,GAAK,EAAG,SAAS,WAAW,EAAG,OACpF,OAAO,EAAsB,CAC3B,gBAAiB,SACjB,iBAAkB,OAMlB,QAAS,CAAC,6BAA6B,EACvC,cACE,EAAQ,gBAAkB,IAAQ,EAAG,SAAS,QAAQ,GAAK,CAAC,EAAG,SAAS,OAAO,GAAK,CAAC,EAAG,SAAS,OAAO,EACpG,MACA,MACR,CAAC,GAGU,EAAuB,CAClC,EACA,EAAgD,CAAC,IAEjD,EAAqB,EAAsB,CAAE,MAAO,EAAM,CAAC,EAAG,EAAmB,EAAS,CAAO,CAAC,EAEvF,EAAoB,CAC/B,EACA,EACA,EAAiD,CAAC,IACoC,CACtF,MAAO,IACF,EACH,gBAAiB,EAAqB,EAAqB,EAAS,CAAQ,EAAG,EAAQ,eAAe,CACxG", | ||
| "debugId": "279F100773F595B764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "DEB6B5EF41C1AA9964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/plugin/sdk.ts", "../plugin/src/v2/effect/tool.ts", "../plugin/src/v2/effect/plugin.ts", "../schema/src/session.ts", "../schema/src/command.ts", "../schema/src/reference.ts"], | ||
| "sourcesContent": [ | ||
| "export * as SdkPlugins from \"./sdk\"\n\nimport type { Plugin } from \"@opencode-ai/plugin/v2/effect/plugin\"\nimport { Context, Effect, Layer } from \"effect\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { EventV2 } from \"../event\"\nimport type { PluginV2 } from \"../plugin\"\n\nexport const Updated = EventV2.ephemeral({ type: \"sdk.plugin.updated\", schema: {} })\n\n/**\n * Holds the plugins an embedder (the `@opencode-ai/sdk-next` host) contributes,\n * so `PluginSupervisor` can add them on every Location boot through the ordinary\n * generation path that `PluginSupervisor` uses for plugins discovered from\n * config. Registration publishes an unlocated update so every booted Location\n * reloads its plugin generation from the shared store.\n *\n * Each host-global layer owns one private store. Location graphs reuse that\n * layer through Effect's memoization, so separate hosts remain isolated while\n * every Location in one host sees the same registrations.\n */\nexport interface Interface {\n readonly register: (plugin: Plugin) => Effect.Effect<void>\n readonly all: () => readonly PluginV2.Versioned[]\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/SdkPlugins\") {}\n\nexport const layer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const events = yield* EventV2.Service\n const plugins = new Map<string, PluginV2.Versioned>()\n let revision = 0\n return Service.of({\n register: (plugin) =>\n Effect.sync(() => {\n plugins.set(plugin.id, { ...plugin, version: String(++revision) })\n }).pipe(Effect.andThen(events.publish(Updated, {})), Effect.asVoid),\n all: () => [...plugins.values()],\n })\n }),\n)\n\nexport const node = makeGlobalNode({ service: Service, layer, deps: [EventV2.node] })\n", | ||
| "export * as Tool from \"./tool.js\"\n\nimport { Agent } from \"@opencode-ai/schema/agent\"\nimport type { LLM } from \"@opencode-ai/schema/llm\"\nimport { Session } from \"@opencode-ai/schema/session\"\nimport { SessionMessage } from \"@opencode-ai/schema/session-message\"\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\"\nimport { Effect, JsonSchema, Schema } from \"effect\"\nimport type { Hooks, Transform } from \"./registration.js\"\n\nexport interface Context {\n readonly sessionID: Session.ID\n readonly agent: Agent.ID\n readonly messageID: SessionMessage.ID\n readonly callID: string\n readonly progress: (update: Progress) => Effect.Effect<void>\n}\n\nexport interface Progress {\n readonly structured: Readonly<Record<string, unknown>>\n readonly content?: ReadonlyArray<Content>\n}\n\nexport type StandardSchemaType<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output> &\n StandardJSONSchemaV1<Input, Output>\nexport type SchemaType<A> = Schema.Codec<A, any> | StandardSchemaType<any, A>\ntype IsAny<A> = 0 extends 1 & A ? true : false\nexport type InputValue<S> =\n IsAny<S> extends true\n ? any\n : S extends Schema.Codec<infer A, any>\n ? A\n : S extends StandardSchemaV1<any, infer A>\n ? A\n : never\nexport type OutputValue<S> =\n IsAny<S> extends true\n ? any\n : S extends Schema.Codec<infer A, any>\n ? A\n : S extends StandardSchemaV1<infer A, any>\n ? A\n : never\nexport type EncodedValue<S> =\n IsAny<S> extends true\n ? any\n : S extends Schema.Codec<any, infer A>\n ? A\n : S extends StandardSchemaV1<any, infer A>\n ? A\n : never\n\ntype ToolDefinition = {\n readonly name: string\n readonly description: string\n readonly inputSchema: JsonSchema.JsonSchema\n readonly outputSchema?: JsonSchema.JsonSchema\n}\n\ntype ToolCall = {\n readonly input: unknown\n readonly [key: string]: unknown\n}\n\ntype ToolResultValue =\n | { readonly type: \"json\"; readonly value: unknown }\n | { readonly type: \"text\"; readonly value: unknown }\n | { readonly type: \"error\"; readonly value: unknown }\n | { readonly type: \"content\"; readonly value: ReadonlyArray<LLM.ToolContent> }\n\ntype ToolOutput = {\n readonly structured: unknown\n readonly content: ReadonlyArray<LLM.ToolContent>\n}\n\nexport class Failure extends Schema.TaggedErrorClass<Failure>()(\"LLM.ToolFailure\", {\n message: Schema.String,\n error: Schema.optional(Schema.Defect()),\n metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n}) {}\n\nexport class RegistrationError extends Schema.TaggedErrorClass<RegistrationError>()(\"Tool.RegistrationError\", {\n name: Schema.String,\n message: Schema.String,\n}) {}\n\nexport type Content =\n | { readonly type: \"text\"; readonly text: string }\n | { readonly type: \"file\"; readonly data: string; readonly mime: string; readonly name?: string }\n\nexport type Definition<\n Input extends SchemaType<any>,\n Structured extends SchemaType<any>,\n Output extends SchemaType<any> = any,\n> = {\n readonly description: string\n readonly input: Input\n readonly output: Output\n readonly structured?: Structured\n readonly permission?: string\n readonly toStructuredOutput?: (input: {\n readonly input: InputValue<Input>\n readonly output: EncodedValue<Output>\n }) => OutputValue<Structured>\n readonly execute: (input: InputValue<Input>, context: Context) => Effect.Effect<OutputValue<Output>, Failure>\n readonly toModelOutput?: (input: {\n readonly input: InputValue<Input>\n readonly output: EncodedValue<Output>\n }) => ReadonlyArray<Content>\n}\n\nexport type DynamicOutput = {\n readonly structured: unknown\n readonly content: ReadonlyArray<Content>\n}\n\n/**\n * Config for a tool whose input shape is a raw JSON Schema not known at compile\n * time (MCP servers, plugin manifests). Input is passed through as `unknown`;\n * `execute` returns the already-projected structured value and model content.\n */\nexport type DynamicDefinition = {\n readonly description: string\n readonly jsonSchema: JsonSchema.JsonSchema\n readonly outputSchema?: JsonSchema.JsonSchema\n readonly permission?: string\n readonly execute: (input: unknown, context: Context) => Effect.Effect<DynamicOutput, Failure>\n}\n\nexport type AnyTool = Definition<any, any> | DynamicDefinition\n\nexport function make<\n Input extends SchemaType<any>,\n Output extends SchemaType<any>,\n Structured extends SchemaType<any> = Output,\n>(config: Definition<Input, Structured, Output>): Definition<Input, Structured, Output>\nexport function make(config: DynamicDefinition): DynamicDefinition\nexport function make(config: AnyTool): AnyTool\nexport function make(config: AnyTool): AnyTool {\n return config\n}\n\nfunction toModelContent(part: Content) {\n if (part.type === \"text\") return { type: \"text\" as const, text: part.text }\n return { type: \"file\" as const, uri: `data:${part.mime};base64,${part.data}`, mime: part.mime, name: part.name }\n}\n\nexport const validateName = (name: string) =>\n /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(name)\n ? Effect.void\n : Effect.fail(new RegistrationError({ name, message: `Invalid tool name: ${name}` }))\n\nexport const registrationEntries = (tools: Readonly<Record<string, AnyTool>>, namespace?: string) =>\n Object.entries(tools).map(([name, tool]) => {\n const normalized = name.replace(/[^a-zA-Z0-9_-]/g, \"_\")\n return {\n key: namespace === undefined ? normalized : `${namespace.replaceAll(\".\", \"_\")}_${normalized}`,\n name: normalized,\n namespace,\n tool,\n }\n })\n\nexport const validateNamespace = (namespace: string) =>\n namespace.split(\".\").every((segment) => /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(segment))\n ? Effect.void\n : Effect.fail(\n new RegistrationError({ name: namespace, message: `Invalid tool namespace: ${JSON.stringify(namespace)}` }),\n )\n\nexport const withPermission = <T extends AnyTool>(\n tool: T,\n permission: string,\n): Omit<T, \"permission\"> & {\n readonly permission: string\n} => ({ ...tool, permission })\n\nexport const permission = (tool: AnyTool, name: string) => tool.permission ?? name\n\nexport const definition = (name: string, tool: AnyTool): ToolDefinition =>\n \"jsonSchema\" in tool\n ? {\n name,\n description: tool.description,\n inputSchema: tool.jsonSchema,\n outputSchema: tool.outputSchema,\n }\n : {\n name,\n description: tool.description,\n inputSchema: inputJsonSchema(tool.input),\n outputSchema: outputJsonSchema(tool.structured ?? tool.output),\n }\n\nexport const settle = (tool: AnyTool, call: ToolCall, context: Context): Effect.Effect<ToolOutput, Failure> =>\n Effect.gen(function* () {\n if (\"jsonSchema\" in tool) {\n const output = yield* tool.execute(call.input, context)\n return { structured: output.structured, content: output.content.map(toModelContent) }\n }\n\n const input = yield* decodeInput(tool.input, call.input)\n const value = yield* tool.execute(input, context)\n const output = yield* encodeOutput(tool.output, value)\n const structured =\n tool.structured && tool.toStructuredOutput\n ? yield* encodeOutput(tool.structured, tool.toStructuredOutput({ input, output }))\n : output\n return {\n structured,\n content:\n tool.toModelOutput?.({ input, output }).map(toModelContent) ??\n (typeof output === \"string\" ? [{ type: \"text\" as const, text: output }] : []),\n }\n })\n\nfunction decodeInput(schema: SchemaType<any>, value: unknown): Effect.Effect<any, Failure> {\n if (Schema.isSchema(schema))\n return Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError((error) => new Failure({ message: `Invalid tool input: ${error.message}` })),\n )\n return validateStandard(schema, value, \"Invalid tool input\")\n}\n\nfunction encodeOutput(schema: SchemaType<any>, value: unknown): Effect.Effect<any, Failure> {\n if (Schema.isSchema(schema))\n return Schema.encodeEffect(schema)(value).pipe(\n Effect.mapError(\n (error) => new Failure({ message: `Tool returned an invalid value for its output schema: ${error.message}` }),\n ),\n )\n return validateStandard(schema, value, \"Tool returned an invalid value for its output schema\")\n}\n\nfunction validateStandard(schema: StandardSchemaType, value: unknown, prefix: string): Effect.Effect<unknown, Failure> {\n return Effect.gen(function* () {\n const pending = yield* Effect.try({\n try: () => schema[\"~standard\"].validate(value),\n catch: (error) => standardFailure(prefix, error),\n })\n const result =\n pending instanceof Promise\n ? yield* Effect.tryPromise({ try: () => pending, catch: (error) => standardFailure(prefix, error) })\n : pending\n if (result.issues)\n return yield* Effect.fail(\n new Failure({ message: `${prefix}: ${result.issues.map((issue) => issue.message).join(\", \")}` }),\n )\n return result.value\n })\n}\n\nfunction standardFailure(prefix: string, error: unknown) {\n return new Failure({ message: `${prefix}: ${error instanceof Error ? error.message : String(error)}` })\n}\n\nfunction inputJsonSchema(schema: SchemaType<any>): JsonSchema.JsonSchema {\n if (!Schema.isSchema(schema))\n return schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" }) as JsonSchema.JsonSchema\n return toJsonSchema(schema)\n}\n\nfunction outputJsonSchema(schema: SchemaType<any>): JsonSchema.JsonSchema {\n if (!Schema.isSchema(schema))\n return schema[\"~standard\"].jsonSchema.output({ target: \"draft-2020-12\" }) as JsonSchema.JsonSchema\n return toJsonSchema(schema)\n}\n\nfunction toJsonSchema(schema: Schema.Top): JsonSchema.JsonSchema {\n const document = Schema.toJsonSchemaDocument(schema)\n if (Object.keys(document.definitions).length === 0) return document.schema\n return { ...document.schema, $defs: document.definitions }\n}\n\nexport interface ToolExecuteBeforeEvent {\n readonly tool: string\n readonly sessionID: Session.ID\n readonly agent: Agent.ID\n readonly messageID: SessionMessage.ID\n readonly callID: string\n input: unknown\n}\n\nexport interface ToolExecuteAfterEvent {\n readonly tool: string\n readonly sessionID: Session.ID\n readonly agent: Agent.ID\n readonly messageID: SessionMessage.ID\n readonly callID: string\n readonly input: unknown\n result: ToolResultValue\n output?: ToolOutput\n outputPaths?: ReadonlyArray<string>\n}\n\nexport interface RegisterOptions {\n readonly namespace?: string\n /** Defaults to true. False exposes the tool directly to the provider. */\n readonly codemode?: boolean\n}\n\nexport interface ToolDraft {\n add(name: string, tool: AnyTool, options?: RegisterOptions): void\n}\n\nexport interface ToolHooks {\n readonly \"execute.before\": ToolExecuteBeforeEvent\n readonly \"execute.after\": ToolExecuteAfterEvent\n}\n\nexport interface ToolDomain {\n readonly transform: Transform<ToolDraft>\n readonly hook: Hooks<ToolHooks>\n}\n", | ||
| "import type { PluginApi } from \"@opencode-ai/client/effect/api\"\nimport type { Effect, Scope } from \"effect\"\nimport type { PluginOptions } from \"../options.js\"\nimport type { App } from \"../app.js\"\nimport type { AgentDomain } from \"./agent.js\"\nimport type { AISDKDomain } from \"./aisdk.js\"\nimport type { CatalogDomain } from \"./catalog.js\"\nimport type { CommandDomain } from \"./command.js\"\nimport type { EventDomain } from \"./event.js\"\nimport type { IntegrationDomain } from \"./integration.js\"\nimport type { ReferenceDomain } from \"./reference.js\"\nimport type { SessionDomain } from \"./session.js\"\nimport type { SkillDomain } from \"./skill.js\"\nimport type { ToolDomain } from \"./tool.js\"\n\nexport interface Context {\n readonly app: App\n readonly options: PluginOptions\n readonly agent: AgentDomain\n readonly aisdk: AISDKDomain\n readonly catalog: CatalogDomain\n readonly command: CommandDomain\n readonly event: EventDomain\n readonly integration: IntegrationDomain\n readonly plugin: PluginApi<unknown>\n readonly reference: ReferenceDomain\n readonly session: SessionDomain\n readonly skill: SkillDomain\n readonly tool: ToolDomain\n}\n\nexport interface Plugin<R = Scope.Scope> {\n readonly id: string\n readonly effect: (context: Context) => Effect.Effect<void, never, R>\n}\n\nexport function define<R = Scope.Scope>(plugin: Plugin<R>) {\n return plugin\n}\n", | ||
| "export * as Session from \"./session.js\"\n\nimport { Schema } from \"effect\"\nimport { Agent } from \"./agent.js\"\nimport { Location } from \"./location.js\"\nimport { Model } from \"./model.js\"\nimport { Project } from \"./project.js\"\nimport { DateTimeUtcFromMillis, optional, RelativePath } from \"./schema.js\"\nimport { SessionEvent } from \"./session-event.js\"\nimport { SessionID } from \"./session-id.js\"\nimport { SessionMessage } from \"./session-message.js\"\nimport { Money } from \"./money.js\"\nimport { TokenUsage } from \"./token-usage.js\"\nimport { Revert } from \"./session-revert.js\"\n\nexport const ID = SessionID\nexport type ID = SessionID\n\nexport const Event = SessionEvent\n\nexport { Revert }\n\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\nexport const Info = Schema.Struct({\n id: ID,\n parentID: ID.pipe(optional),\n fork: Schema.Struct({\n sessionID: ID,\n /** Messages before this exclusive boundary are copied into the fork. */\n messageID: SessionMessage.ID.pipe(optional),\n }).pipe(optional),\n projectID: Project.ID,\n agent: Agent.ID.pipe(optional),\n model: Model.Ref.pipe(optional),\n cost: Money.USD,\n tokens: TokenUsage.Info,\n time: Schema.Struct({\n created: DateTimeUtcFromMillis,\n updated: DateTimeUtcFromMillis,\n archived: DateTimeUtcFromMillis.pipe(optional),\n }),\n title: Schema.String,\n location: Location.Ref,\n subpath: RelativePath.pipe(optional),\n revert: Revert.pipe(optional),\n}).annotate({ identifier: \"Session.Info\" })\n\nexport const ListAnchor = Schema.Struct({\n id: ID,\n time: Schema.Finite,\n direction: Schema.Literals([\"previous\", \"next\"]),\n}).annotate({ identifier: \"Session.ListAnchor\" })\nexport interface ListAnchor extends Schema.Schema.Type<typeof ListAnchor> {}\n", | ||
| "export * as Command from \"./command.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.js\"\nimport { Model } from \"./model.js\"\nimport { Agent } from \"./agent.js\"\n\nconst Updated = ephemeral({ type: \"command.updated\", schema: {} })\n\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\nexport const Info = Schema.Struct({\n name: Schema.String,\n template: Schema.String,\n description: Schema.String.pipe(optional),\n agent: Agent.ID.pipe(optional),\n model: Model.Ref.pipe(optional),\n subtask: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Command.Info\" })\n\nexport const Event = {\n Updated,\n Definitions: inventory(Updated),\n}\n", | ||
| "export * as Reference from \"./reference.js\"\n\nimport { Schema } from \"effect\"\nimport { optional } from \"./schema.js\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { AbsolutePath } from \"./schema.js\"\n\nconst Updated = ephemeral({ type: \"reference.updated\", schema: {} })\nexport const Event = { Updated, Definitions: inventory(Updated) }\n\nexport interface LocalSource extends Schema.Schema.Type<typeof LocalSource> {}\nexport const LocalSource = Schema.Struct({\n type: Schema.Literal(\"local\"),\n path: AbsolutePath,\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Reference.LocalSource\" })\n\nexport interface GitSource extends Schema.Schema.Type<typeof GitSource> {}\nexport const GitSource = Schema.Struct({\n type: Schema.Literal(\"git\"),\n repository: Schema.String,\n branch: Schema.String.pipe(optional),\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Reference.GitSource\" })\n\nexport const Source = Schema.Union([LocalSource, GitSource])\n .pipe(Schema.toTaggedUnion(\"type\"))\n .annotate({ identifier: \"Reference.Source\" })\nexport type Source = typeof Source.Type\n\nexport const Info = Schema.Struct({\n name: Schema.String,\n path: AbsolutePath,\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n source: Source,\n}).annotate({ identifier: \"Reference.Info\" })\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\n" | ||
| ], | ||
| "mappings": ";kiBAQO,SAAM,OAAU,OAAQ,eAAU,MAAE,UAAM,qBAAsB,OAAQ,CAAC,CAAE,CAAC,EAkB5E,MAAM,UAAgB,EAAQ,QAA4B,EAAE,sBAAsB,CAAE,CAAC,CAErF,IAAM,EAAQ,EAAM,OACzB,EACA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAS,MAAO,EAAQ,QACxB,EAAU,IAAI,IAChB,EAAW,EACf,OAAO,EAAQ,GAAG,CAChB,SAAU,CAAC,IACT,EAAO,KAAK,IAAM,CAChB,EAAQ,IAAI,EAAO,GAAI,IAAK,EAAQ,QAAS,OAAO,EAAE,CAAQ,CAAE,CAAC,EAClE,EAAE,KAAK,EAAO,QAAQ,EAAO,QAAQ,EAAS,CAAC,CAAC,CAAC,EAAG,EAAO,MAAM,EACpE,IAAK,IAAM,CAAC,GAAG,EAAQ,OAAO,CAAC,CACjC,CAAC,EACF,CACH,EAEa,EAAO,EAAe,CAAE,QAAS,EAAS,QAAO,KAAM,CAAC,EAAQ,IAAI,CAAE,CAAC,6NC+B7E,MAAM,UAAgB,EAAO,iBAA0B,EAAE,kBAAmB,CACjF,QAAS,EAAO,OAChB,MAAO,EAAO,SAAS,EAAO,OAAO,CAAC,EACtC,SAAU,EAAO,SAAS,EAAO,OAAO,EAAO,OAAQ,EAAO,OAAO,CAAC,CACxE,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QAAQ,OAAO,EAC5B,KAAM,EACN,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,CACtC,CAAC,EAAE,SAAS,CAAE,WAAY,uBAAwB,CAAC,EAGtC,EAAY,EAAO,OAAO,CACrC,KAAM,EAAO,QAAQ,KAAK,EAC1B,WAAY,EAAO,OACnB,OAAQ,EAAO,OAAO,KAAK,CAAQ,EACnC,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,CACtC,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAEpC,EAAS,EAAO,MAAM,CAAC,EAAa,CAAS,CAAC,EACxD,KAAK,EAAO,cAAc,MAAM,CAAC,EACjC,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAGjC,GAAO,EAAO,OAAO,CAChC,KAAM,EAAO,OACb,KAAM,EACN,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,EACpC,OAAQ,CACV,CAAC,EAAE,SAAS,CAAE,WAAY,gBAAiB,CAAC", | ||
| "debugId": "4D34D2768624CC1464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "BC776CB298FA9DB964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+togetherai@2.0.41+d6123d32214422cb/node_modules/@ai-sdk/togetherai/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/togetherai-provider.ts\nimport {\n OpenAICompatibleChatLanguageModel,\n OpenAICompatibleCompletionLanguageModel,\n OpenAICompatibleEmbeddingModel\n} from \"@ai-sdk/openai-compatible\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/reranking/togetherai-reranking-model.ts\nimport {\n combineHeaders,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\n\n// src/reranking/togetherai-reranking-api.ts\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\nvar togetheraiErrorSchema = lazySchema(\n () => zodSchema(\n z.object({\n error: z.object({\n message: z.string()\n })\n })\n )\n);\nvar togetheraiRerankingResponseSchema = lazySchema(\n () => zodSchema(\n z.object({\n id: z.string().nullish(),\n model: z.string().nullish(),\n results: z.array(\n z.object({\n index: z.number(),\n relevance_score: z.number()\n })\n ),\n usage: z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number(),\n total_tokens: z.number()\n })\n })\n )\n);\n\n// src/reranking/togetherai-reranking-options.ts\nimport { lazySchema as lazySchema2, zodSchema as zodSchema2 } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar togetheraiRerankingModelOptionsSchema = lazySchema2(\n () => zodSchema2(\n z2.object({\n rankFields: z2.array(z2.string()).optional()\n })\n )\n);\n\n// src/reranking/togetherai-reranking-model.ts\nvar TogetherAIRerankingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n // see https://docs.together.ai/reference/rerank-1\n async doRerank({\n documents,\n headers,\n query,\n topN,\n abortSignal,\n providerOptions\n }) {\n var _a, _b;\n const rerankingOptions = await parseProviderOptions({\n provider: \"togetherai\",\n providerOptions,\n schema: togetheraiRerankingModelOptionsSchema\n });\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi({\n url: `${this.config.baseURL}/rerank`,\n headers: combineHeaders(this.config.headers(), headers),\n body: {\n model: this.modelId,\n documents: documents.values,\n query,\n top_n: topN,\n rank_fields: rerankingOptions == null ? void 0 : rerankingOptions.rankFields,\n return_documents: false\n // reduce response size\n },\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: togetheraiErrorSchema,\n errorToMessage: (data) => data.error.message\n }),\n successfulResponseHandler: createJsonResponseHandler(\n togetheraiRerankingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n ranking: response.results.map((result) => ({\n index: result.index,\n relevanceScore: result.relevance_score\n })),\n response: {\n id: (_a = response.id) != null ? _a : void 0,\n modelId: (_b = response.model) != null ? _b : void 0,\n headers: responseHeaders,\n body: rawValue\n }\n };\n }\n};\n\n// src/togetherai-image-model.ts\nimport {\n combineHeaders as combineHeaders2,\n convertImageModelFileToDataUri,\n createJsonResponseHandler as createJsonResponseHandler2,\n createJsonErrorResponseHandler as createJsonErrorResponseHandler2,\n lazySchema as lazySchema3,\n parseProviderOptions as parseProviderOptions2,\n postJsonToApi as postJsonToApi2,\n zodSchema as zodSchema3\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\nvar TogetherAIImageModel = class {\n constructor(modelId, config) {\n this.modelId = modelId;\n this.config = config;\n this.specificationVersion = \"v3\";\n this.maxImagesPerCall = 1;\n }\n get provider() {\n return this.config.provider;\n }\n async doGenerate({\n prompt,\n n,\n size,\n seed,\n providerOptions,\n headers,\n abortSignal,\n files,\n mask\n }) {\n var _a, _b, _c;\n const warnings = [];\n if (mask != null) {\n throw new Error(\n \"Together AI does not support mask-based image editing. Use FLUX Kontext models (e.g., black-forest-labs/FLUX.1-kontext-pro) with a reference image and descriptive prompt instead.\"\n );\n }\n if (size != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"aspectRatio\",\n details: \"This model does not support the `aspectRatio` option. Use `size` instead.\"\n });\n }\n const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();\n const togetheraiOptions = await parseProviderOptions2({\n provider: \"togetherai\",\n providerOptions,\n schema: togetheraiImageModelOptionsSchema\n });\n let imageUrl;\n if (files != null && files.length > 0) {\n imageUrl = convertImageModelFileToDataUri(files[0]);\n if (files.length > 1) {\n warnings.push({\n type: \"other\",\n message: \"Together AI only supports a single input image. Additional images are ignored.\"\n });\n }\n }\n const splitSize = size == null ? void 0 : size.split(\"x\");\n const { value: response, responseHeaders } = await postJsonToApi2({\n url: `${this.config.baseURL}/images/generations`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n prompt,\n seed,\n ...n > 1 ? { n } : {},\n ...splitSize && {\n width: parseInt(splitSize[0]),\n height: parseInt(splitSize[1])\n },\n ...imageUrl != null ? { image_url: imageUrl } : {},\n response_format: \"base64\",\n ...togetheraiOptions != null ? togetheraiOptions : {}\n },\n failedResponseHandler: createJsonErrorResponseHandler2({\n errorSchema: togetheraiErrorSchema2,\n errorToMessage: (data) => data.error.message\n }),\n successfulResponseHandler: createJsonResponseHandler2(\n togetheraiImageResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n images: response.data.map((item) => item.b64_json),\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders\n }\n };\n }\n};\nvar togetheraiImageResponseSchema = z3.object({\n data: z3.array(\n z3.object({\n b64_json: z3.string()\n })\n )\n});\nvar togetheraiErrorSchema2 = z3.object({\n error: z3.object({\n message: z3.string()\n })\n});\nvar togetheraiImageModelOptionsSchema = lazySchema3(\n () => zodSchema3(\n z3.object({\n /**\n * Number of generation steps. Higher values can improve quality.\n */\n steps: z3.number().nullish(),\n /**\n * Guidance scale for image generation.\n */\n guidance: z3.number().nullish(),\n /**\n * Negative prompt to guide what to avoid.\n */\n negative_prompt: z3.string().nullish(),\n /**\n * Disable the safety checker for image generation.\n * When true, the API will not reject images flagged as potentially NSFW.\n * Not available for Flux Schnell Free and Flux Pro models.\n */\n disable_safety_checker: z3.boolean().nullish()\n }).passthrough()\n )\n);\n\n// src/version.ts\nvar VERSION = true ? \"2.0.41\" : \"0.0.0-test\";\n\n// src/togetherai-provider.ts\nfunction loadDeprecatedApiKey() {\n if (typeof process === \"undefined\") {\n return void 0;\n }\n if (typeof process.env.TOGETHER_API_KEY === \"string\") {\n return void 0;\n }\n const key = process.env.TOGETHER_AI_API_KEY;\n if (typeof key === \"string\") {\n console.warn(\n \"TOGETHER_AI_API_KEY is deprecated and will be removed in a future release. Please use TOGETHER_API_KEY instead.\"\n );\n }\n return key;\n}\nfunction createTogetherAI(options = {}) {\n var _a;\n const baseURL = withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.together.xyz/v1/\"\n );\n const getHeaders = () => {\n var _a2;\n return withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: (_a2 = options.apiKey) != null ? _a2 : loadDeprecatedApiKey(),\n environmentVariableName: \"TOGETHER_API_KEY\",\n description: \"TogetherAI\"\n })}`,\n ...options.headers\n },\n `ai-sdk/togetherai/${VERSION}`\n );\n };\n const getCommonModelConfig = (modelType) => ({\n provider: `togetherai.${modelType}`,\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createChatModel = (modelId) => {\n return new OpenAICompatibleChatLanguageModel(\n modelId,\n getCommonModelConfig(\"chat\")\n );\n };\n const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(\n modelId,\n getCommonModelConfig(\"completion\")\n );\n const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(\n modelId,\n getCommonModelConfig(\"embedding\")\n );\n const createImageModel = (modelId) => new TogetherAIImageModel(modelId, {\n ...getCommonModelConfig(\"image\"),\n baseURL: baseURL != null ? baseURL : \"https://api.together.xyz/v1/\"\n });\n const createRerankingModel = (modelId) => new TogetherAIRerankingModel(modelId, {\n ...getCommonModelConfig(\"reranking\"),\n baseURL: baseURL != null ? baseURL : \"https://api.together.xyz/v1/\"\n });\n const provider = (modelId) => createChatModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.completionModel = createCompletionModel;\n provider.languageModel = createChatModel;\n provider.chatModel = createChatModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.image = createImageModel;\n provider.imageModel = createImageModel;\n provider.reranking = createRerankingModel;\n provider.rerankingModel = createRerankingModel;\n return provider;\n}\nvar togetherai = createTogetherAI();\nexport {\n VERSION,\n createTogetherAI,\n togetherai\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";4ZAwBA,SAAI,OAAwB,OAC1B,SAAM,OACJ,OAAE,YAAO,CACP,MAAO,EAAE,OAAO,CACd,QAAS,EAAE,OAAO,CACpB,CAAC,CACH,CAAC,CACH,CACF,EACI,EAAoC,EACtC,IAAM,EACJ,EAAE,OAAO,CACP,GAAI,EAAE,OAAO,EAAE,QAAQ,EACvB,MAAO,EAAE,OAAO,EAAE,QAAQ,EAC1B,QAAS,EAAE,MACT,EAAE,OAAO,CACP,MAAO,EAAE,OAAO,EAChB,gBAAiB,EAAE,OAAO,CAC5B,CAAC,CACH,EACA,MAAO,EAAE,OAAO,CACd,cAAe,EAAE,OAAO,EACxB,kBAAmB,EAAE,OAAO,EAC5B,aAAc,EAAE,OAAO,CACzB,CAAC,CACH,CAAC,CACH,CACF,EAKI,EAAwC,EAC1C,IAAM,EACJ,EAAG,OAAO,CACR,WAAY,EAAG,MAAM,EAAG,OAAO,CAAC,EAAE,SAAS,CAC7C,CAAC,CACH,CACF,EAGI,EAA2B,KAAM,CACnC,WAAW,CAAC,EAAS,EAAQ,CAC3B,KAAK,qBAAuB,KAC5B,KAAK,QAAU,EACf,KAAK,OAAS,KAEZ,SAAQ,EAAG,CACb,OAAO,KAAK,OAAO,cAGf,SAAQ,EACZ,YACA,UACA,QACA,OACA,cACA,mBACC,CACD,IAAI,EAAI,EACR,IAAM,EAAmB,MAAM,EAAqB,CAClD,SAAU,aACV,kBACA,OAAQ,CACV,CAAC,GAEC,kBACA,MAAO,EACP,YACE,MAAM,EAAc,CACtB,IAAK,GAAG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,EAC9B,EAAS,MAAQ,EACjB,EAAS,WAAa,EACtB,EAAS,UAAY,EACrB,EAAS,eAAiB,EACnB,EAET,IAAI,GAAa,EAAiB", | ||
| "debugId": "226141210FC0052264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/auth.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport {\n OpenCode,\n type IntegrationAttemptStatus,\n type IntegrationOAuthMethod,\n type OpenCodeClient,\n} from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.auth,\n Effect.fn(\"cli.mcp.auth\")(function* (input) {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n const method = integration.methods.find(\n (candidate): candidate is IntegrationOAuthMethod => candidate.type === \"oauth\",\n )\n if (!method)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n\n const started = yield* Effect.promise(() =>\n client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),\n )\n const attempt = started.data\n if (attempt.mode === \"code\")\n return yield* Effect.fail(new Error(\"This server requires manual code entry, which the CLI does not support\"))\n\n process.stdout.write(attempt.instructions + EOL + attempt.url + EOL)\n\n const result = yield* poll(client, integration.id, attempt.attemptID)\n if (result.status === \"complete\") {\n process.stdout.write(`Authenticated with ${input.name}` + EOL)\n return\n }\n const reason = result.status === \"failed\" ? `: ${result.message}` : \"\"\n return yield* Effect.fail(new Error(`Authentication ${result.status}${reason}`))\n }),\n)\n\nconst poll = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n): Effect.Effect<Exclude<IntegrationAttemptStatus, { status: \"pending\" }>> =>\n Effect.gen(function* () {\n const status = yield* Effect.promise(() =>\n client.integration.oauth.status({ integrationID, attemptID, location }),\n ).pipe(Effect.map((result) => result.data))\n if (status.status === \"pending\") {\n yield* Effect.sleep(\"1 second\")\n return yield* poll(client, integrationID, attemptID)\n }\n return status\n })\n" | ||
| ], | ||
| "mappings": ";66BAAA,mBAAS,gBAcT,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,UAC/B,OAAO,QAAG,mBAAc,OAAE,cAAU,MAAC,OAAO,CAC1C,IAAM,EAAU,MAAO,EAAc,QAAQ,EAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,eAAe,EAAM,6CAA6C,CAAC,EACzG,IAAM,EAAS,EAAY,QAAQ,KACjC,CAAC,IAAmD,EAAU,OAAS,OACzE,EACA,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,eAAe,EAAM,6CAA6C,CAAC,EAKzG,IAAM,GAHU,MAAO,EAAO,QAAQ,IACpC,EAAO,YAAY,MAAM,QAAQ,CAAE,cAAe,EAAY,GAAI,SAAU,EAAO,GAAI,OAAQ,CAAC,EAAG,UAAS,CAAC,CAC/G,GACwB,KACxB,GAAI,EAAQ,OAAS,OACnB,OAAO,MAAO,EAAO,KAAS,MAAM,wEAAwE,CAAC,EAE/G,QAAQ,OAAO,MAAM,EAAQ,aAAe,EAAM,EAAQ,IAAM,CAAG,EAEnE,IAAM,EAAS,MAAO,EAAK,EAAQ,EAAY,GAAI,EAAQ,SAAS,EACpE,GAAI,EAAO,SAAW,WAAY,CAChC,QAAQ,OAAO,MAAM,sBAAsB,EAAM,OAAS,CAAG,EAC7D,OAEF,IAAM,EAAS,EAAO,SAAW,SAAW,KAAK,EAAO,UAAY,GACpE,OAAO,MAAO,EAAO,KAAS,MAAM,kBAAkB,EAAO,SAAS,GAAQ,CAAC,EAChF,CACH,EAEM,EAAO,CACX,EACA,EACA,IAEA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAS,MAAO,EAAO,QAAQ,IACnC,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,CAAC,CACxE,EAAE,KAAK,EAAO,IAAI,CAAC,IAAW,EAAO,IAAI,CAAC,EAC1C,GAAI,EAAO,SAAW,UAEpB,OADA,MAAO,EAAO,MAAM,UAAU,EACvB,MAAO,EAAK,EAAQ,EAAe,CAAS,EAErD,OAAO,EACR", | ||
| "debugId": "408C18CAC640DF8A64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/openai-compatible.ts"], | ||
| "sourcesContent": [ | ||
| "import { ProviderID, type ModelID } from \"../schema\"\nimport * as OpenAICompatibleChat from \"../protocols/openai-compatible-chat\"\nimport type { RouteDefaultsInput } from \"../route/client\"\nimport { AuthOptions, type ProviderAuthOption } from \"../route/auth-options\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { profiles, type OpenAICompatibleProfile } from \"./openai-compatible-profile\"\n\nexport const id = ProviderID.make(\"openai-compatible\")\n\ntype GenericModelOptions = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly provider?: string\n readonly baseURL: string\n }\n\nexport interface Settings extends ProviderPackage.Settings {\n readonly apiKey?: string\n readonly baseURL: string\n readonly provider?: string\n}\n\nexport type FamilyModelOptions = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n }\n\nexport const routes = [OpenAICompatibleChat.route]\n\nexport const configure = (input: GenericModelOptions) => {\n const provider = input.provider ?? \"openai-compatible\"\n const { provider: _, baseURL, apiKey: _apiKey, auth: _auth, ...rest } = input\n const route = OpenAICompatibleChat.route.with({\n ...rest,\n provider,\n endpoint: { baseURL },\n auth: AuthOptions.bearer(input, []),\n })\n return {\n id: ProviderID.make(provider),\n model: (modelID: string | ModelID) => route.model({ id: modelID, provider: ProviderID.make(provider) }),\n configure,\n }\n}\n\nconst define = (profile: OpenAICompatibleProfile) => {\n const configureProfile = (input: FamilyModelOptions = {}) => {\n const facade = configure({\n ...input,\n baseURL: input.baseURL ?? profile.baseURL,\n provider: profile.provider,\n })\n return {\n id: ProviderID.make(profile.provider),\n model: facade.model,\n configure: configureProfile,\n }\n }\n return configureProfile()\n}\n\nexport const provider = {\n id,\n configure,\n}\n\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure({\n apiKey: settings.apiKey,\n baseURL: settings.baseURL,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n provider: settings.provider,\n }).model(modelID)\n\nexport const baseten = define(profiles.baseten)\nexport const cerebras = define(profiles.cerebras)\nexport const deepinfra = define(profiles.deepinfra)\nexport const deepseek = define(profiles.deepseek)\nexport const fireworks = define(profiles.fireworks)\nexport const groq = define(profiles.groq)\nexport const togetherai = define(profiles.togetherai)\n" | ||
| ], | ||
| "mappings": ";qhBAOO,SAAM,OAAK,OAAW,UAAK,wBAAmB,OAmBxC,OAAS,MAAsB,MAAK,OAEpC,OAAY,MAAC,SAA+B,CACvD,IAAM,EAAW,EAAM,UAAY,qBAC3B,SAAU,EAAG,UAAS,OAAQ,EAAS,KAAM,KAAU,GAAS,EAClE,EAA6B,EAAM,KAAK,IACzC,EACH,WACA,SAAU,CAAE,SAAQ,EACpB,KAAM,EAAY,OAAO,EAAO,CAAC,CAAC,CACpC,CAAC,EACD,MAAO,CACL,GAAI,EAAW,KAAK,CAAQ,EAC5B,MAAO,CAAC,IAA8B,EAAM,MAAM,CAAE,GAAI,EAAS,SAAU,EAAW,KAAK,CAAQ,CAAE,CAAC,EACtG,WACF,GAGI,EAAS,CAAC,IAAqC,CACnD,IAAM,EAAmB,CAAC,EAA4B,CAAC,IAAM,CAC3D,IAAM,EAAS,EAAU,IACpB,EACH,QAAS,EAAM,SAAW,EAAQ,QAClC,SAAU,EAAQ,QACpB,CAAC,EACD,MAAO,CACL,GAAI,EAAW,KAAK,EAAQ,QAAQ,EACpC,MAAO,EAAO,MACd,UAAW,CACb,GAEF,OAAO,EAAiB,GAGb,EAAW,CACtB,KACA,WACF,EAEa,EAAuD,CAAC,EAAS,IAC5E,EAAU,CACR,OAAQ,EAAS,OACjB,QAAS,EAAS,QAClB,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,OACjB,SAAU,EAAS,QACrB,CAAC,EAAE,MAAM,CAAO,EAEL,EAAU,EAAO,EAAS,OAAO,EACjC,EAAW,EAAO,EAAS,QAAQ,EACnC,EAAY,EAAO,EAAS,SAAS,EACrC,EAAW,EAAO,EAAS,QAAQ,EACnC,EAAY,EAAO,EAAS,SAAS,EACrC,EAAO,EAAO,EAAS,IAAI,EAC3B,EAAa,EAAO,EAAS,UAAU", | ||
| "debugId": "47DE75E77A74C4E564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/mini.ts", "src/mini-host.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { setTimeout } from \"node:timers/promises\"\nimport { readStdin } from \"./util/io\"\nimport { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from \"./mini-host\"\nimport { parseSessionTargetModel, resolveSessionTarget, type SessionTargetPreparation } from \"./session-target\"\n\nexport type MiniCommandInput = {\n server: {\n endpoint: Endpoint\n reconnect?: (signal: AbortSignal) => Promise<Endpoint>\n }\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n prompt?: string\n replay?: boolean\n replayLimit?: number\n demo?: boolean\n tuiConfig?: MiniFrontendInput[\"tuiConfig\"]\n config?: MiniFrontendInput[\"config\"]\n}\n\ntype Model = MiniFrontendInput[\"model\"]\n\nclass MiniInputError extends Error {}\n\nexport async function runMini(input: MiniCommandInput) {\n try {\n validate(input)\n const result = await usingInteractiveStdin(async (terminal) => {\n const initialInput = mergeInput(process.stdin.isTTY ? undefined : await readStdin(), input.prompt)\n const frontendTask = import(\"@opencode-ai/tui/mini\")\n const directory = localDirectory()\n const connection = createMiniConnection(input.server)\n const sdk = connection.sdk\n const requested = parseModel(input.model)\n const model = requested ? { providerID: requested.providerID, modelID: requested.id } : undefined\n const prepare = prepareTarget(input.agent)\n const resolveTarget = async (initial: OpenCodeClient, signal: AbortSignal) => {\n const resolved = await resolveMiniTarget({\n sdk: initial,\n reconnect: connection.reconnect,\n signal,\n resolve: (client) =>\n resolveSessionTarget({\n client,\n location: { directory },\n continue: input.continue,\n session: input.session,\n fork: input.fork,\n model: requested,\n agent: input.agent,\n prepare,\n signal,\n }).catch((error) => {\n if (error instanceof Error && error.message === \"Session not found\")\n throw new MiniInputError(error.message)\n throw error\n }),\n })\n const target = resolved.value\n return {\n sdk: resolved.sdk,\n sessionID: target.session.id,\n sessionTitle: target.session.title,\n location: target.location,\n model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,\n variant: target.model?.variant,\n agent: target.agent,\n resume: target.resume,\n }\n }\n const create = (\n client: OpenCodeClient,\n next: {\n location: { directory: string; workspaceID?: string }\n agent: string | undefined\n model: Model\n variant: string | undefined\n },\n signal?: AbortSignal,\n ) =>\n resolveSessionTarget({\n client,\n location: { directory: next.location.directory, workspace: next.location.workspaceID },\n agent: next.agent,\n model: next.model\n ? { providerID: next.model.providerID, id: next.model.modelID, variant: next.variant }\n : undefined,\n prepare,\n signal,\n }).then((target) => ({\n sessionID: target.session.id,\n sessionTitle: target.session.title,\n location: target.location,\n model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,\n variant: target.model?.variant,\n agent: target.agent,\n resume: false,\n }))\n const frontend = await frontendTask\n return frontend.runMiniFrontend({\n host: createMiniHost({ terminal, directory }),\n sdk,\n directory,\n target: resolveTarget,\n reconnect: connection.reconnect,\n createSession: create,\n agent: input.agent,\n model,\n variant: requested?.variant,\n files: [],\n initialInput,\n replay: input.replay ?? true,\n replayLimit: input.replayLimit,\n demo: input.demo,\n tuiConfig: input.tuiConfig,\n config: input.config,\n })\n })\n if (result.exitCode !== 0) process.exit(result.exitCode)\n } catch (error) {\n if (error instanceof MiniInputError || (error instanceof Error && error.message === INTERACTIVE_INPUT_ERROR))\n fail(error.message)\n throw error\n }\n}\n\n/** @internal Exported for CLI boundary tests. */\nexport function createMiniConnection(input: MiniCommandInput[\"server\"]) {\n const make = (endpoint: Endpoint) =>\n OpenCode.make({\n baseUrl: endpoint.url,\n headers: Service.headers(endpoint),\n })\n const reconnect = input.reconnect\n return {\n sdk: make(input.endpoint),\n reconnect: reconnect\n ? async (signal: AbortSignal) => {\n const endpoint = await reconnect(signal)\n return make(endpoint)\n }\n : undefined,\n }\n}\n\n/** @internal Exported for reconnect lifecycle tests. */\nexport async function resolveMiniTarget<A>(input: {\n sdk: OpenCodeClient\n reconnect?: (signal: AbortSignal) => Promise<OpenCodeClient>\n signal: AbortSignal\n resolve: (sdk: OpenCodeClient) => Promise<A>\n}) {\n let sdk = input.sdk\n while (true) {\n try {\n return { sdk, value: await input.resolve(sdk) }\n } catch (error) {\n if (!input.reconnect || !(error instanceof ClientError) || error.reason !== \"Transport\") throw error\n while (true) {\n try {\n sdk = await input.reconnect(input.signal)\n break\n } catch (resolveError) {\n if (input.signal.aborted) throw resolveError\n await setTimeout(250, undefined, { signal: input.signal })\n }\n }\n }\n }\n}\n\nexport function validateMiniTerminal() {\n if (!process.stdout.isTTY) fail(\"opencode mini requires a TTY stdout\")\n}\n\n/** @internal Exported for testing. */\nexport function mergeInput(piped: string | undefined, prompt: string | undefined) {\n if (!prompt) return piped || undefined\n if (!piped) return prompt\n return piped + \"\\n\" + prompt\n}\n\nfunction validate(input: MiniCommandInput) {\n validateMiniTerminal()\n if (input.replayLimit !== undefined && (!Number.isInteger(input.replayLimit) || input.replayLimit <= 0)) {\n fail(\"--replay-limit must be a positive integer\")\n }\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n}\n\nfunction localDirectory(): string {\n const root = process.env.PWD ?? process.cwd()\n try {\n process.chdir(root)\n return process.cwd()\n } catch {\n throw new MiniInputError(`Failed to change directory to ${root}`)\n }\n}\n\nfunction parseModel(value?: string) {\n try {\n return parseSessionTargetModel(value)\n } catch {\n throw new MiniInputError(\"--model must use the format provider/model[#variant]\")\n }\n}\n\nfunction prepareTarget(requestedAgent?: string): SessionTargetPreparation {\n return async (input) => ({ model: input.model, agent: requestedAgent ?? input.agent })\n}\n\nfunction fail(message: string): never {\n process.stderr.write(`\\x1b[91m\\x1b[1mError: \\x1b[0m${message}\\n`)\n process.exit(1)\n}\n", | ||
| "import type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { createModelPreferenceRepository } from \"@opencode-ai/tui/model-preference\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport fs from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { ReadStream } from \"node:tty\"\n\nexport const INTERACTIVE_INPUT_ERROR = \"opencode mini requires a controlling terminal for input\"\n\nexport type InteractiveStdin = {\n stdin: NodeJS.ReadStream\n cleanup(): void\n}\n\ntype MiniHost = MiniFrontendInput[\"host\"]\n\nfunction preferences(statePath: string): MiniHost[\"preferences\"] {\n const repository = createModelPreferenceRepository(path.join(statePath, \"model.json\"))\n return {\n async resolveVariant(model) {\n if (!model) return\n return repository.resolveVariant(model)\n },\n async saveVariant(model, variant) {\n if (!model) return\n await repository.saveVariant(model, variant).catch(() => undefined)\n },\n }\n}\n\nfunction signal(name: \"SIGINT\" | \"SIGUSR2\"): MiniHost[\"signals\"][\"sigint\"] {\n return {\n subscribe(listener) {\n let subscribed = true\n process.on(name, listener)\n return () => {\n if (!subscribed) return\n subscribed = false\n process.off(name, listener)\n }\n },\n }\n}\n\nfunction createTrace(\n logPath: string,\n diagnostics: { pid: number; cwd: string; argv: string[] },\n): MiniHost[\"diagnostics\"][\"trace\"] {\n if (!process.env.OPENCODE_DIRECT_TRACE) return\n const stamp = new Date()\n .toISOString()\n .replace(/[-:]/g, \"\")\n .replace(/\\.\\d+Z$/, \"Z\")\n const target = path.join(logPath, \"direct\", `${stamp}-${diagnostics.pid}.jsonl`)\n const text = (data: unknown) =>\n JSON.stringify(data, (_key, value) => (typeof value === \"bigint\" ? String(value) : value), 0)\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(\n path.join(logPath, \"direct\", \"latest.json\"),\n text({\n time: new Date().toISOString(),\n ...diagnostics,\n path: target,\n }) + \"\\n\",\n )\n const trace = {\n write(type: string, data?: unknown) {\n fs.appendFileSync(\n target,\n text({\n time: new Date().toISOString(),\n pid: diagnostics.pid,\n type,\n data,\n }) + \"\\n\",\n )\n },\n }\n trace.write(\"trace.start\", {\n argv: diagnostics.argv,\n cwd: diagnostics.cwd,\n path: target,\n })\n return trace\n}\n\nfunction openTerminalStdin(target: string): NodeJS.ReadStream {\n return new ReadStream(fs.openSync(target, \"r\"))\n}\n\nexport function resolveInteractiveStdin(\n stdin: NodeJS.ReadStream = process.stdin,\n open: (target: string) => NodeJS.ReadStream = openTerminalStdin,\n platform: NodeJS.Platform = process.platform,\n): InteractiveStdin {\n if (stdin.isTTY) return { stdin, cleanup() {} }\n const target = platform === \"win32\" ? \"CONIN$\" : \"/dev/tty\"\n try {\n const source = open(target)\n let cleaned = false\n return {\n stdin: source,\n cleanup() {\n if (cleaned) return\n cleaned = true\n source.destroy()\n },\n }\n } catch (error) {\n throw new Error(INTERACTIVE_INPUT_ERROR, { cause: error })\n }\n}\n\n/** @internal Exported for owner-local resource cleanup tests. */\nexport async function usingInteractiveStdin<T>(\n run: (terminal: InteractiveStdin) => Promise<T>,\n resolve: () => InteractiveStdin = resolveInteractiveStdin,\n) {\n const terminal = resolve()\n try {\n return await run(terminal)\n } finally {\n terminal.cleanup()\n }\n}\n\n/** @internal Exported for owner-local host capability tests. */\nexport function createMiniHost(input: {\n terminal: InteractiveStdin\n directory: string\n paths?: { home: string; state: string; log: string }\n}): MiniHost {\n const paths = input.paths ?? {\n home: Global.Path.home,\n state: Global.Path.state,\n log: Global.Path.log,\n }\n const diagnostics = {\n pid: process.pid,\n cwd: input.directory,\n argv: process.argv.slice(2),\n }\n return {\n terminal: { stdin: input.terminal.stdin },\n platform: process.platform,\n stdout: {\n write(value) {\n process.stdout.write(value)\n },\n },\n files: {\n readText: (url) => readFile(new URL(url), \"utf8\"),\n },\n editor: {\n async open(options) {\n const { openEditor } = await import(\"@opencode-ai/tui/editor\")\n return openEditor(options)\n },\n },\n paths: { home: paths.home },\n signals: {\n sigint: signal(\"SIGINT\"),\n sigusr2: signal(\"SIGUSR2\"),\n },\n startup: {\n showTiming: [\"1\", \"true\"].includes(process.env.OPENCODE_SHOW_TTFD?.toLowerCase() ?? \"\"),\n now: () => performance.now(),\n },\n diagnostics: {\n trace: createTrace(paths.log, diagnostics),\n },\n preferences: preferences(paths.state),\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,QAAQ,IAAI,KAAO,QAAQ,IAAI,EAC5C,GAAI,CAEF,OADA,QAAQ,MAAM,CAAI,EACX,QAAQ,IAAI,EACnB,KAAM,CACN,MAAM,IAAI,EAAe,iCAAiC,GAAM,GAIpE,SAAS,CAAU,CAAC,EAAgB,CAClC,GAAI,CACF,OAAO,EAAwB,CAAK,EACpC,KAAM,CACN,MAAM,IAAI,EAAe,sDAAsD,GAInF,SAAS,CAAa,CAAC,EAAmD,CACxE,MAAO,OAAO,KAAW,CAAE,MAAO,EAAM,MAAO,MAAO,GAAkB,EAAM,KAAM,GAGtF,SAAS,CAAI,CAAC,EAAwB,CACpC,QAAQ,OAAO,MAAM,gCAAgC;AAAA,CAAW,EAChE,QAAQ,KAAK,CAAC", | ||
| "debugId": "FFEB8B23C302D97A64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "6D4DF097FAC97A7564756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/pair.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode } from \"@opencode-ai/client/promise\"\nimport { renderUnicodeCompact } from \"uqr\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServiceConfig } from \"../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.pair,\n Effect.fn(\"cli.pair\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const password = yield* ServiceConfig.password()\n const server = yield* Effect.tryPromise(() =>\n OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.get(),\n )\n const info = { urls: server.urls, username: \"opencode\", password }\n process.stdout.write(\n [\n \"\",\n ` URLs ${info.urls[0] ?? \"(none)\"}`,\n ...info.urls.slice(1).map((url) => ` ${url}`),\n ` Username ${info.username}`,\n ` Password ${info.password}`,\n \"\",\n \" Scan to pair\",\n \"\",\n renderUnicodeCompact(JSON.stringify(info), { border: 2 })\n .split(EOL)\n .map((line) => \" \" + line)\n .join(EOL),\n \"\",\n ].join(EOL) + EOL,\n )\n\n const hostname = new URL(endpoint.url).hostname\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(hostname)) return\n process.stderr.write(\n ` Run \\`opencode service set hostname 0.0.0.0\\` to access the service remotely.${EOL}${EOL}`,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";66BAAA,mBAAS,gBAST,SAAe,SAAQ,aACrB,OAAS,cAAS,UAClB,OAAO,QAAG,eAAU,OAAE,cAAU,OAAG,MACjC,SAAM,OAAW,WAAO,OAAQ,YAAO,WAAO,OAAc,aAAQ,MAAC,EAC/D,EAAW,MAAO,EAAc,SAAS,EAIzC,EAAO,CAAE,MAHA,MAAO,EAAO,WAAW,IACtC,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAAE,OAAO,IAAI,CAC1F,GAC4B,KAAM,SAAU,WAAY,UAAS,EACjE,QAAQ,OAAO,MACb,CACE,GACA,eAAe,EAAK,KAAK,IAAM,WAC/B,GAAG,EAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,IAAQ,eAAe,GAAK,EACvD,eAAe,EAAK,WACpB,eAAe,EAAK,WACpB,GACA,iBACA,GACA,EAAqB,KAAK,UAAU,CAAI,EAAG,CAAE,OAAQ,CAAE,CAAC,EACrD,MAAM,CAAG,EACT,IAAI,CAAC,IAAS,KAAO,CAAI,EACzB,KAAK,CAAG,EACX,EACF,EAAE,KAAK,CAAG,EAAI,CAChB,EAEA,IAAM,EAAW,IAAI,IAAI,EAAS,GAAG,EAAE,SACvC,GAAI,CAAC,CAAC,YAAa,YAAa,OAAO,EAAE,SAAS,CAAQ,EAAG,OAC7D,QAAQ,OAAO,MACb,kFAAkF,IAAM,GAC1F,EACD,CACH", | ||
| "debugId": "4CE250B634AF740E64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/add.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { readFile, stat, writeFile } from \"node:fs/promises\"\nimport { Effect, Option } from \"effect\"\nimport { applyEdits, modify } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.add,\n Effect.fn(\"cli.mcp.add\")(function* (input) {\n const url = Option.getOrUndefined(input.url)\n const headers = Option.getOrUndefined(input.header)\n const environment = Option.getOrUndefined(input.env)\n // The CLI framework strands `--` operands on the root command, so read the local server command\n // straight from argv after `--`. This also lets the command carry its own flags (e.g. `npx -y`).\n const dash = process.argv.indexOf(\"--\")\n const command = dash === -1 ? [...input.command] : process.argv.slice(dash + 1)\n\n const hasCommand = command.length > 0\n if (url && hasCommand)\n return yield* Effect.fail(new Error(\"Provide either --url <url> or a command after --, not both\"))\n if (!url && !hasCommand) return yield* Effect.fail(new Error(\"Provide either --url <url> or a command after --\"))\n if (url && !URL.canParse(url)) return yield* Effect.fail(new Error(`Invalid URL: ${url}`))\n if (url && environment) return yield* Effect.fail(new Error(\"--env is only valid for local MCP servers\"))\n if (hasCommand && headers) return yield* Effect.fail(new Error(\"--header is only valid for remote MCP servers\"))\n\n const server = url\n ? { type: \"remote\" as const, url, ...(headers ? { headers } : {}) }\n : { type: \"local\" as const, command, ...(environment ? { environment } : {}) }\n\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(input.global ? global.config : process.cwd()))\n yield* Effect.promise(() => write(configPath, input.name, server))\n process.stdout.write(`MCP server \"${input.name}\" added to ${configPath}` + EOL)\n }),\n)\n\nexport async function resolveConfigPath(directory: string) {\n const candidates = [\n path.join(directory, \"opencode.json\"),\n path.join(directory, \"opencode.jsonc\"),\n path.join(directory, \".opencode\", \"opencode.json\"),\n path.join(directory, \".opencode\", \"opencode.jsonc\"),\n ]\n for (const candidate of candidates) {\n if (\n await stat(candidate).then(\n (info) => info.isFile(),\n () => false,\n )\n )\n return candidate\n }\n return candidates[0]\n}\n\nasync function write(configPath: string, name: string, server: unknown) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return \"{}\"\n throw error\n })\n const edits = modify(text, [\"mcp\", \"servers\", name], server, {\n formattingOptions: { tabSize: 2, insertSpaces: true },\n })\n await writeFile(configPath, applyEdits(text, edits))\n}\n" | ||
| ], | ||
| "mappings": ";qrBAAA,mBAAS,gBACT,yBACA,wBAAS,eAAU,oBAAM,yBAOzB,SAAe,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,SAC/B,OAAO,QAAG,aAAa,EAAE,SAAU,CAAC,EAAO,CACzC,IAAM,EAAM,EAAO,eAAe,EAAM,GAAG,EACrC,EAAU,EAAO,eAAe,EAAM,MAAM,EAC5C,EAAc,EAAO,eAAe,EAAM,GAAG,EAG7C,EAAO,QAAQ,KAAK,QAAQ,IAAI,EAChC,EAAU,IAAS,GAAK,CAAC,GAAG,EAAM,OAAO,EAAI,QAAQ,KAAK,MAAM,EAAO,CAAC,EAExE,EAAa,EAAQ,OAAS,EACpC,GAAI,GAAO,EACT,OAAO,MAAO,EAAO,KAAS,MAAM,4DAA4D,CAAC,EACnG,GAAI,CAAC,GAAO,CAAC,EAAY,OAAO,MAAO,EAAO,KAAS,MAAM,kDAAkD,CAAC,EAChH,GAAI,GAAO,CAAC,IAAI,SAAS,CAAG,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,gBAAgB,GAAK,CAAC,EACzF,GAAI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AAC", | ||
| "debugId": "5935E728C5B31F9964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/run/run.ts", "src/run/noninteractive.ts", "src/run/ui.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient, type SessionMessageAssistantTool } from \"@opencode-ai/client/promise\"\nimport { FSUtil } from \"@opencode-ai/util/fs-util\"\nimport { open } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { readStdin } from \"../util/io\"\nimport { ServerConnection } from \"../services/server-connection\"\nimport { parseSessionTargetModel, resolveSessionTarget } from \"../session-target\"\nimport { toolInlineInfo } from \"@opencode-ai/tui/mini/tool\"\nimport { runNonInteractivePrompt } from \"./noninteractive\"\nimport { UI } from \"./ui\"\n\nexport type RunCommandInput = {\n server: ServerConnection.Resolved\n message: string[]\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n format: \"default\" | \"json\"\n file: string[]\n title?: string\n thinking?: boolean\n auto?: boolean\n}\n\ntype FilePart = {\n url: string\n filename: string\n mime: string\n}\n\ntype Prepared = {\n directory?: string\n message: string\n files: FilePart[]\n}\n\ntype ExecutionOptions = {\n root?: string\n directory?: string\n useServerDirectory?: boolean\n variant?: string\n attached?: boolean\n compatibility?: \"v1\"\n}\n\nclass RunTargetError extends Error {\n constructor(\n message: string,\n readonly sessionID?: string,\n ) {\n super(message)\n }\n}\n\nconst ATTACH_FILE_MAX_BYTES = 10 * 1024 * 1024\n\nexport function runNonInteractive(input: RunCommandInput) {\n return runNonInteractiveWithOptions(input, {})\n}\n\n/** @internal Used only by the V1 command boundary. */\nexport function runNonInteractiveWithOptions(input: RunCommandInput, options: ExecutionOptions) {\n return run(input, options).catch((error) => reportRunError(input, errorMessage(error)))\n}\n\nasync function run(input: RunCommandInput, options: ExecutionOptions) {\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n const root = options.root ?? process.env.PWD ?? process.cwd()\n const local = localDirectory(root)\n const directory = options.useServerDirectory ? undefined : (options.directory ?? local)\n const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin())\n if (!message?.trim()) fail(\"You must provide a message\")\n const files = await Promise.all(input.file.map((file) => prepareFile(file, root, options)))\n const prepared = { directory, message, files }\n return execute(input, prepared, input.server.endpoint, options)\n}\n\nasync function execute(input: RunCommandInput, prepared: Prepared, endpoint: Endpoint, options: ExecutionOptions) {\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const explicit = parseRunModel(input.model)\n const target = await resolveSessionTarget({\n client,\n location: prepared.directory ? { directory: prepared.directory } : undefined,\n continue: input.continue,\n session: input.session,\n fork: input.fork,\n model: explicit\n ? { providerID: explicit.model.providerID, id: explicit.model.modelID, variant: explicit.variant }\n : undefined,\n agent: input.agent,\n prepare: async (next) => {\n const selected =\n next.model ??\n (options.variant\n ? await client.model\n .default({ location: { directory: next.location.directory, workspace: next.location.workspaceID } })\n .then((result) => result.data)\n : undefined)\n const model = selected\n ? {\n providerID: selected.providerID,\n id: selected.id,\n variant: options.variant ?? (\"variant\" in selected ? selected.variant : undefined),\n }\n : undefined\n if ((options.variant ?? explicit?.variant) && !model)\n throw new RunTargetError(\"Cannot select a variant before selecting a model\", next.session?.id)\n return { model, agent: next.agent }\n },\n }).catch((error) => {\n if (!(error instanceof RunTargetError)) throw error\n reportRunError(input, error.message, error.sessionID)\n return undefined\n })\n if (!target) return\n const model = target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined\n const variant = target.model?.variant\n if (!target.resume && input.title !== undefined) {\n await client.session.rename({\n sessionID: target.session.id,\n title: input.title || prepared.message.slice(0, 50) + (prepared.message.length > 50 ? \"...\" : \"\"),\n })\n }\n\n await runNonInteractivePrompt({\n client,\n sessionID: target.session.id,\n location: target.location,\n message: prepared.message,\n files: prepared.files,\n agent: target.agent,\n model,\n variant,\n thinking: input.thinking ?? false,\n format: input.format,\n auto: input.auto ?? false,\n attached: options.attached ?? true,\n compatibility: options.compatibility,\n renderTool: (part) => renderTool(part, target.location.directory),\n renderToolError: (part) => renderToolError(part, target.location.directory),\n }).catch((error) => reportRunError(input, errorMessage(error), target.session.id))\n}\n\nexport function mergeInput(message: string | undefined, piped: string | undefined) {\n if (!message) return piped || undefined\n if (!piped) return message\n return message + \"\\n\" + piped\n}\n\nfunction formatMessage(message: string[]) {\n const value = message.map((part) => (part.includes(\" \") ? `\"${part.replace(/\"/g, '\\\\\"')}\"` : part)).join(\" \")\n return value || undefined\n}\n\nfunction localDirectory(root: string) {\n try {\n process.chdir(root)\n return process.cwd()\n } catch {\n fail(`Failed to change directory to ${root}`)\n }\n}\n\nexport function parseRunModel(value?: string) {\n const ref = parseSessionTargetModel(value)\n if (!ref) return\n return {\n model: { providerID: ref.providerID, modelID: ref.id },\n variant: ref.variant,\n }\n}\n\nasync function prepareFile(input: string, directory: string, options: ExecutionOptions): Promise<FilePart> {\n const file = path.resolve(directory, input)\n const handle = await open(file, \"r\").catch(() => fail(`File not found: ${input}`))\n try {\n const stat = await handle.stat()\n if (options.compatibility === \"v1\" && options.attached && stat.isDirectory())\n fail(`Cannot attach local directory without a shared filesystem: ${input}`)\n if (!stat.isFile() || stat.size > ATTACH_FILE_MAX_BYTES)\n fail(`Cannot attach a directory, special file, or file larger than 10 MiB: ${input}`)\n const content = Buffer.alloc(Number(stat.size))\n let offset = 0\n while (offset < content.length) {\n const read = await handle.read(content, offset, content.length - offset, offset)\n if (read.bytesRead === 0) break\n offset += read.bytesRead\n }\n const bytes = content.subarray(0, offset)\n const detected = FSUtil.mimeType(file)\n const text = bytes.toString(\"utf8\")\n const mime =\n detected.startsWith(\"image/\") || detected === \"application/pdf\"\n ? detected\n : !isBinaryContent(bytes) && Buffer.from(text, \"utf8\").equals(bytes)\n ? \"text/plain\"\n : detected\n return {\n url: `data:${mime};base64,${bytes.toString(\"base64\")}`,\n filename: path.basename(file),\n mime,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction isBinaryContent(bytes: Uint8Array) {\n if (bytes.length === 0) return false\n if (bytes.includes(0)) return true\n return bytes.reduce((count, byte) => count + Number(byte < 9 || (byte > 13 && byte < 32)), 0) / bytes.length > 0.3\n}\n\nasync function renderTool(part: SessionMessageAssistantTool, directory: string) {\n const info = toolInlineInfo(part, directory)\n if (info.mode === \"block\") {\n UI.empty()\n UI.println(UI.Style.TEXT_NORMAL + info.icon, UI.Style.TEXT_NORMAL + info.title)\n if (info.body?.trim()) UI.println(info.body)\n UI.empty()\n return\n }\n UI.println(\n UI.Style.TEXT_NORMAL + info.icon,\n UI.Style.TEXT_NORMAL + info.title,\n info.description ? UI.Style.TEXT_DIM + info.description + UI.Style.TEXT_NORMAL : \"\",\n )\n}\n\nasync function renderToolError(part: SessionMessageAssistantTool, directory: string) {\n const info = toolInlineInfo(part, directory)\n UI.println(UI.Style.TEXT_NORMAL + \"✗\", UI.Style.TEXT_NORMAL + `${info.title} failed`)\n}\n\nfunction warning(message: string) {\n UI.println(UI.Style.TEXT_WARNING_BOLD + \"!\", UI.Style.TEXT_NORMAL, message)\n}\n\nfunction errorMessage(error: unknown) {\n if (error instanceof Error) return error.message\n if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\")\n return error.message\n return String(error)\n}\n\n/** @internal Used by the V1 command boundary before a Session exists. */\nexport function reportRunError(input: Pick<RunCommandInput, \"format\">, message: string, sessionID?: string) {\n process.exitCode = 1\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify({\n type: \"error\",\n timestamp: Date.now(),\n sessionID: sessionID ?? \"\",\n error: { type: \"unknown\", message },\n }) + \"\\n\",\n )\n return\n }\n UI.error(message)\n}\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n", | ||
| "import type {\n EventSubscribeOutput,\n JsonValue,\n LLMToolContent,\n LocationRef,\n OpenCodeClient,\n SessionMessageAssistantTool,\n SessionMessageInfo,\n} from \"@opencode-ai/client/promise\"\nimport { SessionMessage } from \"@opencode-ai/schema/session-message\"\nimport { EOL } from \"node:os\"\nimport { readFile } from \"node:fs/promises\"\nimport { toolOutputText, type MiniToolPart } from \"@opencode-ai/tui/mini/tool\"\nimport { UI } from \"./ui\"\n\ntype Model = {\n providerID: string\n modelID: string\n}\n\ntype File = {\n url: string\n filename: string\n mime: string\n}\n\ntype Input = {\n client: OpenCodeClient\n sessionID: string\n location: LocationRef\n message: string\n files: File[]\n agent?: string\n model?: Model\n variant?: string\n thinking: boolean\n format: \"default\" | \"json\"\n auto: boolean\n /** True when the client is attached to a shared server rather than an exclusive in-process one. */\n attached: boolean\n compatibility?: \"v1\"\n renderTool: (part: SessionMessageAssistantTool) => Promise<void>\n renderToolError: (part: SessionMessageAssistantTool) => Promise<void>\n}\n\ntype StartedPart = {\n id: string\n timestamp: number\n}\n\ntype ToolState = StartedPart & {\n assistantMessageID: string\n tool: string\n input: Record<string, JsonValue>\n raw?: string\n provider?: unknown\n providerState?: SessionMessageAssistantTool[\"providerState\"]\n structured: Record<string, JsonValue>\n content: LLMToolContent[]\n}\n\ntype V2Event = EventSubscribeOutput\ntype FormRequest = Extract<V2Event, { type: \"form.created\" }>[\"data\"][\"form\"]\n\n// MCP elicitations are temporarily owned by the \"global\" sentinel instead of a real\n// session. An exclusive local process may treat them as this run's blockers; an\n// attached client must not cancel input that may belong to another session.\nconst GLOBAL_FORM_SESSION_ID = \"global\"\n\nexport async function runNonInteractivePrompt(input: Input) {\n const controller = new AbortController()\n const stream = input.client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()\n const connected = await stream.next()\n if (connected.done) throw new Error(\"Event stream disconnected before prompt admission\")\n\n const messageID = SessionMessage.ID.create()\n const starts = new Map<string, StartedPart>()\n const tools = new Map<string, ToolState>()\n const renderedText = new Map<string, string>()\n const renderedReasoning = new Map<string, string>()\n const renderedTools = new Set<string>()\n let submitted = false\n let promoted = false\n let emittedError = false\n let permissionRejected = false\n let formCancelled = false\n let interrupted = false\n let v1InvalidOutput = false\n let prePromotionError: { message: string; [key: string]: unknown } | undefined\n let finalizing = false\n let admission: AbortController | undefined\n let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined\n\n const emit = (type: string, timestamp: number, data: Record<string, unknown>) => {\n if (input.format !== \"json\") return false\n process.stdout.write(JSON.stringify({ type, timestamp, sessionID: input.sessionID, ...data }) + EOL)\n return true\n }\n\n const writeText = (part: { text: string; [key: string]: unknown }, timestamp: number) => {\n if (emit(\"text\", timestamp, { part })) return\n const text = part.text.trim()\n if (!text) return\n if (!process.stdout.isTTY) {\n process.stdout.write(text + EOL)\n return\n }\n UI.empty()\n UI.println(text)\n UI.empty()\n }\n\n const writeReasoning = (part: { text: string; [key: string]: unknown }, timestamp: number) => {\n if (emit(\"reasoning\", timestamp, { part })) return\n const text = part.text.trim()\n if (!text) return\n const line = `Thinking: ${text}`\n if (!process.stdout.isTTY) return void process.stdout.write(line + EOL)\n UI.empty()\n UI.println(`${UI.Style.TEXT_DIM}\\u001b[3m${line}\\u001b[0m${UI.Style.TEXT_NORMAL}`)\n UI.empty()\n }\n\n const flushStep = () => {\n if (!pendingStep) return\n const value = pendingStep\n pendingStep = undefined\n if (!emit(\"step_start\", value.timestamp, { part: value.part }) && input.format !== \"json\") {\n UI.empty()\n UI.println(value.label)\n UI.empty()\n }\n }\n\n const replyPermission = async (request: { id: string; action: string; resources: ReadonlyArray<string> }) => {\n if (!input.auto) {\n permissionRejected = true\n UI.println(\n UI.Style.TEXT_WARNING_BOLD + \"!\",\n UI.Style.TEXT_NORMAL +\n `permission requested: ${request.action} (${request.resources.join(\", \")}); auto-rejecting`,\n )\n }\n await input.client.permission\n .reply({\n sessionID: input.sessionID,\n requestID: request.id,\n reply: input.auto ? \"once\" : \"reject\",\n })\n .catch(() => {})\n if (!input.auto) {\n await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n }\n\n const cancelForm = async (request: Pick<FormRequest, \"id\" | \"sessionID\">) => {\n try {\n await input.client.form.cancel(\n { sessionID: request.sessionID, formID: request.id },\n ...formRequestOptions(request.sessionID === GLOBAL_FORM_SESSION_ID ? input.location : undefined),\n )\n } catch (error) {\n if (!formAlreadySettled(error)) throw error\n }\n formCancelled = true\n }\n\n const consume = async () => {\n while (!controller.signal.aborted) {\n const next = await stream.next().catch((error) => {\n if (!emittedError) throw error\n return { done: true as const, value: undefined }\n })\n if (next.done) {\n if (emittedError) return\n throw new Error(\"Event stream disconnected during prompt execution\")\n }\n const event = next.value\n\n if (event.type === \"permission.v2.asked\" && submitted && event.data.sessionID === input.sessionID) {\n await replyPermission(event.data)\n continue\n }\n if (\n event.type === \"form.created\" &&\n submitted &&\n (event.data.form.sessionID === input.sessionID ||\n (!input.attached &&\n event.data.form.sessionID === GLOBAL_FORM_SESSION_ID &&\n sameLocation(event.location, input.location)))\n ) {\n await cancelForm(event.data.form)\n continue\n }\n if (!(\"sessionID\" in event.data) || event.data.sessionID !== input.sessionID) continue\n const time = toMillis(\"created\" in event ? event.created : undefined)\n\n if (event.type === \"session.input.promoted\") {\n if (event.data.inputID === messageID) {\n promoted = true\n prePromotionError = undefined\n continue\n }\n }\n if (\n event.type === \"session.execution.interrupted\" &&\n event.data.reason === \"user\" &&\n (interrupted || permissionRejected || formCancelled)\n ) {\n return\n }\n if (!promoted && event.type === \"session.execution.failed\") {\n prePromotionError = event.data.error\n if (finalizing) return\n continue\n }\n if (\n !promoted &&\n finalizing &&\n (event.type === \"session.execution.succeeded\" || event.type === \"session.execution.interrupted\")\n )\n return\n if (!promoted) continue\n if (finalizing && !event.type.startsWith(\"session.execution.\")) continue\n\n if (event.type === \"session.step.started\") {\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-start\",\n snapshot: event.data.snapshot,\n }\n if (input.compatibility === \"v1\") {\n pendingStep = {\n timestamp: time,\n part,\n label: `> ${event.data.agent} · ${event.data.model.id}`,\n }\n continue\n }\n if (!emit(\"step_start\", time, { part }) && input.format !== \"json\") {\n UI.empty()\n UI.println(`> ${event.data.agent} · ${event.data.model.id}`)\n UI.empty()\n }\n continue\n }\n\n if (event.type === \"session.text.started\") {\n flushStep()\n starts.set(`text\\u0000${contentKey(event.data.assistantMessageID, event.data.ordinal)}`, {\n id: partID(event.id),\n timestamp: time,\n })\n continue\n }\n if (event.type === \"session.text.ended\") {\n const key = contentKey(event.data.assistantMessageID, event.data.ordinal)\n const started = starts.get(`text\\u0000${key}`)\n starts.delete(`text\\u0000${key}`)\n const part = {\n id: started?.id ?? partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"text\",\n text: event.data.text,\n time: { start: started?.timestamp ?? time, end: time },\n }\n renderedText.set(key, event.data.text)\n writeText(part, time)\n continue\n }\n\n if (event.type === \"session.reasoning.started\") {\n flushStep()\n starts.set(`reasoning\\u0000${contentKey(event.data.assistantMessageID, event.data.ordinal)}`, {\n id: partID(event.id),\n timestamp: time,\n })\n continue\n }\n if (event.type === \"session.reasoning.ended\" && input.thinking) {\n const key = contentKey(event.data.assistantMessageID, event.data.ordinal)\n const started = starts.get(`reasoning\\u0000${key}`)\n starts.delete(`reasoning\\u0000${key}`)\n const part = {\n id: started?.id ?? partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"reasoning\",\n text: event.data.text,\n metadata: event.data.state,\n time: { start: started?.timestamp ?? time, end: time },\n }\n renderedReasoning.set(key, event.data.text)\n writeReasoning(part, time)\n continue\n }\n\n if (event.type === \"session.tool.input.started\") {\n flushStep()\n tools.set(toolKey(event.data.assistantMessageID, event.data.callID), {\n id: partID(event.id),\n timestamp: time,\n assistantMessageID: event.data.assistantMessageID,\n tool: event.data.name,\n input: {},\n structured: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.input.ended\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))\n if (current) current.raw = event.data.text\n continue\n }\n if (event.type === \"session.tool.input.delta\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))\n if (current) current.raw = (current.raw ?? \"\") + event.data.delta\n continue\n }\n if (event.type === \"session.tool.called\") {\n flushStep()\n const key = toolKey(event.data.assistantMessageID, event.data.callID)\n const current = tools.get(key)\n tools.set(key, {\n id: current?.id ?? partID(event.id),\n timestamp: current?.timestamp ?? time,\n assistantMessageID: event.data.assistantMessageID,\n tool: current?.tool ?? \"tool\",\n input: event.data.input,\n raw: current?.raw,\n provider: { executed: event.data.executed, state: event.data.state },\n providerState: event.data.state,\n structured: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.progress\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))\n if (current) {\n current.structured = event.data.structured\n current.content = event.data.content\n }\n continue\n }\n if (event.type === \"session.tool.success\") {\n const key = toolKey(event.data.assistantMessageID, event.data.callID)\n const current = tools.get(key) ?? fallbackTool(event)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.callID,\n name: current.tool,\n executed: event.data.executed,\n providerState: current.providerState,\n providerResultState: event.data.resultState,\n state: {\n status: \"completed\",\n input: current.input,\n structured: event.data.structured,\n content: event.data.content,\n result: event.data.result,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n id: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n callID: event.data.callID,\n tool: current.tool,\n state: {\n status: \"completed\",\n input: current.input,\n output: toolOutputText(current.tool, event.data.content),\n title: current.tool,\n metadata: {\n structured: event.data.structured,\n content: event.data.content,\n result: event.data.result,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(key)\n renderedTools.add(key)\n if (!emit(\"tool_use\", time, { part })) await input.renderTool(tool)\n continue\n }\n if (event.type === \"session.tool.failed\") {\n const key = toolKey(event.data.assistantMessageID, event.data.callID)\n const current = tools.get(key) ?? fallbackTool(event)\n const error = event.data.error.message\n const structured = event.data.metadata ?? current.structured\n const content = event.data.content ?? current.content\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.callID,\n name: current.tool,\n executed: event.data.executed,\n providerState: current.providerState,\n providerResultState: event.data.resultState,\n state: {\n status: \"error\",\n input: current.input,\n structured,\n content,\n error: event.data.error,\n result: event.data.result,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n id: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n callID: event.data.callID,\n tool: current.tool,\n state: {\n status: \"error\",\n input: current.input,\n error,\n metadata: {\n result: event.data.result,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(key)\n renderedTools.add(key)\n if (input.compatibility === \"v1\" && (permissionRejected || formCancelled)) continue\n if (!emit(\"tool_use\", time, { part })) {\n if (toolOutputText(current.tool, content).trim())\n await input.renderTool({\n ...tool,\n state: {\n status: \"completed\",\n input: current.input,\n structured,\n content,\n result: event.data.result,\n },\n })\n await input.renderToolError(tool)\n UI.error(error)\n }\n continue\n }\n\n if (event.type === \"session.step.ended\") {\n flushStep()\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-finish\",\n reason: event.data.finish,\n snapshot: event.data.snapshot,\n cost: event.data.cost,\n tokens: event.data.tokens,\n }\n emit(\"step_finish\", time, { part })\n continue\n }\n if (event.type === \"session.step.failed\") {\n if (\n input.compatibility === \"v1\" &&\n event.data.error.message === \"Provider stream ended without a terminal finish event\"\n ) {\n pendingStep = undefined\n v1InvalidOutput = true\n continue\n }\n if (interrupted || permissionRejected || formCancelled) continue\n flushStep()\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", time, { error: event.data.error })) UI.error(event.data.error.message)\n continue\n }\n if (event.type === \"session.execution.failed\") {\n if (input.compatibility === \"v1\" && (v1InvalidOutput || permissionRejected || formCancelled)) return\n flushStep()\n if (!emittedError && !formCancelled) {\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", time, { error: event.data.error })) UI.error(event.data.error.message)\n }\n return\n }\n if (event.type === \"session.execution.interrupted\") {\n if (input.compatibility === \"v1\" && (permissionRejected || formCancelled)) return\n if (event.data.reason === \"user\" && interrupted) process.exitCode = 130\n if (event.data.reason !== \"user\" && !emittedError) {\n emittedError = true\n process.exitCode = 1\n const error = { type: \"aborted\" as const, message: `Session interrupted: ${event.data.reason}` }\n if (!emit(\"error\", time, { error })) UI.error(error.message)\n }\n return\n }\n if (event.type === \"session.execution.succeeded\") return\n }\n }\n\n const projectedMessages = async () => {\n const messages: SessionMessageInfo[] = []\n let cursor: string | undefined\n while (true) {\n const page = await input.client.message.list(\n cursor\n ? { sessionID: input.sessionID, limit: 200, cursor }\n : { sessionID: input.sessionID, limit: 200, order: \"desc\" },\n )\n for (const message of page.data) {\n if (message.id === messageID) return { found: true, messages: messages.toReversed() }\n messages.push(message)\n }\n cursor = page.cursor.next ?? undefined\n if (!cursor) return { found: false, messages: [] }\n }\n }\n\n const reconcile = async () => {\n const projected = await projectedMessages()\n for (const message of projected.messages) {\n if (message.type !== \"assistant\") continue\n const timestamp = message.time.completed ?? message.time.created\n let textOrdinal = 0\n let reasoningOrdinal = 0\n for (const item of message.content) {\n if (item.type === \"text\") {\n const ordinal = textOrdinal++\n const key = contentKey(message.id, ordinal)\n const rendered = renderedText.get(key) ?? \"\"\n if (rendered === item.text || !item.text.startsWith(rendered)) continue\n const text = item.text.slice(rendered.length)\n writeText(\n {\n id: projectedPartID(message.id, `text-${ordinal}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"text\",\n text,\n time: { start: message.time.created, end: timestamp },\n },\n timestamp,\n )\n renderedText.set(key, item.text)\n continue\n }\n if (item.type === \"reasoning\") {\n const ordinal = reasoningOrdinal++\n if (!input.thinking) continue\n const key = contentKey(message.id, ordinal)\n const rendered = renderedReasoning.get(key) ?? \"\"\n if (rendered === item.text || !item.text.startsWith(rendered)) continue\n const text = item.text.slice(rendered.length)\n const part = {\n id: projectedPartID(message.id, `reasoning-${ordinal}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"reasoning\",\n text,\n metadata: item.state,\n time: { start: message.time.created, end: timestamp },\n }\n renderedReasoning.set(key, item.text)\n writeReasoning(part, timestamp)\n continue\n }\n\n const key = toolKey(message.id, item.id)\n if (renderedTools.has(key) || item.state.status === \"streaming\" || item.state.status === \"running\") continue\n const part: MiniToolPart = {\n id: projectedPartID(message.id, `tool-${item.id}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"tool\",\n callID: item.id,\n tool: item.name,\n state:\n item.state.status === \"completed\"\n ? {\n status: \"completed\",\n input: item.state.input,\n output: toolOutputText(item.name, item.state.content),\n title: item.name,\n metadata: { structured: item.state.structured, content: item.state.content, result: item.state.result },\n time: { start: item.time.ran ?? item.time.created, end: item.time.completed ?? timestamp },\n }\n : {\n status: \"error\",\n input: item.state.input,\n error: item.state.error.message,\n metadata: { structured: item.state.structured, content: item.state.content, result: item.state.result },\n time: { start: item.time.ran ?? item.time.created, end: item.time.completed ?? timestamp },\n },\n }\n renderedTools.add(key)\n if (emit(\"tool_use\", timestamp, { part })) continue\n if (item.state.status === \"completed\") {\n await input.renderTool(item)\n continue\n }\n if (toolOutputText(item.name, item.state.content).trim()) {\n await input.renderTool({ ...item, state: { ...item.state, status: \"completed\" } })\n }\n await input.renderToolError(item)\n UI.error(item.state.error.message)\n }\n\n if (message.error && !emittedError) {\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", timestamp, { error: message.error })) UI.error(message.error.message)\n }\n }\n return {\n found: projected.found,\n responded: projected.messages.some((message) => message.type === \"assistant\"),\n }\n }\n\n const interrupt = () => {\n if (interrupted) process.exit(130)\n interrupted = true\n process.exitCode = 130\n admission?.abort()\n void input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n process.on(\"SIGINT\", interrupt)\n\n let completed: Promise<void> | undefined\n try {\n if (input.agent) {\n await input.client.session.switchAgent({ sessionID: input.sessionID, agent: input.agent })\n }\n const selected = input.model\n ? { providerID: input.model.providerID, id: input.model.modelID, variant: input.variant }\n : input.variant\n ? await input.client.session\n .get({ sessionID: input.sessionID })\n .then((result) => result.model)\n .then(async (model) => {\n if (model) return { ...model, variant: input.variant }\n const result = await input.client.model.default()\n const fallback = result.data\n return fallback ? { providerID: fallback.providerID, id: fallback.id, variant: input.variant } : undefined\n })\n : undefined\n if (input.variant && !selected) throw new Error(\"Cannot select a variant before selecting a model\")\n if (selected) {\n await input.client.session.switchModel({ sessionID: input.sessionID, model: selected })\n }\n\n const prepared = await Promise.all(input.files.map(prepareFile))\n if (interrupted) return\n submitted = true\n completed = consume()\n admission = new AbortController()\n const response = await input.client.session\n .prompt(\n {\n sessionID: input.sessionID,\n id: messageID,\n text: [input.message, ...prepared.flatMap((file) => (file.text ? [file.text] : []))].join(\"\\n\\n\"),\n files: prepared.flatMap((file) => (file.attachment ? [file.attachment] : [])),\n delivery: \"steer\",\n },\n { signal: admission.signal },\n )\n .catch(async (error) => {\n if (interrupted) {\n await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n controller.abort()\n await completed?.catch(() => {})\n if (interrupted || emittedError) return undefined\n throw error\n })\n admission = undefined\n if (!response) return\n if (interrupted) await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n\n const [permissions, forms, globals] = await Promise.all([\n input.client.permission.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.client.form.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.attached\n ? Promise.resolve(undefined)\n : input.client.form.request\n .list({\n location: { directory: input.location.directory, workspace: input.location.workspaceID },\n })\n .catch(() => undefined),\n ])\n await Promise.all([\n ...(permissions ?? []).map(replyPermission),\n ...(forms ?? []).map(cancelForm),\n ...(globals && sameLocation(globals.location, input.location)\n ? globals.data.filter((form) => form.sessionID === GLOBAL_FORM_SESSION_ID).map(cancelForm)\n : []),\n ])\n if (input.compatibility === \"v1\") {\n await completed\n return\n }\n\n const waiting = input.client.session.wait({ sessionID: input.sessionID })\n await Promise.race([waiting, completed.then(() => waiting)])\n finalizing = true\n const projected = await reconcile()\n if (\n !projected.responded &&\n !interrupted &&\n !permissionRejected &&\n !formCancelled &&\n !emittedError &&\n !prePromotionError\n ) {\n await completed\n }\n if (!projected.found && !interrupted && !permissionRejected && !formCancelled && !emittedError) {\n const error = prePromotionError ?? { type: \"unknown\", message: \"Prompt was not promoted\" }\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", Date.now(), { error })) UI.error(error.message)\n }\n } finally {\n process.off(\"SIGINT\", interrupt)\n controller.abort()\n if (input.compatibility === \"v1\") await stream.return?.(undefined).catch(() => {})\n else void stream.return?.(undefined).catch(() => {})\n }\n}\n\nfunction sameLocation(left: LocationRef | undefined, right: LocationRef) {\n return !!left && left.directory === right.directory && left.workspaceID === right.workspaceID\n}\n\nfunction formRequestOptions(location: LocationRef | undefined): [] | [{ headers: Record<string, string> }] {\n if (!location) return []\n return [\n {\n headers: {\n \"x-opencode-directory\": encodeURIComponent(location.directory),\n ...(location.workspaceID ? { \"x-opencode-workspace\": location.workspaceID } : {}),\n },\n },\n ]\n}\n\nfunction formAlreadySettled(error: unknown) {\n return !!error && typeof error === \"object\" && Reflect.get(error, \"_tag\") === \"FormAlreadySettledError\"\n}\n\nfunction partID(eventID: string) {\n return `prt_${eventID.replace(/^evt_/, \"\")}`\n}\n\nfunction toolKey(messageID: string, callID: string) {\n return `${messageID}\\u0000${callID}`\n}\n\nfunction contentKey(messageID: string, ordinal: number) {\n return `${messageID}\\u0000${ordinal}`\n}\n\nfunction projectedPartID(messageID: string, part: string) {\n return `prt_${messageID.replace(/^msg_/, \"\")}_${part}`\n}\n\nfunction fallbackTool(event: {\n id: string\n created: number\n data: { assistantMessageID: string; callID: string }\n}): ToolState {\n return {\n id: partID(event.id),\n timestamp: toMillis(event.created),\n assistantMessageID: event.data.assistantMessageID,\n tool: \"tool\",\n input: {},\n structured: {},\n content: [],\n }\n}\n\nfunction toMillis(value: unknown) {\n if (typeof value === \"number\") return value\n if (typeof value === \"string\") return new Date(value).getTime()\n return Date.now()\n}\n\nasync function prepareFile(file: File) {\n if (file.mime !== \"text/plain\") {\n const uri = file.url.startsWith(\"data:\")\n ? file.url\n : `data:${file.mime};base64,${(await readFile(new URL(file.url))).toString(\"base64\")}`\n return { attachment: { uri, name: file.filename } }\n }\n const content = file.url.startsWith(\"data:\")\n ? Buffer.from(file.url.slice(file.url.indexOf(\",\") + 1), \"base64\").toString(\"utf8\")\n : await readFile(new URL(file.url), \"utf8\")\n return { text: `<file name=\"${file.filename}\">\\n${content}\\n</file>` }\n}\n", | ||
| "import { EOL } from \"node:os\"\n\nexport const Style = {\n TEXT_DIM: \"\\x1b[90m\",\n TEXT_NORMAL: \"\\x1b[0m\",\n TEXT_WARNING_BOLD: \"\\x1b[93m\\x1b[1m\",\n TEXT_DANGER_BOLD: \"\\x1b[91m\\x1b[1m\",\n}\n\nexport function println(...message: string[]) {\n process.stderr.write(message.join(\" \") + EOL)\n}\n\nlet blank = false\n\nexport function empty() {\n if (blank) return\n println(Style.TEXT_NORMAL)\n blank = true\n}\n\nexport function error(message: string) {\n if (message.startsWith(\"Error: \")) message = message.slice(\"Error: \".length)\n println(Style.TEXT_DANGER_BOLD + \"Error: \" + Style.TEXT_NORMAL + message)\n}\n\nexport * as UI from \"./ui\"\n" | ||
| ], | ||
| "mappings": ";o/BAGA,oBAAS,0BACT,0BCMA,mBAAS,gBACT,wBAAS,wGCXT,mBAAS,iBAEF,SAAM,OAAQ,MACnB,cAAU,gBACV,iBAAa,eACb,uBAAmB,uBACnB,sBAAkB,sBACpB,OAEO,cAAS,MAAO,SAAI,OAAmB,CAC5C,QAAQ,OAAO,MAAM,EAAQ,KAAK,GAAG,EAAI,EAAG,EAG9C,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,EAAe,CAAC,EAAmC,EAAmB,CACnF,IAAM,EAAO,EAAe,EAAM,CAAS,EAC3C,EAAG,QAAQ,EAAG,MAAM,YAAc,SAAI,EAAG,MAAM,YAAc,GAAG,EAAK,cAAc,EAOrF,SAAS,EAAY,CAAC,EAAgB,CACpC,GAAI,aAAiB,MAAO,OAAO,EAAM,QACzC,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,OAAO,EAAM,UAAY,SAChG,OAAO,EAAM,QACf,OAAO,OAAO,CAAK,EAId,SAAS,CAAc,CAAC,EAAwC,EAAiB,EAAoB,CAE1G,GADA,QAAQ,SAAW,EACf,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UAAU,CACb,KAAM,QACN,UAAW,KAAK,IAAI,EACpB,UAAW,GAAa,GACxB,MAAO,CAAE,KAAM,UAAW,SAAQ,CACpC,CAAC,EAAI;AAAA,CACP,EACA,OAEF,EAAG,MAAM,CAAO,EAGlB,SAAS,CAAI,CAAC,EAAwB,CACpC,MAAU,MAAM,CAAO", | ||
| "debugId": "C3F7ED78D4DC38D564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/bedrock-event-stream.ts", "../ai/src/protocols/utils/bedrock-auth.ts", "../ai/src/protocols/utils/bedrock-cache.ts", "../ai/src/protocols/utils/bedrock-media.ts", "../ai/src/protocols/bedrock-converse.ts", "../ai/src/providers/amazon-bedrock.ts"], | ||
| "sourcesContent": [ | ||
| "import { EventStreamCodec } from \"@smithy/eventstream-codec\"\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\"\nimport { Effect, Stream } from \"effect\"\nimport { Framing } from \"../route/framing\"\nimport { ProviderShared } from \"./shared\"\n\n// Bedrock streams responses using the AWS event stream binary protocol — each\n// frame is `[length:4][headers-length:4][prelude-crc:4][headers][payload][crc:4]`.\n// We use `@smithy/eventstream-codec` to validate framing and CRCs, then\n// reconstruct the JSON wrapping by `:event-type` so the chunk schema can match.\nconst eventCodec = new EventStreamCodec(toUtf8, fromUtf8)\nconst utf8 = new TextDecoder()\n\n// Cursor-tracking buffer state. Bytes accumulate in `buffer`; `offset` is the\n// read position. Reading by `subarray` is zero-copy. We only allocate a fresh\n// buffer when a new network chunk arrives and we need to append.\ninterface FrameBufferState {\n readonly buffer: Uint8Array\n readonly offset: number\n}\n\nconst initialFrameBuffer: FrameBufferState = { buffer: new Uint8Array(0), offset: 0 }\n\nconst appendChunk = (state: FrameBufferState, chunk: Uint8Array): FrameBufferState => {\n const remaining = state.buffer.length - state.offset\n // Compact: drop the consumed prefix and append the new chunk in one alloc.\n // This bounds buffer growth to at most one network chunk past the live\n // window, regardless of stream length.\n const next = new Uint8Array(remaining + chunk.length)\n next.set(state.buffer.subarray(state.offset), 0)\n next.set(chunk, remaining)\n return { buffer: next, offset: 0 }\n}\n\nconst consumeFrames = (route: string) => (state: FrameBufferState, chunk: Uint8Array) =>\n Effect.gen(function* () {\n let cursor = appendChunk(state, chunk)\n const out: object[] = []\n while (cursor.buffer.length - cursor.offset >= 4) {\n const view = cursor.buffer.subarray(cursor.offset)\n const totalLength = new DataView(view.buffer, view.byteOffset, view.byteLength).getUint32(0, false)\n if (view.length < totalLength) break\n\n const decoded = yield* Effect.try({\n try: () => eventCodec.decode(view.subarray(0, totalLength)),\n catch: (error) =>\n ProviderShared.eventError(\n route,\n `Failed to decode Bedrock Converse event-stream frame: ${\n error instanceof Error ? error.message : String(error)\n }`,\n ),\n })\n cursor = { buffer: cursor.buffer, offset: cursor.offset + totalLength }\n\n if (decoded.headers[\":message-type\"]?.value !== \"event\") continue\n const eventType = decoded.headers[\":event-type\"]?.value\n if (typeof eventType !== \"string\") continue\n const payload = utf8.decode(decoded.body)\n if (!payload) continue\n // The AWS event stream pads short payloads with a `p` field. Drop it\n // before handing the object to the chunk schema. JSON decode goes\n // through the shared Schema-driven codec to satisfy the package rule\n // against ad-hoc `JSON.parse` calls.\n const parsed = (yield* ProviderShared.parseJson(\n route,\n payload,\n \"Failed to parse Bedrock Converse event-stream payload\",\n )) as Record<string, unknown>\n delete parsed.p\n out.push({ [eventType]: parsed })\n }\n return [cursor, out] as const\n })\n\n/**\n * AWS event-stream framing for Bedrock Converse. Each frame is decoded by\n * `@smithy/eventstream-codec` (length + header + payload + CRC) and rewrapped\n * under its `:event-type` header so the chunk schema can match the JSON\n * payload directly.\n */\nexport const framing = (route: string): Framing.Definition<object> => ({\n id: \"aws-event-stream\",\n frame: (bytes) => bytes.pipe(Stream.mapAccumEffect(() => initialFrameBuffer, consumeFrames(route))),\n})\n\nexport * as BedrockEventStream from \"./bedrock-event-stream\"\n", | ||
| "import { AwsV4Signer } from \"aws4fetch\"\nimport { Effect } from \"effect\"\nimport { Headers } from \"effect/unstable/http\"\nimport { Auth, type AuthInput } from \"../../route/auth\"\nimport { ProviderShared } from \"../shared\"\n\n/**\n * AWS credentials for SigV4 signing. Bedrock also supports Bearer API key auth,\n * which provider facades configure as route auth instead of SigV4. STS-vended\n * credentials should be refreshed by the consumer (rebuild the model) before\n * they expire; the route does not refresh.\n */\nexport interface Credentials {\n readonly region: string\n readonly accessKeyId: string\n readonly secretAccessKey: string\n readonly sessionToken?: string\n}\n\nconst signRequest = (input: {\n readonly url: string\n readonly body: string\n readonly headers: Headers.Headers\n readonly credentials: Credentials\n}) =>\n Effect.tryPromise({\n try: async () => {\n const signed = await new AwsV4Signer({\n url: input.url,\n method: \"POST\",\n headers: Object.entries(input.headers),\n body: input.body,\n region: input.credentials.region,\n accessKeyId: input.credentials.accessKeyId,\n secretAccessKey: input.credentials.secretAccessKey,\n sessionToken: input.credentials.sessionToken,\n service: \"bedrock\",\n }).sign()\n return Object.fromEntries(signed.headers.entries())\n },\n catch: (error) =>\n ProviderShared.invalidRequest(\n `Bedrock Converse SigV4 signing failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n })\n\n/** Sign the exact JSON bytes with SigV4 using credentials configured on the route. */\nexport const sigV4 = (credentials: Credentials | undefined) =>\n Auth.custom((input: AuthInput) => {\n return Effect.gen(function* () {\n if (!credentials) {\n return yield* ProviderShared.invalidRequest(\n \"Bedrock Converse requires either route bearer auth or AWS credentials configured on the route\",\n )\n }\n const headersForSigning = Headers.set(input.headers, \"content-type\", \"application/json\")\n const signed = yield* signRequest({\n url: input.url,\n body: input.body,\n headers: headersForSigning,\n credentials,\n })\n return Headers.setAll(headersForSigning, signed)\n })\n })\n\n/** Bedrock route auth defaults to SigV4 and expects credentials from route configuration. */\nexport const auth = sigV4(undefined)\n\nexport * as BedrockAuth from \"./bedrock-auth\"\n", | ||
| "import { Schema } from \"effect\"\nimport type { CacheHint } from \"../../schema\"\nimport { newBreakpoints, ttlBucket, type Breakpoints } from \"./cache\"\n\n// Bedrock cache markers are positional: emit a `cachePoint` block immediately\n// after the content the caller wants treated as a cacheable prefix. Bedrock\n// accepts optional `ttl: \"5m\" | \"1h\"` on cachePoint, mirroring Anthropic.\nexport const CachePointBlock = Schema.Struct({\n cachePoint: Schema.Struct({\n type: Schema.tag(\"default\"),\n ttl: Schema.optional(Schema.Literals([\"5m\", \"1h\"])),\n }),\n})\nexport type CachePointBlock = Schema.Schema.Type<typeof CachePointBlock>\n\n// Bedrock-Claude enforces the same 4-breakpoint cap as the Anthropic Messages\n// API. Callers pass a shared counter through every `block()` call site so the\n// budget is respected across `system`, `messages`, and `tools`.\nexport const BEDROCK_BREAKPOINT_CAP = 4\n\nexport type { Breakpoints } from \"./cache\"\nexport const breakpoints = () => newBreakpoints(BEDROCK_BREAKPOINT_CAP)\n\nconst DEFAULT_5M: CachePointBlock = { cachePoint: { type: \"default\" } }\nconst DEFAULT_1H: CachePointBlock = { cachePoint: { type: \"default\", ttl: \"1h\" } }\n\nexport const block = (breakpoints: Breakpoints, cache: CacheHint | undefined): CachePointBlock | undefined => {\n if (cache?.type !== \"ephemeral\" && cache?.type !== \"persistent\") return undefined\n if (breakpoints.remaining <= 0) {\n breakpoints.dropped += 1\n return undefined\n }\n breakpoints.remaining -= 1\n return ttlBucket(cache.ttlSeconds) === \"1h\" ? DEFAULT_1H : DEFAULT_5M\n}\n\nexport * as BedrockCache from \"./bedrock-cache\"\n", | ||
| "import { Effect, Schema } from \"effect\"\nimport type { MediaPart } from \"../../schema\"\nimport { ProviderShared } from \"../shared\"\n\n// Bedrock Converse accepts image `format` as the file extension and\n// `source.bytes` as base64 in the JSON wire format.\nexport const ImageFormat = Schema.Literals([\"png\", \"jpeg\", \"gif\", \"webp\"])\nexport type ImageFormat = Schema.Schema.Type<typeof ImageFormat>\n\nexport const ImageBlock = Schema.Struct({\n image: Schema.Struct({\n format: ImageFormat,\n source: Schema.Struct({ bytes: Schema.String }),\n }),\n})\nexport type ImageBlock = Schema.Schema.Type<typeof ImageBlock>\n\n// Bedrock document blocks require a user-facing name so the model can refer to\n// the uploaded document.\nexport const DocumentFormat = Schema.Literals([\"pdf\", \"csv\", \"doc\", \"docx\", \"xls\", \"xlsx\", \"html\", \"txt\", \"md\"])\nexport type DocumentFormat = Schema.Schema.Type<typeof DocumentFormat>\n\nexport const DocumentBlock = Schema.Struct({\n document: Schema.Struct({\n format: DocumentFormat,\n name: Schema.String,\n source: Schema.Struct({ bytes: Schema.String }),\n }),\n})\nexport type DocumentBlock = Schema.Schema.Type<typeof DocumentBlock>\n\nconst IMAGE_FORMATS = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpeg\",\n \"image/jpg\": \"jpeg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n} as const satisfies Record<string, ImageFormat>\n\nconst DOCUMENT_FORMATS = {\n \"application/pdf\": \"pdf\",\n \"text/csv\": \"csv\",\n \"application/msword\": \"doc\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": \"docx\",\n \"application/vnd.ms-excel\": \"xls\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": \"xlsx\",\n \"text/html\": \"html\",\n \"text/plain\": \"txt\",\n \"text/markdown\": \"md\",\n} as const satisfies Record<string, DocumentFormat>\n\nconst documentBlock = (part: MediaPart, format: DocumentFormat, bytes: string): DocumentBlock => ({\n document: {\n format,\n name: part.filename ?? `document.${format}`,\n source: { bytes },\n },\n})\n\n// Route by MIME. Known image/document formats lower into a typed block; anything\n// else fails with a clear error instead of silently degrading to a malformed\n// document block. Image MIME types not in `IMAGE_FORMATS` (e.g. `image/svg+xml`)\n// get an image-specific error so the caller knows it's a format-support issue,\n// not a kind-detection issue.\nexport const lower = Effect.fn(\"BedrockMedia.lower\")(function* (part: MediaPart) {\n const mime = part.mediaType.toLowerCase()\n const imageFormat = IMAGE_FORMATS[mime as keyof typeof IMAGE_FORMATS]\n if (imageFormat) {\n const media = yield* ProviderShared.validateMedia(\n \"Bedrock Converse\",\n part,\n new Set<string>(Object.keys(IMAGE_FORMATS)),\n )\n return { image: { format: imageFormat, source: { bytes: media.base64 } } } satisfies ImageBlock\n }\n if (mime.startsWith(\"image/\"))\n return yield* ProviderShared.invalidRequest(`Bedrock Converse does not support image media type ${part.mediaType}`)\n const documentFormat = DOCUMENT_FORMATS[mime as keyof typeof DOCUMENT_FORMATS]\n if (documentFormat) {\n const media = yield* ProviderShared.validateMedia(\n \"Bedrock Converse\",\n part,\n new Set<string>(Object.keys(DOCUMENT_FORMATS)),\n )\n return documentBlock(part, documentFormat, media.base64)\n }\n return yield* ProviderShared.invalidRequest(`Bedrock Converse does not support media type ${part.mediaType}`)\n})\n\nexport * as BedrockMedia from \"./bedrock-media\"\n", | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route } from \"../route/client\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Protocol } from \"../route/protocol\"\nimport {\n LLMError,\n LLMEvent,\n Usage,\n type CacheHint,\n type FinishReason,\n type JsonSchema,\n type LLMRequest,\n type ModelToolSchemaCompatibility,\n type ProviderMetadata,\n type ReasoningPart,\n type ToolCallPart,\n type ToolDefinition,\n type ToolResultPart,\n} from \"../schema\"\nimport { BedrockEventStream } from \"./bedrock-event-stream\"\nimport { classifyProviderFailure } from \"../provider-error\"\nimport { JsonObject, optionalArray, ProviderShared } from \"./shared\"\nimport { BedrockAuth } from \"./utils/bedrock-auth\"\nimport { BedrockCache } from \"./utils/bedrock-cache\"\nimport { BedrockMedia } from \"./utils/bedrock-media\"\nimport { Lifecycle } from \"./utils/lifecycle\"\nimport { ToolSchemaProjection } from \"./utils/tool-schema\"\nimport { ToolStream } from \"./utils/tool-stream\"\n\nconst ADAPTER = \"bedrock-converse\"\n\nexport type { Credentials as BedrockCredentials } from \"./utils/bedrock-auth\"\n\n// =============================================================================\n// Request Body Schema\n// =============================================================================\nconst BedrockTextBlock = Schema.Struct({\n text: Schema.String,\n})\ntype BedrockTextBlock = Schema.Schema.Type<typeof BedrockTextBlock>\n\nconst BedrockToolUseBlock = Schema.Struct({\n toolUse: Schema.Struct({\n toolUseId: Schema.String,\n name: Schema.String,\n input: Schema.Unknown,\n }),\n})\ntype BedrockToolUseBlock = Schema.Schema.Type<typeof BedrockToolUseBlock>\n\nconst BedrockToolResultContentItem = Schema.Union([\n Schema.Struct({ text: Schema.String }),\n Schema.Struct({ json: Schema.Unknown }),\n BedrockMedia.ImageBlock,\n])\n\nconst BedrockToolResultBlock = Schema.Struct({\n toolResult: Schema.Struct({\n toolUseId: Schema.String,\n content: Schema.Array(BedrockToolResultContentItem),\n status: Schema.optional(Schema.Literals([\"success\", \"error\"])),\n }),\n})\ntype BedrockToolResultBlock = Schema.Schema.Type<typeof BedrockToolResultBlock>\n\nconst BedrockReasoningBlock = Schema.Struct({\n reasoningContent: Schema.Struct({\n reasoningText: Schema.optional(\n Schema.Struct({\n text: Schema.String,\n signature: Schema.optional(Schema.String),\n }),\n ),\n }),\n})\n\nconst BedrockUserBlock = Schema.Union([\n BedrockTextBlock,\n BedrockMedia.ImageBlock,\n BedrockMedia.DocumentBlock,\n BedrockToolResultBlock,\n BedrockCache.CachePointBlock,\n])\ntype BedrockUserBlock = Schema.Schema.Type<typeof BedrockUserBlock>\n\nconst BedrockAssistantBlock = Schema.Union([\n BedrockTextBlock,\n BedrockReasoningBlock,\n BedrockToolUseBlock,\n BedrockCache.CachePointBlock,\n])\ntype BedrockAssistantBlock = Schema.Schema.Type<typeof BedrockAssistantBlock>\n\nconst BedrockMessage = Schema.Union([\n Schema.Struct({ role: Schema.Literal(\"user\"), content: Schema.Array(BedrockUserBlock) }),\n Schema.Struct({ role: Schema.Literal(\"assistant\"), content: Schema.Array(BedrockAssistantBlock) }),\n]).pipe(Schema.toTaggedUnion(\"role\"))\ntype BedrockMessage = Schema.Schema.Type<typeof BedrockMessage>\n\nconst BedrockSystemBlock = Schema.Union([BedrockTextBlock, BedrockCache.CachePointBlock])\ntype BedrockSystemBlock = Schema.Schema.Type<typeof BedrockSystemBlock>\n\nconst BedrockToolSpec = Schema.Struct({\n toolSpec: Schema.Struct({\n name: Schema.String,\n description: Schema.String,\n inputSchema: Schema.Struct({\n json: JsonObject,\n }),\n }),\n})\ntype BedrockToolSpec = Schema.Schema.Type<typeof BedrockToolSpec>\n\nconst BedrockTool = Schema.Union([BedrockToolSpec, BedrockCache.CachePointBlock])\ntype BedrockTool = Schema.Schema.Type<typeof BedrockTool>\n\nconst BedrockToolChoice = Schema.Union([\n Schema.Struct({ auto: Schema.Struct({}) }),\n Schema.Struct({ any: Schema.Struct({}) }),\n Schema.Struct({ tool: Schema.Struct({ name: Schema.String }) }),\n])\n\nconst BedrockBodyFields = {\n modelId: Schema.String,\n messages: Schema.Array(BedrockMessage),\n system: optionalArray(BedrockSystemBlock),\n inferenceConfig: Schema.optional(\n Schema.Struct({\n maxTokens: Schema.optional(Schema.Number),\n temperature: Schema.optional(Schema.Number),\n topP: Schema.optional(Schema.Number),\n stopSequences: optionalArray(Schema.String),\n }),\n ),\n toolConfig: Schema.optional(\n Schema.Struct({\n tools: Schema.Array(BedrockTool),\n toolChoice: Schema.optional(BedrockToolChoice),\n }),\n ),\n additionalModelRequestFields: Schema.optional(JsonObject),\n}\nconst BedrockConverseBody = Schema.Struct(BedrockBodyFields)\nexport type BedrockConverseBody = Schema.Schema.Type<typeof BedrockConverseBody>\n\nconst BedrockUsageSchema = Schema.Struct({\n inputTokens: Schema.optional(Schema.Number),\n outputTokens: Schema.optional(Schema.Number),\n totalTokens: Schema.optional(Schema.Number),\n cacheReadInputTokens: Schema.optional(Schema.Number),\n cacheWriteInputTokens: Schema.optional(Schema.Number),\n})\ntype BedrockUsageSchema = Schema.Schema.Type<typeof BedrockUsageSchema>\n\n// Streaming event shape — the AWS event stream wraps each JSON payload by its\n// `:event-type` header (e.g. `messageStart`, `contentBlockDelta`). We\n// reconstruct that wrapping in `decodeFrames` below so the event schema can\n// stay a plain discriminated record.\nconst BedrockEvent = Schema.Struct({\n messageStart: Schema.optional(Schema.Struct({ role: Schema.String })),\n contentBlockStart: Schema.optional(\n Schema.Struct({\n contentBlockIndex: Schema.Number,\n start: Schema.optional(\n Schema.Struct({\n toolUse: Schema.optional(Schema.Struct({ toolUseId: Schema.String, name: Schema.String })),\n }),\n ),\n }),\n ),\n contentBlockDelta: Schema.optional(\n Schema.Struct({\n contentBlockIndex: Schema.Number,\n delta: Schema.optional(\n Schema.Struct({\n text: Schema.optional(Schema.String),\n toolUse: Schema.optional(Schema.Struct({ input: Schema.String })),\n reasoningContent: Schema.optional(\n Schema.Struct({\n text: Schema.optional(Schema.String),\n signature: Schema.optional(Schema.String),\n }),\n ),\n }),\n ),\n }),\n ),\n contentBlockStop: Schema.optional(Schema.Struct({ contentBlockIndex: Schema.Number })),\n messageStop: Schema.optional(\n Schema.Struct({\n stopReason: Schema.String,\n additionalModelResponseFields: Schema.optional(Schema.Unknown),\n }),\n ),\n metadata: Schema.optional(\n Schema.Struct({\n usage: Schema.optional(BedrockUsageSchema),\n metrics: Schema.optional(Schema.Unknown),\n }),\n ),\n internalServerException: Schema.optional(Schema.Struct({ message: Schema.String })),\n modelStreamErrorException: Schema.optional(Schema.Struct({ message: Schema.String })),\n validationException: Schema.optional(Schema.Struct({ message: Schema.String })),\n throttlingException: Schema.optional(Schema.Struct({ message: Schema.String })),\n serviceUnavailableException: Schema.optional(Schema.Struct({ message: Schema.String })),\n})\ntype BedrockEvent = Schema.Schema.Type<typeof BedrockEvent>\n\n// =============================================================================\n// Request Lowering\n// =============================================================================\nconst lowerToolSpec = (tool: ToolDefinition, inputSchema: JsonSchema): BedrockToolSpec => ({\n toolSpec: {\n name: tool.name,\n description: tool.description,\n inputSchema: { json: inputSchema },\n },\n})\n\nconst lowerTools = (\n compatibility: ModelToolSchemaCompatibility | undefined,\n breakpoints: BedrockCache.Breakpoints,\n tools: ReadonlyArray<ToolDefinition>,\n): BedrockTool[] => {\n const result: BedrockTool[] = []\n for (const tool of tools) {\n result.push(lowerToolSpec(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, compatibility)))\n const cachePoint = BedrockCache.block(breakpoints, tool.cache)\n if (cachePoint) result.push(cachePoint)\n }\n return result\n}\n\nconst textWithCache = (\n breakpoints: BedrockCache.Breakpoints,\n text: string,\n cache: CacheHint | undefined,\n): Array<BedrockTextBlock | BedrockCache.CachePointBlock> => {\n const cachePoint = BedrockCache.block(breakpoints, cache)\n return cachePoint ? [{ text }, cachePoint] : [{ text }]\n}\n\nconst lowerToolChoice = (toolChoice: NonNullable<LLMRequest[\"toolChoice\"]>) =>\n ProviderShared.matchToolChoice(\"Bedrock Converse\", toolChoice, {\n auto: () => ({ auto: {} }) as const,\n none: () => undefined,\n required: () => ({ any: {} }) as const,\n tool: (name) => ({ tool: { name } }) as const,\n })\n\nconst bedrockMetadata = (metadata: Record<string, unknown>): ProviderMetadata => ({ bedrock: metadata })\n\nconst reasoningSignature = (part: ReasoningPart) => {\n const bedrock = part.providerMetadata?.bedrock\n return (\n part.encrypted ??\n (ProviderShared.isRecord(bedrock) && typeof bedrock.signature === \"string\" ? bedrock.signature : undefined)\n )\n}\n\nconst lowerToolCall = (part: ToolCallPart): BedrockToolUseBlock => ({\n toolUse: {\n toolUseId: part.id,\n name: part.name,\n input: part.input,\n },\n})\n\nconst lowerToolResultContent = Effect.fn(\"BedrockConverse.lowerToolResultContent\")(function* (part: ToolResultPart) {\n if (part.result.type === \"text\" || part.result.type === \"error\")\n return [{ text: ProviderShared.toolResultText(part) }]\n if (part.result.type === \"json\") return [{ json: part.result.value }]\n\n const content: Array<Schema.Schema.Type<typeof BedrockToolResultContentItem>> = []\n for (const item of part.result.value) {\n if (item.type === \"text\") {\n content.push({ text: item.text })\n continue\n }\n const media = yield* BedrockMedia.lower({\n type: \"media\",\n mediaType: item.mime,\n data: item.uri,\n filename: item.name,\n })\n if (!(\"image\" in media))\n return yield* ProviderShared.invalidRequest(\"Bedrock Converse only supports image media in tool results\")\n content.push(media)\n }\n return content\n})\n\nconst lowerToolResult = Effect.fn(\"BedrockConverse.lowerToolResult\")(function* (part: ToolResultPart) {\n return {\n toolResult: {\n toolUseId: part.id,\n content: yield* lowerToolResultContent(part),\n status: part.result.type === \"error\" ? \"error\" : \"success\",\n },\n } satisfies BedrockToolResultBlock\n})\n\nconst lowerMessages = Effect.fn(\"BedrockConverse.lowerMessages\")(function* (\n request: LLMRequest,\n breakpoints: BedrockCache.Breakpoints,\n) {\n const messages: BedrockMessage[] = []\n\n for (const message of request.messages) {\n if (message.role === \"system\") {\n const part = yield* ProviderShared.wrappedSystemUpdate(\"Bedrock Converse\", message)\n const content = textWithCache(breakpoints, part.text, part.cache)\n const previous = messages.at(-1)\n if (previous?.role === \"user\")\n messages[messages.length - 1] = { role: \"user\", content: [...previous.content, ...content] }\n else messages.push({ role: \"user\", content })\n continue\n }\n\n if (message.role === \"user\") {\n const content: BedrockUserBlock[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"media\"]))\n return yield* ProviderShared.unsupportedContent(\"Bedrock Converse\", \"user\", [\"text\", \"media\"])\n if (part.type === \"text\") {\n content.push(...textWithCache(breakpoints, part.text, part.cache))\n continue\n }\n if (part.type === \"media\") {\n content.push(yield* BedrockMedia.lower(part))\n continue\n }\n }\n messages.push({ role: \"user\", content })\n continue\n }\n\n if (message.role === \"assistant\") {\n const content: BedrockAssistantBlock[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"reasoning\", \"tool-call\"]))\n return yield* ProviderShared.unsupportedContent(\"Bedrock Converse\", \"assistant\", [\n \"text\",\n \"reasoning\",\n \"tool-call\",\n ])\n if (part.type === \"text\") {\n content.push(...textWithCache(breakpoints, part.text, part.cache))\n continue\n }\n if (part.type === \"reasoning\") {\n content.push({\n reasoningContent: {\n reasoningText: { text: part.text, signature: reasoningSignature(part) },\n },\n })\n continue\n }\n if (part.type === \"tool-call\") {\n content.push(lowerToolCall(part))\n continue\n }\n }\n messages.push({ role: \"assistant\", content })\n continue\n }\n\n const content: BedrockUserBlock[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"tool-result\"]))\n return yield* ProviderShared.unsupportedContent(\"Bedrock Converse\", \"tool\", [\"tool-result\"])\n content.push(yield* lowerToolResult(part))\n const cachePoint = BedrockCache.block(breakpoints, part.cache)\n if (cachePoint) content.push(cachePoint)\n }\n messages.push({ role: \"user\", content })\n }\n\n return messages\n})\n\n// System prompts share the cache-point convention: emit the text block, then\n// optionally a positional `cachePoint` marker.\nconst lowerSystem = (\n breakpoints: BedrockCache.Breakpoints,\n system: ReadonlyArray<LLMRequest[\"system\"][number]>,\n): BedrockSystemBlock[] => system.flatMap((part) => textWithCache(breakpoints, part.text, part.cache))\n\nconst fromRequest = Effect.fn(\"BedrockConverse.fromRequest\")(function* (request: LLMRequest) {\n const toolChoice = request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined\n const generation = request.generation\n // Bedrock-Claude shares Anthropic's 4-breakpoint cap. Spend the budget in\n // tools → system → messages order to favour the highest-impact prefixes.\n const breakpoints = BedrockCache.breakpoints()\n const toolConfig =\n request.tools.length > 0 && request.toolChoice?.type !== \"none\"\n ? { tools: lowerTools(request.model.compatibility?.toolSchema, breakpoints, request.tools), toolChoice }\n : undefined\n const system = request.system.length === 0 ? undefined : lowerSystem(breakpoints, request.system)\n const messages = yield* lowerMessages(request, breakpoints)\n if (breakpoints.dropped > 0) {\n yield* Effect.logWarning(\n `Bedrock Converse: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${BedrockCache.BEDROCK_BREAKPOINT_CAP} per request.`,\n )\n }\n return {\n modelId: request.model.id,\n messages,\n system,\n inferenceConfig:\n generation?.maxTokens === undefined &&\n generation?.temperature === undefined &&\n generation?.topP === undefined &&\n (generation?.stop === undefined || generation.stop.length === 0)\n ? undefined\n : {\n maxTokens: generation?.maxTokens,\n temperature: generation?.temperature,\n topP: generation?.topP,\n stopSequences: generation?.stop,\n },\n toolConfig,\n // Converse's base inferenceConfig has no topK; Anthropic/Nova accept it\n // as a model-specific field, so it goes through additionalModelRequestFields.\n additionalModelRequestFields: generation?.topK === undefined ? undefined : { top_k: generation.topK },\n }\n})\n\n// =============================================================================\n// Stream Parsing\n// =============================================================================\nconst mapFinishReason = (reason: string): FinishReason => {\n if (reason === \"end_turn\" || reason === \"stop_sequence\") return \"stop\"\n if (reason === \"max_tokens\") return \"length\"\n if (reason === \"tool_use\") return \"tool-calls\"\n if (reason === \"content_filtered\" || reason === \"guardrail_intervened\") return \"content-filter\"\n return \"unknown\"\n}\n\n// AWS Bedrock Converse reports `inputTokens` (inclusive total) with\n// `cacheReadInputTokens` and `cacheWriteInputTokens` as subsets. Pass\n// the total through and derive the non-cached breakdown. Bedrock does\n// not break reasoning out of `outputTokens` for any current model.\nconst mapUsage = (usage: BedrockUsageSchema | undefined): Usage | undefined => {\n if (!usage) return undefined\n const cacheTotal = (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0)\n const nonCached = ProviderShared.subtractTokens(usage.inputTokens, cacheTotal)\n return new Usage({\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n nonCachedInputTokens: nonCached,\n cacheReadInputTokens: usage.cacheReadInputTokens,\n cacheWriteInputTokens: usage.cacheWriteInputTokens,\n totalTokens: ProviderShared.totalTokens(usage.inputTokens, usage.outputTokens, usage.totalTokens),\n providerMetadata: { bedrock: usage },\n })\n}\n\ninterface ParserState {\n readonly tools: ToolStream.State<number>\n // Bedrock splits the finish into `messageStop` (carries `stopReason`) and\n // `metadata` (carries usage). Hold the terminal event in state so `onHalt`\n // can emit exactly one finish after both chunks have had a chance to arrive.\n readonly pendingFinish: { readonly reason: FinishReason; readonly usage?: Usage } | undefined\n readonly hasToolCalls: boolean\n readonly lifecycle: Lifecycle.State\n readonly reasoningSignatures: Readonly<Record<number, string>>\n}\n\nconst step = (state: ParserState, event: BedrockEvent) =>\n Effect.gen(function* () {\n if (event.contentBlockStart?.start?.toolUse) {\n const index = event.contentBlockStart.contentBlockIndex\n const events: LLMEvent[] = []\n const lifecycle = Lifecycle.stepStart(state.lifecycle, events)\n return [\n {\n ...state,\n lifecycle,\n tools: ToolStream.start(state.tools, index, {\n id: event.contentBlockStart.start.toolUse.toolUseId,\n name: event.contentBlockStart.start.toolUse.name,\n }),\n },\n [\n ...events,\n LLMEvent.toolInputStart({\n id: event.contentBlockStart.start.toolUse.toolUseId,\n name: event.contentBlockStart.start.toolUse.name,\n }),\n ],\n ] as const\n }\n\n if (event.contentBlockDelta?.delta?.text) {\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: Lifecycle.textDelta(\n state.lifecycle,\n events,\n `text-${event.contentBlockDelta.contentBlockIndex}`,\n event.contentBlockDelta.delta.text,\n ),\n },\n events,\n ] as const\n }\n\n if (event.contentBlockDelta?.delta?.reasoningContent) {\n const index = event.contentBlockDelta.contentBlockIndex\n const reasoning = event.contentBlockDelta.delta.reasoningContent\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: reasoning.text\n ? Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${index}`, reasoning.text)\n : state.lifecycle,\n reasoningSignatures: reasoning.signature\n ? { ...state.reasoningSignatures, [index]: reasoning.signature }\n : state.reasoningSignatures,\n },\n events,\n ] as const\n }\n\n if (event.contentBlockDelta?.delta?.toolUse) {\n const index = event.contentBlockDelta.contentBlockIndex\n const result = ToolStream.appendExisting(\n ADAPTER,\n state.tools,\n index,\n event.contentBlockDelta.delta.toolUse.input,\n \"Bedrock Converse tool delta is missing its tool call\",\n )\n if (ToolStream.isError(result)) return yield* result\n const events: LLMEvent[] = []\n const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle\n events.push(...result.events)\n return [{ ...state, lifecycle, tools: result.tools }, events] as const\n }\n\n if (event.contentBlockStop) {\n const index = event.contentBlockStop.contentBlockIndex\n const result = yield* ToolStream.finish(ADAPTER, state.tools, index)\n const events: LLMEvent[] = []\n const resultEvents = result.events ?? []\n const lifecycle = resultEvents.length\n ? Lifecycle.stepStart(state.lifecycle, events)\n : Lifecycle.reasoningEnd(\n Lifecycle.textEnd(state.lifecycle, events, `text-${index}`),\n events,\n `reasoning-${index}`,\n state.reasoningSignatures[index]\n ? bedrockMetadata({ signature: state.reasoningSignatures[index] })\n : undefined,\n )\n events.push(...resultEvents)\n return [\n {\n ...state,\n hasToolCalls:\n resultEvents.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)) ||\n state.hasToolCalls,\n lifecycle,\n tools: result.tools,\n reasoningSignatures: Object.fromEntries(\n Object.entries(state.reasoningSignatures).filter(([key]) => key !== String(index)),\n ),\n },\n events,\n ] as const\n }\n\n if (event.messageStop) {\n return [\n {\n ...state,\n pendingFinish: { reason: mapFinishReason(event.messageStop.stopReason), usage: state.pendingFinish?.usage },\n },\n [],\n ] as const\n }\n\n if (event.metadata) {\n const usage = mapUsage(event.metadata.usage)\n return [{ ...state, pendingFinish: { reason: state.pendingFinish?.reason ?? \"stop\", usage } }, []] as const\n }\n\n const exception = (\n [\n [\"internalServerException\", event.internalServerException],\n [\"modelStreamErrorException\", event.modelStreamErrorException],\n [\"serviceUnavailableException\", event.serviceUnavailableException],\n [\"throttlingException\", event.throttlingException],\n [\"validationException\", event.validationException],\n ] as const\n ).find((entry) => entry[1] !== undefined)\n if (exception) {\n return yield* new LLMError({\n module: ADAPTER,\n method: \"stream\",\n reason: classifyProviderFailure({\n message: exception[1]?.message ?? \"Bedrock Converse stream error\",\n code: exception[0],\n }),\n })\n }\n\n return [state, []] as const\n })\n\nconst framing = BedrockEventStream.framing(ADAPTER)\n\nconst onHalt = (state: ParserState): ReadonlyArray<LLMEvent> =>\n state.pendingFinish\n ? (() => {\n const events: LLMEvent[] = []\n Lifecycle.finish(state.lifecycle, events, {\n reason:\n state.pendingFinish.reason === \"stop\" && state.hasToolCalls ? \"tool-calls\" : state.pendingFinish.reason,\n usage: state.pendingFinish.usage,\n })\n return events\n })()\n : []\n\n// =============================================================================\n// Protocol And Bedrock Route\n// =============================================================================\n/**\n * The Bedrock Converse protocol — request body construction, body schema, and\n * the streaming-event state machine.\n */\nexport const protocol = Protocol.make({\n id: ADAPTER,\n body: {\n schema: BedrockConverseBody,\n from: fromRequest,\n },\n stream: {\n event: BedrockEvent,\n initial: () => ({\n tools: ToolStream.empty<number>(),\n pendingFinish: undefined,\n hasToolCalls: false,\n lifecycle: Lifecycle.initial(),\n reasoningSignatures: {},\n }),\n step,\n onHalt,\n },\n})\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: \"bedrock\",\n providerMetadataKey: \"bedrock\",\n protocol,\n // Bedrock's URL embeds the region in the route endpoint host and the\n // validated modelId in the path. We read the validated body so the URL\n // matches the body that gets signed.\n endpoint: Endpoint.path<BedrockConverseBody>(\n ({ body }) => `/model/${encodeURIComponent(body.modelId)}/converse-stream`,\n ),\n auth: BedrockAuth.auth,\n framing,\n})\n\nexport const sigV4Auth = BedrockAuth.sigV4\n\nexport * as BedrockConverse from \"./bedrock-converse\"\n", | ||
| "import type { RouteDefaultsInput } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { ProviderID, type ModelID } from \"../schema\"\nimport * as BedrockConverse from \"../protocols/bedrock-converse\"\nimport type { BedrockCredentials } from \"../protocols/bedrock-converse\"\n\nexport const id = ProviderID.make(\"amazon-bedrock\")\n\nexport type Config = RouteDefaultsInput & {\n readonly apiKey?: string\n readonly headers?: Record<string, string>\n readonly credentials?: BedrockCredentials\n /** AWS region. Defaults to `us-east-1` when neither this nor `credentials.region` is set. */\n readonly region?: string\n /** Override the computed `https://bedrock-runtime.<region>.amazonaws.com` URL. */\n readonly baseURL?: string\n}\n\nexport interface Settings extends ProviderPackage.Settings {\n readonly apiKey?: string\n readonly auth?: \"bearer\" | \"sigv4\"\n readonly baseURL?: string\n readonly credentials?: BedrockCredentials\n readonly region?: string\n readonly topP?: number\n}\nexport const routes = [BedrockConverse.route]\n\nconst bedrockBaseURL = (region: string) => `https://bedrock-runtime.${region}.amazonaws.com`\n\nconst configuredRoute = (input: Config) => {\n const { apiKey, credentials, region, baseURL, ...rest } = input\n const resolvedRegion = region ?? credentials?.region ?? \"us-east-1\"\n return BedrockConverse.route.with({\n ...rest,\n provider: id,\n endpoint: { baseURL: baseURL ?? bedrockBaseURL(resolvedRegion) },\n auth: apiKey === undefined ? BedrockConverse.sigV4Auth(credentials) : Auth.bearer(apiKey),\n })\n}\n\nexport const configure = (input: Config = {}) => {\n const route = configuredRoute(input)\n return {\n id,\n model: (modelID: string | ModelID) => route.model({ id: modelID }),\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) => {\n if (settings.auth === \"bearer\" && settings.apiKey === undefined)\n throw new Error(\"Amazon Bedrock bearer auth requires apiKey\")\n if (settings.auth === \"sigv4\" && settings.apiKey !== undefined)\n throw new Error(\"Amazon Bedrock SigV4 auth does not accept apiKey\")\n return configure({\n apiKey: settings.auth === \"sigv4\" ? undefined : settings.apiKey,\n baseURL: settings.baseURL,\n credentials: settings.credentials,\n generation: settings.topP === undefined ? undefined : { topP: settings.topP },\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n region: settings.region,\n }).model(modelID)\n}\n" | ||
| ], | ||
| "mappings": ";kxBAUA,SAAM,QAAa,SAAI,OAAiB,OAAQ,MAAQ,OAClD,QAAO,SAAI,iBAUX,QAAuC,MAAE,YAAQ,IAAI,WAAW,CAAC,EAAG,OAAQ,CAAE,EAE9E,GAAc,CAAC,EAAyB,IAAwC,CACpF,IAAM,EAAY,EAAM,OAAO,OAAS,EAAM,OAIxC,EAAO,IAAI,WAAW,EAAY,EAAM,MAAM,EAGpD,OAFA,EAAK,IAAI,EAAM,OAAO,SAAS,EAAM,MAAM,EAAG,CAAC,EAC/C,EAAK,IAAI,EAAO,CAAS,EAClB,CAAE,OAAQ,EAAM,OAAQ,CAAE,GAG7B,GAAgB,CAAC,IAAkB,CAAC,EAAyB,IACjE,EAAO,IAAI,SAAU,EAAG,CACtB,IAAI,EAAS,GAAY,EAAO,CAAK,EAC/B,EAAgB,CAAC,EACvB,MAAO,EAAO,OAAO,OAAS,EAAO,QAAU,EAAG,CAChD,IAAM,EAAO,EAAO,OAAO,SAAS,EAAO,MAAM,EAC3C,EAAc,IAAI,SAAS,EAAK,OAAQ,EAAK,WAAY,EAAK,UAAU,EAAE,UAAU,EAAG,EAAK,EAClG,GAAI,EAAK,OAAS,EAAa,MAE/B,IAAM,EAAU,MAAO,EAAO,IAAI,CAChC,IAAK,IAAM,GAAW,OAAO,EAAK,SAAS,EAAG,CAAW,CAAC,EAC1D,MAAO,CAAC,IACN,EAAe,WACb,EACA,yDACE,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,GAEzD,CACJ,CAAC,EAGD,GAFA,EAAS,CAAE,OAAQ,EAAO,OAAQ,OAAQ,EAAO,OAAS,CAAY,EAElE,EAAQ,QAAQ,kBAAkB,QAAU,QAAS,SACzD,IAAM,EAAY,EAAQ,QAAQ,gBAAgB,MAClD,GAAI,OAAO,IAAc,SAAU,SACnC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AAS,GAAW,GAAe,CAAc,CAAE,EAC/D,KAAM,IAAW,OAA4B,EAAU,CAAW,EAAI,EAAK,OAAO,CAAM,CAC1F,CAAC,GAGU,EAAY,CAAC,EAAgB,CAAC,IAAM,CAC/C,IAAM,EAAQ,GAAgB,CAAK,EACnC,MAAO,CACL,MACA,MAAO,CAAC,IAA8B,EAAM,MAAM,CAAE,GAAI,CAAQ,CAAC,EACjE,WACF,GAGW,GAAW,EAAU,EACrB,GAAuD,CAAC,EAAS,IAAa,CACzF,GAAI,EAAS,OAAS,UAAY,EAAS,SAAW,OACpD,MAAU,MAAM,4CAA4C,EAC9D,GAAI,EAAS,OAAS,SAAW,EAAS,SAAW,OACnD,MAAU,MAAM,kDAAkD,EACpE,OAAO,EAAU,CACf,OAAQ,EAAS,OAAS,QAAU,OAAY,EAAS,OACzD,QAAS,EAAS,QAClB,YAAa,EAAS,YACtB,WAAY,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,EAAS,IAAK,EAC5E,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,OACjB,OAAQ,EAAS,MACnB,CAAC,EAAE,MAAM,CAAO", | ||
| "debugId": "1DA1135372EFD52F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.59/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js", "../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.59/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.59/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js"], | ||
| "sourcesContent": [ | ||
| "import { getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { resolveProcessCredentials } from \"./resolveProcessCredentials\";\nexport const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-process - fromProcess\");\n const profiles = await parseKnownFiles(init);\n return resolveProcessCredentials(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init.logger);\n};\n", | ||
| "import { CredentialsProviderError, externalDataInterceptor } from \"@smithy/core/config\";\nimport { exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { getValidatedProcessCredentials } from \"./getValidatedProcessCredentials\";\nexport const resolveProcessCredentials = async (profileName, profiles, logger) => {\n const profile = profiles[profileName];\n if (profiles[profileName]) {\n const credentialProcess = profile[\"credential_process\"];\n if (credentialProcess !== undefined) {\n const execPromise = promisify(externalDataInterceptor?.getTokenRecord?.().exec ?? exec);\n try {\n const { stdout } = await execPromise(credentialProcess);\n let data;\n try {\n data = JSON.parse(stdout.trim());\n }\n catch {\n throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);\n }\n return getValidatedProcessCredentials(profileName, data, profiles);\n }\n catch (error) {\n throw new CredentialsProviderError(error.message, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {\n logger,\n });\n }\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const getValidatedProcessCredentials = (profileName, data, profiles) => {\n if (data.Version !== 1) {\n throw Error(`Profile ${profileName} credential_process did not return Version 1.`);\n }\n if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {\n throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);\n }\n if (data.Expiration) {\n const currentTime = new Date();\n const expireTime = new Date(data.Expiration);\n if (expireTime < currentTime) {\n throw Error(`Profile ${profileName} credential_process returned expired credentials.`);\n }\n }\n let accountId = data.AccountId;\n if (!accountId && profiles?.[profileName]?.aws_account_id) {\n accountId = profiles[profileName].aws_account_id;\n }\n const credentials = {\n accessKeyId: data.AccessKeyId,\n secretAccessKey: data.SecretAccessKey,\n ...(data.SessionToken && { sessionToken: data.SessionToken }),\n ...(data.Expiration && { expiration: new Date(data.Expiration) }),\n ...(data.CredentialScope && { credentialScope: data.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_PROCESS\", \"w\");\n return credentials;\n};\n" | ||
| ], | ||
| "mappings": ";kJAAA,oBCAA,oBACA,eAAS,sBACT,oBAAS,aCFT,eACa,EAAiC,CAAC,EAAa,EAAM,IAAa,CAC3E,GAAI,EAAK,UAAY,EACjB,MAAM,MAAM,WAAW,gDAA0D,EAErF,GAAI,EAAK,cAAgB,QAAa,EAAK,kBAAoB,OAC3D,MAAM,MAAM,WAAW,oDAA8D,EAEzF,GAAI,EAAK,WAAY,CACjB,IAAM,EAAc,IAAI,KAExB,GADmB,IAAI,KAAK,EAAK,UAAU,EAC1B,EACb,MAAM,MAAM,WAAW,oDAA8D,EAG7F,IAAI,EAAY,EAAK,UACrB,GAAI,CAAC,GAAa,IAAW,IAAc,eACvC,EAAY,EAAS,GAAa,eAEtC,IAAM,EAAc,CAChB,YAAa,EAAK,YAClB,gBAAiB,EAAK,mBAClB,EAAK,cAAgB,CAAE,aAAc,EAAK,YAAa,KACvD,EAAK,YAAc,CAAE,WAAY,IAAI,KAAK,EAAK,UAAU,CAAE,KAC3D,EAAK,iBAAmB,CAAE,gBAAiB,EAAK,eAAgB,KAChE,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,sBAAuB,GAAG,EACrD,GDxBJ,IAAM,EAA4B,MAAO,EAAa,EAAU,IAAW,CAC9E,IAAM,EAAU,EAAS,GACzB,GAAI,EAAS,GAAc,CACvB,IAAM,EAAoB,EAAQ,mBAClC,GAAI,IAAsB,OAAW,CACjC,IAAM,EAAc,EAAU,2BAAyB,iBAAiB,EAAE,MAAQ,CAAI,EACtF,GAAI,CACA,IAAQ,UAAW,MAAM,EAAY,CAAiB,EAClD,EACJ,GAAI,CACA,EAAO,KAAK,MAAM,EAAO,KAAK,CAAC,EAEnC,KAAM,CACF,MAAM,MAAM,WAAW,6CAAuD,EAElF,OAAO,EAA+B,EAAa,EAAM,CAAQ,EAErE,MAAO,EAAO,CACV,MAAM,IAAI,2BAAyB,EAAM,QAAS,CAAE,QAAO,CAAC,GAIhE,WAAM,IAAI,2BAAyB,WAAW,wCAAmD,CAAE,QAAO,CAAC,EAI/G,WAAM,IAAI,2BAAyB,WAAW,mDAA8D,CACxG,QACJ,CAAC,GD9BF,IAAM,EAAc,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CAC7E,EAAK,QAAQ,MAAM,oDAAoD,EACvE,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAA0B,iBAAe,CAC5C,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAK,MAAM", | ||
| "debugId": "B7891E76FC4C28D864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/database/migration/20260722011141_delete_tool_progress_events.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport type { DatabaseMigration } from \"../migration\"\n\nexport default {\n id: \"20260722011141_delete_tool_progress_events\",\n up(tx) {\n return Effect.gen(function* () {\n yield* tx.run(`DELETE FROM \\`event\\` WHERE \\`type\\` = 'session.tool.progress.1';`)\n })\n },\n} satisfies DatabaseMigration.Migration\n" | ||
| ], | ||
| "mappings": ";wHAGA,SAAe,QACb,GAAI,6CACJ,EAAE,CAAC,EAAI,CACL,OAAO,EAAO,IAAI,SAAU,EAAG,CAC7B,MAAO,EAAG,IAAI,+DAAmE,EAClF,EAEL", | ||
| "debugId": "322B28D04A0CBE4D64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../tui/src/mini/demo.ts"], | ||
| "sourcesContent": [ | ||
| "// Demo mode for testing direct interactive mode without a real SDK.\n//\n// Enabled with `--demo`. Intercepts prompt submissions and drives the same\n// presentation commits and footer actions as the live transport. This\n// lets you test scrollback formatting, permission UI, canonical Form UI, and tool\n// snapshots without making actual model calls. Pass a demo slash command as\n// the initial interactive message to trigger a preview immediately.\n//\n// Slash commands:\n// /permission [kind] → triggers a permission request variant\n// /form [kind] → triggers a canonical Form request variant\n// /fmt <kind> → emits a specific tool/text type (text, reasoning, shell,\n// write, edit, patch, subagent, question, error, mix)\n//\n// Demo mode handles permission and Form replies locally, completing or failing\n// the synthetic tool parts through the same callbacks used by the live footer.\nimport path from \"path\"\nimport type { JsonValue, SessionMessageAssistantTool } from \"@opencode-ai/client/promise\"\nimport { parseSlashHead } from \"../prompt/parse\"\nimport { writeSessionOutput } from \"./stream\"\nimport { toolCommit, toolFinalPhase } from \"./stream-v2.subagent\"\nimport type {\n FooterApi,\n FooterView,\n FormCancel,\n FormReply,\n MiniFormRequest,\n MiniPermissionRequest,\n PermissionReply,\n RunPrompt,\n StreamCommit,\n} from \"./types\"\n\nconst KINDS = [\n \"markdown\",\n \"table\",\n \"text\",\n \"reasoning\",\n \"shell\",\n \"write\",\n \"edit\",\n \"patch\",\n \"subagent\",\n \"question\",\n \"error\",\n \"mix\",\n]\nconst PERMISSIONS = [\"edit\", \"shell\", \"read\", \"subagent\", \"external\", \"doom\"] as const\nconst FORMS = [\"question\", \"external\"] as const\n\ntype PermissionKind = (typeof PERMISSIONS)[number]\ntype FormKind = (typeof FORMS)[number]\n\nfunction permissionKind(value: string | undefined): PermissionKind | undefined {\n const next = (value || \"edit\").toLowerCase()\n return PERMISSIONS.find((item) => item === next)\n}\n\nfunction formKind(value: string | undefined): FormKind | undefined {\n const next = (value || \"question\").toLowerCase()\n return FORMS.find((item) => item === next)\n}\n\nconst SAMPLE_MARKDOWN = [\n \"# Direct Mode Demo\",\n \"\",\n \"This is a realistic assistant response for direct-mode formatting checks.\",\n \"It mixes **bold**, _italic_, `inline code`, links, code fences, and tables in one streamed reply.\",\n \"\",\n \"## Summary\",\n \"\",\n \"- Restored the final markdown flush so the last block is committed on idle.\",\n \"- Switched markdown scrollback commits back to top-level block boundaries.\",\n \"- Added footer-level regression coverage for split-footer rendering.\",\n \"\",\n \"## Status\",\n \"\",\n \"| Area | Before | After | Notes |\",\n \"| --- | --- | --- | --- |\",\n \"| Direct mode | Missing final rows | Stable | Final markdown block now flushes on idle |\",\n \"| Tables | Dropped in streaming mode | Visible | Block-based commits match the working OpenTUI demo |\",\n \"| Tests | Partial coverage | Broader coverage | Includes a footer-level split render capture |\",\n \"\",\n \"> This sample intentionally includes a wide table so you can spot wrapping and commit bugs quickly.\",\n \"\",\n \"```ts\",\n \"const result = { markdown: true, tables: 2, stable: true }\",\n \"```\",\n \"\",\n \"## Files\",\n \"\",\n \"| File | Change |\",\n \"| --- | --- |\",\n \"| `scrollback.surface.ts` | Align markdown commit logic with the split-footer demo |\",\n \"| `footer.ts` | Keep active surfaces across footer-height-only resizes |\",\n \"| `footer.test.ts` | Capture real split-footer markdown payloads during idle completion |\",\n \"\",\n \"Next step: run `/fmt table` if you want a tighter table-only sample.\",\n].join(\"\\n\")\n\nconst SAMPLE_TABLE = [\n \"# Table Sample\",\n \"\",\n \"| Kind | Example | Notes |\",\n \"| --- | --- | --- |\",\n \"| Pipe | `A\\\\|B` | Escaped pipes should stay in one cell |\",\n \"| Unicode | `漢字` | Wide characters should remain aligned |\",\n \"| Wrap | `LongTokenWithoutNaturalBreaks_1234567890` | Useful for width stress |\",\n \"| Status | done | Final row should still appear after idle |\",\n].join(\"\\n\")\n\ntype Ref = {\n msg: string\n call: string\n tool: string\n input: Record<string, JsonValue>\n start: number\n}\n\ntype FormRequest = {\n ref: Ref\n kind: FormKind\n request: MiniFormRequest\n}\n\ntype Perm = {\n ref: Ref\n done: {\n output: string\n metadata?: Record<string, JsonValue>\n }\n}\n\ntype Permit = {\n ref: Ref\n permission: string\n patterns: string[]\n metadata?: MiniPermissionRequest[\"metadata\"]\n always: string[]\n done: Perm[\"done\"]\n}\n\ntype State = {\n id: string\n thinking: boolean\n footer: FooterApi\n msg: number\n part: number\n call: number\n perm: number\n form: number\n perms: Map<string, Perm>\n forms: Map<string, FormRequest>\n started: Set<string>\n}\n\ntype Input = {\n sessionID: string\n thinking: boolean\n footer: FooterApi\n}\n\nfunction note(footer: FooterApi, text: string): void {\n footer.append({\n kind: \"system\",\n text,\n phase: \"start\",\n source: \"system\",\n })\n}\n\nfunction clearSubagent(footer: FooterApi): void {\n footer.event({\n type: \"stream.subagent\",\n state: {\n tabs: [],\n details: {},\n permissions: [],\n forms: [],\n },\n })\n}\n\nfunction showSubagent(\n state: State,\n input: {\n sessionID: string\n label: string\n description: string\n status: \"running\" | \"completed\" | \"cancelled\" | \"error\"\n title?: string\n commits: StreamCommit[]\n },\n) {\n state.footer.event({\n type: \"stream.subagent\",\n state: {\n tabs: [\n {\n sessionID: input.sessionID,\n label: input.label,\n description: input.description,\n status: input.status,\n title: input.title,\n },\n ],\n details: {\n [input.sessionID]: {\n commits: input.commits,\n },\n },\n permissions: [],\n forms: [],\n },\n })\n}\n\nfunction wait(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (!signal) {\n setTimeout(resolve, ms)\n return\n }\n\n if (signal.aborted) {\n resolve()\n return\n }\n\n const done = () => {\n clearTimeout(timer)\n signal.removeEventListener(\"abort\", done)\n resolve()\n }\n\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", done)\n resolve()\n }, ms)\n\n signal.addEventListener(\"abort\", done, { once: true })\n })\n}\n\nfunction split(text: string): string[] {\n if (text.length <= 48) {\n return [text]\n }\n\n const size = Math.ceil(text.length / 3)\n return [text.slice(0, size), text.slice(size, size * 2), text.slice(size * 2)]\n}\n\nfunction take(state: State, key: \"msg\" | \"part\" | \"call\" | \"perm\", prefix: string): string {\n state[key] += 1\n return `demo_${prefix}_${state[key]}`\n}\n\nfunction present(state: State, commits: StreamCommit[], view?: FooterView): void {\n writeSessionOutput(\n { footer: state.footer },\n {\n commits,\n updates: view\n ? [\n {\n type: \"stream.patch\" as const,\n patch: { status: view.type === \"permission\" ? \"awaiting permission\" : \"awaiting form\" },\n },\n { type: \"stream.view\" as const, view },\n ]\n : undefined,\n },\n )\n}\n\nfunction clearBlocker(state: State): void {\n writeSessionOutput(\n { footer: state.footer },\n {\n commits: [],\n updates: [\n { type: \"stream.patch\", patch: { status: \"\" } },\n { type: \"stream.view\", view: { type: \"prompt\" } },\n ],\n },\n )\n}\n\nfunction open(state: State): string {\n return take(state, \"msg\", \"msg\")\n}\n\nasync function emitText(state: State, body: string, signal?: AbortSignal): Promise<void> {\n const msg = open(state)\n const part = take(state, \"part\", \"part\")\n for (const item of split(body)) {\n if (signal?.aborted) {\n return\n }\n\n present(state, [\n { kind: \"assistant\", source: \"assistant\", text: item, phase: \"progress\", messageID: msg, partID: part },\n ])\n await wait(45, signal)\n }\n}\n\nasync function emitReasoning(state: State, body: string, signal?: AbortSignal): Promise<void> {\n const msg = open(state)\n const part = take(state, \"part\", \"part\")\n let first = true\n for (const item of split(body)) {\n if (signal?.aborted) {\n return\n }\n\n if (state.thinking) {\n present(state, [\n {\n kind: \"reasoning\",\n source: \"reasoning\",\n text: first ? `Thinking: ${item.replace(/\\[REDACTED\\]/g, \"\")}` : item.replace(/\\[REDACTED\\]/g, \"\"),\n phase: \"progress\",\n messageID: msg,\n partID: part,\n },\n ])\n first = false\n }\n await wait(45, signal)\n }\n}\n\nfunction make(state: State, tool: string, input: Record<string, JsonValue>): Ref {\n return {\n msg: open(state),\n call: take(state, \"call\", \"call\"),\n tool,\n input,\n start: Date.now(),\n }\n}\n\nfunction startTool(state: State, ref: Ref, structured: Record<string, JsonValue> = {}): SessionMessageAssistantTool {\n state.started.add(ref.call)\n const part = {\n type: \"tool\" as const,\n id: ref.call,\n name: ref.tool,\n state: { status: \"running\" as const, input: ref.input, structured, content: [] },\n time: { created: ref.start, ran: ref.start },\n }\n present(state, [toolCommit(part, ref.msg, \"start\")])\n return part\n}\n\nfunction askPermission(state: State, item: Permit): void {\n const tool = startTool(state, item.ref)\n\n const id = take(state, \"perm\", \"perm\")\n state.perms.set(id, {\n ref: item.ref,\n done: item.done,\n })\n\n present(state, [], {\n type: \"permission\",\n request: {\n id,\n sessionID: state.id,\n action: item.permission,\n resources: item.patterns,\n metadata: item.metadata ?? {},\n save: item.always,\n source: { type: \"tool\", messageID: item.ref.msg, callID: item.ref.call },\n tool,\n },\n })\n}\n\nfunction doneTool(\n state: State,\n ref: Ref,\n output: {\n output: string\n metadata?: Record<string, JsonValue>\n },\n): void {\n if (!state.started.has(ref.call)) startTool(state, ref)\n const part: SessionMessageAssistantTool = {\n type: \"tool\",\n id: ref.call,\n name: ref.tool,\n state: {\n status: \"completed\",\n input: ref.input,\n content: output.output ? [{ type: \"text\", text: output.output }] : [],\n structured: output.metadata ?? {},\n },\n time: { created: ref.start, ran: ref.start, completed: Date.now() },\n }\n present(state, [toolCommit(part, ref.msg, toolFinalPhase(part))])\n}\n\nfunction failTool(state: State, ref: Ref, error: string): void {\n if (!state.started.has(ref.call)) startTool(state, ref)\n present(state, [\n toolCommit(\n {\n type: \"tool\",\n id: ref.call,\n name: ref.tool,\n state: {\n status: \"error\",\n input: ref.input,\n error: { type: \"unknown\", message: error },\n structured: {},\n content: [],\n },\n time: { created: ref.start, ran: ref.start, completed: Date.now() },\n },\n ref.msg,\n \"final\",\n ),\n ])\n}\n\nfunction emitError(state: State, text: string): void {\n present(state, [{ kind: \"error\", source: \"system\", text, phase: \"start\" }])\n}\n\nasync function emitBash(state: State, signal?: AbortSignal): Promise<void> {\n const ref = make(state, \"shell\", {\n command: \"git status\",\n workdir: process.cwd(),\n description: \"Show git status\",\n })\n startTool(state, ref)\n await wait(70, signal)\n doneTool(state, ref, {\n output: `${process.cwd()}\\ngit status\\nOn branch demo\\nnothing to commit, working tree clean\\n`,\n metadata: {\n exit: 0,\n },\n })\n}\n\nfunction emitWrite(state: State): void {\n const file = path.join(process.cwd(), \"src\", \"demo-format.ts\")\n const ref = make(state, \"write\", {\n path: file,\n content: \"export const demo = 42\\n\",\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {},\n })\n}\n\nfunction emitEdit(state: State): void {\n const file = path.join(process.cwd(), \"src\", \"demo-format.ts\")\n const ref = make(state, \"edit\", {\n path: file,\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {\n files: [\n {\n file,\n status: \"modified\",\n patch: \"@@ -1 +1 @@\\n-export const demo = 1\\n+export const demo = 42\\n\",\n },\n ],\n },\n })\n}\n\nfunction emitPatch(state: State): void {\n const file = path.join(process.cwd(), \"src\", \"demo-format.ts\")\n const ref = make(state, \"patch\", {\n patchText: \"*** Begin Patch\\n*** End Patch\",\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {\n files: [\n {\n status: \"modified\",\n file,\n patch: \"@@ -1 +1 @@\\n-export const demo = 1\\n+export const demo = 42\\n\",\n deletions: 1,\n },\n {\n status: \"added\",\n file: path.join(process.cwd(), \"README-demo.md\"),\n patch: \"@@ -0,0 +1,4 @@\\n+# Demo\\n+This is a generated preview file.\\n\",\n deletions: 0,\n },\n ],\n },\n })\n}\n\nfunction emitTask(state: State): void {\n const ref = make(state, \"subagent\", {\n description: \"Scan run/* for reducer touchpoints\",\n agent: \"explore\",\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {\n sessionID: \"ses_demo_child\",\n status: \"completed\",\n output: \"\",\n },\n })\n const part = {\n type: \"tool\",\n id: \"sub_demo_call_1\",\n name: \"read\",\n state: {\n status: \"running\",\n input: {\n path: \"packages/tui/src/mini/stream.ts\",\n offset: 1,\n limit: 200,\n },\n structured: {},\n content: [],\n },\n time: { created: Date.now(), ran: Date.now() },\n } satisfies SessionMessageAssistantTool\n showSubagent(state, {\n sessionID: \"ses_demo_child\",\n label: \"Explore\",\n description: \"Scan run/* for reducer touchpoints\",\n status: \"completed\",\n title: \"Reducer touchpoints found\",\n commits: [\n {\n kind: \"user\",\n text: \"Scan run/* for reducer touchpoints\",\n phase: \"start\",\n source: \"system\",\n },\n {\n kind: \"reasoning\",\n text: \"Thinking: tracing reducer and footer boundaries\",\n phase: \"progress\",\n source: \"reasoning\",\n messageID: \"sub_demo_msg_reasoning\",\n partID: \"sub_demo_reasoning_1\",\n },\n toolCommit(part, \"sub_demo_msg_tool\", \"start\"),\n {\n kind: \"assistant\",\n text: \"Footer updates flow through stream.ts into RunFooter\",\n phase: \"progress\",\n source: \"assistant\",\n messageID: \"sub_demo_msg_text\",\n partID: \"sub_demo_text_1\",\n },\n ],\n })\n}\n\nfunction emitQuestionTool(state: State): void {\n const ref = make(state, \"question\", {\n questions: [\n {\n header: \"Style\",\n question: \"Which output style do you want to inspect?\",\n options: [\n { label: \"Diff\", description: \"Show diff block\" },\n { label: \"Code\", description: \"Show code block\" },\n ],\n multiple: false,\n custom: false,\n },\n {\n header: \"Extras\",\n question: \"Pick extra rows\",\n options: [\n { label: \"Usage\", description: \"Add usage row\" },\n { label: \"Duration\", description: \"Add duration row\" },\n ],\n multiple: true,\n custom: true,\n },\n ],\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {\n answers: [[\"Diff\"], [\"Usage\", \"custom-note\"]],\n },\n })\n}\n\nfunction emitPermission(state: State, kind: PermissionKind = \"edit\"): void {\n const root = process.cwd()\n const file = path.join(root, \"src\", \"demo-format.ts\")\n\n if (kind === \"shell\") {\n const command = \"git status --short\"\n const ref = make(state, \"shell\", {\n command,\n workdir: root,\n description: \"Inspect worktree changes\",\n })\n askPermission(state, {\n ref,\n permission: \"shell\",\n patterns: [command],\n always: [\"*\"],\n done: {\n output: `${root}\\ngit status --short\\n M src/demo-format.ts\\n?? src/demo-permission.ts\\n`,\n metadata: {\n exit: 0,\n },\n },\n })\n return\n }\n\n if (kind === \"read\") {\n const target = path.join(root, \"package.json\")\n const ref = make(state, \"read\", {\n path: target,\n offset: 1,\n limit: 80,\n })\n askPermission(state, {\n ref,\n permission: \"read\",\n patterns: [target],\n always: [target],\n done: {\n output: [\"1: {\", '2: \"name\": \"opencode\",', '3: \"private\": true', \"4: }\"].join(\"\\n\"),\n metadata: {},\n },\n })\n return\n }\n\n if (kind === \"subagent\") {\n const ref = make(state, \"subagent\", {\n description: \"Inspect footer spacing across direct-mode prompts\",\n agent: \"explore\",\n })\n askPermission(state, {\n ref,\n permission: \"subagent\",\n patterns: [\"explore\"],\n always: [\"*\"],\n done: {\n output: \"\",\n metadata: {\n sessionID: \"sub_demo_perm_1\",\n status: \"completed\",\n output: \"\",\n },\n },\n })\n return\n }\n\n if (kind === \"external\") {\n const dir = path.join(path.dirname(root), \"demo-shared\")\n const target = path.join(dir, \"README.md\")\n const ref = make(state, \"read\", {\n path: target,\n offset: 1,\n limit: 40,\n })\n askPermission(state, {\n ref,\n permission: \"external_directory\",\n patterns: [`${dir}/**`],\n metadata: {\n parentDir: dir,\n filepath: target,\n },\n always: [`${dir}/**`],\n done: {\n output: `1: # External demo\\n2: Shared preview file\\nPath: ${target}`,\n metadata: {},\n },\n })\n return\n }\n\n if (kind === \"doom\") {\n const ref = make(state, \"subagent\", {\n description: \"Retry the formatter after repeated failures\",\n agent: \"general\",\n })\n askPermission(state, {\n ref,\n permission: \"doom_loop\",\n patterns: [\"*\"],\n always: [\"*\"],\n done: {\n output: \"Continuing after repeated failures.\\n\",\n metadata: {},\n },\n })\n return\n }\n\n const diff = \"@@ -1 +1 @@\\n-export const demo = 1\\n+export const demo = 42\\n\"\n const ref = make(state, \"edit\", {\n path: file,\n })\n askPermission(state, {\n ref,\n permission: \"edit\",\n patterns: [file],\n always: [file],\n done: {\n output: \"\",\n metadata: {\n files: [{ file, status: \"modified\", patch: diff }],\n },\n },\n })\n}\n\nfunction demoForm(kind: FormKind): { title: string; fields: MiniFormRequest[\"fields\"]; questions?: JsonValue[] } {\n if (kind === \"question\") {\n const questions: JsonValue[] = [\n {\n header: \"Layout\",\n question: \"Which footer view should be the reference for spacing checks?\",\n options: [\n { label: \"Form\", description: \"Inspect the canonical Form footer\" },\n { label: \"Prompt\", description: \"Return to the normal composer\" },\n ],\n multiple: false,\n custom: true,\n },\n {\n header: \"Checks\",\n question: \"Pick formatting previews\",\n options: [\n { label: \"Diff\", description: \"Emit an edit diff\" },\n { label: \"Subagent\", description: \"Emit a subagent card\" },\n ],\n multiple: true,\n custom: true,\n },\n ]\n return {\n title: \"Questions\",\n questions,\n fields: [\n {\n key: \"q0\",\n title: \"Layout\",\n description: \"Which footer view should be the reference for spacing checks?\",\n type: \"string\",\n options: [\n { value: \"Form\", label: \"Form\", description: \"Inspect the canonical Form footer\" },\n { value: \"Prompt\", label: \"Prompt\", description: \"Return to the normal composer\" },\n ],\n custom: true,\n },\n {\n key: \"q1\",\n title: \"Checks\",\n description: \"Pick formatting previews\",\n type: \"multiselect\",\n options: [\n { value: \"Diff\", label: \"Diff\", description: \"Emit an edit diff\" },\n { value: \"Subagent\", label: \"Subagent\", description: \"Emit a subagent card\" },\n ],\n custom: true,\n },\n ],\n }\n }\n return {\n title: \"MCP authorization\",\n fields: [\n {\n key: \"authorization\",\n type: \"external\",\n url: \"https://example.com/opencode-demo\",\n title: \"Authorize demo MCP server\",\n description: \"Complete authorization in your browser\",\n },\n ],\n }\n}\n\nfunction emitForm(state: State, kind: FormKind = \"question\"): void {\n const form = demoForm(kind)\n const ref = make(state, kind === \"question\" ? \"question\" : \"mcp_demo\", {\n ...(form.questions ? { questions: form.questions } : { form: kind }),\n })\n startTool(state, ref)\n state.form++\n const request: MiniFormRequest = {\n id: `frm_demo_${state.form}`,\n sessionID: state.id,\n title: form.title,\n metadata:\n kind === \"question\"\n ? { kind: \"question\", tool: { messageID: ref.msg, callID: ref.call } }\n : { kind: \"mcp\", message: `Synthetic ${kind} MCP elicitation` },\n fields: form.fields,\n }\n state.forms.set(request.id, { ref, kind, request })\n present(state, [], { type: \"form\", request })\n}\n\nasync function emitFmt(state: State, kind: string, body: string, signal?: AbortSignal): Promise<boolean> {\n if (kind === \"text\") {\n await emitText(state, body || SAMPLE_MARKDOWN, signal)\n return true\n }\n\n if (kind === \"markdown\" || kind === \"md\") {\n await emitText(state, body || SAMPLE_MARKDOWN, signal)\n return true\n }\n\n if (kind === \"table\") {\n await emitText(state, body || SAMPLE_TABLE, signal)\n return true\n }\n\n if (kind === \"reasoning\") {\n await emitReasoning(state, body || \"Planning next steps [REDACTED] while preserving reducer ordering.\", signal)\n return true\n }\n\n if (kind === \"shell\") {\n await emitBash(state, signal)\n return true\n }\n\n if (kind === \"write\") {\n emitWrite(state)\n return true\n }\n\n if (kind === \"edit\") {\n emitEdit(state)\n return true\n }\n\n if (kind === \"patch\") {\n emitPatch(state)\n return true\n }\n\n if (kind === \"subagent\") {\n emitTask(state)\n return true\n }\n\n if (kind === \"question\") {\n emitQuestionTool(state)\n return true\n }\n\n if (kind === \"error\") {\n emitError(state, body || \"demo error event\")\n return true\n }\n\n if (kind === \"mix\") {\n await emitText(state, SAMPLE_MARKDOWN, signal)\n await wait(50, signal)\n await emitReasoning(state, \"Thinking through formatter edge cases [REDACTED].\", signal)\n await wait(50, signal)\n await emitBash(state, signal)\n emitWrite(state)\n emitEdit(state)\n emitPatch(state)\n emitTask(state)\n emitQuestionTool(state)\n emitError(state, \"demo mixed scenario error\")\n return true\n }\n\n return false\n}\n\nfunction intro(state: State): void {\n note(\n state.footer,\n [\n \"Demo slash commands enabled for interactive mode.\",\n `- /permission [kind] (${PERMISSIONS.join(\", \")})`,\n `- /form [kind] (${FORMS.join(\", \")})`,\n `- /fmt <kind> (${KINDS.join(\", \")})`,\n \"Examples:\",\n \"- /permission shell\",\n \"- /form question\",\n \"- /form external\",\n \"- /fmt markdown\",\n \"- /fmt table\",\n \"- /fmt text your custom text\",\n ].join(\"\\n\"),\n )\n}\n\nexport function createRunDemo(input: Input) {\n const state: State = {\n id: input.sessionID,\n thinking: input.thinking,\n footer: input.footer,\n msg: 0,\n part: 0,\n call: 0,\n perm: 0,\n form: 0,\n perms: new Map(),\n forms: new Map(),\n started: new Set(),\n }\n\n const start = async (): Promise<void> => {\n intro(state)\n }\n\n const prompt = async (line: RunPrompt, signal?: AbortSignal): Promise<boolean> => {\n const text = line.text.trim()\n const head = parseSlashHead(text)\n const list = head?.arguments.split(/\\s+/).filter(Boolean) ?? []\n const cmd = head ? `/${head.name}` : \"\"\n\n clearSubagent(state.footer)\n\n if (cmd === \"/help\") {\n intro(state)\n return true\n }\n\n if (cmd === \"/permission\") {\n const kind = permissionKind(list[0])\n if (!kind) {\n note(state.footer, `Pick a permission kind: ${PERMISSIONS.join(\", \")}`)\n return true\n }\n\n emitPermission(state, kind)\n return true\n }\n\n if (cmd === \"/form\") {\n const kind = formKind(list[0])\n if (!kind) {\n note(state.footer, `Pick a form kind: ${FORMS.join(\", \")}`)\n return true\n }\n\n emitForm(state, kind)\n return true\n }\n\n if (cmd === \"/fmt\") {\n const kind = (list[0] || \"\").toLowerCase()\n const body = list.slice(1).join(\" \")\n if (!kind) {\n note(state.footer, `Pick a kind: ${KINDS.join(\", \")}`)\n return true\n }\n\n const ok = await emitFmt(state, kind, body, signal)\n if (ok) {\n return true\n }\n\n note(state.footer, `Unknown kind \"${kind}\". Use: ${KINDS.join(\", \")}`)\n return true\n }\n\n return false\n }\n\n const permission = (input: PermissionReply): boolean => {\n const item = state.perms.get(input.requestID)\n if (!item || !input.reply) {\n return false\n }\n\n state.perms.delete(input.requestID)\n clearBlocker(state)\n\n if (input.reply === \"reject\") {\n failTool(state, item.ref, input.message || \"permission rejected\")\n return true\n }\n\n doneTool(state, item.ref, item.done)\n return true\n }\n\n const formReply = (input: FormReply): boolean => {\n const form = state.forms.get(input.formID)\n if (!form || input.sessionID !== form.request.sessionID) return false\n state.forms.delete(input.formID)\n clearBlocker(state)\n if (form.kind === \"question\") {\n doneTool(state, form.ref, {\n output: \"\",\n metadata: {\n answers: form.request.fields.map((field) => {\n const value = input.answer[field.key]\n if (value === undefined) return []\n return Array.isArray(value) ? [...value] : [String(value)]\n }),\n },\n })\n return true\n }\n doneTool(state, form.ref, {\n output: `Form submitted: ${Object.entries(input.answer)\n .map(([key, value]) => `${key}=${Array.isArray(value) ? value.join(\", \") : String(value)}`)\n .join(\"; \")}\\n`,\n metadata: { answer: input.answer },\n })\n return true\n }\n\n const formCancel = (input: FormCancel): boolean => {\n const form = state.forms.get(input.formID)\n if (!form || input.sessionID !== form.request.sessionID) return false\n state.forms.delete(input.formID)\n clearBlocker(state)\n failTool(state, form.ref, \"form cancelled\")\n return true\n }\n\n return {\n start,\n prompt,\n permission,\n formReply,\n formCancel,\n }\n}\n" | ||
| ], | ||
| "mappings": ";2PAgBA,yBAiBA,SAAM,OAAQ,MACZ,gBACA,QACA,OACA,YACA,QACA,QACA,OACA,QACA,WACA,WACA,QACA,KACF,EACM,EAAc,CAAC,OAAQ,QAAS,OAAQ,WAAY,WAAY,MAAM,EACtE,EAAQ,CAAC,WAAY,UAAU,EAKrC,SAAS,CAAc,CAAC,EAAuD,CAC7E,IAAM,GAAQ,GAAS,QAAQ,YAAY,EAC3C,OAAO,EAAY,KAAK,CAAC,IAAS,IAAS,CAAI,EAGjD,SAAS,CAAQ,CAAC,EAAiD,CACjE,IAAM,GAAQ,GAAS,YAAY,YAAY,EAC/C,OAAO,EAAM,KAAK,CAAC,IAAS,IAAS,CAAI,EAG3C,IAAM,EAAkB,CACtB,qBACA,GACA,4EACA,oGACA,GACA,aACA,GACA,8EACA,6EACA,uEACA,GACA,YACA,GACA,oCACA,4BACA,2FACA,wGACA,iGACA,GACA,sGACA,GACA,QACA,6DACA,MACA,GACA,WACA,GACA,oBACA,gBACA,uFACA,2EACA,4FACA,GACA,sEACF,EAAE,KAAK;AAAA,CAAI,EAEL,EAAe,CACnB,iBACA,GACA,6BACA,sBACA,6DACA,uEACA,kFACA,8DACF,EAAE,KAAK;AAAA,CAAI,EAqDX,SAAS,CAAI,CAAC,EAAmB,EAAoB,CACnD,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AO,EAAM,MAAM,IAAI,EAAM,MAAM,EACzC,GAAI,CAAC,GAAQ,EAAM,YAAc,EAAK,QAAQ,UAAW,MAAO,GAGhE,GAFA,EAAM,MAAM,OAAO,EAAM,MAAM,EAC/B,EAAa,CAAK,EACd,EAAK,OAAS,WAWhB,OAVA,EAAS,EAAO,EAAK,IAAK,CACxB,OAAQ,GACR,SAAU,CACR,QAAS,EAAK,QAAQ,OAAO,IAAI,CAAC,IAAU,CAC1C,IAAM,EAAQ,EAAM,OAAO,EAAM,KACjC,GAAI,IAAU,OAAW,MAAO,CAAC,EACjC,OAAO,MAAM,QAAQ,CAAK,EAAI,CAAC,GAAG,CAAK,EAAI,CAAC,OAAO,CAAK,CAAC,EAC1D,CACH,CACF,CAAC,EACM,GAQT,OANA,EAAS,EAAO,EAAK,IAAK,CACxB,OAAQ,mBAAmB,OAAO,QAAQ,EAAM,MAAM,EACnD,IAAI,EAAE,EAAK,KAAW,GAAG,KAAO,MAAM,QAAQ,CAAK,EAAI,EAAM,KAAK,IAAI,EAAI,OAAO,CAAK,GAAG,EACzF,KAAK,IAAI;AAAA,EACZ,SAAU,CAAE,OAAQ,EAAM,MAAO,CACnC,CAAC,EACM,IAiBP,WAdiB,CAAC,IAA+B,CACjD,IAAM,EAAO,EAAM,MAAM,IAAI,EAAM,MAAM,EACzC,GAAI,CAAC,GAAQ,EAAM,YAAc,EAAK,QAAQ,UAAW,MAAO,GAIhE,OAHA,EAAM,MAAM,OAAO,EAAM,MAAM,EAC/B,EAAa,CAAK,EAClB,EAAS,EAAO,EAAK,IAAK,gBAAgB,EACnC,GAST", | ||
| "debugId": "384B84E53C764AFC64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/image/photon-wasm.bun.ts", "../core/src/image/photon.ts"], | ||
| "sourcesContent": [ | ||
| "// @ts-ignore Bun embeds static file imports when compiling the CLI.\nimport photonWasm from \"@silvia-odwyer/photon-node/photon_rs_bg.wasm\" with { type: \"file\" }\n\nexport default photonWasm\n", | ||
| "import photonWasm from \"#photon-wasm\"\nimport { Effect } from \"effect\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { FileSystem } from \"../filesystem\"\nimport { DecodeError, ResizerUnavailableError, SizeError } from \"../image\"\n\nconst JPEG_QUALITIES = [80, 85, 70, 55, 40]\n\nexport const make = Effect.gen(function* () {\n ;(globalThis as typeof globalThis & { __OPENCODE_PHOTON_WASM_PATH?: string }).__OPENCODE_PHOTON_WASM_PATH =\n path.isAbsolute(photonWasm) ? photonWasm : fileURLToPath(new URL(photonWasm, import.meta.url))\n const loadPhoton = yield* Effect.cached(\n Effect.tryPromise({\n try: () => import(\"@silvia-odwyer/photon-node\"),\n catch: () => new ResizerUnavailableError(),\n }),\n )\n return Effect.fn(\"Image.Photon.normalize\")(function* (\n resource: string,\n content: FileSystem.Content & { readonly encoding: \"base64\" },\n limits: {\n readonly autoResize: boolean\n readonly maxWidth: number\n readonly maxHeight: number\n readonly maxBase64Bytes: number\n },\n ) {\n const photon = yield* loadPhoton\n const decoded = yield* Effect.try({\n try: () => photon.PhotonImage.new_from_byteslice(Buffer.from(content.content, \"base64\")),\n catch: () => new DecodeError({ resource }),\n })\n try {\n const width = decoded.get_width()\n const height = decoded.get_height()\n const bytes = Buffer.byteLength(content.content, \"utf-8\")\n if (width <= limits.maxWidth && height <= limits.maxHeight && bytes <= limits.maxBase64Bytes) return content\n if (!limits.autoResize)\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n const scale = Math.min(1, limits.maxWidth / width, limits.maxHeight / height)\n const sizes = Array.from({ length: 32 }).reduce<Array<{ width: number; height: number }>>((acc) => {\n const previous = acc.at(-1) ?? {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n const next =\n acc.length === 0\n ? previous\n : {\n width: previous.width === 1 ? 1 : Math.max(1, Math.floor(previous.width * 0.75)),\n height: previous.height === 1 ? 1 : Math.max(1, Math.floor(previous.height * 0.75)),\n }\n return acc.some((item) => item.width === next.width && item.height === next.height) ? acc : [...acc, next]\n }, [])\n for (const size of sizes) {\n const resized = photon.resize(decoded, size.width, size.height, photon.SamplingFilter.Lanczos3)\n try {\n const encoders: Array<readonly [mime: string, encode: () => Uint8Array]> = [\n [\"image/png\", () => resized.get_bytes()],\n ...JPEG_QUALITIES.map((quality) => [\"image/jpeg\", () => resized.get_bytes_jpeg(quality)] as const),\n ]\n for (const [mime, encode] of encoders) {\n const candidate = Buffer.from(encode()).toString(\"base64\")\n if (Buffer.byteLength(candidate, \"utf-8\") <= limits.maxBase64Bytes)\n return { ...content, content: candidate, encoding: \"base64\" as const, mime }\n }\n } finally {\n resized.free()\n }\n }\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n } finally {\n decoded.free()\n }\n })\n})\n" | ||
| ], | ||
| "mappings": ";6zBAGA,SAAe,SCDf,yBACA,6BAAS,iBAIT,SAAM,OAAiB,MAAC,QAAI,QAAI,QAAI,QAAI,OAAE,OAE7B,OAAO,OAAO,SAAI,cAAU,OAAG,MACxC,gBAA4E,0CAC5E,EAAK,WAAW,CAAU,EAAI,EAAa,EAAc,IAAI,IAAI,EAAY,YAAY,GAAG,CAAC,EAC/F,IAAM,EAAa,MAAO,EAAO,OAC/B,EAAO,WAAW,CAChB,IAAK,IAAa,yCAClB,MAAO,IAAM,IAAI,CACnB,CAAC,CACH,EACA,OAAO,EAAO,GAAG,wBAAwB,EAAE,SAAU,CACnD,EACA,EACA,EAMA,CACA,IAAM,EAAS,MAAO,EAChB,EAAU,MAAO,EAAO,IAAI,CAChC,IAAK,IAAM,EAAO,YAAY,mBAAmB,OAAO,KAAK,EAAQ,QAAS,QAAQ,CAAC,EACvF,MAAO,IAAM,IAAI,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AAG,EAAe,IAAI,CAAC,IAAY,CAAC,aAAc,IAAM,EAAQ,eAAe,CAAO,CAAC,CAAU,CACnG,EACA,QAAY,EAAM,KAAW,EAAU,CACrC,IAAM,EAAY,OAAO,KAAK,EAAO,CAAC,EAAE,SAAS,QAAQ,EACzD,GAAI,OAAO,WAAW,EAAW,OAAO,GAAK,EAAO,eAClD,MAAO,IAAK,EAAS,QAAS,EAAW,SAAU,SAAmB,MAAK,UAE/E,CACA,EAAQ,KAAK,GAGjB,OAAO,MAAO,IAAI,EAAU,CAC1B,WACA,QACA,SACA,QACA,SAAU,EAAO,SACjB,UAAW,EAAO,UAClB,SAAU,EAAO,cACnB,CAAC,SACD,CACA,EAAQ,KAAK,GAEhB,EACF", | ||
| "debugId": "64F9D4BE6DBA346F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "C489F30DC5E79CD364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+vercel@2.0.39+d6123d32214422cb/node_modules/@ai-sdk/vercel/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/vercel-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport { OpenAICompatibleChatLanguageModel } from \"@ai-sdk/openai-compatible\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/version.ts\nvar VERSION = true ? \"2.0.39\" : \"0.0.0-test\";\n\n// src/vercel-provider.ts\nfunction createVercel(options = {}) {\n var _a;\n const baseURL = withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.v0.dev/v1\"\n );\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"VERCEL_API_KEY\",\n description: \"Vercel\"\n })}`,\n ...options.headers\n },\n `ai-sdk/vercel/${VERSION}`\n );\n const getCommonModelConfig = (modelType) => ({\n provider: `vercel.${modelType}`,\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createChatModel = (modelId) => {\n return new OpenAICompatibleChatLanguageModel(modelId, {\n ...getCommonModelConfig(\"chat\")\n });\n };\n const provider = (modelId) => createChatModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar vercel = createVercel();\nexport {\n VERSION,\n createVercel,\n vercel\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";4UAYA,SAAI,OAAiB,cAGrB,cAAS,MAAY,MAAC,OAAU,CAAC,EAAG,CAClC,IAAI,EACJ,IAAM,EAAU,GACb,EAAK,EAAQ,UAAY,KAAO,EAAK,uBACxC,EACM,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,iBACzB,YAAa,QACf,CAAC,OACE,EAAQ,OACb,EACA,iBAAiB,GACnB,EACM,EAAuB,CAAC,KAAe,CAC3C,SAAU,UAAU,IACpB,IAAK,EAAG,UAAW,GAAG,IAAU,IAChC,QAAS,EACT,MAAO,EAAQ,KACjB,GACM,EAAkB,CAAC,IAAY,CACnC,OAAO,IAAI,EAAkC,EAAS,IACjD,EAAqB,MAAM,CAChC,CAAC,GAEG,EAAW,CAAC,IAAY,EAAgB,CAAO,EAUrD,OATA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,EAAS,EAAa", | ||
| "debugId": "F86816A172BAE36264756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/unset.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.unset,\n Effect.fn(\"cli.service.unset\")(function* (input) {\n yield* ServiceConfig.unset(input.key)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";k0BAKA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,WACnC,OAAO,QAAG,wBAAmB,OAAE,cAAU,MAAC,OAAO,MAC/C,WAAO,OAAc,WAAM,OAAM,QAAG,OACrC,CACH", | ||
| "debugId": "3195B6BC099E09E464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "9FC76B8ADB080D1364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "696D8216D02F81D164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/index.js", "../../node_modules/.bun/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/stream.js"], | ||
| "sourcesContent": [ | ||
| "class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nconst LF = 10, CR = 13, SPACE = 32;\nfunction noop(_arg) {\n}\nfunction createParser(config) {\n if (typeof config == \"function\")\n throw new TypeError(\n \"`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];\n let pendingFragmentsLength = 0, isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType, terminated = !1;\n function feed(chunk) {\n if (terminated)\n throw new Error(\n \"Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.\"\n );\n if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n const trailing2 = processLines(chunk);\n trailing2 !== \"\" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();\n return;\n }\n if (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();\n return;\n }\n pendingFragments.push(chunk);\n const input = pendingFragments.join(\"\");\n pendingFragments.length = 0, pendingFragmentsLength = 0;\n const trailing = processLines(input);\n trailing !== \"\" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();\n }\n function checkBufferSize() {\n maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, onError(\n new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: \"max-buffer-size-exceeded\"\n })\n )));\n }\n function processLines(chunk) {\n let searchIndex = 0;\n if (chunk.indexOf(\"\\r\") === -1) {\n let lfIndex = chunk.indexOf(`\n`, searchIndex);\n for (; lfIndex !== -1; ) {\n if (searchIndex === lfIndex) {\n dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n onEvent({ id, event: eventType, data: value }), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(\n chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n lfIndex\n ) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)\n break;\n parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n return;\n }\n if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n id = value2.includes(\"\\0\") ? void 0 : value2;\n return;\n }\n if (firstCharCode === 58) {\n if (onComment) {\n const line2 = chunk.slice(start, end);\n onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex === -1) {\n processField(line, \"\", line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value || void 0;\n break;\n case \"data\":\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n dataLines > 0 && onEvent({\n id,\n event: eventType,\n data\n }), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join(\"\");\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n isFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;\n }\n return { feed, reset };\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n", | ||
| "import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n typeof onError == \"function\" && onError(error), (onError === \"terminate\" || error.type === \"max-buffer-size-exceeded\") && controller.error(error);\n },\n onRetry,\n onComment,\n maxBufferSize\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n" | ||
| ], | ||
| "mappings": ";AAAA,MAAM,UAAmB,KAAM,CAC7B,WAAW,CAAC,EAAS,EAAS,CAC5B,MAAM,CAAO,EAAG,KAAK,KAAO,aAAc,KAAK,KAAO,EAAQ,KAAM,KAAK,MAAQ,EAAQ,MAAO,KAAK,MAAQ,EAAQ,MAAO,KAAK,KAAO,EAAQ,KAEpJ,CACA,IAAM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,EAAO,EAAG,EAAe,CAC7C,OAAO,IAAkB,KAAO,EAAM,WAAW,EAAI,CAAC,IAAM,IAAM,EAAM,WAAW,EAAI,CAAC,IAAM,KAAO,EAAM,WAAW,EAAI,CAAC,IAAM,IAAM,EAAM,WAAW,EAAI,CAAC,IAAM,GAErK,SAAS,CAAa,CAAC,EAAO,EAAG,EAAe,CAC9C,OAAO,IAAkB,KAAO,EAAM,WAAW,EAAI,CAAC,IAAM,KAAO,EAAM,WAAW,EAAI,CAAC,IAAM,KAAO,EAAM,WAAW,EAAI,CAAC,IAAM,KAAO,EAAM,WAAW,EAAI,CAAC,IAAM,KAAO,EAAM,WAAW,EAAI,CAAC,IAAM,GCxK1M,MAAM,UAAgC,eAAgB,CACpD,WAAW,EAAG,UAAS,UAAS,YAAW,iBAAkB,CAAC,EAAG,CAC/D,IAAI,EACJ,MAAM,CACJ,KAAK,CAAC,EAAY,CAChB,EAAS,EAAa,CACpB,QAAS,CAAC,IAAU,CAClB,EAAW,QAAQ,CAAK,GAE1B,OAAO,CAAC,EAAO,CACb,OAAO,GAAW,YAAc,EAAQ,CAAK,GAAI,IAAY,aAAe,EAAM,OAAS,6BAA+B,EAAW,MAAM,CAAK,GAElJ,UACA,YACA,eACF,CAAC,GAEH,SAAS,CAAC,EAAO,CACf,EAAO,KAAK,CAAK,EAErB,CAAC,EAEL", | ||
| "debugId": "75A247689075925764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/status.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.status,\n Effect.fn(\"cli.service.status\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover({ ...options, version: undefined })\n process.stdout.write((found?.url ?? \"stopped\") + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+0BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,YACnC,OAAO,QAAG,yBAAoB,OAAE,cAAU,OAAG,MAC3C,SAAM,OAAU,WAAO,OAAc,aAAQ,EACvC,EAAQ,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,EACxE,QAAQ,OAAO,OAAO,GAAO,KAAO,WAAa,CAAG,EACrD,CACH", | ||
| "debugId": "63FF9ECAF29B058864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mini.ts"], | ||
| "sourcesContent": [ | ||
| "import { Context, Effect, FileSystem, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { Config } from \"../../config\"\nimport { resolve } from \"@opencode-ai/tui/config\"\n\nexport default Runtime.handler(Commands.commands.mini, (input) =>\n Effect.gen(function* () {\n const { runMini, validateMiniTerminal } = yield* Effect.promise(() => import(\"../../mini\"))\n yield* Effect.promise(async () => validateMiniTerminal())\n const serverURL = Option.getOrUndefined(input.server)\n const server = yield* ServerConnection.resolve({ server: serverURL, standalone: input.standalone })\n const config = yield* Config.Service\n const resolved = resolve(yield* config.get(), { terminalSuspend: process.platform !== \"win32\" })\n const fileSystem = yield* FileSystem.FileSystem\n const runServicePromise = Effect.runPromiseWith(Context.make(FileSystem.FileSystem, fileSystem))\n const service = server.service\n yield* Effect.promise(() =>\n runMini({\n server: {\n endpoint: server.endpoint,\n reconnect: service ? (signal) => runServicePromise(service.reconnect(), { signal }) : undefined,\n },\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n prompt: Option.getOrUndefined(input.prompt),\n replay: input.replay,\n replayLimit: Option.getOrUndefined(input.replayLimit),\n demo: input.demo,\n tuiConfig: resolved,\n config: {\n update: (update) => runServicePromise(config.update(update)),\n },\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";ogCAOA,SAAe,SAAQ,aAAQ,OAAS,cAAS,UAAM,MAAC,SACtD,OAAO,SAAI,cAAU,OAAG,MACtB,SAAQ,eAAS,6BAAyB,WAAO,OAAO,aAAQ,SAAa,wCAAa,OAC1F,WAAO,OAAO,aAAQ,cAAY,OAAqB,CAAC,EACxD,IAAM,EAAY,EAAO,eAAe,EAAM,MAAM,EAC9C,EAAS,MAAO,EAAiB,QAAQ,CAAE,OAAQ,EAAW,WAAY,EAAM,UAAW,CAAC,EAC5F,EAAS,MAAO,EAAO,QACvB,EAAW,EAAQ,MAAO,EAAO,IAAI,EAAG,CAAE,gBAAiB,EAA6B,CAAC,EACzF,EAAa,MAAO,EAAW,WAC/B,EAAoB,EAAO,eAAe,EAAQ,KAAK,EAAW,WAAY,CAAU,CAAC,EACzF,EAAU,EAAO,QACvB,MAAO,EAAO,QAAQ,IACpB,EAAQ,CACN,OAAQ,CACN,SAAU,EAAO,SACjB,UAAW,EAAU,CAAC,IAAW,EAAkB,EAAQ,UAAU,EAAG,CAAE,QAAO,CAAC,EAAI,MACxF,EACA,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,OAAQ,EAAM,OACd,YAAa,EAAO,eAAe,EAAM,WAAW,EACpD,KAAM,EAAM,KACZ,UAAW,EACX,OAAQ,CACN,OAAQ,CAAC,IAAW,EAAkB,EAAO,OAAO,CAAM,CAAC,CAC7D,CACF,CAAC,CACH,EACD,CACH", | ||
| "debugId": "B915ABB75B938B5764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.33/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"sso-oauth\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateToken\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"sso-oauth\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.32\";\nvar packageInfo = {\n\tversion: version};\n\nconst k = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = { [k]: \"Endpoint\" }, h = { [k]: d }, i = {}, j = [{ [k]: \"Region\" }];\nconst _data = {\n conditions: [\n [c, [g]],\n [c, j],\n [\"aws.partition\", j, d],\n [e, [{ [k]: \"UseFIPS\" }, b]],\n [e, [{ [k]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [h, \"supportsDualStack\"] }, b]],\n [e, [{ fn: f, argv: [h, \"supportsFIPS\"] }, b]],\n [\"stringEquals\", [{ fn: f, argv: [h, \"name\"] }, \"aws-us-gov\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [g, i],\n [\"https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://oidc.{Region}.amazonaws.com\", i],\n [\"https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://oidc.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 13, 3,\n 1, 4, r + 12,\n 2, 5, r + 12,\n 3, 8, 6,\n 4, 7, r + 11,\n 5, r + 9, r + 10,\n 4, 11, 9,\n 6, 10, r + 8,\n 7, r + 6, r + 7,\n 5, 12, r + 5,\n 6, r + 4, r + 5,\n 3, r + 1, 14,\n 4, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SSOOIDCServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOOIDCServiceException.prototype);\n }\n}\n\nclass AccessDeniedException extends SSOOIDCServiceException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nclass AuthorizationPendingException extends SSOOIDCServiceException {\n name = \"AuthorizationPendingException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"AuthorizationPendingException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AuthorizationPendingException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass ExpiredTokenException extends SSOOIDCServiceException {\n name = \"ExpiredTokenException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"ExpiredTokenException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExpiredTokenException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InternalServerException extends SSOOIDCServiceException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidClientException extends SSOOIDCServiceException {\n name = \"InvalidClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidGrantException extends SSOOIDCServiceException {\n name = \"InvalidGrantException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidGrantException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidGrantException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidRequestException extends SSOOIDCServiceException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidScopeException extends SSOOIDCServiceException {\n name = \"InvalidScopeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidScopeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidScopeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass SlowDownException extends SSOOIDCServiceException {\n name = \"SlowDownException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"SlowDownException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, SlowDownException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass UnauthorizedClientException extends SSOOIDCServiceException {\n name = \"UnauthorizedClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnauthorizedClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass UnsupportedGrantTypeException extends SSOOIDCServiceException {\n name = \"UnsupportedGrantTypeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnsupportedGrantTypeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\n\nconst _ADE = \"AccessDeniedException\";\nconst _APE = \"AuthorizationPendingException\";\nconst _AT = \"AccessToken\";\nconst _CS = \"ClientSecret\";\nconst _CT = \"CreateToken\";\nconst _CTR = \"CreateTokenRequest\";\nconst _CTRr = \"CreateTokenResponse\";\nconst _CV = \"CodeVerifier\";\nconst _ETE = \"ExpiredTokenException\";\nconst _ICE = \"InvalidClientException\";\nconst _IGE = \"InvalidGrantException\";\nconst _IRE = \"InvalidRequestException\";\nconst _ISE = \"InternalServerException\";\nconst _ISEn = \"InvalidScopeException\";\nconst _IT = \"IdToken\";\nconst _RT = \"RefreshToken\";\nconst _SDE = \"SlowDownException\";\nconst _UCE = \"UnauthorizedClientException\";\nconst _UGTE = \"UnsupportedGrantTypeException\";\nconst _aT = \"accessToken\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cS = \"clientSecret\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _dC = \"deviceCode\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ed = \"error_description\";\nconst _gT = \"grantType\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _r = \"reason\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.ssooidc\";\nconst _sc = \"scope\";\nconst _se = \"server\";\nconst _tT = \"tokenType\";\nconst n0 = \"com.amazonaws.ssooidc\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SSOOIDCServiceException$ = [-3, _s, \"SSOOIDCServiceException\", 0, [], []];\n_s_registry.registerError(SSOOIDCServiceException$, SSOOIDCServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar AccessDeniedException$ = [-3, n0, _ADE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0]\n];\nn0_registry.registerError(AccessDeniedException$, AccessDeniedException);\nvar AuthorizationPendingException$ = [-3, n0, _APE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(AuthorizationPendingException$, AuthorizationPendingException);\nvar ExpiredTokenException$ = [-3, n0, _ETE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(ExpiredTokenException$, ExpiredTokenException);\nvar InternalServerException$ = [-3, n0, _ISE,\n { [_e]: _se, [_hE]: 500 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InternalServerException$, InternalServerException);\nvar InvalidClientException$ = [-3, n0, _ICE,\n { [_e]: _c, [_hE]: 401 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidClientException$, InvalidClientException);\nvar InvalidGrantException$ = [-3, n0, _IGE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidGrantException$, InvalidGrantException);\nvar InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0]\n];\nn0_registry.registerError(InvalidRequestException$, InvalidRequestException);\nvar InvalidScopeException$ = [-3, n0, _ISEn,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidScopeException$, InvalidScopeException);\nvar SlowDownException$ = [-3, n0, _SDE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(SlowDownException$, SlowDownException);\nvar UnauthorizedClientException$ = [-3, n0, _UCE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(UnauthorizedClientException$, UnauthorizedClientException);\nvar UnsupportedGrantTypeException$ = [-3, n0, _UGTE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar AccessToken = [0, n0, _AT, 8, 0];\nvar ClientSecret = [0, n0, _CS, 8, 0];\nvar CodeVerifier = [0, n0, _CV, 8, 0];\nvar IdToken = [0, n0, _IT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nvar CreateTokenRequest$ = [3, n0, _CTR,\n 0,\n [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV],\n [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], 3\n];\nvar CreateTokenResponse$ = [3, n0, _CTRr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]]\n];\nvar CreateToken$ = [9, n0, _CT,\n { [_h]: [\"POST\", \"/token\", 200] }, () => CreateTokenRequest$, () => CreateTokenResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.ssooidc\",\n errorTypeRegistries,\n version: \"2019-06-10\",\n serviceTarget: \"AWSSSOOIDCService\",\n },\n serviceId: config?.serviceId ?? \"SSO OIDC\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SSOOIDCClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"AWSSSOOIDCService\", \"SSOOIDCClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass CreateTokenCommand extends command(_ep0, _mw0, \"CreateToken\", CreateToken$) {\n}\n\nconst commands = {\n CreateTokenCommand,\n};\nclass SSOOIDC extends SSOOIDCClient {\n}\ncreateAggregatedClient(commands, SSOOIDC);\n\nconst AccessDeniedExceptionReason = {\n KMS_ACCESS_DENIED: \"KMS_AccessDeniedException\",\n};\nconst InvalidRequestExceptionReason = {\n KMS_DISABLED_KEY: \"KMS_DisabledException\",\n KMS_INVALID_KEY_USAGE: \"KMS_InvalidKeyUsageException\",\n KMS_INVALID_STATE: \"KMS_InvalidStateException\",\n KMS_KEY_NOT_FOUND: \"KMS_NotFoundException\",\n};\n\nexports.AccessDeniedException = AccessDeniedException;\nexports.AccessDeniedException$ = AccessDeniedException$;\nexports.AccessDeniedExceptionReason = AccessDeniedExceptionReason;\nexports.AuthorizationPendingException = AuthorizationPendingException;\nexports.AuthorizationPendingException$ = AuthorizationPendingException$;\nexports.CreateToken$ = CreateToken$;\nexports.CreateTokenCommand = CreateTokenCommand;\nexports.CreateTokenRequest$ = CreateTokenRequest$;\nexports.CreateTokenResponse$ = CreateTokenResponse$;\nexports.ExpiredTokenException = ExpiredTokenException;\nexports.ExpiredTokenException$ = ExpiredTokenException$;\nexports.InternalServerException = InternalServerException;\nexports.InternalServerException$ = InternalServerException$;\nexports.InvalidClientException = InvalidClientException;\nexports.InvalidClientException$ = InvalidClientException$;\nexports.InvalidGrantException = InvalidGrantException;\nexports.InvalidGrantException$ = InvalidGrantException$;\nexports.InvalidRequestException = InvalidRequestException;\nexports.InvalidRequestException$ = InvalidRequestException$;\nexports.InvalidRequestExceptionReason = InvalidRequestExceptionReason;\nexports.InvalidScopeException = InvalidScopeException;\nexports.InvalidScopeException$ = InvalidScopeException$;\nexports.SSOOIDC = SSOOIDC;\nexports.SSOOIDCClient = SSOOIDCClient;\nexports.SSOOIDCServiceException = SSOOIDCServiceException;\nexports.SSOOIDCServiceException$ = SSOOIDCServiceException$;\nexports.SlowDownException = SlowDownException;\nexports.SlowDownException$ = SlowDownException$;\nexports.UnauthorizedClientException = UnauthorizedClientException;\nexports.UnauthorizedClientException$ = UnauthorizedClientException$;\nexports.UnsupportedGrantTypeException = UnsupportedGrantTypeException;\nexports.UnsupportedGrantTypeException$ = UnsupportedGrantTypeException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";8VAAA,SAAQ,6BAAsB,qCAAiC,QAAmC,uCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,SAAQ,eAAa,gCACnN,QAAS,QACjB,IAAQ,GAAW,GACX,GAAW,EACnB,IAAQ,6BAA2B,aAAY,yCAAuC,8CAA4C,8BAA4B,mCAAiC,8BACvL,yBAAuB,iBAAe,kBAAgB,2BAAyB,yBAAuB,4BACtG,YAAU,wCAAsC,mCAAiC,iCACjF,sBAAoB,kCAAgC,mCAAiC,sBAAoB,yBACzG,eAAc,+BACd,4BAA0B,qBAAmB,8CAC7C,UAAQ,YAAU,YAAU,cAAY,8BACxC,mBAAiB,0BACjB,8BACA,gBAEF,GAAiD,MAAO,EAAQ,EAAS,IAAU,CACrF,MAAO,CACH,UAAW,GAAiB,CAAO,EAAE,UACrC,OAAQ,MAAM,EAAkB,EAAO,MAAM,EAAE,IAAM,IAAM,CACvD,MAAU,MAAM,yDAAyD,IAC1E,CACP,GAEJ,SAAS,EAAgC,CAAC,EAAgB,CACtD,MAAO,CACH,SAAU,iBACV,kBAAmB,CACf,KAAM,YACN,OAAQ,EAAe,MAC3B,EACA,oBAAqB,CAAC,EAAQ,KAAa,CACvC,kBAAmB,CACf,SACA,SACJ,CACJ,EACJ,EAEJ,SAAS,EAA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AmB,2BACvB,EACM,GAAgC,CAClC,iBAAkB,wBAClB,sBAAuB,+BACvB,kBAAmB,4BACnB,kBAAmB,uBACvB,EAEA,IAAQ,GAAwB,EACxB,GAAyB,EACzB,GAA8B,GAC9B,GAAgC,EAChC,GAAiC,EACjC,GAAe,GACf,GAAqB,EACrB,GAAsB,GACtB,GAAuB,GACvB,GAAwB,EACxB,GAAyB,EACzB,GAA0B,EAC1B,GAA2B,GAC3B,GAAyB,EACzB,GAA0B,GAC1B,GAAwB,EACxB,GAAyB,GACzB,GAA0B,EAC1B,GAA2B,GAC3B,GAAgC,GAChC,GAAwB,EACxB,GAAyB,GACzB,GAAU,EACV,GAAgB,EAChB,GAA0B,EAC1B,GAA2B,EAC3B,GAAoB,EACpB,GAAqB,GACrB,GAA8B,EAC9B,GAA+B,GAC/B,GAAgC,EAChC,GAAiC,GACjC,GAAsB", | ||
| "debugId": "01D7F6B6EFB2068464756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "7317E85CE270FA2264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js"], | ||
| "sourcesContent": [ | ||
| "import { getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { resolveProfileData } from \"./resolveProfileData\";\nexport const fromIni = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-ini - fromIni\");\n const profiles = await parseKnownFiles(init);\n return resolveProfileData(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init, callerClientConfig);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { isAssumeRoleProfile, resolveAssumeRoleCredentials } from \"./resolveAssumeRoleCredentials\";\nimport { isLoginProfile, resolveLoginCredentials } from \"./resolveLoginCredentials\";\nimport { isProcessProfile, resolveProcessCredentials } from \"./resolveProcessCredentials\";\nimport { isSsoProfile, resolveSsoCredentials } from \"./resolveSsoCredentials\";\nimport { isStaticCredsProfile, resolveStaticCredentials } from \"./resolveStaticCredentials\";\nimport { isWebIdentityProfile, resolveWebIdentityCredentials } from \"./resolveWebIdentityCredentials\";\nexport const resolveProfileData = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {\n const data = profiles[profileName];\n if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {\n return resolveAssumeRoleCredentials(profileName, profiles, options, callerClientConfig, visitedProfiles, resolveProfileData);\n }\n if (isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isWebIdentityProfile(data)) {\n return resolveWebIdentityCredentials(data, options, callerClientConfig);\n }\n if (isProcessProfile(data)) {\n return resolveProcessCredentials(options, profileName);\n }\n if (isSsoProfile(data)) {\n return await resolveSsoCredentials(profileName, data, options, callerClientConfig);\n }\n if (isLoginProfile(data)) {\n return resolveLoginCredentials(profileName, options, callerClientConfig);\n }\n throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger });\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, getProfileName } from \"@smithy/core/config\";\nimport { resolveCredentialSource } from \"./resolveCredentialSource\";\nexport const isAssumeRoleProfile = (arg, { profile = \"default\", logger } = {}) => {\n return (Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.external_id) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.mfa_serial) > -1 &&\n (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })));\n};\nconst isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => {\n const withSourceProfile = typeof arg.source_profile === \"string\" && typeof arg.credential_source === \"undefined\";\n if (withSourceProfile) {\n logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);\n }\n return withSourceProfile;\n};\nconst isCredentialSourceProfile = (arg, { profile, logger }) => {\n const withProviderProfile = typeof arg.credential_source === \"string\" && typeof arg.source_profile === \"undefined\";\n if (withProviderProfile) {\n logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);\n }\n return withProviderProfile;\n};\nexport const resolveAssumeRoleCredentials = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, resolveProfileData) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)\");\n const profileData = profiles[profileName];\n const { source_profile, region } = profileData;\n if (!options.roleAssumer) {\n const { getDefaultRoleAssumer } = await import(\"@aws-sdk/nested-clients/sts\");\n options.roleAssumer = getDefaultRoleAssumer({\n ...options.clientConfig,\n credentialProviderLogger: options.logger,\n parentClientConfig: {\n ...callerClientConfig,\n ...options?.parentClientConfig,\n region: region ?? options?.parentClientConfig?.region ?? callerClientConfig?.region,\n },\n }, options.clientPlugins);\n }\n if (source_profile && source_profile in visitedProfiles) {\n throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` +\n ` ${getProfileName(options)}. Profiles visited: ` +\n Object.keys(visitedProfiles).join(\", \"), { logger: options.logger });\n }\n options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);\n const sourceCredsProvider = source_profile\n ? resolveProfileData(source_profile, profiles, options, callerClientConfig, {\n ...visitedProfiles,\n [source_profile]: true,\n }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}))\n : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();\n if (isCredentialSourceWithoutRoleArn(profileData)) {\n return sourceCredsProvider.then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n else {\n const params = {\n RoleArn: profileData.role_arn,\n RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,\n ExternalId: profileData.external_id,\n DurationSeconds: parseInt(profileData.duration_seconds || \"3600\", 10),\n };\n const { mfa_serial } = profileData;\n if (mfa_serial) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false });\n }\n params.SerialNumber = mfa_serial;\n params.TokenCode = await options.mfaCodeProvider(mfa_serial);\n }\n const sourceCreds = await sourceCredsProvider;\n return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n};\nconst isCredentialSourceWithoutRoleArn = (section) => {\n return !section.role_arn && !!section.credential_source;\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { chain, CredentialsProviderError } from \"@smithy/core/config\";\nexport const resolveCredentialSource = (credentialSource, profileName, logger) => {\n const sourceProvidersMap = {\n EcsContainer: async (options) => {\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n const { fromContainerMetadata } = await import(\"@smithy/credential-provider-imds\");\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is EcsContainer\");\n return async () => chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider);\n },\n Ec2InstanceMetadata: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata\");\n const { fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n return async () => fromInstanceMetadata(options)().then(setNamedProvider);\n },\n Environment: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Environment\");\n const { fromEnv } = await import(\"@aws-sdk/credential-provider-env\");\n return async () => fromEnv(options)().then(setNamedProvider);\n },\n };\n if (credentialSource in sourceProvidersMap) {\n return sourceProvidersMap[credentialSource];\n }\n else {\n throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` +\n `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger });\n }\n};\nconst setNamedProvider = (creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_NAMED_PROVIDER\", \"p\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isLoginProfile = (data) => {\n return Boolean(data && data.login_session);\n};\nexport const resolveLoginCredentials = async (profileName, options, callerClientConfig) => {\n const { fromLoginCredentials } = await import(\"@aws-sdk/credential-provider-login\");\n const credentials = await fromLoginCredentials({\n ...options,\n profile: profileName,\n })({ callerClientConfig });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_LOGIN\", \"AC\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isProcessProfile = (arg) => Boolean(arg) && typeof arg === \"object\" && typeof arg.credential_process === \"string\";\nexport const resolveProcessCredentials = async (options, profile) => {\n const { fromProcess } = await import(\"@aws-sdk/credential-provider-process\");\n const credentials = await fromProcess({\n ...options,\n profile,\n })();\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_PROCESS\", \"v\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => {\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO({\n profile,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n clientConfig: options.clientConfig,\n })({\n callerClientConfig,\n }).then((creds) => {\n if (profileData.sso_session) {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO\", \"r\");\n }\n else {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO_LEGACY\", \"t\");\n }\n });\n};\nexport const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isStaticCredsProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.aws_access_key_id === \"string\" &&\n typeof arg.aws_secret_access_key === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_session_token) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_account_id) > -1;\nexport const resolveStaticCredentials = async (profile, options) => {\n options?.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveStaticCredentials\");\n const credentials = {\n accessKeyId: profile.aws_access_key_id,\n secretAccessKey: profile.aws_secret_access_key,\n sessionToken: profile.aws_session_token,\n ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }),\n ...(profile.aws_account_id && { accountId: profile.aws_account_id }),\n };\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE\", \"n\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => {\n const { fromTokenFile } = await import(\"@aws-sdk/credential-provider-web-identity\");\n const credentials = await fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n })({\n callerClientConfig,\n });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN\", \"q\");\n};\n" | ||
| ], | ||
| "mappings": ";0JAAA,oBCAA,oBCAA,eACA,WCDA,eACA,WACa,EAA0B,CAAC,EAAkB,EAAa,IAAW,CAC9E,IAAM,EAAqB,CACvB,aAAc,MAAO,IAAY,CAC7B,IAAQ,YAAa,KAAa,2CAC1B,yBAA0B,KAAa,0CAE/C,OADA,GAAQ,MAAM,sEAAsE,EAC7E,SAAY,QAAM,EAAS,GAAW,CAAC,CAAC,EAAG,EAAsB,CAAO,CAAC,EAAE,EAAE,KAAK,CAAgB,GAE7G,oBAAqB,MAAO,IAAY,CACpC,GAAQ,MAAM,6EAA6E,EAC3F,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AAO,CAAC,EACvG,OAAO,EAA6B,EAAa,EAAU,EAAS,EAAoB,EAAiB,CAAkB,EAE/H,GAAI,EAAqB,CAAI,EACzB,OAAO,EAAyB,EAAM,CAAO,EAEjD,GAAI,EAAqB,CAAI,EACzB,OAAO,EAA8B,EAAM,EAAS,CAAkB,EAE1E,GAAI,EAAiB,CAAI,EACrB,OAAO,EAA0B,EAAS,CAAW,EAEzD,GAAI,EAAa,CAAI,EACjB,OAAO,MAAM,EAAsB,EAAa,EAAM,EAAS,CAAkB,EAErF,GAAI,EAAe,CAAI,EACnB,OAAO,EAAwB,EAAa,EAAS,CAAkB,EAE3E,MAAM,IAAI,2BAAyB,iDAAiD,2CAAsD,CAAE,OAAQ,EAAQ,MAAO,CAAC,GD5BjK,IAAM,EAAU,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CACzE,EAAK,QAAQ,MAAM,4CAA4C,EAC/D,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAAmB,iBAAe,CACrC,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAM,CAAkB", | ||
| "debugId": "408BB7B2A83A4B2864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "9500D16DE8AD6BCA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+mistral@3.0.27+d6123d32214422cb/node_modules/@ai-sdk/mistral/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/mistral-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/mistral-chat-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n generateId,\n injectJsonInstructionIntoMessages,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/convert-mistral-usage.ts\nfunction convertMistralUsage(usage) {\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = usage.prompt_tokens;\n const completionTokens = usage.completion_tokens;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens,\n reasoning: void 0\n },\n raw: usage\n };\n}\n\n// src/convert-to-mistral-chat-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertToBase64 } from \"@ai-sdk/provider-utils\";\nfunction formatFileUrl({\n data,\n mediaType\n}) {\n return data instanceof URL ? data.toString() : `data:${mediaType};base64,${convertToBase64(data)}`;\n}\nfunction convertToMistralChatMessages(prompt) {\n var _a;\n const messages = [];\n for (let i = 0; i < prompt.length; i++) {\n const { role, content } = prompt[i];\n const isLastMessage = i === prompt.length - 1;\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n switch (part.type) {\n case \"text\": {\n return { type: \"text\", text: part.text };\n }\n case \"file\": {\n if (part.mediaType.startsWith(\"image/\")) {\n const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType;\n return {\n type: \"image_url\",\n image_url: formatFileUrl({ data: part.data, mediaType })\n };\n } else if (part.mediaType === \"application/pdf\") {\n return {\n type: \"document_url\",\n document_url: formatFileUrl({\n data: part.data,\n mediaType: \"application/pdf\"\n })\n };\n } else {\n throw new UnsupportedFunctionalityError({\n functionality: \"Only images and PDF file parts are supported\"\n });\n }\n }\n }\n })\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n case \"reasoning\": {\n text += part.text;\n break;\n }\n default: {\n throw new Error(\n `Unsupported content type in assistant message: ${part.type}`\n );\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: text,\n prefix: isLastMessage ? true : void 0,\n tool_calls: toolCalls.length > 0 ? toolCalls : void 0\n });\n break;\n }\n case \"tool\": {\n for (const toolResponse of content) {\n if (toolResponse.type === \"tool-approval-response\") {\n continue;\n }\n const output = toolResponse.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n messages.push({\n role: \"tool\",\n name: toolResponse.toolName,\n tool_call_id: toolResponse.toolCallId,\n content: contentValue\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/get-response-metadata.ts\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id: id != null ? id : void 0,\n modelId: model != null ? model : void 0,\n timestamp: created != null ? new Date(created * 1e3) : void 0\n };\n}\n\n// src/map-mistral-finish-reason.ts\nfunction mapMistralFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n case \"model_length\":\n return \"length\";\n case \"tool_calls\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/mistral-chat-options.ts\nimport { z } from \"zod/v4\";\nvar mistralLanguageModelOptions = z.object({\n /**\n * Whether to inject a safety prompt before all conversations.\n *\n * Defaults to `false`.\n */\n safePrompt: z.boolean().optional(),\n documentImageLimit: z.number().optional(),\n documentPageLimit: z.number().optional(),\n /**\n * Whether to use structured outputs.\n *\n * @default true\n */\n structuredOutputs: z.boolean().optional(),\n /**\n * Whether to use strict JSON schema validation.\n *\n * @default false\n */\n strictJsonSchema: z.boolean().optional(),\n /**\n * Whether to enable parallel function calling during tool use.\n * When set to false, the model will use at most one tool per response.\n *\n * @default true\n */\n parallelToolCalls: z.boolean().optional(),\n /**\n * Controls the reasoning effort for models that support adjustable reasoning.\n *\n * - `'high'`: Enable reasoning\n * - `'none'`: Disable reasoning\n */\n reasoningEffort: z.enum([\"high\", \"none\"]).optional()\n});\n\n// src/mistral-error.ts\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar mistralErrorDataSchema = z2.object({\n object: z2.literal(\"error\"),\n message: z2.string(),\n type: z2.string(),\n param: z2.string().nullable(),\n code: z2.string().nullable()\n});\nvar mistralFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: mistralErrorDataSchema,\n errorToMessage: (data) => data.message\n});\n\n// src/mistral-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nfunction prepareTools({\n tools,\n toolChoice\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const mistralTools = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n } else {\n mistralTools.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n ...tool.strict != null ? { strict: tool.strict } : {}\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: mistralTools, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n case \"none\":\n return { tools: mistralTools, toolChoice: type, toolWarnings };\n case \"required\":\n return { tools: mistralTools, toolChoice: \"any\", toolWarnings };\n // mistral does not support tool mode directly,\n // so we filter the tools and force the tool choice through 'any'\n case \"tool\":\n return {\n tools: mistralTools.filter(\n (tool) => tool.function.name === toolChoice.toolName\n ),\n toolChoice: \"any\",\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError2({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/mistral-chat-language-model.ts\nvar MistralChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n \"application/pdf\": [/^https:\\/\\/.*$/]\n };\n var _a;\n this.modelId = modelId;\n this.config = config;\n this.generateId = (_a = config.generateId) != null ? _a : generateId;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n providerOptions,\n tools,\n toolChoice\n }) {\n var _a, _b, _c, _d;\n const warnings = [];\n const options = (_a = await parseProviderOptions({\n provider: \"mistral\",\n providerOptions,\n schema: mistralLanguageModelOptions\n })) != null ? _a : {};\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n if (frequencyPenalty != null) {\n warnings.push({ type: \"unsupported\", feature: \"frequencyPenalty\" });\n }\n if (presencePenalty != null) {\n warnings.push({ type: \"unsupported\", feature: \"presencePenalty\" });\n }\n if (stopSequences != null) {\n warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n }\n const structuredOutputs = (_b = options.structuredOutputs) != null ? _b : true;\n const strictJsonSchema = (_c = options.strictJsonSchema) != null ? _c : false;\n if ((responseFormat == null ? void 0 : responseFormat.type) === \"json\" && !(responseFormat == null ? void 0 : responseFormat.schema)) {\n prompt = injectJsonInstructionIntoMessages({\n messages: prompt,\n schema: responseFormat.schema\n });\n }\n const baseArgs = {\n // model id:\n model: this.modelId,\n // model specific settings:\n safe_prompt: options.safePrompt,\n // standardized settings:\n max_tokens: maxOutputTokens,\n temperature,\n top_p: topP,\n random_seed: seed,\n reasoning_effort: options.reasoningEffort,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? structuredOutputs && (responseFormat == null ? void 0 : responseFormat.schema) != null ? {\n type: \"json_schema\",\n json_schema: {\n schema: responseFormat.schema,\n strict: strictJsonSchema,\n name: (_d = responseFormat.name) != null ? _d : \"response\",\n description: responseFormat.description\n }\n } : { type: \"json_object\" } : void 0,\n // mistral-specific provider options:\n document_image_limit: options.documentImageLimit,\n document_page_limit: options.documentPageLimit,\n // messages:\n messages: convertToMistralChatMessages(prompt)\n };\n const {\n tools: mistralTools,\n toolChoice: mistralToolChoice,\n toolWarnings\n } = prepareTools({\n tools,\n toolChoice\n });\n return {\n args: {\n ...baseArgs,\n tools: mistralTools,\n tool_choice: mistralToolChoice,\n ...mistralTools != null && options.parallelToolCalls !== void 0 ? { parallel_tool_calls: options.parallelToolCalls } : {}\n },\n warnings: [...warnings, ...toolWarnings]\n };\n }\n async doGenerate(options) {\n var _a;\n const { args: body, warnings } = await this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n mistralChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n if (choice.message.content != null && Array.isArray(choice.message.content)) {\n for (const part of choice.message.content) {\n if (part.type === \"thinking\") {\n const reasoningText = extractReasoningContent(part.thinking);\n if (reasoningText.length > 0) {\n content.push({ type: \"reasoning\", text: reasoningText });\n }\n } else if (part.type === \"text\") {\n if (part.text.length > 0) {\n content.push({ type: \"text\", text: part.text });\n }\n }\n }\n } else {\n const text = extractTextContent(choice.message.content);\n if (text != null && text.length > 0) {\n content.push({ type: \"text\", text });\n }\n }\n if (choice.message.tool_calls != null) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: toolCall.function.arguments\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapMistralFinishReason(choice.finish_reason),\n raw: (_a = choice.finish_reason) != null ? _a : void 0\n },\n usage: convertMistralUsage(response.usage),\n request: { body },\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs(options);\n const body = { ...args, stream: true };\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n mistralChatChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let isFirstChunk = true;\n let activeText = false;\n let activeReasoningId = null;\n const generateId2 = this.generateId;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (isFirstChunk) {\n isFirstChunk = false;\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n }\n if (value.usage != null) {\n usage = value.usage;\n }\n const choice = value.choices[0];\n const delta = choice.delta;\n const textContent = extractTextContent(delta.content);\n if (delta.content != null && Array.isArray(delta.content)) {\n for (const part of delta.content) {\n if (part.type === \"thinking\") {\n const reasoningDelta = extractReasoningContent(part.thinking);\n if (reasoningDelta.length > 0) {\n if (activeReasoningId == null) {\n if (activeText) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n activeText = false;\n }\n activeReasoningId = generateId2();\n controller.enqueue({\n type: \"reasoning-start\",\n id: activeReasoningId\n });\n }\n controller.enqueue({\n type: \"reasoning-delta\",\n id: activeReasoningId,\n delta: reasoningDelta\n });\n }\n }\n }\n }\n if (textContent != null && textContent.length > 0) {\n if (!activeText) {\n if (activeReasoningId != null) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: activeReasoningId\n });\n activeReasoningId = null;\n }\n controller.enqueue({ type: \"text-start\", id: \"0\" });\n activeText = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"0\",\n delta: textContent\n });\n }\n if ((delta == null ? void 0 : delta.tool_calls) != null) {\n for (const toolCall of delta.tool_calls) {\n const toolCallId = toolCall.id;\n const toolName = toolCall.function.name;\n const input = toolCall.function.arguments;\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolCallId,\n toolName\n });\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCallId,\n delta: input\n });\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCallId\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId,\n toolName,\n input\n });\n }\n }\n if (choice.finish_reason != null) {\n finishReason = {\n unified: mapMistralFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n },\n flush(controller) {\n if (activeReasoningId != null) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: activeReasoningId\n });\n }\n if (activeText) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertMistralUsage(usage)\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction extractReasoningContent(thinking) {\n return thinking.filter((chunk) => chunk.type === \"text\").map((chunk) => chunk.text).join(\"\");\n}\nfunction extractTextContent(content) {\n if (typeof content === \"string\") {\n return content;\n }\n if (content == null) {\n return void 0;\n }\n const textContent = [];\n for (const chunk of content) {\n const { type } = chunk;\n switch (type) {\n case \"text\":\n textContent.push(chunk.text);\n break;\n case \"thinking\":\n case \"image_url\":\n case \"reference\":\n break;\n default: {\n const _exhaustiveCheck = type;\n throw new Error(`Unsupported type: ${_exhaustiveCheck}`);\n }\n }\n }\n return textContent.length ? textContent.join(\"\") : void 0;\n}\nvar mistralContentSchema = z3.union([\n z3.string(),\n z3.array(\n z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"image_url\"),\n image_url: z3.union([\n z3.string(),\n z3.object({\n url: z3.string(),\n detail: z3.string().nullable()\n })\n ])\n }),\n z3.object({\n type: z3.literal(\"reference\"),\n reference_ids: z3.array(z3.union([z3.string(), z3.number()]))\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.array(\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n })\n )\n })\n ])\n )\n]).nullish();\nvar mistralUsageSchema = z3.object({\n prompt_tokens: z3.number(),\n completion_tokens: z3.number(),\n total_tokens: z3.number()\n});\nvar mistralChatResponseSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n message: z3.object({\n role: z3.literal(\"assistant\"),\n content: mistralContentSchema,\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n function: z3.object({ name: z3.string(), arguments: z3.string() })\n })\n ).nullish()\n }),\n index: z3.number(),\n finish_reason: z3.string().nullish()\n })\n ),\n object: z3.literal(\"chat.completion\"),\n usage: mistralUsageSchema\n});\nvar mistralChatChunkSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n delta: z3.object({\n role: z3.enum([\"assistant\"]).optional(),\n content: mistralContentSchema,\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n function: z3.object({ name: z3.string(), arguments: z3.string() })\n })\n ).nullish()\n }),\n finish_reason: z3.string().nullish(),\n index: z3.number()\n })\n ),\n usage: mistralUsageSchema.nullish()\n});\n\n// src/mistral-embedding-model.ts\nimport {\n TooManyEmbeddingValuesForCallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders as combineHeaders2,\n createJsonResponseHandler as createJsonResponseHandler2,\n postJsonToApi as postJsonToApi2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\nvar MistralEmbeddingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.maxEmbeddingsPerCall = 32;\n this.supportsParallelCalls = false;\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async doEmbed({\n values,\n abortSignal,\n headers\n }) {\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi2({\n url: `${this.config.baseURL}/embeddings`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n input: values,\n encoding_format: \"float\"\n },\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n MistralTextEmbeddingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n warnings: [],\n embeddings: response.data.map((item) => item.embedding),\n usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,\n response: { headers: responseHeaders, body: rawValue }\n };\n }\n};\nvar MistralTextEmbeddingResponseSchema = z4.object({\n data: z4.array(z4.object({ embedding: z4.array(z4.number()) })),\n usage: z4.object({ prompt_tokens: z4.number() }).nullish()\n});\n\n// src/version.ts\nvar VERSION = true ? \"3.0.27\" : \"0.0.0-test\";\n\n// src/mistral-provider.ts\nfunction createMistral(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.mistral.ai/v1\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"MISTRAL_API_KEY\",\n description: \"Mistral\"\n })}`,\n ...options.headers\n },\n `ai-sdk/mistral/${VERSION}`\n );\n const createChatModel = (modelId) => new MistralChatLanguageModel(modelId, {\n provider: \"mistral.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: options.generateId\n });\n const createEmbeddingModel = (modelId) => new MistralEmbeddingModel(modelId, {\n provider: \"mistral.embedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Mistral model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar mistral = createMistral();\nexport {\n VERSION,\n createMistral,\n mistral\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";kYAuBA,cAAS,MAAmB,MAAC,OAAO,MAClC,QAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAY,OACZ,KAAW,OACX,UAAgB,MAClB,EACA,IAAU,MACZ,EAEF,IAA2B,cAArB,EACyB,kBAAzB,GAAmB,EACzB,MAAO,CACL,YAAa,CACX,MAAO,EACP,QAAS,EACT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| "sources": ["src/commands/handlers/migrate.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\n\nexport default Runtime.handler(Commands.commands.migrate, (_input) => Effect.log(\"No migrations to run.\"))\n" | ||
| ], | ||
| "mappings": ";2oBAIA,SAAe,SAAQ,aAAQ,OAAS,cAAS,aAAS,MAAC,SAAW,OAAO,SAAI,4BAAuB,MAAC", | ||
| "debugId": "BC8C3A98F28D6D2264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+perplexity@3.0.26+d6123d32214422cb/node_modules/@ai-sdk/perplexity/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/perplexity-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/perplexity-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\n\n// src/convert-perplexity-usage.ts\nfunction convertPerplexityUsage(usage) {\n var _a, _b, _c;\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;\n const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;\n const reasoningTokens = (_c = usage.reasoning_tokens) != null ? _c : 0;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens - reasoningTokens,\n reasoning: reasoningTokens\n },\n raw: usage\n };\n}\n\n// src/convert-to-perplexity-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertUint8ArrayToBase64 } from \"@ai-sdk/provider-utils\";\nfunction convertToPerplexityMessages(prompt) {\n const messages = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\":\n case \"assistant\": {\n const hasMultipartContent = content.some(\n (part) => part.type === \"file\" && part.mediaType.startsWith(\"image/\") || part.type === \"file\" && part.mediaType === \"application/pdf\"\n );\n const messageContent = content.map((part, index) => {\n var _a;\n switch (part.type) {\n case \"text\": {\n return {\n type: \"text\",\n text: part.text\n };\n }\n case \"file\": {\n if (part.mediaType === \"application/pdf\") {\n return part.data instanceof URL ? {\n type: \"file_url\",\n file_url: {\n url: part.data.toString()\n },\n file_name: part.filename\n } : {\n type: \"file_url\",\n file_url: {\n url: typeof part.data === \"string\" ? part.data : convertUint8ArrayToBase64(part.data)\n },\n file_name: part.filename || `document-${index}.pdf`\n };\n } else if (part.mediaType.startsWith(\"image/\")) {\n return part.data instanceof URL ? {\n type: \"image_url\",\n image_url: {\n url: part.data.toString()\n }\n } : {\n type: \"image_url\",\n image_url: {\n url: `data:${(_a = part.mediaType) != null ? _a : \"image/jpeg\"};base64,${typeof part.data === \"string\" ? part.data : convertUint8ArrayToBase64(part.data)}`\n }\n };\n }\n }\n }\n }).filter(Boolean);\n messages.push({\n role,\n content: hasMultipartContent ? messageContent : messageContent.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\")\n });\n break;\n }\n case \"tool\": {\n throw new UnsupportedFunctionalityError({\n functionality: \"Tool messages\"\n });\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/map-perplexity-finish-reason.ts\nfunction mapPerplexityFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n case \"length\":\n return finishReason;\n default:\n return \"other\";\n }\n}\n\n// src/perplexity-language-model.ts\nvar PerplexityLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.provider = \"perplexity\";\n this.supportedUrls = {\n // No URLs are supported.\n };\n this.modelId = modelId;\n this.config = config;\n }\n getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n providerOptions\n }) {\n var _a;\n const warnings = [];\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n if (stopSequences != null) {\n warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n }\n if (seed != null) {\n warnings.push({ type: \"unsupported\", feature: \"seed\" });\n }\n return {\n args: {\n // model id:\n model: this.modelId,\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n max_tokens: maxOutputTokens,\n presence_penalty: presencePenalty,\n temperature,\n top_k: topK,\n top_p: topP,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? {\n type: \"json_schema\",\n json_schema: { schema: responseFormat.schema }\n } : void 0,\n // provider extensions\n ...(_a = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a : {},\n // messages:\n messages: convertToPerplexityMessages(prompt)\n },\n warnings\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;\n const { args: body, warnings } = this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: perplexityErrorSchema,\n errorToMessage\n }),\n successfulResponseHandler: createJsonResponseHandler(\n perplexityResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n const text = choice.message.content;\n if (text.length > 0) {\n content.push({ type: \"text\", text });\n }\n if (response.citations != null) {\n for (const url of response.citations) {\n content.push({\n type: \"source\",\n sourceType: \"url\",\n id: this.config.generateId(),\n url\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapPerplexityFinishReason(choice.finish_reason),\n raw: (_a = choice.finish_reason) != null ? _a : void 0\n },\n usage: convertPerplexityUsage(response.usage),\n request: { body },\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n providerMetadata: {\n perplexity: {\n images: (_c = (_b = response.images) == null ? void 0 : _b.map((image) => ({\n imageUrl: image.image_url,\n originUrl: image.origin_url,\n height: image.height,\n width: image.width\n }))) != null ? _c : null,\n usage: {\n citationTokens: (_e = (_d = response.usage) == null ? void 0 : _d.citation_tokens) != null ? _e : null,\n numSearchQueries: (_g = (_f = response.usage) == null ? void 0 : _f.num_search_queries) != null ? _g : null\n },\n cost: ((_h = response.usage) == null ? void 0 : _h.cost) ? {\n inputTokensCost: (_i = response.usage.cost.input_tokens_cost) != null ? _i : null,\n outputTokensCost: (_j = response.usage.cost.output_tokens_cost) != null ? _j : null,\n requestCost: (_k = response.usage.cost.request_cost) != null ? _k : null,\n totalCost: (_l = response.usage.cost.total_cost) != null ? _l : null\n } : null\n }\n }\n };\n }\n async doStream(options) {\n const { args, warnings } = this.getArgs(options);\n const body = { ...args, stream: true };\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: perplexityErrorSchema,\n errorToMessage\n }),\n successfulResponseHandler: createEventSourceResponseHandler(\n perplexityChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n const providerMetadata = {\n perplexity: {\n usage: {\n citationTokens: null,\n numSearchQueries: null\n },\n cost: null,\n images: null\n }\n };\n let isFirstChunk = true;\n let isActive = false;\n const self = this;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b, _c, _d, _e, _f, _g;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (isFirstChunk) {\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n (_a = value.citations) == null ? void 0 : _a.forEach((url) => {\n controller.enqueue({\n type: \"source\",\n sourceType: \"url\",\n id: self.config.generateId(),\n url\n });\n });\n isFirstChunk = false;\n }\n if (value.usage != null) {\n usage = value.usage;\n providerMetadata.perplexity.usage = {\n citationTokens: (_b = value.usage.citation_tokens) != null ? _b : null,\n numSearchQueries: (_c = value.usage.num_search_queries) != null ? _c : null\n };\n providerMetadata.perplexity.cost = value.usage.cost ? {\n inputTokensCost: (_d = value.usage.cost.input_tokens_cost) != null ? _d : null,\n outputTokensCost: (_e = value.usage.cost.output_tokens_cost) != null ? _e : null,\n requestCost: (_f = value.usage.cost.request_cost) != null ? _f : null,\n totalCost: (_g = value.usage.cost.total_cost) != null ? _g : null\n } : null;\n }\n if (value.images != null) {\n providerMetadata.perplexity.images = value.images.map((image) => ({\n imageUrl: image.image_url,\n originUrl: image.origin_url,\n height: image.height,\n width: image.width\n }));\n }\n const choice = value.choices[0];\n if ((choice == null ? void 0 : choice.finish_reason) != null) {\n finishReason = {\n unified: mapPerplexityFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n if ((choice == null ? void 0 : choice.delta) == null) {\n return;\n }\n const delta = choice.delta;\n const textContent = delta.content;\n if (textContent != null) {\n if (!isActive) {\n controller.enqueue({ type: \"text-start\", id: \"0\" });\n isActive = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"0\",\n delta: textContent\n });\n }\n },\n flush(controller) {\n if (isActive) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertPerplexityUsage(usage),\n providerMetadata\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id,\n modelId: model,\n timestamp: new Date(created * 1e3)\n };\n}\nvar perplexityCostSchema = z.object({\n input_tokens_cost: z.number().nullish(),\n output_tokens_cost: z.number().nullish(),\n request_cost: z.number().nullish(),\n total_cost: z.number().nullish()\n});\nvar perplexityUsageSchema = z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number(),\n total_tokens: z.number().nullish(),\n citation_tokens: z.number().nullish(),\n num_search_queries: z.number().nullish(),\n reasoning_tokens: z.number().nullish(),\n cost: perplexityCostSchema.nullish()\n});\nvar perplexityImageSchema = z.object({\n image_url: z.string(),\n origin_url: z.string(),\n height: z.number(),\n width: z.number()\n});\nvar perplexityResponseSchema = z.object({\n id: z.string(),\n created: z.number(),\n model: z.string(),\n choices: z.array(\n z.object({\n message: z.object({\n role: z.literal(\"assistant\"),\n content: z.string()\n }),\n finish_reason: z.string().nullish()\n })\n ),\n citations: z.array(z.string()).nullish(),\n images: z.array(perplexityImageSchema).nullish(),\n usage: perplexityUsageSchema.nullish()\n});\nvar perplexityChunkSchema = z.object({\n id: z.string(),\n created: z.number(),\n model: z.string(),\n choices: z.array(\n z.object({\n delta: z.object({\n role: z.literal(\"assistant\"),\n content: z.string()\n }),\n finish_reason: z.string().nullish()\n })\n ),\n citations: z.array(z.string()).nullish(),\n images: z.array(perplexityImageSchema).nullish(),\n usage: perplexityUsageSchema.nullish()\n});\nvar perplexityErrorSchema = z.object({\n error: z.object({\n code: z.number(),\n message: z.string().nullish(),\n type: z.string().nullish()\n })\n});\nvar errorToMessage = (data) => {\n var _a, _b;\n return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : \"unknown error\";\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.26\" : \"0.0.0-test\";\n\n// src/perplexity-provider.ts\nfunction createPerplexity(options = {}) {\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"PERPLEXITY_API_KEY\",\n description: \"Perplexity\"\n })}`,\n ...options.headers\n },\n `ai-sdk/perplexity/${VERSION}`\n );\n const createLanguageModel = (modelId) => {\n var _a;\n return new PerplexityLanguageModel(modelId, {\n baseURL: withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.perplexity.ai\"\n ),\n headers: getHeaders,\n generateId,\n fetch: options.fetch\n });\n };\n const provider = (modelId) => createLanguageModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.languageModel = createLanguageModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar perplexity = createPerplexity();\nexport {\n VERSION,\n createPerplexity,\n perplexity\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";0WAsBA,cAAS,MAAsB,MAAC,OAAO,MACrC,SAAI,EAAI,EAAI,EACZ,GAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAY,OACZ,KAAW,OACX,UAAgB,MAClB,EACA,IAAU,MACZ,EAEF,IAAM,GAAgB,EAAK,EAAM,gBAAkB,KAAO,EAAK,EACzD,GAAoB,EAAK,EAAM,oBAAsB,KAAO,EAAK,EACjE,GAAmB,EAAK,EAAM,mBAAqB,KAAO,EAAK,EACrE,MAAO,CACL,YAAa,CACX,MAAO,EACP,QAAS,EACT,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,M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EACzB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAa,EAAiB", | ||
| "debugId": "6F5914E851ACD15D64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/services/service-config.ts"], | ||
| "sourcesContent": [ | ||
| "import { Global } from \"@opencode-ai/util/global\"\nimport { OPENCODE_CHANNEL, OPENCODE_VERSION } from \"../version\"\nimport { Hash } from \"@opencode-ai/util/hash\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, FileSystem, Option, Schema } from \"effect\"\nimport { randomBytes } from \"crypto\"\nimport path from \"path\"\nimport { selfCommand } from \"../util/process\"\n\n// The CLI's service configuration file, plus the Service.EnsureOptions binding that\n// points the client package's service operations at this CLI: which\n// registration file (by channel), which version, and how to spawn opencode.\n\nexport const Info = Schema.Struct({\n hostname: Schema.optional(Schema.String),\n port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),\n password: Schema.optional(Schema.String),\n})\nexport type Info = typeof Info.Type\n\nconst keys = [\"hostname\", \"port\", \"password\"] as const\ntype Key = (typeof keys)[number]\n\nconst decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))\nconst decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info))\n\nexport function filename(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"next\") return \"service.json\"\n return `service-${channel.replace(/[^a-zA-Z0-9._-]/g, \"-\")}.json`\n}\n\nexport function defaultPort(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"next\") return 0xc0de\n if (channel === \"local\") return 0xc0df\n return 10_000 + (Number.parseInt(Hash.fast(channel).slice(0, 8), 16) % 50_000)\n}\n\nexport function legacyFilename(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"local\") return\n return `service-${Hash.fast(channel)}.json`\n}\n\nexport function versionBelongsToChannel(\n version: string | undefined,\n channel = OPENCODE_CHANNEL,\n installedVersion = OPENCODE_VERSION,\n) {\n if (version === undefined) return false\n if (version === installedVersion) return true\n const prefix = `0.0.0-${channel}-`\n if (!version.startsWith(prefix)) return false\n return /^\\d+(?:\\.\\d+)?$/.test(version.slice(prefix.length))\n}\n\nexport const migrateRegistration = Effect.fnUntraced(function* (\n legacy: string,\n file: string,\n channel = OPENCODE_CHANNEL,\n installedVersion = OPENCODE_VERSION,\n) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(legacy).pipe(Effect.option)\n if (Option.isNone(text)) return\n const registration = yield* decodeRegistration(text.value).pipe(Effect.option)\n if (Option.isNone(registration)) return\n if (!versionBelongsToChannel(registration.value.version, channel, installedVersion)) return\n yield* fs.writeFileString(file, text.value, { flag: \"wx\", mode: 0o600 }).pipe(Effect.ignore)\n})\n\nexport const migrateConfig = Effect.fnUntraced(function* (legacy: string, file: string) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(legacy).pipe(Effect.option)\n if (Option.isNone(text)) return\n if (Option.isNone(yield* decodeInfo(text.value).pipe(Effect.option))) return\n yield* fs.writeFileString(file, text.value, { flag: \"wx\", mode: 0o600 }).pipe(Effect.ignore)\n})\n\nfunction configKey(key: string): Key {\n if (key === \"hostname\" || key === \"port\" || key === \"password\") return key\n throw new Error(`Unknown service config key: ${key}`)\n}\n\nconst paths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem\n const global = yield* Global.Service\n const name = filename()\n const legacy = legacyFilename()\n const file = path.join(global.state, name)\n return {\n fs,\n file,\n legacyConfigFile: legacy ? path.join(global.config, legacy) : undefined,\n legacyRegistrationFiles: [\n ...(legacy ? [path.join(global.state, legacy)] : []),\n ...(name !== \"service.json\" && OPENCODE_CHANNEL !== \"local\" ? [path.join(global.state, \"service.json\")] : []),\n ],\n configFile: path.join(global.config, name),\n }\n})\n\nexport const options = Effect.fnUntraced(function* () {\n const { file, legacyRegistrationFiles } = yield* paths\n yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))\n return {\n file,\n version: OPENCODE_VERSION,\n command: [...selfCommand(), \"serve\", \"--service\"],\n }\n})\n\nexport const read = Effect.fn(\"cli.service-config.read\")(function* () {\n const { fs, configFile, legacyConfigFile } = yield* paths\n if (legacyConfigFile) yield* migrateConfig(legacyConfigFile, configFile)\n return yield* fs.readFileString(configFile).pipe(\n Effect.flatMap(decodeInfo),\n Effect.catch(() => Effect.succeed({} as Info)),\n )\n})\n\nconst write = Effect.fn(\"cli.service-config.write\")(function* (value: Info) {\n const { fs, configFile } = yield* paths\n const temp = configFile + \".tmp\"\n yield* fs.makeDirectory(path.dirname(configFile), { recursive: true })\n yield* fs.writeFileString(temp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n yield* fs.rename(temp, configFile)\n})\n\nexport const password = Effect.fn(\"cli.service-config.password\")(function* (value?: string) {\n const existing = yield* read()\n if (value === undefined && existing.password) return existing.password\n const next = value ?? randomBytes(32).toString(\"base64url\")\n\n // Keep one private credential across server restarts so discovered clients\n // can reconnect without exposing a password flag or environment variable.\n yield* write({ ...existing, password: next })\n return next\n})\n\nexport const get = Effect.fn(\"cli.service-config.get\")(function* (key?: string) {\n if (key === undefined) {\n const { password: _password, ...safe } = yield* read()\n return JSON.stringify(safe, null, 2)\n }\n switch (configKey(key)) {\n case \"hostname\": {\n return (yield* read()).hostname ?? \"\"\n }\n case \"port\": {\n const port = (yield* read()).port\n return port === undefined ? \"\" : String(port)\n }\n case \"password\": {\n return yield* password()\n }\n }\n throw new Error(`Unknown service config key: ${key}`)\n})\n\nexport const set = Effect.fn(\"cli.service-config.set\")(function* (key: string, value: string) {\n switch (configKey(key)) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), hostname: value })\n return\n }\n case \"port\": {\n const port = Number(value)\n if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error(\"Port must be between 1 and 65535\")\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), port })\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n yield* password(value)\n return\n }\n }\n})\n\nexport const unset = Effect.fn(\"cli.service-config.unset\")(function* (key: string) {\n switch (configKey(key)) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n const { hostname: _hostname, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"port\": {\n yield* Service.stop(yield* options())\n const { port: _port, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n const { password: _password, ...next } = yield* read()\n yield* write(next)\n return\n }\n }\n})\n\nexport * as ServiceConfig from \"./service-config\"\n" | ||
| ], | ||
| "mappings": ";gkBAKA,2BAAS,oBACT,yBAOO,SAAM,OAAO,EAAO,OAAO,CAChC,SAAU,EAAO,SAAS,EAAO,MAAM,EACvC,KAAM,EAAO,SAAS,EAAO,IAAI,MAAM,EAAO,uBAAuB,CAAC,EAAG,EAAO,oBAAoB,KAAM,CAAC,CAAC,EAC5G,SAAU,EAAO,SAAS,EAAO,MAAM,CACzC,CAAC,EAMD,IAAM,EAAa,EAAO,oBAAoB,EAAO,eAAe,CAAI,CAAC,EACnE,EAAqB,EAAO,oBAAoB,EAAO,eAAe,EAAQ,IAAI,CAAC,EAElF,SAAS,CAAQ,CAAC,EAAU,EAAkB,CACnD,GAAI,IAAY,UAAY,IAAY,OAAQ,MAAO,eACvD,MAAO,WAAW,EAAQ,QAAQ,mBAAoB,GAAG,SAGpD,SAAS,CAAW,CAAC,EAAU,EAAkB,CACtD,GAAI,IAAY,UAAY,IAAY,OAAQ,MAAO,OACvD,GAAI,IAAY,QAAS,MAAO,OAChC,MAAO,KAAU,OAAO,SAAS,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,MAAQ,MAAU,MAAM,kCAAkC,EAC5G,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,MAAO,EAAM,IAAM,MAAO,EAAK,EAAI,MAAK,CAAC,EACzC,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,MAAO,EAAS,CAAK,EACrB,MACF,GAEH,EAEY,EAAQ,EAAO,GAAG,0BAA0B,EAAE,SAAU,CAAC,EAAa,CACjF,OAAQ,EAAU,CAAG,OACd,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,KACK,OAAQ,CACX,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,KAAM,KAAU,GAAS,MAAO,EAAK,EAC7C,MAAO,EAAM,CAAI,EACjB,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,GAEH", | ||
| "debugId": "F078B3565094F56F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/image-client.ts", "../ai/src/image.ts"], | ||
| "sourcesContent": [ | ||
| "import { Context, Effect, Layer } from \"effect\"\nimport { RequestExecutor } from \"./route/executor\"\nimport type { ImageOptions, ImageRequest, ImageRequestFor, ImageResponse } from \"./image\"\nimport type { LLMError } from \"./schema\"\n\nexport type Execute = RequestExecutor.Interface[\"execute\"]\n\nexport interface Interface {\n readonly generate: <Options extends ImageOptions>(\n request: ImageRequestFor<Options>,\n ) => Effect.Effect<ImageResponse, LLMError>\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/ImageClient\") {}\n\nexport const generate = <Options extends ImageOptions>(\n request: ImageRequestFor<Options>,\n): Effect.Effect<ImageResponse, LLMError> =>\n Effect.gen(function* () {\n const client = yield* Service\n return yield* client.generate(request)\n }) as Effect.Effect<ImageResponse, LLMError>\n\nexport const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer.effect(\n Service,\n Effect.gen(function* () {\n const executor = yield* RequestExecutor.Service\n return Service.of({\n generate: (request) => request.model.route.generate(request, executor.execute),\n })\n }),\n)\n\nexport const ImageClient = {\n Service,\n layer,\n generate,\n} as const\n", | ||
| "import { Effect, Schema } from \"effect\"\nimport { HttpOptions, InvalidRequestReason, LLMError, ModelID, ProviderID, ProviderMetadata, Usage } from \"./schema\"\nimport { ImageClient, Service, type Execute as ImageExecute } from \"./image-client\"\n\nexport interface ImageRoute<Options extends ImageOptions = ImageOptions> {\n readonly id: string\n readonly generate: (\n request: ImageRequestFor<Options>,\n execute: ImageExecute,\n ) => Effect.Effect<ImageResponse, LLMError>\n}\n\nexport type ImageOptions = Record<string, unknown>\n\nexport class ImageModel<Options extends ImageOptions = ImageOptions> {\n declare protected readonly _Options: (options: Options) => Options\n readonly id: ModelID\n readonly provider: ProviderID\n readonly route: ImageRoute<Options>\n readonly http?: HttpOptions\n\n constructor(input: ImageModel.Input<Options>) {\n this.id = input.id\n this.provider = input.provider\n this.route = input.route\n this.http = input.http\n }\n\n static make<Options extends ImageOptions = ImageOptions>(input: ImageModel.MakeInput<Options>) {\n return new ImageModel<Options>({\n id: ModelID.make(input.id),\n provider: ProviderID.make(input.provider),\n route: input.route,\n http: input.http,\n })\n }\n}\n\nexport namespace ImageModel {\n export interface Input<Options extends ImageOptions = ImageOptions> {\n readonly id: ModelID\n readonly provider: ProviderID\n readonly route: ImageRoute<Options>\n readonly http?: HttpOptions\n }\n\n export interface MakeInput<Options extends ImageOptions = ImageOptions>\n extends Omit<Input<Options>, \"id\" | \"provider\"> {\n readonly id: string | ModelID\n readonly provider: string | ProviderID\n }\n}\n\nexport const ImageModelSchema = Schema.declare((value): value is ImageModel => value instanceof ImageModel, {\n expected: \"Image.Model\",\n})\n\nconst ImageBytesInput = Schema.Struct({\n type: Schema.Literal(\"bytes\"),\n data: Schema.Uint8Array,\n mediaType: Schema.String,\n})\nconst ImageUrlInput = Schema.Struct({\n type: Schema.Literal(\"url\"),\n url: Schema.String,\n})\nconst ImageFileIDInput = Schema.Struct({\n type: Schema.Literal(\"file-id\"),\n id: Schema.String,\n})\nconst ImageFileURIInput = Schema.Struct({\n type: Schema.Literal(\"file-uri\"),\n uri: Schema.String,\n mediaType: Schema.String,\n})\n\nexport const ImageInputSchema = Schema.Union([\n ImageBytesInput,\n ImageUrlInput,\n ImageFileIDInput,\n ImageFileURIInput,\n]).pipe(Schema.toTaggedUnion(\"type\"))\nexport type ImageInput = Schema.Schema.Type<typeof ImageInputSchema>\n\nexport const ImageInput = {\n bytes: (data: Uint8Array, mediaType: string): ImageInput => ({ type: \"bytes\", data, mediaType }),\n url: (url: string): ImageInput => ({ type: \"url\", url }),\n file: (id: string): ImageInput => ({ type: \"file-id\", id }),\n fileUri: (uri: string, mediaType: string): ImageInput => ({ type: \"file-uri\", uri, mediaType }),\n} as const\n\nexport class ImageRequest extends Schema.Class<ImageRequest>(\"Image.Request\")({\n model: ImageModelSchema,\n prompt: Schema.String,\n images: Schema.optional(Schema.Array(ImageInputSchema)),\n options: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n http: Schema.optional(HttpOptions),\n}) {\n declare protected readonly _ImageRequest: void\n}\n\nexport type ImageRequestFor<Options extends ImageOptions = ImageOptions> = Omit<ImageRequest, \"model\" | \"options\"> & {\n readonly model: ImageModel<Options>\n readonly options?: Options\n}\n\nexport type ImageModelOptions<Model> = Model extends ImageModel<infer Options> ? Options : never\n\nexport type ImageRequestInput<Model extends object = ImageModel> = Omit<\n ConstructorParameters<typeof ImageRequest>[0],\n \"model\" | \"options\" | \"http\"\n> & {\n readonly model: Model\n readonly options?: NoInfer<ImageModelOptions<Model>>\n readonly http?: HttpOptions.Input\n} & (Model extends ImageModel<ImageModelOptions<Model>> ? unknown : never)\n\nexport class GeneratedImage extends Schema.Class<GeneratedImage>(\"Image.Generated\")({\n mediaType: Schema.String,\n data: Schema.Union([Schema.String, Schema.Uint8Array]),\n providerMetadata: Schema.optional(ProviderMetadata),\n}) {}\n\nexport class ImageResponse extends Schema.Class<ImageResponse>(\"Image.Response\")({\n images: Schema.Array(GeneratedImage),\n usage: Schema.optional(Usage),\n providerMetadata: Schema.optional(ProviderMetadata),\n}) {\n get image() {\n return this.images[0]\n }\n}\n\nexport function request<const Model extends object>(\n input: ImageRequestInput<Model>,\n): ImageRequestFor<ImageModelOptions<Model>>\nexport function request(input: ImageRequest): ImageRequest\nexport function request(input: ImageRequest | ImageRequestInput) {\n if (input instanceof ImageRequest) return input\n return new ImageRequest({\n ...input,\n model: input.model as unknown as ImageModel,\n http: input.http === undefined ? undefined : HttpOptions.make(input.http),\n })\n}\n\nexport function generate<const Model extends object>(\n input: ImageRequestInput<Model>,\n): Effect.Effect<ImageResponse, LLMError, Service>\nexport function generate(input: ImageRequest): Effect.Effect<ImageResponse, LLMError, Service>\nexport function generate(input: ImageRequest | ImageRequestInput) {\n return Effect.try({\n try: () => (input instanceof ImageRequest ? input : request(input)),\n catch: (error) =>\n new LLMError({\n module: \"Image\",\n method: \"generate\",\n reason: new InvalidRequestReason({ message: error instanceof Error ? error.message : String(error) }),\n }),\n }).pipe(Effect.flatMap((request) => ImageClient.generate(request as unknown as ImageRequestFor<ImageOptions>)))\n}\n\nexport const Image = {\n request,\n generate,\n} as const\n" | ||
| ], | ||
| "mappings": ";0MAaO,WAAM,eAAgB,EAAQ,QAA4B,EAAE,uBAAuB,CAAE,CAAC,CAUtF,IAAM,EAA8D,EAAM,OAC/E,EACA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAW,MAAO,EAAgB,QACxC,OAAO,EAAQ,GAAG,CAChB,SAAU,CAAC,IAAY,EAAQ,MAAM,MAAM,SAAS,EAAS,EAAS,OAAO,CAC/E,CAAC,EACF,CACH,ECjBO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AAM,CAAC,EAAO,OAAQ,EAAO,UAAU,CAAC,EACrD,iBAAkB,EAAO,SAAS,CAAgB,CACpD,CAAC,CAAE,CAAC,CAEG,MAAM,UAAsB,EAAO,MAAqB,gBAAgB,EAAE,CAC/E,OAAQ,EAAO,MAAM,CAAc,EACnC,MAAO,EAAO,SAAS,CAAK,EAC5B,iBAAkB,EAAO,SAAS,CAAgB,CACpD,CAAC,CAAE,IACG,MAAK,EAAG,CACV,OAAO,KAAK,OAAO,GAEvB", | ||
| "debugId": "F21BE4409B1E697664756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-env@3.972.59/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nexport const ENV_KEY = \"AWS_ACCESS_KEY_ID\";\nexport const ENV_SECRET = \"AWS_SECRET_ACCESS_KEY\";\nexport const ENV_SESSION = \"AWS_SESSION_TOKEN\";\nexport const ENV_EXPIRATION = \"AWS_CREDENTIAL_EXPIRATION\";\nexport const ENV_CREDENTIAL_SCOPE = \"AWS_CREDENTIAL_SCOPE\";\nexport const ENV_ACCOUNT_ID = \"AWS_ACCOUNT_ID\";\nexport const fromEnv = (init) => async () => {\n init?.logger?.debug(\"@aws-sdk/credential-provider-env - fromEnv\");\n const accessKeyId = process.env[ENV_KEY];\n const secretAccessKey = process.env[ENV_SECRET];\n const sessionToken = process.env[ENV_SESSION];\n const expiry = process.env[ENV_EXPIRATION];\n const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];\n const accountId = process.env[ENV_ACCOUNT_ID];\n if (accessKeyId && secretAccessKey) {\n const credentials = {\n accessKeyId,\n secretAccessKey,\n ...(sessionToken && { sessionToken }),\n ...(expiry && { expiration: new Date(expiry) }),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS\", \"g\");\n return credentials;\n }\n throw new CredentialsProviderError(\"Unable to find environment variable credentials.\", { logger: init?.logger });\n};\n" | ||
| ], | ||
| "mappings": ";kJAAA,oBACA,gBACa,EAAU,oBACV,EAAa,wBACb,EAAc,oBACd,EAAiB,4BACjB,EAAuB,uBACvB,EAAiB,iBACjB,EAAU,CAAC,IAAS,SAAY,CACzC,GAAM,QAAQ,MAAM,4CAA4C,EAChE,IAAM,EAAc,QAAQ,IAAI,GAC1B,EAAkB,QAAQ,IAAI,GAC9B,EAAe,QAAQ,IAAI,GAC3B,EAAS,QAAQ,IAAI,GACrB,EAAkB,QAAQ,IAAI,GAC9B,EAAY,QAAQ,IAAI,GAC9B,GAAI,GAAe,EAAiB,CAChC,IAAM,EAAc,CAChB,cACA,qBACI,GAAgB,CAAE,cAAa,KAC/B,GAAU,CAAE,WAAY,IAAI,KAAK,CAAM,CAAE,KACzC,GAAmB,CAAE,iBAAgB,KACrC,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,uBAAwB,GAAG,EACtD,EAEX,MAAM,IAAI,2BAAyB,mDAAoD,CAAE,OAAQ,GAAM,MAAO,CAAC", | ||
| "debugId": "AB20E165247A025364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/aws4fetch@1.0.20/node_modules/aws4fetch/dist/aws4fetch.esm.mjs"], | ||
| "sourcesContent": [ | ||
| "/**\n * @license MIT <https://opensource.org/licenses/MIT>\n * @copyright Michael Hart 2024\n */\nconst encoder = new TextEncoder();\nconst HOST_SERVICES = {\n appstream2: 'appstream',\n cloudhsmv2: 'cloudhsm',\n email: 'ses',\n marketplace: 'aws-marketplace',\n mobile: 'AWSMobileHubService',\n pinpoint: 'mobiletargeting',\n queue: 'sqs',\n 'git-codecommit': 'codecommit',\n 'mturk-requester-sandbox': 'mturk-requester',\n 'personalize-runtime': 'personalize',\n};\nconst UNSIGNABLE_HEADERS = new Set([\n 'authorization',\n 'content-type',\n 'content-length',\n 'user-agent',\n 'presigned-expires',\n 'expect',\n 'x-amzn-trace-id',\n 'range',\n 'connection',\n]);\nclass AwsClient {\n constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n this.service = service;\n this.region = region;\n this.cache = cache || new Map();\n this.retries = retries != null ? retries : 10;\n this.initRetryMs = initRetryMs || 50;\n }\n async sign(input, init) {\n if (input instanceof Request) {\n const { method, url, headers, body } = input;\n init = Object.assign({ method, url, headers }, init);\n if (init.body == null && headers.has('Content-Type')) {\n init.body = body != null && headers.has('X-Amz-Content-Sha256') ? body : await input.clone().arrayBuffer();\n }\n input = url;\n }\n const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));\n const signed = Object.assign({}, init, await signer.sign());\n delete signed.aws;\n try {\n return new Request(signed.url.toString(), signed)\n } catch (e) {\n if (e instanceof TypeError) {\n return new Request(signed.url.toString(), Object.assign({ duplex: 'half' }, signed))\n }\n throw e\n }\n }\n async fetch(input, init) {\n for (let i = 0; i <= this.retries; i++) {\n const fetched = fetch(await this.sign(input, init));\n if (i === this.retries) {\n return fetched\n }\n const res = await fetched;\n if (res.status < 500 && res.status !== 429) {\n return res\n }\n await new Promise(resolve => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));\n }\n throw new Error('An unknown error occurred, ensure retries is not negative')\n }\n}\nclass AwsV4Signer {\n constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {\n if (url == null) throw new TypeError('url is a required option')\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.method = method || (body ? 'POST' : 'GET');\n this.url = new URL(url);\n this.headers = new Headers(headers || {});\n this.body = body;\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n let guessedService, guessedRegion;\n if (!service || !region) {\n[guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);\n }\n this.service = service || guessedService || '';\n this.region = region || guessedRegion || 'us-east-1';\n this.cache = cache || new Map();\n this.datetime = datetime || new Date().toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n this.signQuery = signQuery;\n this.appendSessionToken = appendSessionToken || this.service === 'iotdevicegateway';\n this.headers.delete('Host');\n if (this.service === 's3' && !this.signQuery && !this.headers.has('X-Amz-Content-Sha256')) {\n this.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD');\n }\n const params = this.signQuery ? this.url.searchParams : this.headers;\n params.set('X-Amz-Date', this.datetime);\n if (this.sessionToken && !this.appendSessionToken) {\n params.set('X-Amz-Security-Token', this.sessionToken);\n }\n this.signableHeaders = ['host', ...this.headers.keys()]\n .filter(header => allHeaders || !UNSIGNABLE_HEADERS.has(header))\n .sort();\n this.signedHeaders = this.signableHeaders.join(';');\n this.canonicalHeaders = this.signableHeaders\n .map(header => header + ':' + (header === 'host' ? this.url.host : (this.headers.get(header) || '').replace(/\\s+/g, ' ')))\n .join('\\n');\n this.credentialString = [this.datetime.slice(0, 8), this.region, this.service, 'aws4_request'].join('/');\n if (this.signQuery) {\n if (this.service === 's3' && !params.has('X-Amz-Expires')) {\n params.set('X-Amz-Expires', '86400');\n }\n params.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256');\n params.set('X-Amz-Credential', this.accessKeyId + '/' + this.credentialString);\n params.set('X-Amz-SignedHeaders', this.signedHeaders);\n }\n if (this.service === 's3') {\n try {\n this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\\+/g, ' '));\n } catch (e) {\n this.encodedPath = this.url.pathname;\n }\n } else {\n this.encodedPath = this.url.pathname.replace(/\\/+/g, '/');\n }\n if (!singleEncode) {\n this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, '/');\n }\n this.encodedPath = encodeRfc3986(this.encodedPath);\n const seenKeys = new Set();\n this.encodedSearch = [...this.url.searchParams]\n .filter(([k]) => {\n if (!k) return false\n if (this.service === 's3') {\n if (seenKeys.has(k)) return false\n seenKeys.add(k);\n }\n return true\n })\n .map(pair => pair.map(p => encodeRfc3986(encodeURIComponent(p))))\n .sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0)\n .map(pair => pair.join('='))\n .join('&');\n }\n async sign() {\n if (this.signQuery) {\n this.url.searchParams.set('X-Amz-Signature', await this.signature());\n if (this.sessionToken && this.appendSessionToken) {\n this.url.searchParams.set('X-Amz-Security-Token', this.sessionToken);\n }\n } else {\n this.headers.set('Authorization', await this.authHeader());\n }\n return {\n method: this.method,\n url: this.url,\n headers: this.headers,\n body: this.body,\n }\n }\n async authHeader() {\n return [\n 'AWS4-HMAC-SHA256 Credential=' + this.accessKeyId + '/' + this.credentialString,\n 'SignedHeaders=' + this.signedHeaders,\n 'Signature=' + (await this.signature()),\n ].join(', ')\n }\n async signature() {\n const date = this.datetime.slice(0, 8);\n const cacheKey = [this.secretAccessKey, date, this.region, this.service].join();\n let kCredentials = this.cache.get(cacheKey);\n if (!kCredentials) {\n const kDate = await hmac('AWS4' + this.secretAccessKey, date);\n const kRegion = await hmac(kDate, this.region);\n const kService = await hmac(kRegion, this.service);\n kCredentials = await hmac(kService, 'aws4_request');\n this.cache.set(cacheKey, kCredentials);\n }\n return buf2hex(await hmac(kCredentials, await this.stringToSign()))\n }\n async stringToSign() {\n return [\n 'AWS4-HMAC-SHA256',\n this.datetime,\n this.credentialString,\n buf2hex(await hash(await this.canonicalString())),\n ].join('\\n')\n }\n async canonicalString() {\n return [\n this.method.toUpperCase(),\n this.encodedPath,\n this.encodedSearch,\n this.canonicalHeaders + '\\n',\n this.signedHeaders,\n await this.hexBodyHash(),\n ].join('\\n')\n }\n async hexBodyHash() {\n let hashHeader = this.headers.get('X-Amz-Content-Sha256') || (this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null);\n if (hashHeader == null) {\n if (this.body && typeof this.body !== 'string' && !('byteLength' in this.body)) {\n throw new Error('body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header')\n }\n hashHeader = buf2hex(await hash(this.body || ''));\n }\n return hashHeader\n }\n}\nasync function hmac(key, string) {\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n typeof key === 'string' ? encoder.encode(key) : key,\n { name: 'HMAC', hash: { name: 'SHA-256' } },\n false,\n ['sign'],\n );\n return crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string))\n}\nasync function hash(content) {\n return crypto.subtle.digest('SHA-256', typeof content === 'string' ? encoder.encode(content) : content)\n}\nconst HEX_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nfunction buf2hex(arrayBuffer) {\n const buffer = new Uint8Array(arrayBuffer);\n let out = '';\n for (let idx = 0; idx < buffer.length; idx++) {\n const n = buffer[idx];\n out += HEX_CHARS[(n >>> 4) & 0xF];\n out += HEX_CHARS[n & 0xF];\n }\n return out\n}\nfunction encodeRfc3986(urlEncodedStr) {\n return urlEncodedStr.replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n}\nfunction guessServiceRegion(url, headers) {\n const { hostname, pathname } = url;\n if (hostname.endsWith('.on.aws')) {\n const match = hostname.match(/^[^.]{1,63}\\.lambda-url\\.([^.]{1,63})\\.on\\.aws$/);\n return match != null ? ['lambda', match[1] || ''] : ['', '']\n }\n if (hostname.endsWith('.r2.cloudflarestorage.com')) {\n return ['s3', 'auto']\n }\n if (hostname.endsWith('.backblazeb2.com')) {\n const match = hostname.match(/^(?:[^.]{1,63}\\.)?s3\\.([^.]{1,63})\\.backblazeb2\\.com$/);\n return match != null ? ['s3', match[1] || ''] : ['', '']\n }\n const match = hostname.replace('dualstack.', '').match(/([^.]{1,63})\\.(?:([^.]{0,63})\\.)?amazonaws\\.com(?:\\.cn)?$/);\n let service = (match && match[1]) || '';\n let region = match && match[2];\n if (region === 'us-gov') {\n region = 'us-gov-west-1';\n } else if (region === 's3' || region === 's3-accelerate') {\n region = 'us-east-1';\n service = 's3';\n } else if (service === 'iot') {\n if (hostname.startsWith('iot.')) {\n service = 'execute-api';\n } else if (hostname.startsWith('data.jobs.iot.')) {\n service = 'iot-jobs-data';\n } else {\n service = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata';\n }\n } else if (service === 'autoscaling') {\n const targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0];\n if (targetPrefix === 'AnyScaleFrontendService') {\n service = 'application-autoscaling';\n } else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') {\n service = 'autoscaling-plans';\n }\n } else if (region == null && service.startsWith('s3-')) {\n region = service.slice(3).replace(/^fips-|^external-1/, '');\n service = 's3';\n } else if (service.endsWith('-fips')) {\n service = service.slice(0, -5);\n } else if (region && /-\\d$/.test(service) && !/-\\d$/.test(region)) {\n[service, region] = [region, service];\n }\n return [HOST_SERVICES[service] || service, region || '']\n}\n\nexport { AwsClient, AwsV4Signer };\n" | ||
| ], | ||
| "mappings": ";AAIA,IAAM,EAAU,IAAI,YACd,EAAgB,CACpB,WAAY,YACZ,WAAY,WACZ,MAAO,MACP,YAAa,kBACb,OAAQ,sBACR,SAAU,kBACV,MAAO,MACP,iBAAkB,aAClB,0BAA2B,kBAC3B,sBAAuB,aACzB,EACM,EAAqB,IAAI,IAAI,CACjC,gBACA,eACA,iBACA,aACA,oBACA,SACA,kBACA,QACA,YACF,CAAC,EAkDD,MAAM,CAAY,CAChB,WAAW,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C1D,EAAU,KACL,QAAI,EAAQ,SAAS,OAAO,EACjC,EAAU,EAAQ,MAAM,EAAG,EAAE,EACxB,QAAI,GAAU,OAAO,KAAK,CAAO,GAAK,CAAC,OAAO,KAAK,CAAM,EAClE,CAAC,EAAS,CAAM,EAAI,CAAC,EAAQ,CAAO,EAElC,MAAO,CAAC,EAAc,IAAY,EAAS,GAAU,EAAE", | ||
| "debugId": "641C49AA5D8B195364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+groq@3.0.31+d6123d32214422cb/node_modules/@ai-sdk/groq/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/groq-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/groq-chat-language-model.ts\nimport {\n InvalidResponseDataError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n generateId,\n isParsableJson,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/convert-groq-usage.ts\nfunction convertGroqUsage(usage) {\n var _a, _b, _c, _d;\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;\n const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;\n const reasoningTokens = (_d = (_c = usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : void 0;\n const textTokens = reasoningTokens != null ? completionTokens - reasoningTokens : completionTokens;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: textTokens,\n reasoning: reasoningTokens\n },\n raw: usage\n };\n}\n\n// src/convert-to-groq-chat-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertToBase64 } from \"@ai-sdk/provider-utils\";\nfunction convertToGroqChatMessages(prompt) {\n var _a;\n const messages = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n if (content.length === 1 && content[0].type === \"text\") {\n messages.push({ role: \"user\", content: content[0].text });\n break;\n }\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n switch (part.type) {\n case \"text\": {\n return { type: \"text\", text: part.text };\n }\n case \"file\": {\n if (!part.mediaType.startsWith(\"image/\")) {\n throw new UnsupportedFunctionalityError({\n functionality: \"Non-image file content parts\"\n });\n }\n const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType;\n return {\n type: \"image_url\",\n image_url: {\n url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`\n }\n };\n }\n }\n })\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n let reasoning = \"\";\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n // groq supports reasoning for tool-calls in multi-turn conversations\n // https://github.com/vercel/ai/issues/7860\n case \"reasoning\": {\n reasoning += part.text;\n break;\n }\n case \"text\": {\n text += part.text;\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: text,\n ...reasoning.length > 0 ? { reasoning } : null,\n ...toolCalls.length > 0 ? { tool_calls: toolCalls } : null\n });\n break;\n }\n case \"tool\": {\n for (const toolResponse of content) {\n if (toolResponse.type === \"tool-approval-response\") {\n continue;\n }\n const output = toolResponse.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n messages.push({\n role: \"tool\",\n tool_call_id: toolResponse.toolCallId,\n content: contentValue\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/get-response-metadata.ts\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id: id != null ? id : void 0,\n modelId: model != null ? model : void 0,\n timestamp: created != null ? new Date(created * 1e3) : void 0\n };\n}\n\n// src/groq-chat-options.ts\nimport { z } from \"zod/v4\";\nvar groqLanguageModelOptions = z.object({\n reasoningFormat: z.enum([\"parsed\", \"raw\", \"hidden\"]).optional(),\n /**\n * Specifies the reasoning effort level for model inference.\n * @see https://console.groq.com/docs/reasoning#reasoning-effort\n */\n reasoningEffort: z.enum([\"none\", \"default\", \"low\", \"medium\", \"high\"]).optional(),\n /**\n * Whether to enable parallel function calling during tool use. Default to true.\n */\n parallelToolCalls: z.boolean().optional(),\n /**\n * A unique identifier representing your end-user, which can help OpenAI to\n * monitor and detect abuse. Learn more.\n */\n user: z.string().optional(),\n /**\n * Whether to use structured outputs.\n *\n * @default true\n */\n structuredOutputs: z.boolean().optional(),\n /**\n * Whether to use strict JSON schema validation.\n * When true, the model uses constrained decoding to guarantee schema compliance.\n * Only used when structured outputs are enabled and a schema is provided.\n *\n * @default true\n */\n strictJsonSchema: z.boolean().optional(),\n /**\n * Service tier for the request.\n * - 'on_demand': Default tier with consistent performance and fairness\n * - 'flex': Higher throughput tier optimized for workloads that can handle occasional request failures\n * - 'auto': Uses on_demand rate limits, then falls back to flex tier if exceeded\n *\n * @default 'on_demand'\n */\n serviceTier: z.enum([\"on_demand\", \"flex\", \"auto\"]).optional()\n});\n\n// src/groq-error.ts\nimport { z as z2 } from \"zod/v4\";\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nvar groqErrorDataSchema = z2.object({\n error: z2.object({\n message: z2.string(),\n type: z2.string()\n })\n});\nvar groqFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: groqErrorDataSchema,\n errorToMessage: (data) => data.error.message\n});\n\n// src/groq-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\n\n// src/groq-browser-search-models.ts\nvar BROWSER_SEARCH_SUPPORTED_MODELS = [\n \"openai/gpt-oss-20b\",\n \"openai/gpt-oss-120b\"\n];\nfunction isBrowserSearchSupportedModel(modelId) {\n return BROWSER_SEARCH_SUPPORTED_MODELS.includes(modelId);\n}\nfunction getSupportedModelsString() {\n return BROWSER_SEARCH_SUPPORTED_MODELS.join(\", \");\n}\n\n// src/groq-prepare-tools.ts\nfunction prepareTools({\n tools,\n toolChoice,\n modelId\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const groqTools2 = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n if (tool.id === \"groq.browser_search\") {\n if (!isBrowserSearchSupportedModel(modelId)) {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`,\n details: `Browser search is only supported on the following models: ${getSupportedModelsString()}. Current model: ${modelId}`\n });\n } else {\n groqTools2.push({\n type: \"browser_search\"\n });\n }\n } else {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n }\n } else {\n groqTools2.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n ...tool.strict != null ? { strict: tool.strict } : {}\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: groqTools2, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n case \"none\":\n case \"required\":\n return { tools: groqTools2, toolChoice: type, toolWarnings };\n case \"tool\":\n return {\n tools: groqTools2,\n toolChoice: {\n type: \"function\",\n function: {\n name: toolChoice.toolName\n }\n },\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError2({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/map-groq-finish-reason.ts\nfunction mapGroqFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n return \"length\";\n case \"content_filter\":\n return \"content-filter\";\n case \"function_call\":\n case \"tool_calls\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/groq-chat-language-model.ts\nvar GroqChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n \"image/*\": [/^https?:\\/\\/.*$/]\n };\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n stream,\n tools,\n toolChoice,\n providerOptions\n }) {\n var _a, _b, _c;\n const warnings = [];\n const groqOptions = await parseProviderOptions({\n provider: \"groq\",\n providerOptions,\n schema: groqLanguageModelOptions\n });\n const structuredOutputs = (_a = groqOptions == null ? void 0 : groqOptions.structuredOutputs) != null ? _a : true;\n const strictJsonSchema = (_b = groqOptions == null ? void 0 : groqOptions.strictJsonSchema) != null ? _b : true;\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n if ((responseFormat == null ? void 0 : responseFormat.type) === \"json\" && responseFormat.schema != null && !structuredOutputs) {\n warnings.push({\n type: \"unsupported\",\n feature: \"responseFormat\",\n details: \"JSON response format schema is only supported with structuredOutputs\"\n });\n }\n const {\n tools: groqTools2,\n toolChoice: groqToolChoice,\n toolWarnings\n } = prepareTools({ tools, toolChoice, modelId: this.modelId });\n return {\n args: {\n // model id:\n model: this.modelId,\n // model specific settings:\n user: groqOptions == null ? void 0 : groqOptions.user,\n parallel_tool_calls: groqOptions == null ? void 0 : groqOptions.parallelToolCalls,\n // standardized settings:\n max_tokens: maxOutputTokens,\n temperature,\n top_p: topP,\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n stop: stopSequences,\n seed,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? structuredOutputs && responseFormat.schema != null ? {\n type: \"json_schema\",\n json_schema: {\n schema: responseFormat.schema,\n strict: strictJsonSchema,\n name: (_c = responseFormat.name) != null ? _c : \"response\",\n description: responseFormat.description\n }\n } : { type: \"json_object\" } : void 0,\n // provider options:\n reasoning_format: groqOptions == null ? void 0 : groqOptions.reasoningFormat,\n reasoning_effort: groqOptions == null ? void 0 : groqOptions.reasoningEffort,\n service_tier: groqOptions == null ? void 0 : groqOptions.serviceTier,\n // messages:\n messages: convertToGroqChatMessages(prompt),\n // tools:\n tools: groqTools2,\n tool_choice: groqToolChoice\n },\n warnings: [...warnings, ...toolWarnings]\n };\n }\n async doGenerate(options) {\n var _a, _b;\n const { args, warnings } = await this.getArgs({\n ...options,\n stream: false\n });\n const body = JSON.stringify(args);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: this.config.url({\n path: \"/chat/completions\",\n modelId: this.modelId\n }),\n headers: combineHeaders(this.config.headers(), options.headers),\n body: args,\n failedResponseHandler: groqFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n groqChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n const text = choice.message.content;\n if (text != null && text.length > 0) {\n content.push({ type: \"text\", text });\n }\n const reasoning = choice.message.reasoning;\n if (reasoning != null && reasoning.length > 0) {\n content.push({\n type: \"reasoning\",\n text: reasoning\n });\n }\n if (choice.message.tool_calls != null) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: \"tool-call\",\n toolCallId: (_a = toolCall.id) != null ? _a : generateId(),\n toolName: toolCall.function.name,\n input: toolCall.function.arguments\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapGroqFinishReason(choice.finish_reason),\n raw: (_b = choice.finish_reason) != null ? _b : void 0\n },\n usage: convertGroqUsage(response.usage),\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n request: { body }\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs({ ...options, stream: true });\n const body = JSON.stringify({ ...args, stream: true });\n const { responseHeaders, value: response } = await postJsonToApi({\n url: this.config.url({\n path: \"/chat/completions\",\n modelId: this.modelId\n }),\n headers: combineHeaders(this.config.headers(), options.headers),\n body: {\n ...args,\n stream: true\n },\n failedResponseHandler: groqFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(groqChatChunkSchema),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const toolCalls = [];\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let isFirstChunk = true;\n let isActiveText = false;\n let isActiveReasoning = false;\n let providerMetadata;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n finishReason = {\n unified: \"error\",\n raw: void 0\n };\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (\"error\" in value) {\n finishReason = {\n unified: \"error\",\n raw: void 0\n };\n controller.enqueue({ type: \"error\", error: value.error });\n return;\n }\n if (isFirstChunk) {\n isFirstChunk = false;\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n }\n if (((_a = value.x_groq) == null ? void 0 : _a.usage) != null) {\n usage = value.x_groq.usage;\n }\n const choice = value.choices[0];\n if ((choice == null ? void 0 : choice.finish_reason) != null) {\n finishReason = {\n unified: mapGroqFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n if ((choice == null ? void 0 : choice.delta) == null) {\n return;\n }\n const delta = choice.delta;\n if (delta.reasoning != null && delta.reasoning.length > 0) {\n if (!isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-start\",\n id: \"reasoning-0\"\n });\n isActiveReasoning = true;\n }\n controller.enqueue({\n type: \"reasoning-delta\",\n id: \"reasoning-0\",\n delta: delta.reasoning\n });\n }\n if (delta.content != null && delta.content.length > 0) {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: \"reasoning-0\"\n });\n isActiveReasoning = false;\n }\n if (!isActiveText) {\n controller.enqueue({ type: \"text-start\", id: \"txt-0\" });\n isActiveText = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"txt-0\",\n delta: delta.content\n });\n }\n if (delta.tool_calls != null) {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: \"reasoning-0\"\n });\n isActiveReasoning = false;\n }\n for (const toolCallDelta of delta.tool_calls) {\n const index = toolCallDelta.index;\n if (toolCalls[index] == null) {\n if (toolCallDelta.type !== \"function\") {\n throw new InvalidResponseDataError({\n data: toolCallDelta,\n message: `Expected 'function' type.`\n });\n }\n if (toolCallDelta.id == null) {\n throw new InvalidResponseDataError({\n data: toolCallDelta,\n message: `Expected 'id' to be a string.`\n });\n }\n if (((_b = toolCallDelta.function) == null ? void 0 : _b.name) == null) {\n throw new InvalidResponseDataError({\n data: toolCallDelta,\n message: `Expected 'function.name' to be a string.`\n });\n }\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolCallDelta.id,\n toolName: toolCallDelta.function.name\n });\n toolCalls[index] = {\n id: toolCallDelta.id,\n type: \"function\",\n function: {\n name: toolCallDelta.function.name,\n arguments: (_c = toolCallDelta.function.arguments) != null ? _c : \"\"\n },\n hasFinished: false\n };\n const toolCall2 = toolCalls[index];\n if (((_d = toolCall2.function) == null ? void 0 : _d.name) != null && ((_e = toolCall2.function) == null ? void 0 : _e.arguments) != null) {\n if (toolCall2.function.arguments.length > 0) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCall2.id,\n delta: toolCall2.function.arguments\n });\n }\n if (isParsableJson(toolCall2.function.arguments)) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCall2.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: (_f = toolCall2.id) != null ? _f : generateId(),\n toolName: toolCall2.function.name,\n input: toolCall2.function.arguments\n });\n toolCall2.hasFinished = true;\n }\n }\n continue;\n }\n const toolCall = toolCalls[index];\n if (toolCall.hasFinished) {\n continue;\n }\n if (((_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null) {\n toolCall.function.arguments += (_i = (_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null ? _i : \"\";\n }\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCall.id,\n delta: (_j = toolCallDelta.function.arguments) != null ? _j : \"\"\n });\n if (((_k = toolCall.function) == null ? void 0 : _k.name) != null && ((_l = toolCall.function) == null ? void 0 : _l.arguments) != null && isParsableJson(toolCall.function.arguments)) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCall.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: (_m = toolCall.id) != null ? _m : generateId(),\n toolName: toolCall.function.name,\n input: toolCall.function.arguments\n });\n toolCall.hasFinished = true;\n }\n }\n }\n },\n flush(controller) {\n if (isActiveReasoning) {\n controller.enqueue({ type: \"reasoning-end\", id: \"reasoning-0\" });\n }\n if (isActiveText) {\n controller.enqueue({ type: \"text-end\", id: \"txt-0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertGroqUsage(usage),\n ...providerMetadata != null ? { providerMetadata } : {}\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nvar groqChatResponseSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n message: z3.object({\n content: z3.string().nullish(),\n reasoning: z3.string().nullish(),\n tool_calls: z3.array(\n z3.object({\n id: z3.string().nullish(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n ).nullish()\n }),\n index: z3.number(),\n finish_reason: z3.string().nullish()\n })\n ),\n usage: z3.object({\n prompt_tokens: z3.number().nullish(),\n completion_tokens: z3.number().nullish(),\n total_tokens: z3.number().nullish(),\n prompt_tokens_details: z3.object({\n cached_tokens: z3.number().nullish()\n }).nullish(),\n completion_tokens_details: z3.object({\n reasoning_tokens: z3.number().nullish()\n }).nullish()\n }).nullish()\n});\nvar groqChatChunkSchema = z3.union([\n z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n delta: z3.object({\n content: z3.string().nullish(),\n reasoning: z3.string().nullish(),\n tool_calls: z3.array(\n z3.object({\n index: z3.number(),\n id: z3.string().nullish(),\n type: z3.literal(\"function\").optional(),\n function: z3.object({\n name: z3.string().nullish(),\n arguments: z3.string().nullish()\n })\n })\n ).nullish()\n }).nullish(),\n finish_reason: z3.string().nullable().optional(),\n index: z3.number()\n })\n ),\n x_groq: z3.object({\n usage: z3.object({\n prompt_tokens: z3.number().nullish(),\n completion_tokens: z3.number().nullish(),\n total_tokens: z3.number().nullish(),\n prompt_tokens_details: z3.object({\n cached_tokens: z3.number().nullish()\n }).nullish(),\n completion_tokens_details: z3.object({\n reasoning_tokens: z3.number().nullish()\n }).nullish()\n }).nullish()\n }).nullish()\n }),\n groqErrorDataSchema\n]);\n\n// src/groq-transcription-model.ts\nimport {\n combineHeaders as combineHeaders2,\n convertBase64ToUint8Array,\n createJsonResponseHandler as createJsonResponseHandler2,\n mediaTypeToExtension,\n parseProviderOptions as parseProviderOptions2,\n postFormDataToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\n\n// src/groq-transcription-options.ts\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\nvar groqTranscriptionModelOptions = lazySchema(\n () => zodSchema(\n z4.object({\n language: z4.string().nullish(),\n prompt: z4.string().nullish(),\n responseFormat: z4.string().nullish(),\n temperature: z4.number().min(0).max(1).nullish(),\n timestampGranularities: z4.array(z4.string()).nullish()\n })\n )\n);\n\n// src/groq-transcription-model.ts\nvar GroqTranscriptionModel = class {\n constructor(modelId, config) {\n this.modelId = modelId;\n this.config = config;\n this.specificationVersion = \"v3\";\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n audio,\n mediaType,\n providerOptions\n }) {\n var _a, _b, _c, _d, _e;\n const warnings = [];\n const groqOptions = await parseProviderOptions2({\n provider: \"groq\",\n providerOptions,\n schema: groqTranscriptionModelOptions\n });\n const formData = new FormData();\n const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);\n formData.append(\"model\", this.modelId);\n const fileExtension = mediaTypeToExtension(mediaType);\n formData.append(\n \"file\",\n new File([blob], \"audio\", { type: mediaType }),\n `audio.${fileExtension}`\n );\n if (groqOptions) {\n const transcriptionModelOptions = {\n language: (_a = groqOptions.language) != null ? _a : void 0,\n prompt: (_b = groqOptions.prompt) != null ? _b : void 0,\n response_format: (_c = groqOptions.responseFormat) != null ? _c : void 0,\n temperature: (_d = groqOptions.temperature) != null ? _d : void 0,\n timestamp_granularities: (_e = groqOptions.timestampGranularities) != null ? _e : void 0\n };\n for (const key in transcriptionModelOptions) {\n const value = transcriptionModelOptions[key];\n if (value !== void 0) {\n if (Array.isArray(value)) {\n for (const item of value) {\n formData.append(`${key}[]`, String(item));\n }\n } else {\n formData.append(key, String(value));\n }\n }\n }\n }\n return {\n formData,\n warnings\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g;\n const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();\n const { formData, warnings } = await this.getArgs(options);\n const {\n value: response,\n responseHeaders,\n rawValue: rawResponse\n } = await postFormDataToApi({\n url: this.config.url({\n path: \"/audio/transcriptions\",\n modelId: this.modelId\n }),\n headers: combineHeaders2(this.config.headers(), options.headers),\n formData,\n failedResponseHandler: groqFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n groqTranscriptionResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n return {\n text: response.text,\n segments: (_e = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({\n text: segment.text,\n startSecond: segment.start,\n endSecond: segment.end\n }))) != null ? _e : [],\n language: (_f = response.language) != null ? _f : void 0,\n durationInSeconds: (_g = response.duration) != null ? _g : void 0,\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawResponse\n }\n };\n }\n};\nvar groqTranscriptionResponseSchema = z5.object({\n text: z5.string(),\n x_groq: z5.object({\n id: z5.string()\n }),\n // additional properties are returned when `response_format: 'verbose_json'` is\n task: z5.string().nullish(),\n language: z5.string().nullish(),\n duration: z5.number().nullish(),\n segments: z5.array(\n z5.object({\n id: z5.number(),\n seek: z5.number(),\n start: z5.number(),\n end: z5.number(),\n text: z5.string(),\n tokens: z5.array(z5.number()),\n temperature: z5.number(),\n avg_logprob: z5.number(),\n compression_ratio: z5.number(),\n no_speech_prob: z5.number()\n })\n ).nullish()\n});\n\n// src/tool/browser-search.ts\nimport { createProviderToolFactory } from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar browserSearch = createProviderToolFactory({\n id: \"groq.browser_search\",\n inputSchema: z6.object({})\n});\n\n// src/groq-tools.ts\nvar groqTools = {\n browserSearch\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.31\" : \"0.0.0-test\";\n\n// src/groq-provider.ts\nfunction createGroq(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.groq.com/openai/v1\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"GROQ_API_KEY\",\n description: \"Groq\"\n })}`,\n ...options.headers\n },\n `ai-sdk/groq/${VERSION}`\n );\n const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {\n provider: \"groq.chat\",\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createLanguageModel = (modelId) => {\n if (new.target) {\n throw new Error(\n \"The Groq model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n const createTranscriptionModel = (modelId) => {\n return new GroqTranscriptionModel(modelId, {\n provider: \"groq.transcription\",\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n };\n const provider = function(modelId) {\n return createLanguageModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createLanguageModel;\n provider.chat = createChatModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n provider.transcription = createTranscriptionModel;\n provider.transcriptionModel = createTranscriptionModel;\n provider.tools = groqTools;\n return provider;\n}\nvar groq = createGroq();\nexport {\n VERSION,\n browserSearch,\n createGroq,\n groq\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";ybA0BA,cAAS,MAAgB,MAAC,OAAO,MAC/B,SAAI,EAAI,EAAI,EAAI,EAChB,GAAI,GA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": "3E477C22CC3474F964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/restart.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.restart,\n Effect.fn(\"cli.service.restart\")(function* () {\n const options = yield* ServiceConfig.options()\n yield* Service.stop(options)\n const transport = yield* Service.ensure(options)\n process.stdout.write(transport.url + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+0BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,aACnC,OAAO,QAAG,0BAAqB,OAAE,cAAU,OAAG,MAC5C,SAAM,OAAU,WAAO,OAAc,aAAQ,EAC7C,MAAO,EAAQ,KAAK,CAAO,EAC3B,IAAM,EAAY,MAAO,EAAQ,OAAO,CAAO,EAC/C,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "980F38570B29248F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+cohere@3.0.27+d6123d32214422cb/node_modules/@ai-sdk/cohere/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/cohere-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/cohere-chat-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/cohere-chat-options.ts\nimport { z } from \"zod/v4\";\nvar cohereLanguageModelOptions = z.object({\n /**\n * Configuration for reasoning features (optional)\n *\n * Can be set to an object with the two properties `type` and `tokenBudget`. `type` can be set to `'enabled'` or `'disabled'` (defaults to `'enabled'`).\n * `tokenBudget` is the maximum number of tokens the model can use for thinking, which must be set to a positive integer. The model will stop thinking if it reaches the thinking token budget and will proceed with the response\n *\n * @see https://docs.cohere.com/reference/chat#request.body.thinking\n */\n thinking: z.object({\n type: z.enum([\"enabled\", \"disabled\"]).optional(),\n tokenBudget: z.number().optional()\n }).optional()\n});\n\n// src/cohere-error.ts\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar cohereErrorDataSchema = z2.object({\n message: z2.string()\n});\nvar cohereFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: cohereErrorDataSchema,\n errorToMessage: (data) => data.message\n});\n\n// src/cohere-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nfunction prepareTools({\n tools,\n toolChoice\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const cohereTools = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n } else {\n cohereTools.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: cohereTools, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n return { tools: cohereTools, toolChoice: void 0, toolWarnings };\n case \"none\":\n return { tools: cohereTools, toolChoice: \"NONE\", toolWarnings };\n case \"required\":\n return { tools: cohereTools, toolChoice: \"REQUIRED\", toolWarnings };\n case \"tool\":\n return {\n tools: cohereTools.filter(\n (tool) => tool.function.name === toolChoice.toolName\n ),\n toolChoice: \"REQUIRED\",\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/convert-cohere-usage.ts\nfunction convertCohereUsage(tokens) {\n if (tokens == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const inputTokens = tokens.input_tokens;\n const outputTokens = tokens.output_tokens;\n return {\n inputTokens: {\n total: inputTokens,\n noCache: inputTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: outputTokens,\n text: outputTokens,\n reasoning: void 0\n },\n raw: tokens\n };\n}\n\n// src/convert-to-cohere-chat-prompt.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nfunction convertToCohereChatPrompt(prompt) {\n const messages = [];\n const documents = [];\n const warnings = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n var _a;\n switch (part.type) {\n case \"text\": {\n return part.text;\n }\n case \"file\": {\n let textContent;\n if (typeof part.data === \"string\") {\n textContent = part.data;\n } else if (part.data instanceof Uint8Array) {\n if (!(((_a = part.mediaType) == null ? void 0 : _a.startsWith(\"text/\")) || part.mediaType === \"application/json\")) {\n throw new UnsupportedFunctionalityError2({\n functionality: `document media type: ${part.mediaType}`,\n message: `Media type '${part.mediaType}' is not supported. Supported media types are: text/* and application/json.`\n });\n }\n textContent = new TextDecoder().decode(part.data);\n } else {\n throw new UnsupportedFunctionalityError2({\n functionality: \"File URL data\",\n message: \"URLs should be downloaded by the AI SDK and not reach this point. This indicates a configuration issue.\"\n });\n }\n documents.push({\n data: {\n text: textContent,\n title: part.filename\n }\n });\n return \"\";\n }\n }\n }).join(\"\")\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: toolCalls.length > 0 ? void 0 : text,\n tool_calls: toolCalls.length > 0 ? toolCalls : void 0,\n tool_plan: void 0\n });\n break;\n }\n case \"tool\": {\n messages.push(\n ...content.filter((toolResult) => toolResult.type !== \"tool-approval-response\").map((toolResult) => {\n var _a;\n const output = toolResult.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n return {\n role: \"tool\",\n content: contentValue,\n tool_call_id: toolResult.toolCallId\n };\n })\n );\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return { messages, documents, warnings };\n}\n\n// src/map-cohere-finish-reason.ts\nfunction mapCohereFinishReason(finishReason) {\n switch (finishReason) {\n case \"COMPLETE\":\n case \"STOP_SEQUENCE\":\n return \"stop\";\n case \"MAX_TOKENS\":\n return \"length\";\n case \"ERROR\":\n return \"error\";\n case \"TOOL_CALL\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/cohere-chat-language-model.ts\nvar CohereChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n // No URLs are supported.\n };\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n tools,\n toolChoice,\n providerOptions\n }) {\n var _a, _b;\n const cohereOptions = (_a = await parseProviderOptions({\n provider: \"cohere\",\n providerOptions,\n schema: cohereLanguageModelOptions\n })) != null ? _a : {};\n const {\n messages: chatPrompt,\n documents: cohereDocuments,\n warnings: promptWarnings\n } = convertToCohereChatPrompt(prompt);\n const {\n tools: cohereTools,\n toolChoice: cohereToolChoice,\n toolWarnings\n } = prepareTools({ tools, toolChoice });\n return {\n args: {\n // model id:\n model: this.modelId,\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n max_tokens: maxOutputTokens,\n temperature,\n p: topP,\n k: topK,\n seed,\n stop_sequences: stopSequences,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? { type: \"json_object\", json_schema: responseFormat.schema } : void 0,\n // messages:\n messages: chatPrompt,\n // tools:\n tools: cohereTools,\n tool_choice: cohereToolChoice,\n // documents for RAG:\n ...cohereDocuments.length > 0 && { documents: cohereDocuments },\n // reasoning\n ...cohereOptions.thinking && {\n thinking: {\n type: (_b = cohereOptions.thinking.type) != null ? _b : \"enabled\",\n token_budget: cohereOptions.thinking.tokenBudget\n }\n }\n },\n warnings: [...toolWarnings, ...promptWarnings]\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g;\n const { args, warnings } = await this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: args,\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const content = [];\n for (const item of (_a = response.message.content) != null ? _a : []) {\n if (item.type === \"text\" && item.text.length > 0) {\n content.push({ type: \"text\", text: item.text });\n continue;\n }\n if (item.type === \"thinking\" && item.thinking.length > 0) {\n content.push({ type: \"reasoning\", text: item.thinking });\n continue;\n }\n }\n for (const citation of (_b = response.message.citations) != null ? _b : []) {\n content.push({\n type: \"source\",\n sourceType: \"document\",\n id: this.config.generateId(),\n mediaType: \"text/plain\",\n title: ((_d = (_c = citation.sources[0]) == null ? void 0 : _c.document) == null ? void 0 : _d.title) || \"Document\",\n providerMetadata: {\n cohere: {\n start: citation.start,\n end: citation.end,\n text: citation.text,\n sources: citation.sources,\n ...citation.type && { citationType: citation.type }\n }\n }\n });\n }\n for (const toolCall of (_e = response.message.tool_calls) != null ? _e : []) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n // Cohere sometimes returns `null` for tool call arguments for tools\n // defined as having no arguments.\n input: toolCall.function.arguments.replace(/^null$/, \"{}\")\n });\n }\n return {\n content,\n finishReason: {\n unified: mapCohereFinishReason(response.finish_reason),\n raw: (_f = response.finish_reason) != null ? _f : void 0\n },\n usage: convertCohereUsage(response.usage.tokens),\n request: { body: args },\n response: {\n // TODO timestamp, model id\n id: (_g = response.generation_id) != null ? _g : void 0,\n headers: responseHeaders,\n body: rawResponse\n },\n warnings\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs(options);\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: { ...args, stream: true },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n cohereChatChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let pendingToolCall = null;\n let isActiveReasoning = false;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n finishReason = { unified: \"error\", raw: void 0 };\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n const type = value.type;\n switch (type) {\n case \"content-start\": {\n if (value.delta.message.content.type === \"thinking\") {\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(value.index)\n });\n isActiveReasoning = true;\n return;\n }\n controller.enqueue({\n type: \"text-start\",\n id: String(value.index)\n });\n return;\n }\n case \"content-delta\": {\n if (\"thinking\" in value.delta.message.content) {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(value.index),\n delta: value.delta.message.content.thinking\n });\n return;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: String(value.index),\n delta: value.delta.message.content.text\n });\n return;\n }\n case \"content-end\": {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: String(value.index)\n });\n isActiveReasoning = false;\n return;\n }\n controller.enqueue({\n type: \"text-end\",\n id: String(value.index)\n });\n return;\n }\n case \"tool-call-start\": {\n const toolId = value.delta.message.tool_calls.id;\n const toolName = value.delta.message.tool_calls.function.name;\n const initialArgs = value.delta.message.tool_calls.function.arguments;\n pendingToolCall = {\n id: toolId,\n name: toolName,\n arguments: initialArgs,\n hasFinished: false\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolId,\n toolName\n });\n if (initialArgs.length > 0) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolId,\n delta: initialArgs\n });\n }\n return;\n }\n case \"tool-call-delta\": {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n const argsDelta = value.delta.message.tool_calls.function.arguments;\n pendingToolCall.arguments += argsDelta;\n controller.enqueue({\n type: \"tool-input-delta\",\n id: pendingToolCall.id,\n delta: argsDelta\n });\n }\n return;\n }\n case \"tool-call-end\": {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: pendingToolCall.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: pendingToolCall.id,\n toolName: pendingToolCall.name,\n input: JSON.stringify(\n JSON.parse(((_a = pendingToolCall.arguments) == null ? void 0 : _a.trim()) || \"{}\")\n )\n });\n pendingToolCall.hasFinished = true;\n pendingToolCall = null;\n }\n return;\n }\n case \"message-start\": {\n controller.enqueue({\n type: \"response-metadata\",\n id: (_b = value.id) != null ? _b : void 0\n });\n return;\n }\n case \"message-end\": {\n finishReason = {\n unified: mapCohereFinishReason(value.delta.finish_reason),\n raw: value.delta.finish_reason\n };\n usage = value.delta.usage.tokens;\n return;\n }\n default: {\n return;\n }\n }\n },\n flush(controller) {\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertCohereUsage(usage)\n });\n }\n })\n ),\n request: { body: { ...args, stream: true } },\n response: { headers: responseHeaders }\n };\n }\n};\nvar cohereChatResponseSchema = z3.object({\n generation_id: z3.string().nullish(),\n message: z3.object({\n role: z3.string(),\n content: z3.array(\n z3.union([\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.string()\n })\n ])\n ).nullish(),\n tool_plan: z3.string().nullish(),\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n ).nullish(),\n citations: z3.array(\n z3.object({\n start: z3.number(),\n end: z3.number(),\n text: z3.string(),\n sources: z3.array(\n z3.object({\n type: z3.string().optional(),\n id: z3.string().optional(),\n document: z3.object({\n id: z3.string().optional(),\n text: z3.string(),\n title: z3.string()\n })\n })\n ),\n type: z3.string().optional()\n })\n ).nullish()\n }),\n finish_reason: z3.string(),\n usage: z3.object({\n billed_units: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n }),\n tokens: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n })\n })\n});\nvar cohereChatChunkSchema = z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"citation-start\")\n }),\n z3.object({\n type: z3.literal(\"citation-end\")\n }),\n z3.object({\n type: z3.literal(\"content-start\"),\n index: z3.number(),\n delta: z3.object({\n message: z3.object({\n content: z3.union([\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.string()\n })\n ])\n })\n })\n }),\n z3.object({\n type: z3.literal(\"content-delta\"),\n index: z3.number(),\n delta: z3.object({\n message: z3.object({\n content: z3.union([\n z3.object({\n text: z3.string()\n }),\n z3.object({\n thinking: z3.string()\n })\n ])\n })\n })\n }),\n z3.object({\n type: z3.literal(\"content-end\"),\n index: z3.number()\n }),\n z3.object({\n type: z3.literal(\"message-start\"),\n id: z3.string().nullish()\n }),\n z3.object({\n type: z3.literal(\"message-end\"),\n delta: z3.object({\n finish_reason: z3.string(),\n usage: z3.object({\n tokens: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n })\n })\n })\n }),\n // https://docs.cohere.com/v2/docs/streaming#tool-use-stream-events-for-tool-calling\n z3.object({\n type: z3.literal(\"tool-plan-delta\"),\n delta: z3.object({\n message: z3.object({\n tool_plan: z3.string()\n })\n })\n }),\n z3.object({\n type: z3.literal(\"tool-call-start\"),\n delta: z3.object({\n message: z3.object({\n tool_calls: z3.object({\n id: z3.string(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n })\n })\n }),\n // A single tool call's `arguments` stream in chunks and must be accumulated\n // in a string and so the full tool object info can only be parsed once we see\n // `tool-call-end`.\n z3.object({\n type: z3.literal(\"tool-call-delta\"),\n delta: z3.object({\n message: z3.object({\n tool_calls: z3.object({\n function: z3.object({\n arguments: z3.string()\n })\n })\n })\n })\n }),\n z3.object({\n type: z3.literal(\"tool-call-end\")\n })\n]);\n\n// src/cohere-embedding-model.ts\nimport {\n TooManyEmbeddingValuesForCallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders as combineHeaders2,\n createJsonResponseHandler as createJsonResponseHandler2,\n parseProviderOptions as parseProviderOptions2,\n postJsonToApi as postJsonToApi2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\n\n// src/cohere-embedding-options.ts\nimport { z as z4 } from \"zod/v4\";\nvar cohereEmbeddingModelOptions = z4.object({\n /**\n * Specifies the type of input passed to the model. Default is `search_query`.\n *\n * - \"search_document\": Used for embeddings stored in a vector database for search use-cases.\n * - \"search_query\": Used for embeddings of search queries run against a vector DB to find relevant documents.\n * - \"classification\": Used for embeddings passed through a text classifier.\n * - \"clustering\": Used for embeddings run through a clustering algorithm.\n */\n inputType: z4.enum([\"search_document\", \"search_query\", \"classification\", \"clustering\"]).optional(),\n /**\n * Specifies how the API will handle inputs longer than the maximum token length.\n * Default is `END`.\n *\n * - \"NONE\": If selected, when the input exceeds the maximum input token length will return an error.\n * - \"START\": Will discard the start of the input until the remaining input is exactly the maximum input token length for the model.\n * - \"END\": Will discard the end of the input until the remaining input is exactly the maximum input token length for the model.\n */\n truncate: z4.enum([\"NONE\", \"START\", \"END\"]).optional(),\n /**\n * The number of dimensions of the output embedding.\n * Only available for `embed-v4.0` and newer models.\n *\n * Possible values are `256`, `512`, `1024`, and `1536`.\n * The default is `1536`.\n */\n outputDimension: z4.union([z4.literal(256), z4.literal(512), z4.literal(1024), z4.literal(1536)]).optional()\n});\n\n// src/cohere-embedding-model.ts\nvar CohereEmbeddingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.maxEmbeddingsPerCall = 96;\n this.supportsParallelCalls = true;\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async doEmbed({\n values,\n headers,\n abortSignal,\n providerOptions\n }) {\n var _a;\n const embeddingOptions = await parseProviderOptions2({\n provider: \"cohere\",\n providerOptions,\n schema: cohereEmbeddingModelOptions\n });\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi2({\n url: `${this.config.baseURL}/embed`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n // The AI SDK only supports 'float' embeddings. Note that the Cohere API\n // supports other embedding types, but they are not currently supported by the AI SDK.\n // https://docs.cohere.com/v2/reference/embed#request.body.embedding_types\n embedding_types: [\"float\"],\n texts: values,\n input_type: (_a = embeddingOptions == null ? void 0 : embeddingOptions.inputType) != null ? _a : \"search_query\",\n truncate: embeddingOptions == null ? void 0 : embeddingOptions.truncate,\n output_dimension: embeddingOptions == null ? void 0 : embeddingOptions.outputDimension\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n cohereTextEmbeddingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n warnings: [],\n embeddings: response.embeddings.float,\n usage: { tokens: response.meta.billed_units.input_tokens },\n response: { headers: responseHeaders, body: rawValue }\n };\n }\n};\nvar cohereTextEmbeddingResponseSchema = z5.object({\n embeddings: z5.object({\n float: z5.array(z5.array(z5.number()))\n }),\n meta: z5.object({\n billed_units: z5.object({\n input_tokens: z5.number()\n })\n })\n});\n\n// src/reranking/cohere-reranking-model.ts\nimport {\n combineHeaders as combineHeaders3,\n createJsonResponseHandler as createJsonResponseHandler3,\n parseProviderOptions as parseProviderOptions3,\n postJsonToApi as postJsonToApi3\n} from \"@ai-sdk/provider-utils\";\n\n// src/reranking/cohere-reranking-api.ts\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar cohereRerankingResponseSchema = lazySchema(\n () => zodSchema(\n z6.object({\n id: z6.string().nullish(),\n results: z6.array(\n z6.object({\n index: z6.number(),\n relevance_score: z6.number()\n })\n ),\n meta: z6.any()\n })\n )\n);\n\n// src/reranking/cohere-reranking-options.ts\nimport { lazySchema as lazySchema2, zodSchema as zodSchema2 } from \"@ai-sdk/provider-utils\";\nimport { z as z7 } from \"zod/v4\";\nvar cohereRerankingModelOptionsSchema = lazySchema2(\n () => zodSchema2(\n z7.object({\n maxTokensPerDoc: z7.number().optional(),\n priority: z7.number().optional()\n })\n )\n);\n\n// src/reranking/cohere-reranking-model.ts\nvar CohereRerankingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n // current implementation is based on v2 of the API: https://docs.cohere.com/v2/reference/rerank\n async doRerank({\n documents,\n headers,\n query,\n topN,\n abortSignal,\n providerOptions\n }) {\n var _a;\n const rerankingOptions = await parseProviderOptions3({\n provider: \"cohere\",\n providerOptions,\n schema: cohereRerankingModelOptionsSchema\n });\n const warnings = [];\n if (documents.type === \"object\") {\n warnings.push({\n type: \"compatibility\",\n feature: \"object documents\",\n details: \"Object documents are converted to strings.\"\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi3({\n url: `${this.config.baseURL}/rerank`,\n headers: combineHeaders3(this.config.headers(), headers),\n body: {\n model: this.modelId,\n query,\n documents: documents.type === \"text\" ? documents.values : documents.values.map((value) => JSON.stringify(value)),\n top_n: topN,\n max_tokens_per_doc: rerankingOptions == null ? void 0 : rerankingOptions.maxTokensPerDoc,\n priority: rerankingOptions == null ? void 0 : rerankingOptions.priority\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler3(\n cohereRerankingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n ranking: response.results.map((result) => ({\n index: result.index,\n relevanceScore: result.relevance_score\n })),\n warnings,\n response: {\n id: (_a = response.id) != null ? _a : void 0,\n headers: responseHeaders,\n body: rawValue\n }\n };\n }\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.27\" : \"0.0.0-test\";\n\n// src/cohere-provider.ts\nfunction createCohere(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.cohere.com/v2\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"COHERE_API_KEY\",\n description: \"Cohere\"\n })}`,\n ...options.headers\n },\n `ai-sdk/cohere/${VERSION}`\n );\n const createChatModel = (modelId) => {\n var _a2;\n return new CohereChatLanguageModel(modelId, {\n provider: \"cohere.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: (_a2 = options.generateId) != null ? _a2 : generateId\n });\n };\n const createEmbeddingModel = (modelId) => new CohereEmbeddingModel(modelId, {\n provider: \"cohere.textEmbedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createRerankingModel = (modelId) => new CohereRerankingModel(modelId, {\n provider: \"cohere.reranking\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Cohere model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.reranking = createRerankingModel;\n provider.rerankingModel = createRerankingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar cohere = createCohere();\nexport {\n VERSION,\n cohere,\n createCohere\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";kYAuBA,SAAI,OAA6B,OAAE,YAAO,MASxC,cAAU,EAAE,OAAO,CACjB,KAAM,EAAE,KAAK,CAAC,UAAW,UAAU,CAAC,EAAE,SAAS,EAC/C,YAAa,EAAE,OAAO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||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-error.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-io.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/auth-config.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/oauth.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/auth-errors.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-util.js"], | ||
| "sourcesContent": [ | ||
| "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_error_exports = {};\n__export(token_error_exports, {\n VercelOidcTokenError: () => VercelOidcTokenError\n});\nmodule.exports = __toCommonJS(token_error_exports);\nclass VercelOidcTokenError extends Error {\n constructor(message, cause) {\n super(message);\n this.name = \"VercelOidcTokenError\";\n this.cause = cause;\n }\n toString() {\n if (this.cause) {\n return `${this.name}: ${this.message}: ${this.cause}`;\n }\n return `${this.name}: ${this.message}`;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n VercelOidcTokenError\n});\n", | ||
| "\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_io_exports = {};\n__export(token_io_exports, {\n findRootDir: () => findRootDir,\n getUserDataDir: () => getUserDataDir\n});\nmodule.exports = __toCommonJS(token_io_exports);\nvar import_path = __toESM(require(\"path\"));\nvar import_fs = __toESM(require(\"fs\"));\nvar import_os = __toESM(require(\"os\"));\nvar import_token_error = require(\"./token-error\");\nfunction findRootDir() {\n try {\n let dir = process.cwd();\n while (dir !== import_path.default.dirname(dir)) {\n const pkgPath = import_path.default.join(dir, \".vercel\");\n if (import_fs.default.existsSync(pkgPath)) {\n return dir;\n }\n dir = import_path.default.dirname(dir);\n }\n } catch (e) {\n throw new import_token_error.VercelOidcTokenError(\n \"Token refresh only supported in node server environments\"\n );\n }\n return null;\n}\nfunction getUserDataDir() {\n if (process.env.XDG_DATA_HOME) {\n return process.env.XDG_DATA_HOME;\n }\n switch (import_os.default.platform()) {\n case \"darwin\":\n return import_path.default.join(import_os.default.homedir(), \"Library/Application Support\");\n case \"linux\":\n return import_path.default.join(import_os.default.homedir(), \".local/share\");\n case \"win32\":\n if (process.env.LOCALAPPDATA) {\n return process.env.LOCALAPPDATA;\n }\n return null;\n default:\n return null;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n findRootDir,\n getUserDataDir\n});\n", | ||
| "\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar auth_config_exports = {};\n__export(auth_config_exports, {\n isValidAccessToken: () => isValidAccessToken,\n readAuthConfig: () => readAuthConfig,\n writeAuthConfig: () => writeAuthConfig\n});\nmodule.exports = __toCommonJS(auth_config_exports);\nvar fs = __toESM(require(\"fs\"));\nvar path = __toESM(require(\"path\"));\nvar import_token_util = require(\"./token-util\");\nfunction getAuthConfigPath() {\n const dataDir = (0, import_token_util.getVercelDataDir)();\n if (!dataDir) {\n throw new Error(\n `Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`\n );\n }\n return path.join(dataDir, \"auth.json\");\n}\nfunction readAuthConfig() {\n try {\n const authPath = getAuthConfigPath();\n if (!fs.existsSync(authPath)) {\n return null;\n }\n const content = fs.readFileSync(authPath, \"utf8\");\n if (!content) {\n return null;\n }\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n}\nfunction writeAuthConfig(config) {\n const authPath = getAuthConfigPath();\n const authDir = path.dirname(authPath);\n if (!fs.existsSync(authDir)) {\n fs.mkdirSync(authDir, { mode: 504, recursive: true });\n }\n fs.writeFileSync(authPath, JSON.stringify(config, null, 2), { mode: 384 });\n}\nfunction isValidAccessToken(authConfig, expirationBufferMs = 0) {\n if (!authConfig.token)\n return false;\n if (typeof authConfig.expiresAt !== \"number\")\n return true;\n const nowInSeconds = Math.floor(Date.now() / 1e3);\n const bufferInSeconds = expirationBufferMs / 1e3;\n return authConfig.expiresAt >= nowInSeconds + bufferInSeconds;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n isValidAccessToken,\n readAuthConfig,\n writeAuthConfig\n});\n", | ||
| "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar oauth_exports = {};\n__export(oauth_exports, {\n processTokenResponse: () => processTokenResponse,\n refreshTokenRequest: () => refreshTokenRequest\n});\nmodule.exports = __toCommonJS(oauth_exports);\nvar import_os = require(\"os\");\nconst VERCEL_ISSUER = \"https://vercel.com\";\nconst VERCEL_CLI_CLIENT_ID = \"cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp\";\nconst userAgent = `@vercel/oidc node-${process.version} ${(0, import_os.platform)()} (${(0, import_os.arch)()}) ${(0, import_os.hostname)()}`;\nlet _tokenEndpoint = null;\nasync function getTokenEndpoint() {\n if (_tokenEndpoint) {\n return _tokenEndpoint;\n }\n const discoveryUrl = `${VERCEL_ISSUER}/.well-known/openid-configuration`;\n const response = await fetch(discoveryUrl, {\n headers: { \"user-agent\": userAgent }\n });\n if (!response.ok) {\n throw new Error(\"Failed to discover OAuth endpoints\");\n }\n const metadata = await response.json();\n if (!metadata || typeof metadata.token_endpoint !== \"string\") {\n throw new Error(\"Invalid OAuth discovery response\");\n }\n const endpoint = metadata.token_endpoint;\n _tokenEndpoint = endpoint;\n return endpoint;\n}\nasync function refreshTokenRequest(options) {\n const tokenEndpoint = await getTokenEndpoint();\n return await fetch(tokenEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"user-agent\": userAgent\n },\n body: new URLSearchParams({\n client_id: VERCEL_CLI_CLIENT_ID,\n grant_type: \"refresh_token\",\n ...options\n })\n });\n}\nasync function processTokenResponse(response) {\n const json = await response.json();\n if (!response.ok) {\n const errorMsg = typeof json === \"object\" && json && \"error\" in json ? String(json.error) : \"Token refresh failed\";\n return [new Error(errorMsg)];\n }\n if (typeof json !== \"object\" || json === null) {\n return [new Error(\"Invalid token response\")];\n }\n if (typeof json.access_token !== \"string\") {\n return [new Error(\"Missing access_token in response\")];\n }\n if (json.token_type !== \"Bearer\") {\n return [new Error(\"Invalid token_type in response\")];\n }\n if (typeof json.expires_in !== \"number\") {\n return [new Error(\"Missing expires_in in response\")];\n }\n return [null, json];\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n processTokenResponse,\n refreshTokenRequest\n});\n", | ||
| "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar auth_errors_exports = {};\n__export(auth_errors_exports, {\n AccessTokenMissingError: () => AccessTokenMissingError,\n RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError\n});\nmodule.exports = __toCommonJS(auth_errors_exports);\nclass AccessTokenMissingError extends Error {\n constructor() {\n super(\n \"No authentication found. Please log in with the Vercel CLI (vercel login).\"\n );\n this.name = \"AccessTokenMissingError\";\n }\n}\nclass RefreshAccessTokenFailedError extends Error {\n constructor(cause) {\n super(\"Failed to refresh authentication token.\", { cause });\n this.name = \"RefreshAccessTokenFailedError\";\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n AccessTokenMissingError,\n RefreshAccessTokenFailedError\n});\n", | ||
| "\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_util_exports = {};\n__export(token_util_exports, {\n assertVercelOidcTokenResponse: () => assertVercelOidcTokenResponse,\n findProjectInfo: () => findProjectInfo,\n getTokenPayload: () => getTokenPayload,\n getVercelDataDir: () => getVercelDataDir,\n getVercelOidcToken: () => getVercelOidcToken,\n getVercelToken: () => getVercelToken,\n isExpired: () => isExpired,\n loadToken: () => loadToken,\n saveToken: () => saveToken\n});\nmodule.exports = __toCommonJS(token_util_exports);\nvar path = __toESM(require(\"path\"));\nvar fs = __toESM(require(\"fs\"));\nvar import_token_error = require(\"./token-error\");\nvar import_token_io = require(\"./token-io\");\nvar import_auth_config = require(\"./auth-config\");\nvar import_oauth = require(\"./oauth\");\nvar import_auth_errors = require(\"./auth-errors\");\nfunction getVercelDataDir() {\n const vercelFolder = \"com.vercel.cli\";\n const dataDir = (0, import_token_io.getUserDataDir)();\n if (!dataDir) {\n return null;\n }\n return path.join(dataDir, vercelFolder);\n}\nasync function getVercelToken(options) {\n const authConfig = (0, import_auth_config.readAuthConfig)();\n if (!authConfig?.token) {\n throw new import_auth_errors.AccessTokenMissingError();\n }\n if ((0, import_auth_config.isValidAccessToken)(authConfig, options?.expirationBufferMs)) {\n return authConfig.token;\n }\n if (!authConfig.refreshToken) {\n (0, import_auth_config.writeAuthConfig)({});\n throw new import_auth_errors.RefreshAccessTokenFailedError(\"No refresh token available\");\n }\n try {\n const tokenResponse = await (0, import_oauth.refreshTokenRequest)({\n refresh_token: authConfig.refreshToken\n });\n const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse);\n if (tokensError || !tokens) {\n (0, import_auth_config.writeAuthConfig)({});\n throw new import_auth_errors.RefreshAccessTokenFailedError(tokensError);\n }\n const updatedConfig = {\n token: tokens.access_token,\n expiresAt: Math.floor(Date.now() / 1e3) + tokens.expires_in\n };\n if (tokens.refresh_token) {\n updatedConfig.refreshToken = tokens.refresh_token;\n }\n (0, import_auth_config.writeAuthConfig)(updatedConfig);\n return updatedConfig.token;\n } catch (error) {\n (0, import_auth_config.writeAuthConfig)({});\n if (error instanceof import_auth_errors.AccessTokenMissingError || error instanceof import_auth_errors.RefreshAccessTokenFailedError) {\n throw error;\n }\n throw new import_auth_errors.RefreshAccessTokenFailedError(error);\n }\n}\nasync function getVercelOidcToken(authToken, projectId, teamId) {\n const url = `https://api.vercel.com/v1/projects/${projectId}/token?source=vercel-oidc-refresh${teamId ? `&teamId=${teamId}` : \"\"}`;\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${authToken}`\n }\n });\n if (!res.ok) {\n throw new import_token_error.VercelOidcTokenError(\n `Failed to refresh OIDC token: ${res.statusText}`\n );\n }\n const tokenRes = await res.json();\n assertVercelOidcTokenResponse(tokenRes);\n return tokenRes;\n}\nfunction assertVercelOidcTokenResponse(res) {\n if (!res || typeof res !== \"object\") {\n throw new TypeError(\n \"Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again\"\n );\n }\n if (!(\"token\" in res) || typeof res.token !== \"string\") {\n throw new TypeError(\n \"Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again\"\n );\n }\n}\nfunction findProjectInfo() {\n const dir = (0, import_token_io.findRootDir)();\n if (!dir) {\n throw new import_token_error.VercelOidcTokenError(\n \"Unable to find project root directory. Have you linked your project with `vc link?`\"\n );\n }\n const prjPath = path.join(dir, \".vercel\", \"project.json\");\n if (!fs.existsSync(prjPath)) {\n throw new import_token_error.VercelOidcTokenError(\n \"project.json not found, have you linked your project with `vc link?`\"\n );\n }\n const prj = JSON.parse(fs.readFileSync(prjPath, \"utf8\"));\n if (typeof prj.projectId !== \"string\" && typeof prj.orgId !== \"string\") {\n throw new TypeError(\n \"Expected a string-valued projectId property. Try running `vc link` to re-link your project.\"\n );\n }\n return { projectId: prj.projectId, teamId: prj.orgId };\n}\nfunction saveToken(token, projectId) {\n const dir = (0, import_token_io.getUserDataDir)();\n if (!dir) {\n throw new import_token_error.VercelOidcTokenError(\n \"Unable to find user data directory. Please reach out to Vercel support.\"\n );\n }\n const tokenPath = path.join(dir, \"com.vercel.token\", `${projectId}.json`);\n const tokenJson = JSON.stringify(token);\n fs.mkdirSync(path.dirname(tokenPath), { mode: 504, recursive: true });\n fs.writeFileSync(tokenPath, tokenJson);\n fs.chmodSync(tokenPath, 432);\n return;\n}\nfunction loadToken(projectId) {\n const dir = (0, import_token_io.getUserDataDir)();\n if (!dir) {\n throw new import_token_error.VercelOidcTokenError(\n \"Unable to find user data directory. Please reach out to Vercel support.\"\n );\n }\n const tokenPath = path.join(dir, \"com.vercel.token\", `${projectId}.json`);\n if (!fs.existsSync(tokenPath)) {\n return null;\n }\n const token = JSON.parse(fs.readFileSync(tokenPath, \"utf8\"));\n assertVercelOidcTokenResponse(token);\n return token;\n}\nfunction getTokenPayload(token) {\n const tokenParts = token.split(\".\");\n if (tokenParts.length !== 3) {\n throw new import_token_error.VercelOidcTokenError(\n \"Invalid token. Please run `vc env pull` and try again\"\n );\n }\n const base64 = tokenParts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + (4 - base64.length % 4) % 4,\n \"=\"\n );\n return JSON.parse(Buffer.from(padded, \"base64\").toString(\"utf8\"));\n}\nfunction isExpired(token, bufferMs = 0) {\n return token.exp * 1e3 < Date.now() + bufferMs;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n assertVercelOidcTokenResponse,\n findProjectInfo,\n getTokenPayload,\n getVercelDataDir,\n getVercelOidcToken,\n getVercelToken,\n isExpired,\n loadToken,\n saveToken\n});\n" | ||
| ], | ||
| "mappings": ";6EACA,IAAuB,eAAnB,EAC0B,yBAA1B,GAC2B,oBAA3B,IADmB,OAEnB,GAAe,OAAO,UAAU,eAChC,GAAW,CAAC,EAAQ,IAAQ,CAC9B,QAAS,KAAQ,EACf,EAAU,EAAQ,EAAM,CAAE,IAAK,EAAI,GAAO,WAAY,EAAK,CAAC,GAE5D,GAAc,CAAC,EAAI,EAAM,EAAQ,IAAS,CAC5C,GAAI,GAAQ,OAAO,IAAS,UAAY,OAAO,IAAS,YACtD,QAAS,KAAO,GAAkB,CAAI,EACpC,GAAI,CAAC,GAAa,KAAK,EAAI,CAAG,GAAK,IAAQ,EACzC,EAAU,EAAI,EAAK,CAAE,IAAK,IAAM,EAAK,GAAM,WAAY,EAAE,EAAO,GAAiB,EAAM,CAAG,IAAM,EAAK,UAAW,CAAC,EAEvH,OAAO,GAEL,GAAe,CAAC,IAAQ,GAAY,EAAU,CAAC,EAAG,aAAc,CAAE,MAAO,EAAK,CAAC,EAAG,CAAG,EACrF,EAAsB,CAAC,EAC3B,GAAS,EAAqB,CAC5B,qBAAsB,IAAM,CAC9B,CAAC,EACD,EAAO,QAAU,GAAa,CAAmB,EACjD,MAAM,UAA6B,KAAM,CACvC,WAAW,CAAC,EAAS,EAAO,CAC1B,MAAM,CAAO,EACb,KAAK,KAAO,uBACZ,KAAK,MAAQ,EAEf,QAAQ,EAAG,CACT,GAAI,KAAK,MACP,MAAO,GAAG,KAAK,SAAS,KAAK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AEF,IAAM,EAAY,EAAK,KAAK,EAAK,mBAAoB,GAAG,QAAgB,EAClE,EAAY,KAAK,UAAU,CAAK,EACtC,EAAG,UAAU,EAAK,QAAQ,CAAS,EAAG,CAAE,KAAM,IAAK,UAAW,EAAK,CAAC,EACpE,EAAG,cAAc,EAAW,CAAS,EACrC,EAAG,UAAU,EAAW,GAAG,EAC3B,OAEF,SAAS,EAAS,CAAC,EAAW,CAC5B,IAAM,GAAO,EAAG,EAAgB,gBAAgB,EAChD,GAAI,CAAC,EACH,MAAM,IAAI,EAAmB,qBAC3B,yEACF,EAEF,IAAM,EAAY,EAAK,KAAK,EAAK,mBAAoB,GAAG,QAAgB,EACxE,GAAI,CAAC,EAAG,WAAW,CAAS,EAC1B,OAAO,KAET,IAAM,EAAQ,KAAK,MAAM,EAAG,aAAa,EAAW,MAAM,CAAC,EAE3D,OADA,EAA8B,CAAK,EAC5B,EAET,SAAS,EAAe,CAAC,EAAO,CAC9B,IAAM,EAAa,EAAM,MAAM,GAAG,EAClC,GAAI,EAAW,SAAW,EACxB,MAAM,IAAI,EAAmB,qBAC3B,uDACF,EAEF,IAAM,EAAS,EAAW,GAAG,QAAQ,KAAM,GAAG,EAAE,QAAQ,KAAM,GAAG,EAC3D,EAAS,EAAO,OACpB,EAAO,QAAU,EAAI,EAAO,OAAS,GAAK,EAC1C,GACF,EACA,OAAO,KAAK,MAAM,OAAO,KAAK,EAAQ,QAAQ,EAAE,SAAS,MAAM,CAAC,EAElE,SAAS,EAAS,CAAC,EAAO,EAAW,EAAG,CACtC,OAAO,EAAM,IAAM,KAAM,KAAK,IAAI,EAAI", | ||
| "debugId": "8D7D9B12706228B064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.3/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.3/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.3/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/constants.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.3/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js"], | ||
| "sourcesContent": [ | ||
| "import { CredentialsProviderError, getProfileName, loadSsoSessionData, parseKnownFiles } from \"@smithy/core/config\";\nimport { isSsoProfile } from \"./isSsoProfile\";\nimport { resolveSSOCredentials } from \"./resolveSSOCredentials\";\nimport { validateSsoProfile } from \"./validateSsoProfile\";\nexport const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-sso - fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n const { ssoClient } = init;\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n const profiles = await parseKnownFiles(init);\n const profile = profiles[profileName];\n if (!profile) {\n throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger });\n }\n if (!isSsoProfile(profile)) {\n throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {\n logger: init.logger,\n });\n }\n if (profile?.sso_session) {\n const ssoSessions = await loadSsoSessionData(init);\n const session = ssoSessions[profile.sso_session];\n const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;\n if (ssoRegion && ssoRegion !== session.sso_region) {\n throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {\n throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n profile.sso_region = session.sso_region;\n profile.sso_start_url = session.sso_start_url;\n }\n const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger);\n return resolveSSOCredentials({\n ssoStartUrl: sso_start_url,\n ssoSession: sso_session,\n ssoAccountId: sso_account_id,\n ssoRegion: sso_region,\n ssoRoleName: sso_role_name,\n ssoClient: ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {\n throw new CredentialsProviderError(\"Incomplete configuration. The fromSSO() argument hash must include \" +\n '\"ssoStartUrl\", \"ssoAccountId\", \"ssoRegion\", \"ssoRoleName\"', { tryNextLink: false, logger: init.logger });\n }\n else {\n return resolveSSOCredentials({\n ssoStartUrl,\n ssoSession,\n ssoAccountId,\n ssoRegion,\n ssoRoleName,\n ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n};\n", | ||
| "export const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromSso as getSsoTokenProvider } from \"@aws-sdk/token-providers\";\nimport { CredentialsProviderError, getSSOTokenFromFile } from \"@smithy/core/config\";\nconst SHOULD_FAIL_CREDENTIAL_CHAIN = false;\nexport const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => {\n let token;\n const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;\n if (ssoSession) {\n try {\n const _token = await getSsoTokenProvider({\n profile,\n filepath,\n configFilepath,\n ignoreCache,\n clientConfig,\n parentClientConfig,\n logger,\n })({ callerClientConfig });\n token = {\n accessToken: _token.token,\n expiresAt: new Date(_token.expiration).toISOString(),\n };\n }\n catch (e) {\n throw new CredentialsProviderError(e.message, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n else {\n try {\n token = await getSSOTokenFromFile(ssoStartUrl);\n }\n catch (e) {\n throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {\n throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { accessToken } = token;\n const { SSOClient, GetRoleCredentialsCommand } = await import(\"./loadSso.js\");\n const sso = ssoClient ||\n new SSOClient(Object.assign({}, clientConfig ?? {}, {\n logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger,\n region: clientConfig?.region ?? ssoRegion,\n userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId,\n }));\n let ssoResp;\n try {\n ssoResp = await sso.send(new GetRoleCredentialsCommand({\n accountId: ssoAccountId,\n roleName: ssoRoleName,\n accessToken,\n }));\n }\n catch (e) {\n throw new CredentialsProviderError(e, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp;\n if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {\n throw new CredentialsProviderError(\"SSO returns an invalid temporary credential.\", {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const credentials = {\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiration: new Date(expiration),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n if (ssoSession) {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO\", \"s\");\n }\n else {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO_LEGACY\", \"u\");\n }\n return credentials;\n};\n", | ||
| "import { getProfileName, getSSOTokenFromFile, loadSsoSessionData, parseKnownFiles, TokenProviderError, } from \"@smithy/core/config\";\nimport { EXPIRE_WINDOW_MS, REFRESH_MESSAGE } from \"./constants\";\nimport { getNewSsoOidcToken } from \"./getNewSsoOidcToken\";\nimport { validateTokenExpiry } from \"./validateTokenExpiry\";\nimport { validateTokenKey } from \"./validateTokenKey\";\nimport { writeSSOTokenToFile } from \"./writeSSOTokenToFile\";\nconst lastRefreshAttemptTime = new Date(0);\nexport const fromSso = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/token-providers - fromSso\");\n const profiles = await parseKnownFiles(init);\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile) {\n throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);\n }\n else if (!profile[\"sso_session\"]) {\n throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);\n }\n const ssoSessionName = profile[\"sso_session\"];\n const ssoSessions = await loadSsoSessionData(init);\n const ssoSession = ssoSessions[ssoSessionName];\n if (!ssoSession) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);\n }\n for (const ssoSessionRequiredKey of [\"sso_start_url\", \"sso_region\"]) {\n if (!ssoSession[ssoSessionRequiredKey]) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);\n }\n }\n const ssoStartUrl = ssoSession[\"sso_start_url\"];\n const ssoRegion = ssoSession[\"sso_region\"];\n let ssoToken;\n try {\n ssoToken = await getSSOTokenFromFile(ssoSessionName);\n }\n catch (e) {\n throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);\n }\n validateTokenKey(\"accessToken\", ssoToken.accessToken);\n validateTokenKey(\"expiresAt\", ssoToken.expiresAt);\n const { accessToken, expiresAt } = ssoToken;\n const existingToken = { token: accessToken, expiration: new Date(expiresAt) };\n if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {\n return existingToken;\n }\n if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n validateTokenKey(\"clientId\", ssoToken.clientId, true);\n validateTokenKey(\"clientSecret\", ssoToken.clientSecret, true);\n validateTokenKey(\"refreshToken\", ssoToken.refreshToken, true);\n try {\n lastRefreshAttemptTime.setTime(Date.now());\n const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig);\n validateTokenKey(\"accessToken\", newSsoOidcToken.accessToken);\n validateTokenKey(\"expiresIn\", newSsoOidcToken.expiresIn);\n const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000);\n try {\n await writeSSOTokenToFile(ssoSessionName, {\n ...ssoToken,\n accessToken: newSsoOidcToken.accessToken,\n expiresAt: newTokenExpiration.toISOString(),\n refreshToken: newSsoOidcToken.refreshToken,\n });\n }\n catch (error) {\n }\n return {\n token: newSsoOidcToken.accessToken,\n expiration: newTokenExpiration,\n };\n }\n catch (error) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n};\n", | ||
| "export const EXPIRE_WINDOW_MS = 5 * 60 * 1000;\nexport const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;\n", | ||
| "export const getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => {\n const { SSOOIDCClient } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop];\n const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, {\n region: ssoRegion ?? init.clientConfig?.region,\n logger: coalesce(\"logger\"),\n userAgentAppId: coalesce(\"userAgentAppId\"),\n }));\n return ssoOidcClient;\n};\n", | ||
| "import { getSsoOidcClient } from \"./getSsoOidcClient\";\nexport const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => {\n const { CreateTokenCommand } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig);\n return ssoOidcClient.send(new CreateTokenCommand({\n clientId: ssoToken.clientId,\n clientSecret: ssoToken.clientSecret,\n refreshToken: ssoToken.refreshToken,\n grantType: \"refresh_token\",\n }));\n};\n", | ||
| "import { TokenProviderError } from \"@smithy/core/config\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenExpiry = (token) => {\n if (token.expiration && token.expiration.getTime() < Date.now()) {\n throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);\n }\n};\n", | ||
| "import { TokenProviderError } from \"@smithy/core/config\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenKey = (key, value, forRefresh = false) => {\n if (typeof value === \"undefined\") {\n throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? \". Cannot refresh\" : \"\"}. ${REFRESH_MESSAGE}`, false);\n }\n};\n", | ||
| "import { getSSOTokenFilepath } from \"@smithy/core/config\";\nimport { promises as fsPromises } from \"node:fs\";\nconst { writeFile } = fsPromises;\nexport const writeSSOTokenToFile = (id, ssoToken) => {\n const tokenFilepath = getSSOTokenFilepath(id);\n const tokenString = JSON.stringify(ssoToken, null, 2);\n return writeFile(tokenFilepath, tokenString);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nexport const validateSsoProfile = (profile, logger) => {\n const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;\n if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {\n throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters \"sso_account_id\", ` +\n `\"sso_region\", \"sso_role_name\", \"sso_start_url\". Got ${Object.keys(profile).join(\", \")}\\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger });\n }\n return profile;\n};\n" | ||
| ], | ||
| "mappings": ";4JAAA,oBCAO,SAAM,EAAe,CAAC,IAAQ,IAChC,OAAO,EAAI,gBAAkB,UAC1B,OAAO,EAAI,iBAAmB,UAC9B,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,aAAe,UAC1B,OAAO,EAAI,gBAAkB,UCLrC,gBCAA,eCAO,IAAM,EAAmB,OACnB,EAAkB,kFCDxB,IAAM,EAAmB,MAAO,EAAW,EAAO,CAAC,EAAG,IAAuB,CAChF,IAAQ,iB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D70664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/anthropic-compatible.ts", "../ai/src/providers/anthropic.ts"], | ||
| "sourcesContent": [ | ||
| "import type { ProviderPackage } from \"../provider-package\"\nimport { AnthropicMessages } from \"../protocols/anthropic-messages\"\nimport { Auth } from \"../route/auth\"\nimport type { ProviderAuthOption } from \"../route/auth-options\"\nimport type { RouteDefaultsInput } from \"../route/client\"\nimport { ProviderID, type ModelID } from \"../schema\"\n\nexport const id = ProviderID.make(\"anthropic-compatible\")\n\nexport type Config = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly provider?: string\n readonly baseURL: string\n }\n\nexport type Settings = ProviderPackage.Settings &\n (\n | { readonly apiKey?: string; readonly authToken?: never }\n | { readonly apiKey?: never; readonly authToken?: string }\n ) & {\n readonly baseURL: string\n readonly provider?: string\n }\n\nexport const routes = [AnthropicMessages.route]\n\nconst auth = (input: ProviderAuthOption<\"optional\">) => {\n if (\"auth\" in input && input.auth) return input.auth\n return Auth.optional(\"apiKey\" in input ? input.apiKey : undefined, \"apiKey\").pipe(Auth.header(\"x-api-key\"))\n}\n\nexport const configure = (input: Config) => {\n if (!input.baseURL) throw new Error(\"Anthropic-compatible providers require a baseURL\")\n const provider = input.provider ?? \"anthropic-compatible\"\n const { provider: _, baseURL, apiKey: _apiKey, auth: _auth, ...rest } = input\n const route = AnthropicMessages.route.with({\n ...rest,\n provider,\n endpoint: { baseURL },\n auth: auth(input),\n })\n return {\n id: ProviderID.make(provider),\n model: (modelID: string | ModelID) => route.model({ id: modelID }),\n configure,\n }\n}\n\nexport const provider = {\n id,\n configure,\n}\n\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) => {\n if (settings.apiKey !== undefined && settings.authToken !== undefined)\n throw new Error(\"Anthropic-compatible apiKey cannot be combined with authToken\")\n return configure({\n ...(settings.authToken === undefined ? { apiKey: settings.apiKey } : { auth: Auth.bearer(settings.authToken) }),\n baseURL: settings.baseURL,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n provider: settings.provider,\n }).model(modelID)\n}\n\nexport * as AnthropicCompatible from \"./anthropic-compatible\"\n", | ||
| "import type { RouteDefaultsInput } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport type { ProviderAuthOption } from \"../route/auth-options\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { ProviderID, type ModelID } from \"../schema\"\nimport { AnthropicMessages } from \"../protocols/anthropic-messages\"\nimport { AnthropicCompatible } from \"./anthropic-compatible\"\n\nexport const id = ProviderID.make(\"anthropic\")\n\nexport const routes = [AnthropicMessages.route]\n\nexport type Config = RouteDefaultsInput & ProviderAuthOption<\"optional\"> & { readonly baseURL?: string }\n\nexport type Settings = ProviderPackage.Settings &\n (\n | { readonly apiKey?: string; readonly authToken?: never }\n | { readonly apiKey?: never; readonly authToken?: string }\n ) & {\n readonly baseURL?: string\n }\n\nconst auth = (options: ProviderAuthOption<\"optional\">) => {\n if (\"auth\" in options && options.auth) return options.auth\n return Auth.optional(\"apiKey\" in options ? options.apiKey : undefined, \"apiKey\")\n .orElse(Auth.config(\"ANTHROPIC_API_KEY\"))\n .pipe(Auth.header(\"x-api-key\"))\n}\n\nexport const configure = (input: Config = {}) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n const compatible = AnthropicCompatible.configure({\n ...rest,\n auth: auth(input),\n baseURL: baseURL ?? AnthropicMessages.DEFAULT_BASE_URL,\n provider: id,\n })\n return {\n id,\n model: (modelID: string | ModelID) => compatible.model(modelID),\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) => {\n if (settings.apiKey !== undefined && settings.authToken !== undefined)\n throw new Error(\"Anthropic apiKey cannot be combined with authToken\")\n return configure({\n ...(settings.authToken === undefined ? { apiKey: settings.apiKey } : { auth: Auth.bearer(settings.authToken) }),\n baseURL: settings.baseURL,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n }).model(modelID)\n}\n" | ||
| ], | ||
| "mappings": ";ujBAOO,SAAM,OAAK,OAAW,UAAK,2BAAsB,OAiB3C,OAAS,MAAC,OAAkB,UAAK,OAExC,EAAO,CAAC,IAA0C,CACtD,GAAI,SAAU,GAAS,EAAM,KAAM,OAAO,EAAM,KAChD,OAAO,EAAK,SAAS,WAAY,EAAQ,EAAM,OAAS,OAAW,QAAQ,EAAE,KAAK,EAAK,OAAO,WAAW,CAAC,GAG/F,EAAY,CAAC,IAAkB,CAC1C,GAAI,CAAC,EAAM,QAAS,MAAU,MAAM,kDAAkD,EACtF,IAAM,EAAW,EAAM,UAAY,wBAC3B,SAAU,EAAG,UAAS,OAAQ,EAAS,KAAM,KAAU,GAAS,EAClE,EAAQ,EAAkB,MAAM,KAAK,IACtC,EACH,WACA,SAAU,CAAE,SAAQ,EACpB,KAAM,EAAK,CAAK,CAClB,CAAC,EACD,MAAO,CACL,GAAI,EAAW,KAAK,CAAQ,EAC5B,MAAO,CAAC,IAA8B,EAAM,MAAM,CAAE,GAAI,CAAQ,CAAC,EACjE,WACF,GAGW,EAAW,CACtB,KACA,WACF,EAEa,EAAuD,CAAC,EAAS,IAAa,CACzF,GAAI,EAAS,SAAW,QAAa,EAAS,YAAc,OAC1D,MAAU,MAAM,+DAA+D,EACjF,OAAO,EAAU,IACX,EAAS,YAAc,OAAY,CAAE,OAAQ,EAAS,MAAO,EAAI,CAAE,KAAM,EAAK,OAAO,EAAS,SAAS,CAAE,EAC7G,QAAS,EAAS,QAClB,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,OACjB,SAAU,EAAS,QACrB,CAAC,EAAE,MAAM,CAAO,GCvDX,IAAM,EAAK,EAAW,KAAK,WAAW,EAEhC,EAAS,CAAC,EAAkB,KAAK,EAYxC,EAAO,CAAC,IAA4C,CACxD,GAAI,SAAU,GAAW,EAAQ,KAAM,OAAO,EAAQ,KACtD,OAAO,EAAK,SAAS,WAAY,EAAU,EAAQ,OAAS,OAAW,QAAQ,EAC5E,OAAO,EAAK,OAAO,mBAAmB,CAAC,EACvC,KAAK,EAAK,OAAO,WAAW,CAAC,GAGrB,EAAY,CAAC,EAAgB,CAAC,IAAM,CAC/C,IAAQ,OAAQ,EAAG,KAAM,EAAO,aAAY,GAAS,EAC/C,EAAa,EAAoB,UAAU,IAC5C,EACH,KAAM,EAAK,CAAK,EAChB,QAAS,GAAW,EAAkB,iBACtC,SAAU,CACZ,CAAC,EACD,MAAO,CACL,KACA,MAAO,CAAC,IAA8B,EAAW,MAAM,CAAO,EAC9D,WACF,GAGW,EAAW,EAAU,EACrB,EAAuD,CAAC,EAAS,IAAa,CACzF,GAAI,EAAS,SAAW,QAAa,EAAS,YAAc,OAC1D,MAAU,MAAM,oDAAoD,EACtE,OAAO,EAAU,IACX,EAAS,YAAc,OAAY,CAAE,OAAQ,EAAS,MAAO,EAAI,CAAE,KAAM,EAAK,OAAO,EAAS,SAAS,CAAE,EAC7G,QAAS,EAAS,QAClB,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,MACnB,CAAC,EAAE,MAAM,CAAO", | ||
| "debugId": "F8854DF1FC53DC4B64756E2164756E21", | ||
| "names": [] | ||
| } |
+1
-1
| { | ||
| "name": "@opencode-ai/cli-linux-x64", | ||
| "version": "0.0.0-next-16023", | ||
| "version": "0.0.0-next-16027", | ||
| "license": "MIT", | ||
@@ -5,0 +5,0 @@ "repository": { |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/openai-options.ts"], | ||
| "sourcesContent": [ | ||
| "import type { ProviderOptions, ReasoningEffort, TextVerbosity } from \"../schema\"\nimport { mergeProviderOptions } from \"../schema\"\nimport type { OpenAIResponseIncludable, OpenAIServiceTier } from \"../protocols/utils/openai-options\"\n\nexport type { OpenAIResponseIncludable, OpenAIServiceTier } from \"../protocols/utils/openai-options\"\n\nexport interface OpenAIOptionsInput {\n readonly [key: string]: unknown\n readonly store?: boolean\n readonly promptCacheKey?: string\n readonly reasoningEffort?: ReasoningEffort\n readonly reasoningSummary?: \"auto\"\n // OpenAI Responses `include` wire field. Mirrors the official SDK's\n // `ResponseIncludable[]` union exactly so AI SDK callers and direct\n // native-SDK callers share one shape and no translation is required.\n readonly include?: ReadonlyArray<OpenAIResponseIncludable>\n readonly textVerbosity?: TextVerbosity\n readonly serviceTier?: OpenAIServiceTier\n}\n\nexport type OpenAIProviderOptionsInput = ProviderOptions & {\n readonly openai?: OpenAIOptionsInput\n}\n\nconst definedEntries = (input: Record<string, unknown>) =>\n Object.entries(input).filter((entry) => entry[1] !== undefined)\n\nconst openAIProviderOptions = (options: OpenAIOptionsInput | undefined): ProviderOptions | undefined => {\n const openai = Object.fromEntries(\n definedEntries({\n store: options?.store,\n promptCacheKey: options?.promptCacheKey,\n reasoningEffort: options?.reasoningEffort,\n reasoningSummary: options?.reasoningSummary,\n include: options?.include,\n textVerbosity: options?.textVerbosity,\n serviceTier: options?.serviceTier,\n }),\n )\n if (Object.keys(openai).length === 0) return undefined\n return { openai }\n}\n\nexport const gpt5DefaultOptions = (\n modelID: string,\n options: { readonly textVerbosity?: boolean } = {},\n): ProviderOptions | undefined => {\n const id = modelID.toLowerCase()\n if (!id.includes(\"gpt-5\") || id.includes(\"gpt-5-chat\") || id.includes(\"gpt-5-pro\")) return undefined\n return openAIProviderOptions({\n reasoningEffort: \"medium\",\n reasoningSummary: \"auto\",\n // GPT-5 reasoning models are configured stateless (`store: false`) by\n // `openAIDefaultOptions` below, so the only way a follow-up turn can\n // carry reasoning state is via the encrypted reasoning include. Without\n // this, callers using the default model facade get reasoning summaries\n // they cannot replay statelessly.\n include: [\"reasoning.encrypted_content\"],\n textVerbosity:\n options.textVerbosity === true && id.includes(\"gpt-5.\") && !id.includes(\"codex\") && !id.includes(\"-chat\")\n ? \"low\"\n : undefined,\n })\n}\n\nexport const openAIDefaultOptions = (\n modelID: string,\n options: { readonly textVerbosity?: boolean } = {},\n): ProviderOptions | undefined =>\n mergeProviderOptions(openAIProviderOptions({ store: false }), gpt5DefaultOptions(modelID, options))\n\nexport const withOpenAIOptions = <Options extends { readonly providerOptions?: OpenAIProviderOptionsInput }>(\n modelID: string,\n options: Options,\n defaults: { readonly textVerbosity?: boolean } = {},\n): Omit<Options, \"providerOptions\"> & { readonly providerOptions?: ProviderOptions } => {\n return {\n ...options,\n providerOptions: mergeProviderOptions(openAIDefaultOptions(modelID, defaults), options.providerOptions),\n }\n}\n\nexport * as OpenAIProviderOptions from \"./openai-options\"\n" | ||
| ], | ||
| "mappings": ";oDAwBA,IAAM,EAAiB,CAAC,IACtB,OAAO,QAAQ,CAAK,EAAE,OAAO,CAAC,IAAU,EAAM,KAAO,MAAS,EAE1D,EAAwB,CAAC,IAAyE,CACtG,IAAM,EAAS,OAAO,YACpB,EAAe,CACb,MAAO,GAAS,MAChB,eAAgB,GAAS,eACzB,gBAAiB,GAAS,gBAC1B,iBAAkB,GAAS,iBAC3B,QAAS,GAAS,QAClB,cAAe,GAAS,cACxB,YAAa,GAAS,WACxB,CAAC,CACH,EACA,GAAI,OAAO,KAAK,CAAM,EAAE,SAAW,EAAG,OACtC,MAAO,CAAE,QAAO,GAGL,EAAqB,CAChC,EACA,EAAgD,CAAC,IACjB,CAChC,IAAM,EAAK,EAAQ,YAAY,EAC/B,GAAI,CAAC,EAAG,SAAS,OAAO,GAAK,EAAG,SAAS,YAAY,GAAK,EAAG,SAAS,WAAW,EAAG,OACpF,OAAO,EAAsB,CAC3B,gBAAiB,SACjB,iBAAkB,OAMlB,QAAS,CAAC,6BAA6B,EACvC,cACE,EAAQ,gBAAkB,IAAQ,EAAG,SAAS,QAAQ,GAAK,CAAC,EAAG,SAAS,OAAO,GAAK,CAAC,EAAG,SAAS,OAAO,EACpG,MACA,MACR,CAAC,GAGU,EAAuB,CAClC,EACA,EAAgD,CAAC,IAEjD,EAAqB,EAAsB,CAAE,MAAO,EAAM,CAAC,EAAG,EAAmB,EAAS,CAAO,CAAC,EAEvF,EAAoB,CAC/B,EACA,EACA,EAAiD,CAAC,IACoC,CACtF,MAAO,IACF,EACH,gBAAiB,EAAqB,EAAqB,EAAS,CAAQ,EAAG,EAAQ,eAAe,CACxG", | ||
| "debugId": "F00983A5F194B1CF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/restart.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.restart,\n Effect.fn(\"cli.service.restart\")(function* () {\n const options = yield* ServiceConfig.options()\n yield* Service.stop(options)\n const transport = yield* Service.ensure(options)\n process.stdout.write(transport.url + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+0BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,aACnC,OAAO,QAAG,0BAAqB,OAAE,cAAU,OAAG,MAC5C,SAAM,OAAU,WAAO,OAAc,aAAQ,EAC7C,MAAO,EAAQ,KAAK,CAAO,EAC3B,IAAM,EAAY,MAAO,EAAQ,OAAO,CAAO,EAC/C,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "980F38570B29248F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.3/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.3/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.3/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/constants.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1088.0/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.3/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js"], | ||
| "sourcesContent": [ | ||
| "import { CredentialsProviderError, getProfileName, loadSsoSessionData, parseKnownFiles } from \"@smithy/core/config\";\nimport { isSsoProfile } from \"./isSsoProfile\";\nimport { resolveSSOCredentials } from \"./resolveSSOCredentials\";\nimport { validateSsoProfile } from \"./validateSsoProfile\";\nexport const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-sso - fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n const { ssoClient } = init;\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n const profiles = await parseKnownFiles(init);\n const profile = profiles[profileName];\n if (!profile) {\n throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger });\n }\n if (!isSsoProfile(profile)) {\n throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {\n logger: init.logger,\n });\n }\n if (profile?.sso_session) {\n const ssoSessions = await loadSsoSessionData(init);\n const session = ssoSessions[profile.sso_session];\n const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;\n if (ssoRegion && ssoRegion !== session.sso_region) {\n throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {\n throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n profile.sso_region = session.sso_region;\n profile.sso_start_url = session.sso_start_url;\n }\n const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger);\n return resolveSSOCredentials({\n ssoStartUrl: sso_start_url,\n ssoSession: sso_session,\n ssoAccountId: sso_account_id,\n ssoRegion: sso_region,\n ssoRoleName: sso_role_name,\n ssoClient: ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {\n throw new CredentialsProviderError(\"Incomplete configuration. The fromSSO() argument hash must include \" +\n '\"ssoStartUrl\", \"ssoAccountId\", \"ssoRegion\", \"ssoRoleName\"', { tryNextLink: false, logger: init.logger });\n }\n else {\n return resolveSSOCredentials({\n ssoStartUrl,\n ssoSession,\n ssoAccountId,\n ssoRegion,\n ssoRoleName,\n ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n};\n", | ||
| "export const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromSso as getSsoTokenProvider } from \"@aws-sdk/token-providers\";\nimport { CredentialsProviderError, getSSOTokenFromFile } from \"@smithy/core/config\";\nconst SHOULD_FAIL_CREDENTIAL_CHAIN = false;\nexport const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => {\n let token;\n const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;\n if (ssoSession) {\n try {\n const _token = await getSsoTokenProvider({\n profile,\n filepath,\n configFilepath,\n ignoreCache,\n clientConfig,\n parentClientConfig,\n logger,\n })({ callerClientConfig });\n token = {\n accessToken: _token.token,\n expiresAt: new Date(_token.expiration).toISOString(),\n };\n }\n catch (e) {\n throw new CredentialsProviderError(e.message, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n else {\n try {\n token = await getSSOTokenFromFile(ssoStartUrl);\n }\n catch (e) {\n throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {\n throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { accessToken } = token;\n const { SSOClient, GetRoleCredentialsCommand } = await import(\"./loadSso.js\");\n const sso = ssoClient ||\n new SSOClient(Object.assign({}, clientConfig ?? {}, {\n logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger,\n region: clientConfig?.region ?? ssoRegion,\n userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId,\n }));\n let ssoResp;\n try {\n ssoResp = await sso.send(new GetRoleCredentialsCommand({\n accountId: ssoAccountId,\n roleName: ssoRoleName,\n accessToken,\n }));\n }\n catch (e) {\n throw new CredentialsProviderError(e, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp;\n if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {\n throw new CredentialsProviderError(\"SSO returns an invalid temporary credential.\", {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const credentials = {\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiration: new Date(expiration),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n if (ssoSession) {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO\", \"s\");\n }\n else {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO_LEGACY\", \"u\");\n }\n return credentials;\n};\n", | ||
| "import { getProfileName, getSSOTokenFromFile, loadSsoSessionData, parseKnownFiles, TokenProviderError, } from \"@smithy/core/config\";\nimport { EXPIRE_WINDOW_MS, REFRESH_MESSAGE } from \"./constants\";\nimport { getNewSsoOidcToken } from \"./getNewSsoOidcToken\";\nimport { validateTokenExpiry } from \"./validateTokenExpiry\";\nimport { validateTokenKey } from \"./validateTokenKey\";\nimport { writeSSOTokenToFile } from \"./writeSSOTokenToFile\";\nconst lastRefreshAttemptTime = new Date(0);\nexport const fromSso = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/token-providers - fromSso\");\n const profiles = await parseKnownFiles(init);\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile) {\n throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);\n }\n else if (!profile[\"sso_session\"]) {\n throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);\n }\n const ssoSessionName = profile[\"sso_session\"];\n const ssoSessions = await loadSsoSessionData(init);\n const ssoSession = ssoSessions[ssoSessionName];\n if (!ssoSession) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);\n }\n for (const ssoSessionRequiredKey of [\"sso_start_url\", \"sso_region\"]) {\n if (!ssoSession[ssoSessionRequiredKey]) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);\n }\n }\n const ssoStartUrl = ssoSession[\"sso_start_url\"];\n const ssoRegion = ssoSession[\"sso_region\"];\n let ssoToken;\n try {\n ssoToken = await getSSOTokenFromFile(ssoSessionName);\n }\n catch (e) {\n throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);\n }\n validateTokenKey(\"accessToken\", ssoToken.accessToken);\n validateTokenKey(\"expiresAt\", ssoToken.expiresAt);\n const { accessToken, expiresAt } = ssoToken;\n const existingToken = { token: accessToken, expiration: new Date(expiresAt) };\n if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {\n return existingToken;\n }\n if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n validateTokenKey(\"clientId\", ssoToken.clientId, true);\n validateTokenKey(\"clientSecret\", ssoToken.clientSecret, true);\n validateTokenKey(\"refreshToken\", ssoToken.refreshToken, true);\n try {\n lastRefreshAttemptTime.setTime(Date.now());\n const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig);\n validateTokenKey(\"accessToken\", newSsoOidcToken.accessToken);\n validateTokenKey(\"expiresIn\", newSsoOidcToken.expiresIn);\n const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000);\n try {\n await writeSSOTokenToFile(ssoSessionName, {\n ...ssoToken,\n accessToken: newSsoOidcToken.accessToken,\n expiresAt: newTokenExpiration.toISOString(),\n refreshToken: newSsoOidcToken.refreshToken,\n });\n }\n catch (error) {\n }\n return {\n token: newSsoOidcToken.accessToken,\n expiration: newTokenExpiration,\n };\n }\n catch (error) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n};\n", | ||
| "export const EXPIRE_WINDOW_MS = 5 * 60 * 1000;\nexport const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;\n", | ||
| "export const getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => {\n const { SSOOIDCClient } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop];\n const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, {\n region: ssoRegion ?? init.clientConfig?.region,\n logger: coalesce(\"logger\"),\n userAgentAppId: coalesce(\"userAgentAppId\"),\n }));\n return ssoOidcClient;\n};\n", | ||
| "import { getSsoOidcClient } from \"./getSsoOidcClient\";\nexport const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => {\n const { CreateTokenCommand } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig);\n return ssoOidcClient.send(new CreateTokenCommand({\n clientId: ssoToken.clientId,\n clientSecret: ssoToken.clientSecret,\n refreshToken: ssoToken.refreshToken,\n grantType: \"refresh_token\",\n }));\n};\n", | ||
| "import { TokenProviderError } from \"@smithy/core/config\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenExpiry = (token) => {\n if (token.expiration && token.expiration.getTime() < Date.now()) {\n throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);\n }\n};\n", | ||
| "import { TokenProviderError } from \"@smithy/core/config\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenKey = (key, value, forRefresh = false) => {\n if (typeof value === \"undefined\") {\n throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? \". Cannot refresh\" : \"\"}. ${REFRESH_MESSAGE}`, false);\n }\n};\n", | ||
| "import { getSSOTokenFilepath } from \"@smithy/core/config\";\nimport { promises as fsPromises } from \"node:fs\";\nconst { writeFile } = fsPromises;\nexport const writeSSOTokenToFile = (id, ssoToken) => {\n const tokenFilepath = getSSOTokenFilepath(id);\n const tokenString = JSON.stringify(ssoToken, null, 2);\n return writeFile(tokenFilepath, tokenString);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nexport const validateSsoProfile = (profile, logger) => {\n const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;\n if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {\n throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters \"sso_account_id\", ` +\n `\"sso_region\", \"sso_role_name\", \"sso_start_url\". Got ${Object.keys(profile).join(\", \")}\\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger });\n }\n return profile;\n};\n" | ||
| ], | ||
| "mappings": ";4JAAA,oBCAO,SAAM,EAAe,CAAC,IAAQ,IAChC,OAAO,EAAI,gBAAkB,UAC1B,OAAO,EAAI,iBAAmB,UAC9B,OAAO,EAAI,cAAgB,UAC3B,OAAO,EA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B,mBAAoB,EAAK,mBACzB,mBAAoB,EAAK,mBACzB,QAAS,EACT,SAAU,EAAK,SACf,eAAgB,EAAK,eACrB,YAAa,EAAK,YAClB,OAAQ,EAAK,MACjB,CAAC", | ||
| "debugId": "A60E5A07FF913E3D64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/bedrock-event-stream.ts", "../ai/src/protocols/utils/bedrock-auth.ts", "../ai/src/protocols/utils/bedrock-cache.ts", "../ai/src/protocols/utils/bedrock-media.ts", "../ai/src/protocols/bedrock-converse.ts", "../ai/src/providers/amazon-bedrock.ts"], | ||
| "sourcesContent": [ | ||
| "import { EventStreamCodec } from \"@smithy/eventstream-codec\"\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\"\nimport { Effect, Stream } from \"effect\"\nimport { Framing } from \"../route/framing\"\nimport { ProviderShared } from \"./shared\"\n\n// Bedrock streams responses using the AWS event stream binary protocol — each\n// frame is `[length:4][headers-length:4][prelude-crc:4][headers][payload][crc:4]`.\n// We use `@smithy/eventstream-codec` to validate framing and CRCs, then\n// reconstruct the JSON wrapping by `:event-type` so the chunk schema can match.\nconst eventCodec = new EventStreamCodec(toUtf8, fromUtf8)\nconst utf8 = new TextDecoder()\n\n// Cursor-tracking buffer state. Bytes accumulate in `buffer`; `offset` is the\n// read position. Reading by `subarray` is zero-copy. We only allocate a fresh\n// buffer when a new network chunk arrives and we need to append.\ninterface FrameBufferState {\n readonly buffer: Uint8Array\n readonly offset: number\n}\n\nconst initialFrameBuffer: FrameBufferState = { buffer: new Uint8Array(0), offset: 0 }\n\nconst appendChunk = (state: FrameBufferState, chunk: Uint8Array): FrameBufferState => {\n const remaining = state.buffer.length - state.offset\n // Compact: drop the consumed prefix and append the new chunk in one alloc.\n // This bounds buffer growth to at most one network chunk past the live\n // window, regardless of stream length.\n const next = new Uint8Array(remaining + chunk.length)\n next.set(state.buffer.subarray(state.offset), 0)\n next.set(chunk, remaining)\n return { buffer: next, offset: 0 }\n}\n\nconst consumeFrames = (route: string) => (state: FrameBufferState, chunk: Uint8Array) =>\n Effect.gen(function* () {\n let cursor = appendChunk(state, chunk)\n const out: object[] = []\n while (cursor.buffer.length - cursor.offset >= 4) {\n const view = cursor.buffer.subarray(cursor.offset)\n const totalLength = new DataView(view.buffer, view.byteOffset, view.byteLength).getUint32(0, false)\n if (view.length < totalLength) break\n\n const decoded = yield* Effect.try({\n try: () => eventCodec.decode(view.subarray(0, totalLength)),\n catch: (error) =>\n ProviderShared.eventError(\n route,\n `Failed to decode Bedrock Converse event-stream frame: ${\n error instanceof Error ? error.message : String(error)\n }`,\n ),\n })\n cursor = { buffer: cursor.buffer, offset: cursor.offset + totalLength }\n\n if (decoded.headers[\":message-type\"]?.value !== \"event\") continue\n const eventType = decoded.headers[\":event-type\"]?.value\n if (typeof eventType !== \"string\") continue\n const payload = utf8.decode(decoded.body)\n if (!payload) continue\n // The AWS event stream pads short payloads with a `p` field. Drop it\n // before handing the object to the chunk schema. JSON decode goes\n // through the shared Schema-driven codec to satisfy the package rule\n // against ad-hoc `JSON.parse` calls.\n const parsed = (yield* ProviderShared.parseJson(\n route,\n payload,\n \"Failed to parse Bedrock Converse event-stream payload\",\n )) as Record<string, unknown>\n delete parsed.p\n out.push({ [eventType]: parsed })\n }\n return [cursor, out] as const\n })\n\n/**\n * AWS event-stream framing for Bedrock Converse. Each frame is decoded by\n * `@smithy/eventstream-codec` (length + header + payload + CRC) and rewrapped\n * under its `:event-type` header so the chunk schema can match the JSON\n * payload directly.\n */\nexport const framing = (route: string): Framing.Definition<object> => ({\n id: \"aws-event-stream\",\n frame: (bytes) => bytes.pipe(Stream.mapAccumEffect(() => initialFrameBuffer, consumeFrames(route))),\n})\n\nexport * as BedrockEventStream from \"./bedrock-event-stream\"\n", | ||
| "import { AwsV4Signer } from \"aws4fetch\"\nimport { Effect } from \"effect\"\nimport { Headers } from \"effect/unstable/http\"\nimport { Auth, type AuthInput } from \"../../route/auth\"\nimport { ProviderShared } from \"../shared\"\n\n/**\n * AWS credentials for SigV4 signing. Bedrock also supports Bearer API key auth,\n * which provider facades configure as route auth instead of SigV4. STS-vended\n * credentials should be refreshed by the consumer (rebuild the model) before\n * they expire; the route does not refresh.\n */\nexport interface Credentials {\n readonly region: string\n readonly accessKeyId: string\n readonly secretAccessKey: string\n readonly sessionToken?: string\n}\n\nconst signRequest = (input: {\n readonly url: string\n readonly body: string\n readonly headers: Headers.Headers\n readonly credentials: Credentials\n}) =>\n Effect.tryPromise({\n try: async () => {\n const signed = await new AwsV4Signer({\n url: input.url,\n method: \"POST\",\n headers: Object.entries(input.headers),\n body: input.body,\n region: input.credentials.region,\n accessKeyId: input.credentials.accessKeyId,\n secretAccessKey: input.credentials.secretAccessKey,\n sessionToken: input.credentials.sessionToken,\n service: \"bedrock\",\n }).sign()\n return Object.fromEntries(signed.headers.entries())\n },\n catch: (error) =>\n ProviderShared.invalidRequest(\n `Bedrock Converse SigV4 signing failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n })\n\n/** Sign the exact JSON bytes with SigV4 using credentials configured on the route. */\nexport const sigV4 = (credentials: Credentials | undefined) =>\n Auth.custom((input: AuthInput) => {\n return Effect.gen(function* () {\n if (!credentials) {\n return yield* ProviderShared.invalidRequest(\n \"Bedrock Converse requires either route bearer auth or AWS credentials configured on the route\",\n )\n }\n const headersForSigning = Headers.set(input.headers, \"content-type\", \"application/json\")\n const signed = yield* signRequest({\n url: input.url,\n body: input.body,\n headers: headersForSigning,\n credentials,\n })\n return Headers.setAll(headersForSigning, signed)\n })\n })\n\n/** Bedrock route auth defaults to SigV4 and expects credentials from route configuration. */\nexport const auth = sigV4(undefined)\n\nexport * as BedrockAuth from \"./bedrock-auth\"\n", | ||
| "import { Schema } from \"effect\"\nimport type { CacheHint } from \"../../schema\"\nimport { newBreakpoints, ttlBucket, type Breakpoints } from \"./cache\"\n\n// Bedrock cache markers are positional: emit a `cachePoint` block immediately\n// after the content the caller wants treated as a cacheable prefix. Bedrock\n// accepts optional `ttl: \"5m\" | \"1h\"` on cachePoint, mirroring Anthropic.\nexport const CachePointBlock = Schema.Struct({\n cachePoint: Schema.Struct({\n type: Schema.tag(\"default\"),\n ttl: Schema.optional(Schema.Literals([\"5m\", \"1h\"])),\n }),\n})\nexport type CachePointBlock = Schema.Schema.Type<typeof CachePointBlock>\n\n// Bedrock-Claude enforces the same 4-breakpoint cap as the Anthropic Messages\n// API. Callers pass a shared counter through every `block()` call site so the\n// budget is respected across `system`, `messages`, and `tools`.\nexport const BEDROCK_BREAKPOINT_CAP = 4\n\nexport type { Breakpoints } from \"./cache\"\nexport const breakpoints = () => newBreakpoints(BEDROCK_BREAKPOINT_CAP)\n\nconst DEFAULT_5M: CachePointBlock = { cachePoint: { type: \"default\" } }\nconst DEFAULT_1H: CachePointBlock = { cachePoint: { type: \"default\", ttl: \"1h\" } }\n\nexport const block = (breakpoints: Breakpoints, cache: CacheHint | undefined): CachePointBlock | undefined => {\n if (cache?.type !== \"ephemeral\" && cache?.type !== \"persistent\") return undefined\n if (breakpoints.remaining <= 0) {\n breakpoints.dropped += 1\n return undefined\n }\n breakpoints.remaining -= 1\n return ttlBucket(cache.ttlSeconds) === \"1h\" ? DEFAULT_1H : DEFAULT_5M\n}\n\nexport * as BedrockCache from \"./bedrock-cache\"\n", | ||
| "import { Effect, Schema } from \"effect\"\nimport type { MediaPart } from \"../../schema\"\nimport { ProviderShared } from \"../shared\"\n\n// Bedrock Converse accepts image `format` as the file extension and\n// `source.bytes` as base64 in the JSON wire format.\nexport const ImageFormat = Schema.Literals([\"png\", \"jpeg\", \"gif\", \"webp\"])\nexport type ImageFormat = Schema.Schema.Type<typeof ImageFormat>\n\nexport const ImageBlock = Schema.Struct({\n image: Schema.Struct({\n format: ImageFormat,\n source: Schema.Struct({ bytes: Schema.String }),\n }),\n})\nexport type ImageBlock = Schema.Schema.Type<typeof ImageBlock>\n\n// Bedrock document blocks require a user-facing name so the model can refer to\n// the uploaded document.\nexport const DocumentFormat = Schema.Literals([\"pdf\", \"csv\", \"doc\", \"docx\", \"xls\", \"xlsx\", \"html\", \"txt\", \"md\"])\nexport type DocumentFormat = Schema.Schema.Type<typeof DocumentFormat>\n\nexport const DocumentBlock = Schema.Struct({\n document: Schema.Struct({\n format: DocumentFormat,\n name: Schema.String,\n source: Schema.Struct({ bytes: Schema.String }),\n }),\n})\nexport type DocumentBlock = Schema.Schema.Type<typeof DocumentBlock>\n\nconst IMAGE_FORMATS = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpeg\",\n \"image/jpg\": \"jpeg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n} as const satisfies Record<string, ImageFormat>\n\nconst DOCUMENT_FORMATS = {\n \"application/pdf\": \"pdf\",\n \"text/csv\": \"csv\",\n \"application/msword\": \"doc\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": \"docx\",\n \"application/vnd.ms-excel\": \"xls\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": \"xlsx\",\n \"text/html\": \"html\",\n \"text/plain\": \"txt\",\n \"text/markdown\": \"md\",\n} as const satisfies Record<string, DocumentFormat>\n\nconst documentBlock = (part: MediaPart, format: DocumentFormat, bytes: string): DocumentBlock => ({\n document: {\n format,\n name: part.filename ?? `document.${format}`,\n source: { bytes },\n },\n})\n\n// Route by MIME. Known image/document formats lower into a typed block; anything\n// else fails with a clear error instead of silently degrading to a malformed\n// document block. Image MIME types not in `IMAGE_FORMATS` (e.g. `image/svg+xml`)\n// get an image-specific error so the caller knows it's a format-support issue,\n// not a kind-detection issue.\nexport const lower = Effect.fn(\"BedrockMedia.lower\")(function* (part: MediaPart) {\n const mime = part.mediaType.toLowerCase()\n const imageFormat = IMAGE_FORMATS[mime as keyof typeof IMAGE_FORMATS]\n if (imageFormat) {\n const media = yield* ProviderShared.validateMedia(\n \"Bedrock Converse\",\n part,\n new Set<string>(Object.keys(IMAGE_FORMATS)),\n )\n return { image: { format: imageFormat, source: { bytes: media.base64 } } } satisfies ImageBlock\n }\n if (mime.startsWith(\"image/\"))\n return yield* ProviderShared.invalidRequest(`Bedrock Converse does not support image media type ${part.mediaType}`)\n const documentFormat = DOCUMENT_FORMATS[mime as keyof typeof DOCUMENT_FORMATS]\n if (documentFormat) {\n const media = yield* ProviderShared.validateMedia(\n \"Bedrock Converse\",\n part,\n new Set<string>(Object.keys(DOCUMENT_FORMATS)),\n )\n return documentBlock(part, documentFormat, media.base64)\n }\n return yield* ProviderShared.invalidRequest(`Bedrock Converse does not support media type ${part.mediaType}`)\n})\n\nexport * as BedrockMedia from \"./bedrock-media\"\n", | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route } from \"../route/client\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Protocol } from \"../route/protocol\"\nimport {\n LLMError,\n LLMEvent,\n Usage,\n type CacheHint,\n type FinishReason,\n type JsonSchema,\n type LLMRequest,\n type ModelToolSchemaCompatibility,\n type ProviderMetadata,\n type ReasoningPart,\n type ToolCallPart,\n type ToolDefinition,\n type ToolResultPart,\n} from \"../schema\"\nimport { BedrockEventStream } from \"./bedrock-event-stream\"\nimport { classifyProviderFailure } from \"../provider-error\"\nimport { JsonObject, optionalArray, ProviderShared } from \"./shared\"\nimport { BedrockAuth } from \"./utils/bedrock-auth\"\nimport { BedrockCache } from \"./utils/bedrock-cache\"\nimport { BedrockMedia } from \"./utils/bedrock-media\"\nimport { Lifecycle } from \"./utils/lifecycle\"\nimport { ToolSchemaProjection } from \"./utils/tool-schema\"\nimport { ToolStream } from \"./utils/tool-stream\"\n\nconst ADAPTER = \"bedrock-converse\"\n\nexport type { Credentials as BedrockCredentials } from \"./utils/bedrock-auth\"\n\n// =============================================================================\n// Request Body Schema\n// =============================================================================\nconst BedrockTextBlock = Schema.Struct({\n text: Schema.String,\n})\ntype BedrockTextBlock = Schema.Schema.Type<typeof BedrockTextBlock>\n\nconst BedrockToolUseBlock = Schema.Struct({\n toolUse: Schema.Struct({\n toolUseId: Schema.String,\n name: Schema.String,\n input: Schema.Unknown,\n }),\n})\ntype BedrockToolUseBlock = Schema.Schema.Type<typeof BedrockToolUseBlock>\n\nconst BedrockToolResultContentItem = Schema.Union([\n Schema.Struct({ text: Schema.String }),\n Schema.Struct({ json: Schema.Unknown }),\n BedrockMedia.ImageBlock,\n])\n\nconst BedrockToolResultBlock = Schema.Struct({\n toolResult: Schema.Struct({\n toolUseId: Schema.String,\n content: Schema.Array(BedrockToolResultContentItem),\n status: Schema.optional(Schema.Literals([\"success\", \"error\"])),\n }),\n})\ntype BedrockToolResultBlock = Schema.Schema.Type<typeof BedrockToolResultBlock>\n\nconst BedrockReasoningBlock = Schema.Struct({\n reasoningContent: Schema.Struct({\n reasoningText: Schema.optional(\n Schema.Struct({\n text: Schema.String,\n signature: Schema.optional(Schema.String),\n }),\n ),\n }),\n})\n\nconst BedrockUserBlock = Schema.Union([\n BedrockTextBlock,\n BedrockMedia.ImageBlock,\n BedrockMedia.DocumentBlock,\n BedrockToolResultBlock,\n BedrockCache.CachePointBlock,\n])\ntype BedrockUserBlock = Schema.Schema.Type<typeof BedrockUserBlock>\n\nconst BedrockAssistantBlock = Schema.Union([\n BedrockTextBlock,\n BedrockReasoningBlock,\n BedrockToolUseBlock,\n BedrockCache.CachePointBlock,\n])\ntype BedrockAssistantBlock = Schema.Schema.Type<typeof BedrockAssistantBlock>\n\nconst BedrockMessage = Schema.Union([\n Schema.Struct({ role: Schema.Literal(\"user\"), content: Schema.Array(BedrockUserBlock) }),\n Schema.Struct({ role: Schema.Literal(\"assistant\"), content: Schema.Array(BedrockAssistantBlock) }),\n]).pipe(Schema.toTaggedUnion(\"role\"))\ntype BedrockMessage = Schema.Schema.Type<typeof BedrockMessage>\n\nconst BedrockSystemBlock = Schema.Union([BedrockTextBlock, BedrockCache.CachePointBlock])\ntype BedrockSystemBlock = Schema.Schema.Type<typeof BedrockSystemBlock>\n\nconst BedrockToolSpec = Schema.Struct({\n toolSpec: Schema.Struct({\n name: Schema.String,\n description: Schema.String,\n inputSchema: Schema.Struct({\n json: JsonObject,\n }),\n }),\n})\ntype BedrockToolSpec = Schema.Schema.Type<typeof BedrockToolSpec>\n\nconst BedrockTool = Schema.Union([BedrockToolSpec, BedrockCache.CachePointBlock])\ntype BedrockTool = Schema.Schema.Type<typeof BedrockTool>\n\nconst BedrockToolChoice = Schema.Union([\n Schema.Struct({ auto: Schema.Struct({}) }),\n Schema.Struct({ any: Schema.Struct({}) }),\n Schema.Struct({ tool: Schema.Struct({ name: Schema.String }) }),\n])\n\nconst BedrockBodyFields = {\n modelId: Schema.String,\n messages: Schema.Array(BedrockMessage),\n system: optionalArray(BedrockSystemBlock),\n inferenceConfig: Schema.optional(\n Schema.Struct({\n maxTokens: Schema.optional(Schema.Number),\n temperature: Schema.optional(Schema.Number),\n topP: Schema.optional(Schema.Number),\n stopSequences: optionalArray(Schema.String),\n }),\n ),\n toolConfig: Schema.optional(\n Schema.Struct({\n tools: Schema.Array(BedrockTool),\n toolChoice: Schema.optional(BedrockToolChoice),\n }),\n ),\n additionalModelRequestFields: Schema.optional(JsonObject),\n}\nconst BedrockConverseBody = Schema.Struct(BedrockBodyFields)\nexport type BedrockConverseBody = Schema.Schema.Type<typeof BedrockConverseBody>\n\nconst BedrockUsageSchema = Schema.Struct({\n inputTokens: Schema.optional(Schema.Number),\n outputTokens: Schema.optional(Schema.Number),\n totalTokens: Schema.optional(Schema.Number),\n cacheReadInputTokens: Schema.optional(Schema.Number),\n cacheWriteInputTokens: Schema.optional(Schema.Number),\n})\ntype BedrockUsageSchema = Schema.Schema.Type<typeof BedrockUsageSchema>\n\n// Streaming event shape — the AWS event stream wraps each JSON payload by its\n// `:event-type` header (e.g. `messageStart`, `contentBlockDelta`). We\n// reconstruct that wrapping in `decodeFrames` below so the event schema can\n// stay a plain discriminated record.\nconst BedrockEvent = Schema.Struct({\n messageStart: Schema.optional(Schema.Struct({ role: Schema.String })),\n contentBlockStart: Schema.optional(\n Schema.Struct({\n contentBlockIndex: Schema.Number,\n start: Schema.optional(\n Schema.Struct({\n toolUse: Schema.optional(Schema.Struct({ toolUseId: Schema.String, name: Schema.String })),\n }),\n ),\n }),\n ),\n contentBlockDelta: Schema.optional(\n Schema.Struct({\n contentBlockIndex: Schema.Number,\n delta: Schema.optional(\n Schema.Struct({\n text: Schema.optional(Schema.String),\n toolUse: Schema.optional(Schema.Struct({ input: Schema.String })),\n reasoningContent: Schema.optional(\n Schema.Struct({\n text: Schema.optional(Schema.String),\n signature: Schema.optional(Schema.String),\n }),\n ),\n }),\n ),\n }),\n ),\n contentBlockStop: Schema.optional(Schema.Struct({ contentBlockIndex: Schema.Number })),\n messageStop: Schema.optional(\n Schema.Struct({\n stopReason: Schema.String,\n additionalModelResponseFields: Schema.optional(Schema.Unknown),\n }),\n ),\n metadata: Schema.optional(\n Schema.Struct({\n usage: Schema.optional(BedrockUsageSchema),\n metrics: Schema.optional(Schema.Unknown),\n }),\n ),\n internalServerException: Schema.optional(Schema.Struct({ message: Schema.String })),\n modelStreamErrorException: Schema.optional(Schema.Struct({ message: Schema.String })),\n validationException: Schema.optional(Schema.Struct({ message: Schema.String })),\n throttlingException: Schema.optional(Schema.Struct({ message: Schema.String })),\n serviceUnavailableException: Schema.optional(Schema.Struct({ message: Schema.String })),\n})\ntype BedrockEvent = Schema.Schema.Type<typeof BedrockEvent>\n\n// =============================================================================\n// Request Lowering\n// =============================================================================\nconst lowerToolSpec = (tool: ToolDefinition, inputSchema: JsonSchema): BedrockToolSpec => ({\n toolSpec: {\n name: tool.name,\n description: tool.description,\n inputSchema: { json: inputSchema },\n },\n})\n\nconst lowerTools = (\n compatibility: ModelToolSchemaCompatibility | undefined,\n breakpoints: BedrockCache.Breakpoints,\n tools: ReadonlyArray<ToolDefinition>,\n): BedrockTool[] => {\n const result: BedrockTool[] = []\n for (const tool of tools) {\n result.push(lowerToolSpec(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, compatibility)))\n const cachePoint = BedrockCache.block(breakpoints, tool.cache)\n if (cachePoint) result.push(cachePoint)\n }\n return result\n}\n\nconst textWithCache = (\n breakpoints: BedrockCache.Breakpoints,\n text: string,\n cache: CacheHint | undefined,\n): Array<BedrockTextBlock | BedrockCache.CachePointBlock> => {\n const cachePoint = BedrockCache.block(breakpoints, cache)\n return cachePoint ? [{ text }, cachePoint] : [{ text }]\n}\n\nconst lowerToolChoice = (toolChoice: NonNullable<LLMRequest[\"toolChoice\"]>) =>\n ProviderShared.matchToolChoice(\"Bedrock Converse\", toolChoice, {\n auto: () => ({ auto: {} }) as const,\n none: () => undefined,\n required: () => ({ any: {} }) as const,\n tool: (name) => ({ tool: { name } }) as const,\n })\n\nconst bedrockMetadata = (metadata: Record<string, unknown>): ProviderMetadata => ({ bedrock: metadata })\n\nconst reasoningSignature = (part: ReasoningPart) => {\n const bedrock = part.providerMetadata?.bedrock\n return (\n part.encrypted ??\n (ProviderShared.isRecord(bedrock) && typeof bedrock.signature === \"string\" ? bedrock.signature : undefined)\n )\n}\n\nconst lowerToolCall = (part: ToolCallPart): BedrockToolUseBlock => ({\n toolUse: {\n toolUseId: part.id,\n name: part.name,\n input: part.input,\n },\n})\n\nconst lowerToolResultContent = Effect.fn(\"BedrockConverse.lowerToolResultContent\")(function* (part: ToolResultPart) {\n if (part.result.type === \"text\" || part.result.type === \"error\")\n return [{ text: ProviderShared.toolResultText(part) }]\n if (part.result.type === \"json\") return [{ json: part.result.value }]\n\n const content: Array<Schema.Schema.Type<typeof BedrockToolResultContentItem>> = []\n for (const item of part.result.value) {\n if (item.type === \"text\") {\n content.push({ text: item.text })\n continue\n }\n const media = yield* BedrockMedia.lower({\n type: \"media\",\n mediaType: item.mime,\n data: item.uri,\n filename: item.name,\n })\n if (!(\"image\" in media))\n return yield* ProviderShared.invalidRequest(\"Bedrock Converse only supports image media in tool results\")\n content.push(media)\n }\n return content\n})\n\nconst lowerToolResult = Effect.fn(\"BedrockConverse.lowerToolResult\")(function* (part: ToolResultPart) {\n return {\n toolResult: {\n toolUseId: part.id,\n content: yield* lowerToolResultContent(part),\n status: part.result.type === \"error\" ? \"error\" : \"success\",\n },\n } satisfies BedrockToolResultBlock\n})\n\nconst lowerMessages = Effect.fn(\"BedrockConverse.lowerMessages\")(function* (\n request: LLMRequest,\n breakpoints: BedrockCache.Breakpoints,\n) {\n const messages: BedrockMessage[] = []\n\n for (const message of request.messages) {\n if (message.role === \"system\") {\n const part = yield* ProviderShared.wrappedSystemUpdate(\"Bedrock Converse\", message)\n const content = textWithCache(breakpoints, part.text, part.cache)\n const previous = messages.at(-1)\n if (previous?.role === \"user\")\n messages[messages.length - 1] = { role: \"user\", content: [...previous.content, ...content] }\n else messages.push({ role: \"user\", content })\n continue\n }\n\n if (message.role === \"user\") {\n const content: BedrockUserBlock[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"media\"]))\n return yield* ProviderShared.unsupportedContent(\"Bedrock Converse\", \"user\", [\"text\", \"media\"])\n if (part.type === \"text\") {\n content.push(...textWithCache(breakpoints, part.text, part.cache))\n continue\n }\n if (part.type === \"media\") {\n content.push(yield* BedrockMedia.lower(part))\n continue\n }\n }\n messages.push({ role: \"user\", content })\n continue\n }\n\n if (message.role === \"assistant\") {\n const content: BedrockAssistantBlock[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"reasoning\", \"tool-call\"]))\n return yield* ProviderShared.unsupportedContent(\"Bedrock Converse\", \"assistant\", [\n \"text\",\n \"reasoning\",\n \"tool-call\",\n ])\n if (part.type === \"text\") {\n content.push(...textWithCache(breakpoints, part.text, part.cache))\n continue\n }\n if (part.type === \"reasoning\") {\n content.push({\n reasoningContent: {\n reasoningText: { text: part.text, signature: reasoningSignature(part) },\n },\n })\n continue\n }\n if (part.type === \"tool-call\") {\n content.push(lowerToolCall(part))\n continue\n }\n }\n messages.push({ role: \"assistant\", content })\n continue\n }\n\n const content: BedrockUserBlock[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"tool-result\"]))\n return yield* ProviderShared.unsupportedContent(\"Bedrock Converse\", \"tool\", [\"tool-result\"])\n content.push(yield* lowerToolResult(part))\n const cachePoint = BedrockCache.block(breakpoints, part.cache)\n if (cachePoint) content.push(cachePoint)\n }\n messages.push({ role: \"user\", content })\n }\n\n return messages\n})\n\n// System prompts share the cache-point convention: emit the text block, then\n// optionally a positional `cachePoint` marker.\nconst lowerSystem = (\n breakpoints: BedrockCache.Breakpoints,\n system: ReadonlyArray<LLMRequest[\"system\"][number]>,\n): BedrockSystemBlock[] => system.flatMap((part) => textWithCache(breakpoints, part.text, part.cache))\n\nconst fromRequest = Effect.fn(\"BedrockConverse.fromRequest\")(function* (request: LLMRequest) {\n const toolChoice = request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined\n const generation = request.generation\n // Bedrock-Claude shares Anthropic's 4-breakpoint cap. Spend the budget in\n // tools → system → messages order to favour the highest-impact prefixes.\n const breakpoints = BedrockCache.breakpoints()\n const toolConfig =\n request.tools.length > 0 && request.toolChoice?.type !== \"none\"\n ? { tools: lowerTools(request.model.compatibility?.toolSchema, breakpoints, request.tools), toolChoice }\n : undefined\n const system = request.system.length === 0 ? undefined : lowerSystem(breakpoints, request.system)\n const messages = yield* lowerMessages(request, breakpoints)\n if (breakpoints.dropped > 0) {\n yield* Effect.logWarning(\n `Bedrock Converse: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${BedrockCache.BEDROCK_BREAKPOINT_CAP} per request.`,\n )\n }\n return {\n modelId: request.model.id,\n messages,\n system,\n inferenceConfig:\n generation?.maxTokens === undefined &&\n generation?.temperature === undefined &&\n generation?.topP === undefined &&\n (generation?.stop === undefined || generation.stop.length === 0)\n ? undefined\n : {\n maxTokens: generation?.maxTokens,\n temperature: generation?.temperature,\n topP: generation?.topP,\n stopSequences: generation?.stop,\n },\n toolConfig,\n // Converse's base inferenceConfig has no topK; Anthropic/Nova accept it\n // as a model-specific field, so it goes through additionalModelRequestFields.\n additionalModelRequestFields: generation?.topK === undefined ? undefined : { top_k: generation.topK },\n }\n})\n\n// =============================================================================\n// Stream Parsing\n// =============================================================================\nconst mapFinishReason = (reason: string): FinishReason => {\n if (reason === \"end_turn\" || reason === \"stop_sequence\") return \"stop\"\n if (reason === \"max_tokens\") return \"length\"\n if (reason === \"tool_use\") return \"tool-calls\"\n if (reason === \"content_filtered\" || reason === \"guardrail_intervened\") return \"content-filter\"\n return \"unknown\"\n}\n\n// AWS Bedrock Converse reports `inputTokens` (inclusive total) with\n// `cacheReadInputTokens` and `cacheWriteInputTokens` as subsets. Pass\n// the total through and derive the non-cached breakdown. Bedrock does\n// not break reasoning out of `outputTokens` for any current model.\nconst mapUsage = (usage: BedrockUsageSchema | undefined): Usage | undefined => {\n if (!usage) return undefined\n const cacheTotal = (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0)\n const nonCached = ProviderShared.subtractTokens(usage.inputTokens, cacheTotal)\n return new Usage({\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n nonCachedInputTokens: nonCached,\n cacheReadInputTokens: usage.cacheReadInputTokens,\n cacheWriteInputTokens: usage.cacheWriteInputTokens,\n totalTokens: ProviderShared.totalTokens(usage.inputTokens, usage.outputTokens, usage.totalTokens),\n providerMetadata: { bedrock: usage },\n })\n}\n\ninterface ParserState {\n readonly tools: ToolStream.State<number>\n // Bedrock splits the finish into `messageStop` (carries `stopReason`) and\n // `metadata` (carries usage). Hold the terminal event in state so `onHalt`\n // can emit exactly one finish after both chunks have had a chance to arrive.\n readonly pendingFinish: { readonly reason: FinishReason; readonly usage?: Usage } | undefined\n readonly hasToolCalls: boolean\n readonly lifecycle: Lifecycle.State\n readonly reasoningSignatures: Readonly<Record<number, string>>\n}\n\nconst step = (state: ParserState, event: BedrockEvent) =>\n Effect.gen(function* () {\n if (event.contentBlockStart?.start?.toolUse) {\n const index = event.contentBlockStart.contentBlockIndex\n const events: LLMEvent[] = []\n const lifecycle = Lifecycle.stepStart(state.lifecycle, events)\n return [\n {\n ...state,\n lifecycle,\n tools: ToolStream.start(state.tools, index, {\n id: event.contentBlockStart.start.toolUse.toolUseId,\n name: event.contentBlockStart.start.toolUse.name,\n }),\n },\n [\n ...events,\n LLMEvent.toolInputStart({\n id: event.contentBlockStart.start.toolUse.toolUseId,\n name: event.contentBlockStart.start.toolUse.name,\n }),\n ],\n ] as const\n }\n\n if (event.contentBlockDelta?.delta?.text) {\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: Lifecycle.textDelta(\n state.lifecycle,\n events,\n `text-${event.contentBlockDelta.contentBlockIndex}`,\n event.contentBlockDelta.delta.text,\n ),\n },\n events,\n ] as const\n }\n\n if (event.contentBlockDelta?.delta?.reasoningContent) {\n const index = event.contentBlockDelta.contentBlockIndex\n const reasoning = event.contentBlockDelta.delta.reasoningContent\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: reasoning.text\n ? Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${index}`, reasoning.text)\n : state.lifecycle,\n reasoningSignatures: reasoning.signature\n ? { ...state.reasoningSignatures, [index]: reasoning.signature }\n : state.reasoningSignatures,\n },\n events,\n ] as const\n }\n\n if (event.contentBlockDelta?.delta?.toolUse) {\n const index = event.contentBlockDelta.contentBlockIndex\n const result = ToolStream.appendExisting(\n ADAPTER,\n state.tools,\n index,\n event.contentBlockDelta.delta.toolUse.input,\n \"Bedrock Converse tool delta is missing its tool call\",\n )\n if (ToolStream.isError(result)) return yield* result\n const events: LLMEvent[] = []\n const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle\n events.push(...result.events)\n return [{ ...state, lifecycle, tools: result.tools }, events] as const\n }\n\n if (event.contentBlockStop) {\n const index = event.contentBlockStop.contentBlockIndex\n const result = yield* ToolStream.finish(ADAPTER, state.tools, index)\n const events: LLMEvent[] = []\n const resultEvents = result.events ?? []\n const lifecycle = resultEvents.length\n ? Lifecycle.stepStart(state.lifecycle, events)\n : Lifecycle.reasoningEnd(\n Lifecycle.textEnd(state.lifecycle, events, `text-${index}`),\n events,\n `reasoning-${index}`,\n state.reasoningSignatures[index]\n ? bedrockMetadata({ signature: state.reasoningSignatures[index] })\n : undefined,\n )\n events.push(...resultEvents)\n return [\n {\n ...state,\n hasToolCalls:\n resultEvents.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)) ||\n state.hasToolCalls,\n lifecycle,\n tools: result.tools,\n reasoningSignatures: Object.fromEntries(\n Object.entries(state.reasoningSignatures).filter(([key]) => key !== String(index)),\n ),\n },\n events,\n ] as const\n }\n\n if (event.messageStop) {\n return [\n {\n ...state,\n pendingFinish: { reason: mapFinishReason(event.messageStop.stopReason), usage: state.pendingFinish?.usage },\n },\n [],\n ] as const\n }\n\n if (event.metadata) {\n const usage = mapUsage(event.metadata.usage)\n return [{ ...state, pendingFinish: { reason: state.pendingFinish?.reason ?? \"stop\", usage } }, []] as const\n }\n\n const exception = (\n [\n [\"internalServerException\", event.internalServerException],\n [\"modelStreamErrorException\", event.modelStreamErrorException],\n [\"serviceUnavailableException\", event.serviceUnavailableException],\n [\"throttlingException\", event.throttlingException],\n [\"validationException\", event.validationException],\n ] as const\n ).find((entry) => entry[1] !== undefined)\n if (exception) {\n return yield* new LLMError({\n module: ADAPTER,\n method: \"stream\",\n reason: classifyProviderFailure({\n message: exception[1]?.message ?? \"Bedrock Converse stream error\",\n code: exception[0],\n }),\n })\n }\n\n return [state, []] as const\n })\n\nconst framing = BedrockEventStream.framing(ADAPTER)\n\nconst onHalt = (state: ParserState): ReadonlyArray<LLMEvent> =>\n state.pendingFinish\n ? (() => {\n const events: LLMEvent[] = []\n Lifecycle.finish(state.lifecycle, events, {\n reason:\n state.pendingFinish.reason === \"stop\" && state.hasToolCalls ? \"tool-calls\" : state.pendingFinish.reason,\n usage: state.pendingFinish.usage,\n })\n return events\n })()\n : []\n\n// =============================================================================\n// Protocol And Bedrock Route\n// =============================================================================\n/**\n * The Bedrock Converse protocol — request body construction, body schema, and\n * the streaming-event state machine.\n */\nexport const protocol = Protocol.make({\n id: ADAPTER,\n body: {\n schema: BedrockConverseBody,\n from: fromRequest,\n },\n stream: {\n event: BedrockEvent,\n initial: () => ({\n tools: ToolStream.empty<number>(),\n pendingFinish: undefined,\n hasToolCalls: false,\n lifecycle: Lifecycle.initial(),\n reasoningSignatures: {},\n }),\n step,\n onHalt,\n },\n})\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: \"bedrock\",\n providerMetadataKey: \"bedrock\",\n protocol,\n // Bedrock's URL embeds the region in the route endpoint host and the\n // validated modelId in the path. We read the validated body so the URL\n // matches the body that gets signed.\n endpoint: Endpoint.path<BedrockConverseBody>(\n ({ body }) => `/model/${encodeURIComponent(body.modelId)}/converse-stream`,\n ),\n auth: BedrockAuth.auth,\n framing,\n})\n\nexport const sigV4Auth = BedrockAuth.sigV4\n\nexport * as BedrockConverse from \"./bedrock-converse\"\n", | ||
| "import type { RouteDefaultsInput } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { ProviderID, type ModelID } from \"../schema\"\nimport * as BedrockConverse from \"../protocols/bedrock-converse\"\nimport type { BedrockCredentials } from \"../protocols/bedrock-converse\"\n\nexport const id = ProviderID.make(\"amazon-bedrock\")\n\nexport type Config = RouteDefaultsInput & {\n readonly apiKey?: string\n readonly headers?: Record<string, string>\n readonly credentials?: BedrockCredentials\n /** AWS region. Defaults to `us-east-1` when neither this nor `credentials.region` is set. */\n readonly region?: string\n /** Override the computed `https://bedrock-runtime.<region>.amazonaws.com` URL. */\n readonly baseURL?: string\n}\n\nexport interface Settings extends ProviderPackage.Settings {\n readonly apiKey?: string\n readonly auth?: \"bearer\" | \"sigv4\"\n readonly baseURL?: string\n readonly credentials?: BedrockCredentials\n readonly region?: string\n readonly topP?: number\n}\nexport const routes = [BedrockConverse.route]\n\nconst bedrockBaseURL = (region: string) => `https://bedrock-runtime.${region}.amazonaws.com`\n\nconst configuredRoute = (input: Config) => {\n const { apiKey, credentials, region, baseURL, ...rest } = input\n const resolvedRegion = region ?? credentials?.region ?? \"us-east-1\"\n return BedrockConverse.route.with({\n ...rest,\n provider: id,\n endpoint: { baseURL: baseURL ?? bedrockBaseURL(resolvedRegion) },\n auth: apiKey === undefined ? BedrockConverse.sigV4Auth(credentials) : Auth.bearer(apiKey),\n })\n}\n\nexport const configure = (input: Config = {}) => {\n const route = configuredRoute(input)\n return {\n id,\n model: (modelID: string | ModelID) => route.model({ id: modelID }),\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) => {\n if (settings.auth === \"bearer\" && settings.apiKey === undefined)\n throw new Error(\"Amazon Bedrock bearer auth requires apiKey\")\n if (settings.auth === \"sigv4\" && settings.apiKey !== undefined)\n throw new Error(\"Amazon Bedrock SigV4 auth does not accept apiKey\")\n return configure({\n apiKey: settings.auth === \"sigv4\" ? undefined : settings.apiKey,\n baseURL: settings.baseURL,\n credentials: settings.credentials,\n generation: settings.topP === undefined ? undefined : { topP: settings.topP },\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n region: settings.region,\n }).model(modelID)\n}\n" | ||
| ], | ||
| "mappings": ";kxBAUA,SAAM,QAAa,SAAI,OAAiB,OAAQ,MAAQ,OAClD,QAAO,SAAI,iBAUX,QAAuC,MAAE,YAAQ,IAAI,WAAW,CAAC,EAAG,OAAQ,CAAE,EAE9E,GAAc,CAAC,EAAyB,IAAwC,CACpF,IAAM,EAAY,EAAM,OAAO,OAAS,EAAM,OAIxC,EAAO,IAAI,WAAW,EAAY,EAAM,MAAM,EAGpD,OAFA,EAAK,IAAI,EAAM,OAAO,SAAS,EAAM,MAAM,EAAG,CAAC,EAC/C,EAAK,IAAI,EAAO,CAAS,EAClB,CAAE,OAAQ,EAAM,OAAQ,CAAE,GAG7B,GAAgB,CAAC,IAA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S,QAClB,YAAa,EAAS,YACtB,WAAY,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,EAAS,IAAK,EAC5E,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,OACjB,OAAQ,EAAS,MACnB,CAAC,EAAE,MAAM,CAAO", | ||
| "debugId": "1DE476F4D3EBE3FE64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-error.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-io.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/auth-config.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/oauth.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/auth-errors.js", "../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token-util.js"], | ||
| "sourcesContent": [ | ||
| "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_error_exports = {};\n__export(token_error_exports, {\n VercelOidcTokenError: () => VercelOidcTokenError\n});\nmodule.exports = __toCommonJS(token_error_exports);\nclass VercelOidcTokenError extends Error {\n constructor(message, cause) {\n super(message);\n this.name = \"VercelOidcTokenError\";\n this.cause = cause;\n }\n toString() {\n if (this.cause) {\n return `${this.name}: ${this.message}: ${this.cause}`;\n }\n return `${this.name}: ${this.message}`;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n VercelOidcTokenError\n});\n", | ||
| "\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_io_exports = {};\n__export(token_io_exports, {\n findRootDir: () => findRootDir,\n getUserDataDir: () => getUserDataDir\n});\nmodule.exports = __toCommonJS(token_io_exports);\nvar import_path = __toESM(require(\"path\"));\nvar import_fs = __toESM(require(\"fs\"));\nvar import_os = __toESM(require(\"os\"));\nvar import_token_error = require(\"./token-error\");\nfunction findRootDir() {\n try {\n let dir = process.cwd();\n while (dir !== import_path.default.dirname(dir)) {\n const pkgPath = import_path.default.join(dir, \".vercel\");\n if (import_fs.default.existsSync(pkgPath)) {\n return dir;\n }\n dir = import_path.default.dirname(dir);\n }\n } catch (e) {\n throw new import_token_error.VercelOidcTokenError(\n \"Token refresh only supported in node server environments\"\n );\n }\n return null;\n}\nfunction getUserDataDir() {\n if (process.env.XDG_DATA_HOME) {\n return process.env.XDG_DATA_HOME;\n }\n switch (import_os.default.platform()) {\n case \"darwin\":\n return import_path.default.join(import_os.default.homedir(), \"Library/Application Support\");\n case \"linux\":\n return import_path.default.join(import_os.default.homedir(), \".local/share\");\n case \"win32\":\n if (process.env.LOCALAPPDATA) {\n return process.env.LOCALAPPDATA;\n }\n return null;\n default:\n return null;\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n findRootDir,\n getUserDataDir\n});\n", | ||
| "\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar auth_config_exports = {};\n__export(auth_config_exports, {\n isValidAccessToken: () => isValidAccessToken,\n readAuthConfig: () => readAuthConfig,\n writeAuthConfig: () => writeAuthConfig\n});\nmodule.exports = __toCommonJS(auth_config_exports);\nvar fs = __toESM(require(\"fs\"));\nvar path = __toESM(require(\"path\"));\nvar import_token_util = require(\"./token-util\");\nfunction getAuthConfigPath() {\n const dataDir = (0, import_token_util.getVercelDataDir)();\n if (!dataDir) {\n throw new Error(\n `Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`\n );\n }\n return path.join(dataDir, \"auth.json\");\n}\nfunction readAuthConfig() {\n try {\n const authPath = getAuthConfigPath();\n if (!fs.existsSync(authPath)) {\n return null;\n }\n const content = fs.readFileSync(authPath, \"utf8\");\n if (!content) {\n return null;\n }\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n}\nfunction writeAuthConfig(config) {\n const authPath = getAuthConfigPath();\n const authDir = path.dirname(authPath);\n if (!fs.existsSync(authDir)) {\n fs.mkdirSync(authDir, { mode: 504, recursive: true });\n }\n fs.writeFileSync(authPath, JSON.stringify(config, null, 2), { mode: 384 });\n}\nfunction isValidAccessToken(authConfig, expirationBufferMs = 0) {\n if (!authConfig.token)\n return false;\n if (typeof authConfig.expiresAt !== \"number\")\n return true;\n const nowInSeconds = Math.floor(Date.now() / 1e3);\n const bufferInSeconds = expirationBufferMs / 1e3;\n return authConfig.expiresAt >= nowInSeconds + bufferInSeconds;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n isValidAccessToken,\n readAuthConfig,\n writeAuthConfig\n});\n", | ||
| "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar oauth_exports = {};\n__export(oauth_exports, {\n processTokenResponse: () => processTokenResponse,\n refreshTokenRequest: () => refreshTokenRequest\n});\nmodule.exports = __toCommonJS(oauth_exports);\nvar import_os = require(\"os\");\nconst VERCEL_ISSUER = \"https://vercel.com\";\nconst VERCEL_CLI_CLIENT_ID = \"cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp\";\nconst userAgent = `@vercel/oidc node-${process.version} ${(0, import_os.platform)()} (${(0, import_os.arch)()}) ${(0, import_os.hostname)()}`;\nlet _tokenEndpoint = null;\nasync function getTokenEndpoint() {\n if (_tokenEndpoint) {\n return _tokenEndpoint;\n }\n const discoveryUrl = `${VERCEL_ISSUER}/.well-known/openid-configuration`;\n const response = await fetch(discoveryUrl, {\n headers: { \"user-agent\": userAgent }\n });\n if (!response.ok) {\n throw new Error(\"Failed to discover OAuth endpoints\");\n }\n const metadata = await response.json();\n if (!metadata || typeof metadata.token_endpoint !== \"string\") {\n throw new Error(\"Invalid OAuth discovery response\");\n }\n const endpoint = metadata.token_endpoint;\n _tokenEndpoint = endpoint;\n return endpoint;\n}\nasync function refreshTokenRequest(options) {\n const tokenEndpoint = await getTokenEndpoint();\n return await fetch(tokenEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"user-agent\": userAgent\n },\n body: new URLSearchParams({\n client_id: VERCEL_CLI_CLIENT_ID,\n grant_type: \"refresh_token\",\n ...options\n })\n });\n}\nasync function processTokenResponse(response) {\n const json = await response.json();\n if (!response.ok) {\n const errorMsg = typeof json === \"object\" && json && \"error\" in json ? String(json.error) : \"Token refresh failed\";\n return [new Error(errorMsg)];\n }\n if (typeof json !== \"object\" || json === null) {\n return [new Error(\"Invalid token response\")];\n }\n if (typeof json.access_token !== \"string\") {\n return [new Error(\"Missing access_token in response\")];\n }\n if (json.token_type !== \"Bearer\") {\n return [new Error(\"Invalid token_type in response\")];\n }\n if (typeof json.expires_in !== \"number\") {\n return [new Error(\"Missing expires_in in response\")];\n }\n return [null, json];\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n processTokenResponse,\n refreshTokenRequest\n});\n", | ||
| "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar auth_errors_exports = {};\n__export(auth_errors_exports, {\n AccessTokenMissingError: () => AccessTokenMissingError,\n RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError\n});\nmodule.exports = __toCommonJS(auth_errors_exports);\nclass AccessTokenMissingError extends Error {\n constructor() {\n super(\n \"No authentication found. Please log in with the Vercel CLI (vercel login).\"\n );\n this.name = \"AccessTokenMissingError\";\n }\n}\nclass RefreshAccessTokenFailedError extends Error {\n constructor(cause) {\n super(\"Failed to refresh authentication token.\", { cause });\n this.name = \"RefreshAccessTokenFailedError\";\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n AccessTokenMissingError,\n RefreshAccessTokenFailedError\n});\n", | ||
| "\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_util_exports = {};\n__export(token_util_exports, {\n assertVercelOidcTokenResponse: () => assertVercelOidcTokenResponse,\n findProjectInfo: () => findProjectInfo,\n getTokenPayload: () => getTokenPayload,\n getVercelDataDir: () => getVercelDataDir,\n getVercelOidcToken: () => getVercelOidcToken,\n getVercelToken: () => getVercelToken,\n isExpired: () => isExpired,\n loadToken: () => loadToken,\n saveToken: () => saveToken\n});\nmodule.exports = __toCommonJS(token_util_exports);\nvar path = __toESM(require(\"path\"));\nvar fs = __toESM(require(\"fs\"));\nvar import_token_error = require(\"./token-error\");\nvar import_token_io = require(\"./token-io\");\nvar import_auth_config = require(\"./auth-config\");\nvar import_oauth = require(\"./oauth\");\nvar import_auth_errors = require(\"./auth-errors\");\nfunction getVercelDataDir() {\n const vercelFolder = \"com.vercel.cli\";\n const dataDir = (0, import_token_io.getUserDataDir)();\n if (!dataDir) {\n return null;\n }\n return path.join(dataDir, vercelFolder);\n}\nasync function getVercelToken(options) {\n const authConfig = (0, import_auth_config.readAuthConfig)();\n if (!authConfig?.token) {\n throw new import_auth_errors.AccessTokenMissingError();\n }\n if ((0, import_auth_config.isValidAccessToken)(authConfig, options?.expirationBufferMs)) {\n return authConfig.token;\n }\n if (!authConfig.refreshToken) {\n (0, import_auth_config.writeAuthConfig)({});\n throw new import_auth_errors.RefreshAccessTokenFailedError(\"No refresh token available\");\n }\n try {\n const tokenResponse = await (0, import_oauth.refreshTokenRequest)({\n refresh_token: authConfig.refreshToken\n });\n const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse);\n if (tokensError || !tokens) {\n (0, import_auth_config.writeAuthConfig)({});\n throw new import_auth_errors.RefreshAccessTokenFailedError(tokensError);\n }\n const updatedConfig = {\n token: tokens.access_token,\n expiresAt: Math.floor(Date.now() / 1e3) + tokens.expires_in\n };\n if (tokens.refresh_token) {\n updatedConfig.refreshToken = tokens.refresh_token;\n }\n (0, import_auth_config.writeAuthConfig)(updatedConfig);\n return updatedConfig.token;\n } catch (error) {\n (0, import_auth_config.writeAuthConfig)({});\n if (error instanceof import_auth_errors.AccessTokenMissingError || error instanceof import_auth_errors.RefreshAccessTokenFailedError) {\n throw error;\n }\n throw new import_auth_errors.RefreshAccessTokenFailedError(error);\n }\n}\nasync function getVercelOidcToken(authToken, projectId, teamId) {\n const url = `https://api.vercel.com/v1/projects/${projectId}/token?source=vercel-oidc-refresh${teamId ? `&teamId=${teamId}` : \"\"}`;\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${authToken}`\n }\n });\n if (!res.ok) {\n throw new import_token_error.VercelOidcTokenError(\n `Failed to refresh OIDC token: ${res.statusText}`\n );\n }\n const tokenRes = await res.json();\n assertVercelOidcTokenResponse(tokenRes);\n return tokenRes;\n}\nfunction assertVercelOidcTokenResponse(res) {\n if (!res || typeof res !== \"object\") {\n throw new TypeError(\n \"Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again\"\n );\n }\n if (!(\"token\" in res) || typeof res.token !== \"string\") {\n throw new TypeError(\n \"Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again\"\n );\n }\n}\nfunction findProjectInfo() {\n const dir = (0, import_token_io.findRootDir)();\n if (!dir) {\n throw new import_token_error.VercelOidcTokenError(\n \"Unable to find project root directory. Have you linked your project with `vc link?`\"\n );\n }\n const prjPath = path.join(dir, \".vercel\", \"project.json\");\n if (!fs.existsSync(prjPath)) {\n throw new import_token_error.VercelOidcTokenError(\n \"project.json not found, have you linked your project with `vc link?`\"\n );\n }\n const prj = JSON.parse(fs.readFileSync(prjPath, \"utf8\"));\n if (typeof prj.projectId !== \"string\" && typeof prj.orgId !== \"string\") {\n throw new TypeError(\n \"Expected a string-valued projectId property. Try running `vc link` to re-link your project.\"\n );\n }\n return { projectId: prj.projectId, teamId: prj.orgId };\n}\nfunction saveToken(token, projectId) {\n const dir = (0, import_token_io.getUserDataDir)();\n if (!dir) {\n throw new import_token_error.VercelOidcTokenError(\n \"Unable to find user data directory. Please reach out to Vercel support.\"\n );\n }\n const tokenPath = path.join(dir, \"com.vercel.token\", `${projectId}.json`);\n const tokenJson = JSON.stringify(token);\n fs.mkdirSync(path.dirname(tokenPath), { mode: 504, recursive: true });\n fs.writeFileSync(tokenPath, tokenJson);\n fs.chmodSync(tokenPath, 432);\n return;\n}\nfunction loadToken(projectId) {\n const dir = (0, import_token_io.getUserDataDir)();\n if (!dir) {\n throw new import_token_error.VercelOidcTokenError(\n \"Unable to find user data directory. Please reach out to Vercel support.\"\n );\n }\n const tokenPath = path.join(dir, \"com.vercel.token\", `${projectId}.json`);\n if (!fs.existsSync(tokenPath)) {\n return null;\n }\n const token = JSON.parse(fs.readFileSync(tokenPath, \"utf8\"));\n assertVercelOidcTokenResponse(token);\n return token;\n}\nfunction getTokenPayload(token) {\n const tokenParts = token.split(\".\");\n if (tokenParts.length !== 3) {\n throw new import_token_error.VercelOidcTokenError(\n \"Invalid token. Please run `vc env pull` and try again\"\n );\n }\n const base64 = tokenParts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + (4 - base64.length % 4) % 4,\n \"=\"\n );\n return JSON.parse(Buffer.from(padded, \"base64\").toString(\"utf8\"));\n}\nfunction isExpired(token, bufferMs = 0) {\n return token.exp * 1e3 < Date.now() + bufferMs;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n assertVercelOidcTokenResponse,\n findProjectInfo,\n getTokenPayload,\n getVercelDataDir,\n getVercelOidcToken,\n getVercelToken,\n isExpired,\n loadToken,\n saveToken\n});\n" | ||
| ], | ||
| "mappings": ";6EACA,IAAuB,eAAnB,EAC0B,yBAA1B,GAC2B,oBAA3B,IADmB,OAEnB,GAAe,OAAO,UAAU,eAChC,GAAW,CAAC,EAAQ,IAAQ,CAC9B,QAAS,KAAQ,EACf,EAAU,EAAQ,EAAM,CAAE,IAAK,EAAI,GAAO,WAAY,EAAK,CAAC,GAE5D,GAAc,CAAC,EAAI,EAAM,EAAQ,IAAS,CAC5C,GAAI,GAAQ,OAAO,IAAS,UAAY,OAAO,IAAS,YACtD,QAAS,KAAO,GAAkB,CAAI,EACpC,GAAI,CAAC,GAAa,KAAK,EAAI,CAAG,GAAK,IAAQ,EACzC,EAAU,EAAI,EAAK,CAAE,IAAK,IAAM,EAAK,GAAM,WAAY,EAAE,EAAO,GAAiB,EAAM,CAAG,IAAM,EAAK,UAAW,CAAC,EAEvH,OAAO,GAEL,GAAe,CAAC,IAAQ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Q,QAAQ,EAAE,SAAS,MAAM,CAAC,EAElE,SAAS,EAAS,CAAC,EAAO,EAAW,EAAG,CACtC,OAAO,EAAM,IAAM,KAAM,KAAK,IAAI,EAAI", | ||
| "debugId": "0926EE309A93CC3464756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/api.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nconst methods = new Set([\"delete\", \"get\", \"head\", \"options\", \"patch\", \"post\", \"put\"])\n\ntype Operation = {\n operationId?: string\n}\n\ntype OpenApi = {\n paths?: Record<string, Record<string, Operation>>\n}\n\nexport default Runtime.handler(\n Commands.commands.api,\n Effect.fn(\"cli.api\")(function* (input) {\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n mismatch: \"ignore\",\n })\n const endpoint = server.endpoint\n const params = Option.getOrElse(input.param, () => ({}))\n const request = yield* resolveRequest(endpoint, input.request, params)\n const headers = new Headers(Service.headers(endpoint))\n for (const header of input.header) {\n const index = header.indexOf(\":\")\n if (index < 1) return yield* Effect.fail(new Error(`Invalid header, expected name:value: ${header}`))\n headers.set(header.slice(0, index).trim(), header.slice(index + 1).trim())\n }\n const body = Option.getOrUndefined(input.data)\n if (body !== undefined && !headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n\n const response = yield* Effect.tryPromise(() =>\n fetch(new URL(request.path, endpoint.url), {\n method: request.method,\n headers,\n body,\n }),\n )\n const output = yield* Effect.promise(() => response.text())\n if (output) process.stdout.write(output + (output.endsWith(EOL) ? \"\" : EOL))\n }),\n)\n\nexport function resolveOperation(spec: OpenApi, operationID: string, params: Record<string, string>) {\n for (const [path, operations] of Object.entries(spec.paths ?? {})) {\n for (const [method, operation] of Object.entries(operations)) {\n if (!methods.has(method) || operation.operationId !== operationID) continue\n return { method: method.toUpperCase(), path: interpolate(path, params) }\n }\n }\n throw new Error(`Operation not found: ${operationID}`)\n}\n\nexport function rawRequest(input: readonly string[]) {\n if (input.length !== 2 || !methods.has(input[0].toLowerCase()) || !input[1].startsWith(\"/\")) return\n return { method: input[0].toUpperCase(), path: input[1] }\n}\n\nfunction resolveRequest(endpoint: Endpoint, input: readonly string[], params: Record<string, string>) {\n const raw = rawRequest(input)\n if (raw) return Effect.succeed(raw)\n if (input.length !== 1) return Effect.fail(new Error(\"Expected an operation name or an HTTP method and path\"))\n return Effect.tryPromise(async () => {\n const response = await fetch(new URL(\"/openapi.json\", endpoint.url), { headers: Service.headers(endpoint) })\n if (!response.ok) throw new Error(`Failed to load OpenAPI document: HTTP ${response.status}`)\n return resolveOperation((await response.json()) as OpenApi, input[0], params)\n })\n}\n\nfunction interpolate(path: string, params: Record<string, string>) {\n const used = new Set<string>()\n const pathname = path.replaceAll(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = params[name]\n if (value === undefined) throw new Error(`Missing path parameter: ${name}`)\n used.add(name)\n return encodeURIComponent(value)\n })\n const query = new URLSearchParams(Object.entries(params).filter(([name]) => !used.has(name))).toString()\n return query ? `${pathname}?${query}` : pathname\n}\n" | ||
| ], | ||
| "mappings": ";+9BAAA,mBAAS,gBAOT,SAAM,OAAU,SAAI,SAAI,MAAC,cAAU,WAAO,YAAQ,eAAW,aAAS,YAAQ,UAAK,MAAC,OAUrE,SAAQ,aACrB,OAAS,cAAS,SAClB,OAAO,QAAG,cAAS,OAAE,cAAU,CAAC,EAAO,CAMrC,IAAM,GALS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,WAClB,SAAU,QACZ,CAAC,GACuB,SAClB,EAAS,EAAO,UAA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CAAC,GAAK,CAAC,EAAM,GAAG,WAAW,GAAG,EAAG,OAC7F,MAAO,CAAE,OAAQ,EAAM,GAAG,YAAY,EAAG,KAAM,EAAM,EAAG,EAG1D,SAAS,CAAc,CAAC,EAAoB,EAA0B,EAAgC,CACpG,IAAM,EAAM,EAAW,CAAK,EAC5B,GAAI,EAAK,OAAO,EAAO,QAAQ,CAAG,EAClC,GAAI,EAAM,SAAW,EAAG,OAAO,EAAO,KAAS,MAAM,uDAAuD,CAAC,EAC7G,OAAO,EAAO,WAAW,SAAY,CACnC,IAAM,EAAW,MAAM,MAAM,IAAI,IAAI,gBAAiB,EAAS,GAAG,EAAG,CAAE,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAC3G,GAAI,CAAC,EAAS,GAAI,MAAU,MAAM,yCAAyC,EAAS,QAAQ,EAC5F,OAAO,EAAkB,MAAM,EAAS,KAAK,EAAe,EAAM,GAAI,CAAM,EAC7E,EAGH,SAAS,CAAW,CAAC,EAAc,EAAgC,CACjE,IAAM,EAAO,IAAI,IACX,EAAW,EAAK,WAAW,eAAgB,CAAC,EAAG,IAAiB,CACpE,IAAM,EAAQ,EAAO,GACrB,GAAI,IAAU,OAAW,MAAU,MAAM,2BAA2B,GAAM,EAE1E,OADA,EAAK,IAAI,CAAI,EACN,mBAAmB,CAAK,EAChC,EACK,EAAQ,IAAI,gBAAgB,OAAO,QAAQ,CAAM,EAAE,OAAO,EAAE,KAAU,CAAC,EAAK,IAAI,CAAI,CAAC,CAAC,EAAE,SAAS,EACvG,OAAO,EAAQ,GAAG,KAAY,IAAU", | ||
| "debugId": "E0CE0AF1CF9C51D464756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.33/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSigninHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"signin\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSigninHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateOAuth2Token\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"signin\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.32\";\nvar packageInfo = {\n\tversion: version};\n\nconst s = \"ref\";\nconst a = -1, b = false, c = true, d = \"isSet\", e = \"booleanEquals\", f = \"coalesce\", g = \"PartitionResult\", h = \"stringEquals\", i = \"getAttr\", j = \"https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}\", k = { [s]: \"Endpoint\" }, l = { \"fn\": i, \"argv\": [{ [s]: g }, \"name\"] }, m = { [s]: \"Region\" }, n = { [s]: g }, o = { \"authSchemes\": [{ \"name\": \"sigv4\", \"signingName\": \"signin\", \"signingRegion\": \"{Region}\" }] }, p = {}, q = [m];\nconst _data = {\n conditions: [\n [d, q],\n [e, [{ fn: f, argv: [{ [s]: \"IsControlPlane\" }, b] }, c]],\n [d, [k]],\n [\"aws.partition\", q, g],\n [e, [{ [s]: \"UseFIPS\" }, c]],\n [h, [l, \"aws\"]],\n [e, [{ fn: f, argv: [{ [s]: \"IsOAuthEndpoint\" }, b] }, c]],\n [e, [{ [s]: \"UseDualStack\" }, c]],\n [h, [l, \"aws-cn\"]],\n [h, [m, \"us-gov-west-1\"]],\n [h, [l, \"aws-us-gov\"]],\n [e, [{ fn: i, argv: [n, \"supportsFIPS\"] }, c]],\n [h, [l, \"aws-iso\"]],\n [h, [l, \"aws-iso-b\"]],\n [h, [l, \"aws-iso-f\"]],\n [h, [l, \"aws-iso-e\"]],\n [h, [l, \"aws-eusc\"]],\n [e, [{ fn: i, argv: [n, \"supportsDualStack\"] }, c]]\n ],\n results: [\n [a],\n [\"https://signin.{Region}.api.aws\", o],\n [\"https://signin.{Region}.api.amazonwebservices.com.cn\", o],\n [j, o],\n [a, \"FIPS endpoints are not supported for OAuth operations. Disable FIPS or use a non-OAuth operation.\"],\n [\"https://{Region}.oauth.signin.aws\", o],\n [\"https://{Region}.signin.aws.amazon.com\", p],\n [\"https://{Region}.signin.amazonaws.cn\", p],\n [\"https://{Region}.signin.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin.c2shome.ic.gov\", p],\n [\"https://{Region}.signin.sc2shome.sgov.gov\", p],\n [\"https://{Region}.signin.csphome.hci.ic.gov\", p],\n [\"https://{Region}.signin.csphome.adc-e.uk\", p],\n [\"https://{Region}.signin.amazonaws-eusc.eu\", p],\n [\"https://signin-fips.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin-fips.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin.{PartitionResult#dnsSuffix}\", p],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [k, p],\n [\"https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", p],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://signin-fips.{Region}.{PartitionResult#dnsSuffix}\", p],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [j, p],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://signin.{Region}.{PartitionResult#dnsSuffix}\", p],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 6, 3,\n 2, 36, 4,\n 4, 5, r + 27,\n 6, r + 4, r + 27,\n 1, 29, 7,\n 2, 36, 8,\n 3, 9, 31,\n 4, 22, 10,\n 5, 19, 11,\n 7, 21, 12,\n 8, r + 7, 13,\n 10, r + 8, 14,\n 12, r + 9, 15,\n 13, r + 10, 16,\n 14, r + 11, 17,\n 15, r + 12, 18,\n 16, r + 13, r + 16,\n 6, r + 5, 20,\n 7, 21, r + 6,\n 17, r + 24, r + 25,\n 6, r + 4, 23,\n 7, 27, 24,\n 9, r + 14, 25,\n 10, r + 15, 26,\n 11, r + 22, r + 23,\n 11, 28, r + 21,\n 17, r + 20, r + 21,\n 2, 35, 30,\n 3, 39, 31,\n 4, 32, r + 27,\n 6, r + 4, 33,\n 7, r + 27, 34,\n 9, r + 14, r + 27,\n 3, 39, 36,\n 4, 38, 37,\n 7, r + 18, r + 19,\n 6, r + 4, r + 17,\n 5, r + 1, 40,\n 8, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"IsControlPlane\", \"IsOAuthEndpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SigninServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SigninServiceException.prototype);\n }\n}\n\nclass AccessDeniedException extends SigninServiceException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n }\n}\nclass InternalServerException extends SigninServiceException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n }\n}\nclass TooManyRequestsError extends SigninServiceException {\n name = \"TooManyRequestsError\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"TooManyRequestsError\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n this.error = opts.error;\n }\n}\nclass ValidationException extends SigninServiceException {\n name = \"ValidationException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"ValidationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ValidationException.prototype);\n this.error = opts.error;\n }\n}\n\nconst _ADE = \"AccessDeniedException\";\nconst _AT = \"AccessToken\";\nconst _COAT = \"CreateOAuth2Token\";\nconst _COATR = \"CreateOAuth2TokenRequest\";\nconst _COATRB = \"CreateOAuth2TokenRequestBody\";\nconst _COATRBr = \"CreateOAuth2TokenResponseBody\";\nconst _COATRr = \"CreateOAuth2TokenResponse\";\nconst _COATWIAM = \"CreateOAuth2TokenWithIAM\";\nconst _COATWIAMR = \"CreateOAuth2TokenWithIAMRequest\";\nconst _COATWIAMRr = \"CreateOAuth2TokenWithIAMResponse\";\nconst _ISE = \"InternalServerException\";\nconst _OAAT = \"OAuthAccessToken\";\nconst _RT = \"RefreshToken\";\nconst _TMRE = \"TooManyRequestsError\";\nconst _VE = \"ValidationException\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _at = \"access_token\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ei = \"expires_in\";\nconst _gT = \"grantType\";\nconst _gt = \"grant_type\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _jN = \"jsonName\";\nconst _m = \"message\";\nconst _r = \"resource\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.signin\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _se = \"server\";\nconst _tI = \"tokenInput\";\nconst _tO = \"tokenOutput\";\nconst _tT = \"tokenType\";\nconst _tt = \"token_type\";\nconst n0 = \"com.amazonaws.signin\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SigninServiceException$ = [-3, _s, \"SigninServiceException\", 0, [], []];\n_s_registry.registerError(SigninServiceException$, SigninServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar AccessDeniedException$ = [-3, n0, _ADE,\n { [_e]: _c },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(AccessDeniedException$, AccessDeniedException);\nvar InternalServerException$ = [-3, n0, _ISE,\n { [_e]: _se, [_hE]: 500 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(InternalServerException$, InternalServerException);\nvar TooManyRequestsError$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(TooManyRequestsError$, TooManyRequestsError);\nvar ValidationException$ = [-3, n0, _VE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(ValidationException$, ValidationException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar OAuthAccessToken = [0, n0, _OAAT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nvar AccessToken$ = [3, n0, _AT,\n 8,\n [_aKI, _sAK, _sT],\n [[0, { [_jN]: _aKI }], [0, { [_jN]: _sAK }], [0, { [_jN]: _sT }]], 3\n];\nvar CreateOAuth2TokenRequest$ = [3, n0, _COATR,\n 0,\n [_tI],\n [[() => CreateOAuth2TokenRequestBody$, 16]], 1\n];\nvar CreateOAuth2TokenRequestBody$ = [3, n0, _COATRB,\n 0,\n [_cI, _gT, _co, _rU, _cV, _rT],\n [[0, { [_jN]: _cI }], [0, { [_jN]: _gT }], 0, [0, { [_jN]: _rU }], [0, { [_jN]: _cV }], [() => RefreshToken, { [_jN]: _rT }]], 2\n];\nvar CreateOAuth2TokenResponse$ = [3, n0, _COATRr,\n 0,\n [_tO],\n [[() => CreateOAuth2TokenResponseBody$, 16]], 1\n];\nvar CreateOAuth2TokenResponseBody$ = [3, n0, _COATRBr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken$, { [_jN]: _aT }], [0, { [_jN]: _tT }], [1, { [_jN]: _eI }], [() => RefreshToken, { [_jN]: _rT }], [0, { [_jN]: _iT }]], 4\n];\nvar CreateOAuth2TokenWithIAMRequest$ = [3, n0, _COATWIAMR,\n 0,\n [_gT, _r],\n [[0, { [_jN]: _gt }], 0], 2\n];\nvar CreateOAuth2TokenWithIAMResponse$ = [3, n0, _COATWIAMRr,\n 0,\n [_aT, _tT, _eI],\n [[() => OAuthAccessToken, { [_jN]: _at }], [0, { [_jN]: _tt }], [1, { [_jN]: _ei }]], 3\n];\nvar CreateOAuth2Token$ = [9, n0, _COAT,\n { [_h]: [\"POST\", \"/v1/token\", 200] }, () => CreateOAuth2TokenRequest$, () => CreateOAuth2TokenResponse$\n];\nvar CreateOAuth2TokenWithIAM$ = [9, n0, _COATWIAM,\n { [_h]: [\"POST\", \"/v1/token?x-amz-client-auth-method=iam\", 200] }, () => CreateOAuth2TokenWithIAMRequest$, () => CreateOAuth2TokenWithIAMResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2023-01-01\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSigninHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.signin\",\n errorTypeRegistries,\n version: \"2023-01-01\",\n serviceTarget: \"Signin\",\n },\n serviceId: config?.serviceId ?? \"Signin\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SigninClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSigninHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"Signin\", \"SigninClient\", getEndpointPlugin);\nconst _ep0 = {\n IsControlPlane: { type: \"staticContextParams\", value: false },\n};\nconst _ep1 = {\n IsOAuthEndpoint: { type: \"staticContextParams\", value: true },\n};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass CreateOAuth2TokenCommand extends command(_ep0, _mw0, \"CreateOAuth2Token\", CreateOAuth2Token$) {\n}\n\nclass CreateOAuth2TokenWithIAMCommand extends command(_ep1, _mw0, \"CreateOAuth2TokenWithIAM\", CreateOAuth2TokenWithIAM$) {\n}\n\nconst commands = {\n CreateOAuth2TokenCommand,\n CreateOAuth2TokenWithIAMCommand,\n};\nclass Signin extends SigninClient {\n}\ncreateAggregatedClient(commands, Signin);\n\nconst OAuth2ErrorCode = {\n AUTHCODE_EXPIRED: \"AUTHCODE_EXPIRED\",\n CONFLICT: \"CONFLICT\",\n INSUFFICIENT_PERMISSIONS: \"INSUFFICIENT_PERMISSIONS\",\n INVALID_REQUEST: \"INVALID_REQUEST\",\n RESOURCE_NOT_FOUND: \"RESOURCE_NOT_FOUND\",\n SERVER_ERROR: \"server_error\",\n SERVICE_QUOTA_EXCEEDED: \"SERVICE_QUOTA_EXCEEDED\",\n TOKEN_EXPIRED: \"TOKEN_EXPIRED\",\n USER_CREDENTIALS_CHANGED: \"USER_CREDENTIALS_CHANGED\",\n};\n\nexports.AccessDeniedException = AccessDeniedException;\nexports.AccessDeniedException$ = AccessDeniedException$;\nexports.AccessToken$ = AccessToken$;\nexports.CreateOAuth2Token$ = CreateOAuth2Token$;\nexports.CreateOAuth2TokenCommand = CreateOAuth2TokenCommand;\nexports.CreateOAuth2TokenRequest$ = CreateOAuth2TokenRequest$;\nexports.CreateOAuth2TokenRequestBody$ = CreateOAuth2TokenRequestBody$;\nexports.CreateOAuth2TokenResponse$ = CreateOAuth2TokenResponse$;\nexports.CreateOAuth2TokenResponseBody$ = CreateOAuth2TokenResponseBody$;\nexports.CreateOAuth2TokenWithIAM$ = CreateOAuth2TokenWithIAM$;\nexports.CreateOAuth2TokenWithIAMCommand = CreateOAuth2TokenWithIAMCommand;\nexports.CreateOAuth2TokenWithIAMRequest$ = CreateOAuth2TokenWithIAMRequest$;\nexports.CreateOAuth2TokenWithIAMResponse$ = CreateOAuth2TokenWithIAMResponse$;\nexports.InternalServerException = InternalServerException;\nexports.InternalServerException$ = InternalServerException$;\nexports.OAuth2ErrorCode = OAuth2ErrorCode;\nexports.Signin = Signin;\nexports.SigninClient = SigninClient;\nexports.SigninServiceException = SigninServiceException;\nexports.SigninServiceException$ = SigninServiceException$;\nexports.TooManyRequestsError = TooManyRequestsError;\nexports.TooManyRequestsError$ = TooManyRequestsError$;\nexports.ValidationException = ValidationException;\nexports.ValidationException$ = ValidationException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";+VAAA,SAAQ,6BAAsB,qCAAiC,QAAmC,uCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAA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C1B,GAAuB,EACvB,GAAwB,GACxB,GAAsB,EACtB,GAAuB,GACvB,GAAsB", | ||
| "debugId": "C11C8CE5D6976AF364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/utils/image-input.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Encoding } from \"effect\"\nimport type { ImageInput } from \"../../image\"\nimport { InvalidRequestReason, LLMError } from \"../../schema\"\n\nconst invalid = (module: string, message: string) =>\n new LLMError({\n module,\n method: \"generate\",\n reason: new InvalidRequestReason({ message }),\n })\n\nexport const dataUrl = (input: Extract<ImageInput, { readonly type: \"bytes\" }>) =>\n `data:${input.mediaType};base64,${Encoding.encodeBase64(input.data)}`\n\nexport const decodeDataUrl = (\n url: string,\n module: string,\n): Effect.Effect<{ readonly mediaType: string; readonly data: Uint8Array } | undefined, LLMError> => {\n if (!url.startsWith(\"data:\")) return Effect.succeed(undefined)\n const match = /^data:([^;,]+);base64,(.*)$/s.exec(url)\n if (!match) return Effect.fail(invalid(module, \"Image data URLs must contain a MIME type and base64 data\"))\n return Effect.fromResult(Encoding.decodeBase64(match[2])).pipe(\n Effect.mapError(() => invalid(module, \"Image data URL contains invalid base64 data\")),\n Effect.map((data) => ({ mediaType: match[1], data })),\n )\n}\n\nexport const invalidImageInput = invalid\n\nexport const ImageInputs = {\n dataUrl,\n decodeDataUrl,\n invalid: invalidImageInput,\n} as const\n" | ||
| ], | ||
| "mappings": ";mHAIA,SAAM,EAAU,CAAC,EAAgB,IAC/B,IAAI,EAAS,CACX,SACA,OAAQ,WACR,OAAQ,IAAI,EAAqB,CAAE,SAAQ,CAAC,CAC9C,CAAC,EAEU,EAAU,CAAC,IACtB,QAAQ,EAAM,oBAAoB,EAAS,aAAa,EAAM,IAAI,IAEvD,EAAgB,CAC3B,EACA,IACmG,CACnG,GAAI,CAAC,EAAI,WAAW,OAAO,EAAG,OAAO,EAAO,QAAQ,MAAS,EAC7D,IAAM,EAAQ,+BAA+B,KAAK,CAAG,EACrD,GAAI,CAAC,EAAO,OAAO,EAAO,KAAK,EAAQ,EAAQ,0DAA0D,CAAC,EAC1G,OAAO,EAAO,WAAW,EAAS,aAAa,EAAM,EAAE,CAAC,EAAE,KACxD,EAAO,SAAS,IAAM,EAAQ,EAAQ,6CAA6C,CAAC,EACpF,EAAO,IAAI,CAAC,KAAU,CAAE,UAAW,EAAM,GAAI,MAAK,EAAE,CACtD,GAGW,EAAoB,EAEpB,EAAc,CACzB,UACA,gBACA,QAAS,CACX", | ||
| "debugId": "BB3E1AD4AB6DF80164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "E32D77328B59962364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.33/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"awsssoportal\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSSOHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetRoleCredentials\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"awsssoportal\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.32\";\nvar packageInfo = {\n\tversion: version};\n\nconst k = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = { [k]: \"Endpoint\" }, h = { [k]: d }, i = {}, j = [{ [k]: \"Region\" }];\nconst _data = {\n conditions: [\n [c, [g]],\n [c, j],\n [\"aws.partition\", j, d],\n [e, [{ [k]: \"UseFIPS\" }, b]],\n [e, [{ [k]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [h, \"supportsDualStack\"] }, b]],\n [e, [{ fn: f, argv: [h, \"supportsFIPS\"] }, b]],\n [\"stringEquals\", [{ fn: f, argv: [h, \"name\"] }, \"aws-us-gov\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [g, i],\n [\"https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://portal.sso.{Region}.amazonaws.com\", i],\n [\"https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://portal.sso.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 13, 3,\n 1, 4, r + 12,\n 2, 5, r + 12,\n 3, 8, 6,\n 4, 7, r + 11,\n 5, r + 9, r + 10,\n 4, 11, 9,\n 6, 10, r + 8,\n 7, r + 6, r + 7,\n 5, 12, r + 5,\n 6, r + 4, r + 5,\n 3, r + 1, 14,\n 4, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SSOServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOServiceException.prototype);\n }\n}\n\nclass InvalidRequestException extends SSOServiceException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n }\n}\nclass ResourceNotFoundException extends SSOServiceException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nclass TooManyRequestsException extends SSOServiceException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nclass UnauthorizedException extends SSOServiceException {\n name = \"UnauthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"UnauthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedException.prototype);\n }\n}\n\nconst _ATT = \"AccessTokenType\";\nconst _GRC = \"GetRoleCredentials\";\nconst _GRCR = \"GetRoleCredentialsRequest\";\nconst _GRCRe = \"GetRoleCredentialsResponse\";\nconst _IRE = \"InvalidRequestException\";\nconst _RC = \"RoleCredentials\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SAKT = \"SecretAccessKeyType\";\nconst _STT = \"SessionTokenType\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _UE = \"UnauthorizedException\";\nconst _aI = \"accountId\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _ai = \"account_id\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _ex = \"expiration\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _hH = \"httpHeader\";\nconst _hQ = \"httpQuery\";\nconst _m = \"message\";\nconst _rC = \"roleCredentials\";\nconst _rN = \"roleName\";\nconst _rn = \"role_name\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.sso\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _xasbt = \"x-amz-sso_bearer_token\";\nconst n0 = \"com.amazonaws.sso\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SSOServiceException$ = [-3, _s, \"SSOServiceException\", 0, [], []];\n_s_registry.registerError(SSOServiceException$, SSOServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidRequestException$, InvalidRequestException);\nvar ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);\nvar TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nn0_registry.registerError(TooManyRequestsException$, TooManyRequestsException);\nvar UnauthorizedException$ = [-3, n0, _UE,\n { [_e]: _c, [_hE]: 401 },\n [_m],\n [0]\n];\nn0_registry.registerError(UnauthorizedException$, UnauthorizedException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar AccessTokenType = [0, n0, _ATT, 8, 0];\nvar SecretAccessKeyType = [0, n0, _SAKT, 8, 0];\nvar SessionTokenType = [0, n0, _STT, 8, 0];\nvar GetRoleCredentialsRequest$ = [3, n0, _GRCR,\n 0,\n [_rN, _aI, _aT],\n [[0, { [_hQ]: _rn }], [0, { [_hQ]: _ai }], [() => AccessTokenType, { [_hH]: _xasbt }]], 3\n];\nvar GetRoleCredentialsResponse$ = [3, n0, _GRCRe,\n 0,\n [_rC],\n [[() => RoleCredentials$, 0]]\n];\nvar RoleCredentials$ = [3, n0, _RC,\n 0,\n [_aKI, _sAK, _sT, _ex],\n [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1]\n];\nvar GetRoleCredentials$ = [9, n0, _GRC,\n { [_h]: [\"GET\", \"/federation/credentials\", 200] }, () => GetRoleCredentialsRequest$, () => GetRoleCredentialsResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.sso\",\n errorTypeRegistries,\n version: \"2019-06-10\",\n serviceTarget: \"SWBPortalService\",\n },\n serviceId: config?.serviceId ?? \"SSO\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SSOClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"SWBPortalService\", \"SSOClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass GetRoleCredentialsCommand extends command(_ep0, _mw0, \"GetRoleCredentials\", GetRoleCredentials$) {\n}\n\nconst commands = {\n GetRoleCredentialsCommand,\n};\nclass SSO extends SSOClient {\n}\ncreateAggregatedClient(commands, SSO);\n\nexports.GetRoleCredentials$ = GetRoleCredentials$;\nexports.GetRoleCredentialsCommand = GetRoleCredentialsCommand;\nexports.GetRoleCredentialsRequest$ = GetRoleCredentialsRequest$;\nexports.GetRoleCredentialsResponse$ = GetRoleCredentialsResponse$;\nexports.InvalidRequestException = InvalidRequestException;\nexports.InvalidRequestException$ = InvalidRequestException$;\nexports.ResourceNotFoundException = ResourceNotFoundException;\nexports.ResourceNotFoundException$ = ResourceNotFoundException$;\nexports.RoleCredentials$ = RoleCredentials$;\nexports.SSO = SSO;\nexports.SSOClient = SSOClient;\nexports.SSOServiceException = SSOServiceException;\nexports.SSOServiceException$ = SSOServiceException$;\nexports.TooManyRequestsException = TooManyRequestsException;\nexports.TooManyRequestsException$ = TooManyRequestsException$;\nexports.UnauthorizedException = UnauthorizedException;\nexports.UnauthorizedException$ = UnauthorizedException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";uVAAA,SAAQ,6BAAsB,qCAAiC,QAAmC,uCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,UAAQ,eAAa,gCACnN,QAAS,QAGjB,IAAQ,6BAA2B,aAAY,yCAAuC,8C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GAAwB,CAAS,EAC7C,EAAY,GAAsB,CAAS,EAC3C,EAAY,GAA4B,CAAS,EACjD,EAAY,GAAyB,EAAW,GAAe,YAAc,CAAC,CAAC,EACrF,KAAK,OAAS,EACd,KAAK,gBAAgB,IAAI,GAAqB,KAAK,MAAM,CAAC,EAC1D,KAAK,gBAAgB,IAAI,GAAmB,KAAK,MAAM,CAAC,EACxD,KAAK,gBAAgB,IAAI,GAAe,KAAK,MAAM,CAAC,EACpD,KAAK,gBAAgB,IAAI,GAAuB,KAAK,MAAM,CAAC,EAC5D,KAAK,gBAAgB,IAAI,GAAoB,KAAK,MAAM,CAAC,EACzD,KAAK,gBAAgB,IAAI,GAAgB,KAAK,MAAM,CAAC,EACrD,KAAK,gBAAgB,IAAI,GAA4B,KAAK,MAAM,CAAC,EACjE,KAAK,gBAAgB,IAAI,GAAuC,KAAK,OAAQ,CACzE,iCAAkC,GAClC,+BAAgC,MAAO,IAAW,IAAI,GAA8B,CAChF,iBAAkB,EAAO,WAC7B,CAAC,CACL,CAAC,CAAC,EACF,KAAK,gBAAgB,IAAI,GAAqB,KAAK,MAAM,CAAC,EAE9D,OAAO,EAAG,CACN,MAAM,QAAQ,EAEtB,CAEA,IAAM,GAAU,GAAY,GAAc,mBAAoB,YAAa,EAAiB,EACtF,GAAO,CAAC,EACR,GAAO,CAAC,EAAS,EAAI,EAAQ,IAAM,CAAC,EAE1C,MAAM,UAAkC,GAAQ,GAAM,GAAM,qBAAsB,EAAmB,CAAE,CACvG,CAEA,IAAM,GAAW,CACb,2BACJ,EACA,MAAM,UAAY,CAAU,CAC5B,CACA,GAAuB,GAAU,CAAG,EAGpC,IAAQ,EAA4B,EASpC,IAAQ,EAAY", | ||
| "debugId": "50252FD8E1C76EF064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/gemini.ts", "../ai/src/protocols/google-images.ts", "../ai/src/providers/google.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Framing } from \"../route/framing\"\nimport { Protocol } from \"../route/protocol\"\nimport {\n LLMEvent,\n Usage,\n type FinishReason,\n type JsonSchema,\n type LLMRequest,\n type MediaPart,\n type ProviderMetadata,\n type TextPart,\n type ToolCallPart,\n type ToolDefinition,\n type ToolContent,\n} from \"../schema\"\nimport { JsonObject, optionalArray, ProviderShared } from \"./shared\"\nimport { GeminiToolSchema } from \"./utils/gemini-tool-schema\"\nimport { Lifecycle } from \"./utils/lifecycle\"\nimport { ToolSchemaProjection } from \"./utils/tool-schema\"\n\nconst ADAPTER = \"gemini\"\nconst MEDIA_MIMES = new Set<string>(ProviderShared.MEDIA_MIMES)\nexport const DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com/v1beta\"\n\n// =============================================================================\n// Request Body Schema\n// =============================================================================\nconst GeminiTextPart = Schema.Struct({\n text: Schema.String,\n thought: Schema.optional(Schema.Boolean),\n thoughtSignature: Schema.optional(Schema.String),\n})\n\nconst GeminiInlineDataPart = Schema.Struct({\n inlineData: Schema.Struct({\n mimeType: Schema.String,\n data: Schema.String,\n }),\n})\n\nconst GeminiFunctionCallPart = Schema.Struct({\n functionCall: Schema.Struct({\n name: Schema.String,\n args: Schema.Unknown,\n }),\n thoughtSignature: Schema.optional(Schema.String),\n})\n\nconst GeminiFunctionResponsePart = Schema.Struct({\n functionResponse: Schema.Struct({\n name: Schema.String,\n response: Schema.Unknown,\n }),\n})\n\nconst GeminiContentPart = Schema.Union([\n GeminiTextPart,\n GeminiInlineDataPart,\n GeminiFunctionCallPart,\n GeminiFunctionResponsePart,\n])\n\nconst GeminiContent = Schema.Struct({\n role: Schema.Literals([\"user\", \"model\"]),\n parts: Schema.Array(GeminiContentPart),\n})\ntype GeminiContent = Schema.Schema.Type<typeof GeminiContent>\n\nconst GeminiSystemInstruction = Schema.Struct({\n parts: Schema.Array(Schema.Struct({ text: Schema.String })),\n})\n\nconst GeminiFunctionDeclaration = Schema.Struct({\n name: Schema.String,\n description: Schema.String,\n parameters: Schema.optional(JsonObject),\n})\n\nconst GeminiTool = Schema.Struct({\n functionDeclarations: Schema.Array(GeminiFunctionDeclaration),\n})\n\nconst GeminiToolConfig = Schema.Struct({\n functionCallingConfig: Schema.Struct({\n mode: Schema.Literals([\"AUTO\", \"NONE\", \"ANY\"]),\n allowedFunctionNames: optionalArray(Schema.String),\n }),\n})\n\nconst GeminiThinkingConfig = Schema.Struct({\n thinkingBudget: Schema.optional(Schema.Number),\n includeThoughts: Schema.optional(Schema.Boolean),\n})\n\nconst GeminiGenerationConfig = Schema.Struct({\n maxOutputTokens: Schema.optional(Schema.Number),\n temperature: Schema.optional(Schema.Number),\n topP: Schema.optional(Schema.Number),\n topK: Schema.optional(Schema.Number),\n stopSequences: optionalArray(Schema.String),\n thinkingConfig: Schema.optional(GeminiThinkingConfig),\n})\n\nconst GeminiBodyFields = {\n contents: Schema.Array(GeminiContent),\n systemInstruction: Schema.optional(GeminiSystemInstruction),\n tools: optionalArray(GeminiTool),\n toolConfig: Schema.optional(GeminiToolConfig),\n generationConfig: Schema.optional(GeminiGenerationConfig),\n}\nconst GeminiBody = Schema.Struct(GeminiBodyFields)\nexport type GeminiBody = Schema.Schema.Type<typeof GeminiBody>\n\nconst GeminiUsage = Schema.Struct({\n cachedContentTokenCount: Schema.optional(Schema.Number),\n thoughtsTokenCount: Schema.optional(Schema.Number),\n promptTokenCount: Schema.optional(Schema.Number),\n candidatesTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n})\ntype GeminiUsage = Schema.Schema.Type<typeof GeminiUsage>\n\nconst GeminiCandidate = Schema.Struct({\n content: Schema.optional(GeminiContent),\n finishReason: Schema.optional(Schema.String),\n})\n\nconst GeminiEvent = Schema.Struct({\n candidates: optionalArray(GeminiCandidate),\n usageMetadata: Schema.optional(GeminiUsage),\n})\ntype GeminiEvent = Schema.Schema.Type<typeof GeminiEvent>\n\ninterface ParserState {\n readonly finishReason?: string\n readonly hasToolCalls: boolean\n readonly nextToolCallId: number\n readonly usage?: Usage\n readonly lifecycle: Lifecycle.State\n readonly reasoningSignature?: string\n}\n\n// =============================================================================\n// Tool Schema Conversion\n// =============================================================================\n// Tool-schema conversion has two distinct concerns:\n//\n// 1. Sanitize — fix common authoring mistakes Gemini rejects: integer/number\n// enums (must be strings), `required` entries that don't match a property,\n// untyped arrays (`items` must be present), and `properties`/`required`\n// keys on non-object scalars. Mirrors OpenCode's historical Gemini rules.\n//\n// 2. Project — lossy mapping from JSON Schema to Gemini's schema dialect:\n// drop empty objects, derive `nullable: true` from `type: [..., \"null\"]`,\n// coerce `const` to `[const]` enum, recurse properties/items, propagate\n// only an allowlisted set of keys (description, required, format, type,\n// properties, items, allOf, anyOf, oneOf, minLength). Anything outside the\n// allowlist (e.g. `additionalProperties`, `$ref`) is silently dropped.\n//\n// Sanitize runs first, then project. The implementation lives in\n// `utils/gemini-tool-schema` so this protocol keeps the same shape as the other\n// provider protocols.\n\n// =============================================================================\n// Request Lowering\n// =============================================================================\nconst lowerTool = (tool: ToolDefinition, inputSchema: JsonSchema) => ({\n name: tool.name,\n description: tool.description,\n parameters: GeminiToolSchema.convert(inputSchema),\n})\n\nconst lowerToolConfig = (toolChoice: NonNullable<LLMRequest[\"toolChoice\"]>) =>\n ProviderShared.matchToolChoice(\"Gemini\", toolChoice, {\n auto: () => ({ functionCallingConfig: { mode: \"AUTO\" as const } }),\n none: () => ({ functionCallingConfig: { mode: \"NONE\" as const } }),\n required: () => ({ functionCallingConfig: { mode: \"ANY\" as const } }),\n tool: (name) => ({ functionCallingConfig: { mode: \"ANY\" as const, allowedFunctionNames: [name] } }),\n })\n\nconst lowerUserPart = Effect.fn(\"Gemini.lowerUserPart\")(function* (part: TextPart | MediaPart) {\n if (part.type === \"text\") return { text: part.text }\n const media = yield* ProviderShared.validateMedia(\"Gemini\", part, MEDIA_MIMES)\n return { inlineData: { mimeType: media.mime, data: media.base64 } }\n})\n\nconst googleMetadata = (metadata: Record<string, unknown>): ProviderMetadata => ({ google: metadata })\n\nconst thoughtSignature = (providerMetadata: ProviderMetadata | undefined) => {\n const google = providerMetadata?.google\n return ProviderShared.isRecord(google) && typeof google.thoughtSignature === \"string\"\n ? google.thoughtSignature\n : undefined\n}\n\nconst lowerToolCall = (part: ToolCallPart) => ({\n functionCall: { name: part.name, args: part.input },\n thoughtSignature: thoughtSignature(part.providerMetadata),\n})\n\nconst lowerMessages = Effect.fn(\"Gemini.lowerMessages\")(function* (request: LLMRequest) {\n const contents: GeminiContent[] = []\n\n for (const message of request.messages) {\n if (message.role === \"system\") {\n const part = yield* ProviderShared.wrappedSystemUpdate(\"Gemini\", message)\n const previous = contents.at(-1)\n if (previous?.role === \"user\")\n contents[contents.length - 1] = { role: \"user\", parts: [...previous.parts, { text: part.text }] }\n else contents.push({ role: \"user\", parts: [{ text: part.text }] })\n continue\n }\n\n if (message.role === \"user\") {\n const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"media\"]))\n return yield* ProviderShared.unsupportedContent(\"Gemini\", \"user\", [\"text\", \"media\"])\n parts.push(yield* lowerUserPart(part))\n }\n contents.push({ role: \"user\", parts })\n continue\n }\n\n if (message.role === \"assistant\") {\n const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"reasoning\", \"tool-call\"]))\n return yield* ProviderShared.unsupportedContent(\"Gemini\", \"assistant\", [\"text\", \"reasoning\", \"tool-call\"])\n if (part.type === \"text\") {\n parts.push({ text: part.text })\n continue\n }\n if (part.type === \"reasoning\") {\n parts.push({ text: part.text, thought: true, thoughtSignature: thoughtSignature(part.providerMetadata) })\n continue\n }\n if (part.type === \"tool-call\") {\n parts.push(lowerToolCall(part))\n continue\n }\n }\n contents.push({ role: \"model\", parts })\n continue\n }\n\n const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"tool-result\"]))\n return yield* ProviderShared.unsupportedContent(\"Gemini\", \"tool\", [\"tool-result\"])\n if (part.result.type !== \"content\") {\n parts.push({\n functionResponse: {\n name: part.name,\n response: {\n name: part.name,\n content: ProviderShared.toolResultText(part),\n },\n },\n })\n continue\n }\n const content: ReadonlyArray<ToolContent> = part.result.value\n const text = content.filter((item) => item.type === \"text\").map((item) => item.text)\n parts.push({\n functionResponse: {\n name: part.name,\n response: {\n name: part.name,\n content: text.join(\"\\n\"),\n },\n },\n })\n for (const item of content) {\n if (item.type === \"text\") continue\n const media = yield* ProviderShared.validateToolFile(\"Gemini\", item, MEDIA_MIMES)\n parts.push({ inlineData: { mimeType: media.mime, data: media.base64 } })\n }\n }\n contents.push({ role: \"user\", parts })\n }\n\n return contents\n})\n\nconst geminiOptions = (request: LLMRequest) => request.providerOptions?.gemini\n\nconst thinkingConfig = (request: LLMRequest) => {\n const value = geminiOptions(request)?.thinkingConfig\n if (!ProviderShared.isRecord(value)) return undefined\n const result = {\n thinkingBudget: typeof value.thinkingBudget === \"number\" ? value.thinkingBudget : undefined,\n includeThoughts: typeof value.includeThoughts === \"boolean\" ? value.includeThoughts : undefined,\n }\n return Object.values(result).some((item) => item !== undefined) ? result : undefined\n}\n\nconst fromRequest = Effect.fn(\"Gemini.fromRequest\")(function* (request: LLMRequest) {\n const toolsEnabled = request.tools.length > 0 && request.toolChoice?.type !== \"none\"\n const generation = request.generation\n const toolSchemaCompatibility = request.model.compatibility?.toolSchema\n const generationConfig = {\n maxOutputTokens: generation?.maxTokens,\n temperature: generation?.temperature,\n topP: generation?.topP,\n topK: generation?.topK,\n stopSequences: generation?.stop,\n thinkingConfig: thinkingConfig(request),\n }\n\n return {\n contents: yield* lowerMessages(request),\n systemInstruction:\n request.system.length === 0 ? undefined : { parts: [{ text: ProviderShared.joinText(request.system) }] },\n tools: toolsEnabled\n ? [\n {\n functionDeclarations: request.tools.map((tool) =>\n lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),\n ),\n },\n ]\n : undefined,\n toolConfig: toolsEnabled && request.toolChoice ? yield* lowerToolConfig(request.toolChoice) : undefined,\n generationConfig: Object.values(generationConfig).some((value) => value !== undefined)\n ? generationConfig\n : undefined,\n }\n})\n\n// =============================================================================\n// Stream Parsing\n// =============================================================================\n// Gemini reports `promptTokenCount` (inclusive total) with a\n// `cachedContentTokenCount` subset. `candidatesTokenCount` is *exclusive*\n// of `thoughtsTokenCount` — visible-only, not a total — so we sum the two\n// to produce the inclusive `outputTokens` the rest of the contract expects.\nconst mapUsage = (usage: GeminiUsage | undefined) => {\n if (!usage) return undefined\n const cached = usage.cachedContentTokenCount\n const nonCached = ProviderShared.subtractTokens(usage.promptTokenCount, cached)\n // `candidatesTokenCount` is visible-only; sum with thoughts to produce the\n // inclusive `outputTokens` the contract expects. Only compute the total\n // when the visible component is reported — otherwise we'd fabricate an\n // inclusive number from a partial breakdown.\n const outputTokens =\n usage.candidatesTokenCount !== undefined ? usage.candidatesTokenCount + (usage.thoughtsTokenCount ?? 0) : undefined\n return new Usage({\n inputTokens: usage.promptTokenCount,\n outputTokens,\n nonCachedInputTokens: nonCached,\n cacheReadInputTokens: cached,\n reasoningTokens: usage.thoughtsTokenCount,\n totalTokens: ProviderShared.totalTokens(usage.promptTokenCount, outputTokens, usage.totalTokenCount),\n providerMetadata: { google: usage },\n })\n}\n\nconst mapFinishReason = (finishReason: string | undefined, hasToolCalls: boolean): FinishReason => {\n if (finishReason === \"STOP\") return hasToolCalls ? \"tool-calls\" : \"stop\"\n if (finishReason === \"MAX_TOKENS\") return \"length\"\n if (\n finishReason === \"IMAGE_SAFETY\" ||\n finishReason === \"RECITATION\" ||\n finishReason === \"SAFETY\" ||\n finishReason === \"BLOCKLIST\" ||\n finishReason === \"PROHIBITED_CONTENT\" ||\n finishReason === \"SPII\"\n )\n return \"content-filter\"\n if (finishReason === \"MALFORMED_FUNCTION_CALL\") return \"error\"\n return \"unknown\"\n}\n\nconst finish = (state: ParserState): ReadonlyArray<LLMEvent> =>\n state.finishReason || state.usage\n ? (() => {\n const events: LLMEvent[] = []\n const lifecycle = state.reasoningSignature\n ? Lifecycle.reasoningEnd(\n state.lifecycle,\n events,\n \"reasoning-0\",\n googleMetadata({ thoughtSignature: state.reasoningSignature }),\n )\n : state.lifecycle\n Lifecycle.finish(lifecycle, events, {\n reason: mapFinishReason(state.finishReason, state.hasToolCalls),\n usage: state.usage,\n })\n return events\n })()\n : []\n\nconst step = (state: ParserState, event: GeminiEvent) => {\n const nextState = {\n ...state,\n usage: event.usageMetadata ? (mapUsage(event.usageMetadata) ?? state.usage) : state.usage,\n }\n const candidate = event.candidates?.[0]\n if (!candidate?.content)\n return Effect.succeed([\n { ...nextState, finishReason: candidate?.finishReason ?? nextState.finishReason },\n [],\n ] as const)\n\n const events: LLMEvent[] = []\n let hasToolCalls = nextState.hasToolCalls\n let lifecycle = nextState.lifecycle\n let nextToolCallId = nextState.nextToolCallId\n let reasoningSignature = nextState.reasoningSignature\n\n for (const part of candidate.content.parts) {\n if (\"thoughtSignature\" in part && part.thoughtSignature && \"thought\" in part && part.thought)\n reasoningSignature = part.thoughtSignature\n if (\"text\" in part && part.text.length > 0) {\n if (part.thought) {\n lifecycle = Lifecycle.reasoningDelta(\n lifecycle,\n events,\n \"reasoning-0\",\n part.text,\n part.thoughtSignature ? googleMetadata({ thoughtSignature: part.thoughtSignature }) : undefined,\n )\n continue\n }\n lifecycle = Lifecycle.reasoningEnd(\n lifecycle,\n events,\n \"reasoning-0\",\n reasoningSignature ? googleMetadata({ thoughtSignature: reasoningSignature }) : undefined,\n )\n lifecycle = Lifecycle.textDelta(lifecycle, events, \"text-0\", part.text)\n continue\n }\n\n if (\"functionCall\" in part) {\n const input = part.functionCall.args\n const id = `tool_${nextToolCallId++}`\n lifecycle = Lifecycle.reasoningEnd(\n lifecycle,\n events,\n \"reasoning-0\",\n reasoningSignature ? googleMetadata({ thoughtSignature: reasoningSignature }) : undefined,\n )\n lifecycle = Lifecycle.stepStart(lifecycle, events)\n events.push(\n LLMEvent.toolCall({\n id,\n name: part.functionCall.name,\n input,\n providerMetadata: part.thoughtSignature\n ? googleMetadata({ thoughtSignature: part.thoughtSignature })\n : undefined,\n }),\n )\n hasToolCalls = true\n }\n }\n\n return Effect.succeed([\n {\n ...nextState,\n hasToolCalls,\n lifecycle,\n nextToolCallId,\n reasoningSignature,\n finishReason: candidate.finishReason ?? nextState.finishReason,\n },\n events,\n ] as const)\n}\n\n// =============================================================================\n// Protocol And Gemini Route\n// =============================================================================\n/**\n * The Gemini protocol — request body construction, body schema, and the\n * streaming-event state machine. Used by Google AI Studio Gemini and (once\n * registered) Vertex Gemini.\n */\nexport const protocol = Protocol.make({\n id: ADAPTER,\n body: {\n schema: GeminiBody,\n from: fromRequest,\n },\n stream: {\n event: Protocol.jsonEvent(GeminiEvent),\n initial: () => ({ hasToolCalls: false, nextToolCallId: 0, lifecycle: Lifecycle.initial() }),\n step,\n onHalt: finish,\n },\n})\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: \"google\",\n providerMetadataKey: \"google\",\n protocol,\n // Gemini's path embeds the model id and pins SSE framing at the URL level.\n endpoint: Endpoint.path(({ request }) => `/models/${request.model.id}:streamGenerateContent?alt=sse`, {\n baseURL: DEFAULT_BASE_URL,\n }),\n auth: Auth.none,\n framing: Framing.sse,\n})\n\nexport * as Gemini from \"./gemini\"\n", | ||
| "import { Effect, Encoding, Schema } from \"effect\"\nimport { Headers, HttpClientRequest } from \"effect/unstable/http\"\nimport {\n GeneratedImage,\n ImageModel,\n ImageResponse,\n type ImageInput,\n type ImageRequestFor,\n type ImageRoute,\n} from \"../image\"\nimport { Auth, type Definition as AuthDefinition } from \"../route/auth\"\nimport {\n InvalidProviderOutputReason,\n LLMError,\n Usage,\n mergeHttpOptions,\n mergeJsonRecords,\n type HttpOptions,\n type ProviderMetadata,\n} from \"../schema\"\nimport { ProviderShared } from \"./shared\"\nimport { ImageInputs } from \"./utils/image-input\"\n\nconst ADAPTER = \"google-images\"\nexport const DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com/v1beta\"\n\nexport type GoogleImageString<Known extends string> = Known | (string & {})\n\nexport type GoogleImageOptions = {\n readonly aspectRatio?: GoogleImageString<\n \"1:1\" | \"2:3\" | \"3:2\" | \"3:4\" | \"4:3\" | \"4:5\" | \"5:4\" | \"9:16\" | \"16:9\" | \"21:9\"\n >\n readonly imageSize?: GoogleImageString<\"1K\" | \"2K\" | \"4K\">\n readonly seed?: number\n readonly thinkingLevel?: GoogleImageString<\"MINIMAL\" | \"LOW\" | \"MEDIUM\" | \"HIGH\">\n readonly includeThoughts?: boolean\n} & Record<string, unknown>\n\nexport type GoogleImageBody = Record<string, unknown> & {\n readonly contents: ReadonlyArray<{\n readonly role: \"user\"\n readonly parts: ReadonlyArray<Record<string, unknown>>\n }>\n readonly generationConfig: Record<string, unknown>\n}\n\nconst GoogleUsage = Schema.StructWithRest(\n Schema.Struct({\n cachedContentTokenCount: Schema.optional(Schema.Number),\n thoughtsTokenCount: Schema.optional(Schema.Number),\n promptTokenCount: Schema.optional(Schema.Number),\n candidatesTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n promptTokensDetails: Schema.optional(Schema.Unknown),\n candidatesTokensDetails: Schema.optional(Schema.Unknown),\n }),\n [Schema.Record(Schema.String, Schema.Unknown)],\n)\n\nconst GoogleImageResponse = Schema.Struct({\n candidates: Schema.optional(\n Schema.Array(\n Schema.Struct({\n index: Schema.optional(Schema.Number),\n content: Schema.optional(\n Schema.Struct({\n parts: Schema.Array(\n Schema.Struct({\n text: Schema.optional(Schema.String),\n thought: Schema.optional(Schema.Boolean),\n thoughtSignature: Schema.optional(Schema.String),\n inlineData: Schema.optional(\n Schema.Struct({\n mimeType: Schema.String,\n data: Schema.String,\n }),\n ),\n }),\n ),\n }),\n ),\n finishReason: Schema.optional(Schema.String),\n finishMessage: Schema.optional(Schema.String),\n safetyRatings: Schema.optional(Schema.Unknown),\n citationMetadata: Schema.optional(Schema.Unknown),\n groundingMetadata: Schema.optional(Schema.Unknown),\n }),\n ),\n ),\n usageMetadata: Schema.optional(GoogleUsage),\n modelVersion: Schema.optional(Schema.String),\n responseId: Schema.optional(Schema.String),\n promptFeedback: Schema.optional(Schema.Unknown),\n})\n\nexport interface ModelInput {\n readonly id: string\n readonly auth: AuthDefinition\n readonly baseURL?: string\n readonly headers?: Record<string, string>\n readonly http?: HttpOptions\n}\n\nconst nativeOptions = (options: GoogleImageOptions | undefined) => {\n const { aspectRatio, imageSize, seed, thinkingLevel, includeThoughts, ...native } = options ?? {}\n const image = {\n aspectRatio,\n imageSize,\n }\n const thinkingConfig = {\n thinkingLevel,\n includeThoughts,\n }\n return (\n mergeJsonRecords(\n {\n responseModalities: [\"IMAGE\"],\n imageConfig: Object.values(image).some((value) => value !== undefined) ? image : undefined,\n seed,\n thinkingConfig: Object.values(thinkingConfig).some((value) => value !== undefined) ? thinkingConfig : undefined,\n },\n native,\n ) ?? { responseModalities: [\"IMAGE\"] }\n )\n}\n\nconst invalidOutput = (message: string, providerMetadata?: ProviderMetadata) =>\n new LLMError({\n module: ADAPTER,\n method: \"generate\",\n reason: new InvalidProviderOutputReason({ message, route: ADAPTER, providerMetadata }),\n })\n\nconst applyQuery = (url: string, query: Record<string, string> | undefined) => {\n if (!query) return url\n const next = new URL(url)\n Object.entries(query).forEach(([key, value]) => next.searchParams.set(key, value))\n return next.toString()\n}\n\nexport const model = (input: ModelInput) => {\n const route: ImageRoute<GoogleImageOptions> = {\n id: ADAPTER,\n generate: Effect.fn(\"GoogleImages.generate\")(function* (request: ImageRequestFor<GoogleImageOptions>, execute) {\n const imageParts = yield* Effect.forEach(request.images ?? [], googleImagePart)\n const http = mergeHttpOptions(request.model.http, request.http)\n const requestBody = mergeJsonRecords(\n {\n contents: [{ role: \"user\", parts: [{ text: request.prompt }, ...imageParts] }],\n generationConfig: nativeOptions(request.options),\n },\n http?.body,\n ) as GoogleImageBody\n const text = ProviderShared.encodeJson(requestBody)\n const url = applyQuery(\n `${(input.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\")}/models/${request.model.id}:generateContent`,\n http?.query,\n )\n const headers = yield* Auth.toEffect(input.auth)({\n request,\n method: \"POST\",\n url,\n body: text,\n headers: Headers.fromInput({ ...input.headers, ...http?.headers }),\n })\n const response = yield* execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(text, \"application/json\"),\n ),\n )\n const payload = yield* response.json.pipe(\n Effect.mapError(() => invalidOutput(\"Failed to read the Google Images response\")),\n )\n const decoded = yield* Schema.decodeUnknownEffect(GoogleImageResponse)(payload).pipe(\n Effect.mapError(() => invalidOutput(\"Google Images returned an invalid response\")),\n )\n const candidates = decoded.candidates ?? []\n const candidateMetadata = candidates.map((candidate, candidateIndex) => ({\n index: candidate.index ?? candidateIndex,\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n citationMetadata: candidate.citationMetadata,\n groundingMetadata: candidate.groundingMetadata,\n parts: (candidate.content?.parts ?? []).map((part) =>\n part.inlineData === undefined\n ? {\n type: \"text\",\n text: part.text,\n thought: part.thought,\n thoughtSignature: part.thoughtSignature,\n }\n : {\n type: \"inlineData\",\n mediaType: part.inlineData.mimeType,\n thought: part.thought,\n thoughtSignature: part.thoughtSignature,\n },\n ),\n }))\n const encoded = candidates.flatMap((candidate, candidateIndex) =>\n (candidate.content?.parts ?? []).flatMap((part, partIndex) =>\n part.inlineData === undefined || part.thought === true\n ? []\n : [{ candidate, candidateIndex, partIndex, inlineData: part.inlineData }],\n ),\n )\n const images = yield* Effect.forEach(encoded, (item) =>\n Effect.fromResult(Encoding.decodeBase64(item.inlineData.data)).pipe(\n Effect.mapError(() =>\n invalidOutput(\n `Google Images candidate ${item.candidateIndex} part ${item.partIndex} contains invalid base64 data`,\n ),\n ),\n Effect.map(\n (data) =>\n new GeneratedImage({\n mediaType: item.inlineData.mimeType,\n data,\n providerMetadata: {\n google: {\n candidateIndex: item.candidate.index ?? item.candidateIndex,\n partIndex: item.partIndex,\n finishReason: item.candidate.finishReason,\n safetyRatings: item.candidate.safetyRatings,\n citationMetadata: item.candidate.citationMetadata,\n groundingMetadata: item.candidate.groundingMetadata,\n thoughtSignature: item.candidate.content?.parts[item.partIndex]?.thoughtSignature,\n },\n },\n }),\n ),\n ),\n )\n if (images.length === 0) {\n const finishReasons = candidates.flatMap((candidate) =>\n candidate.finishReason === undefined ? [] : [candidate.finishReason],\n )\n return yield* invalidOutput(\n `Google Images returned no final images${\n finishReasons.length === 0 ? \"\" : ` (finish reasons: ${finishReasons.join(\", \")})`\n }; inspect reason.providerMetadata.google for prompt feedback and candidate details`,\n {\n google: {\n promptFeedback: decoded.promptFeedback,\n candidates: candidateMetadata,\n },\n },\n )\n }\n const usage = decoded.usageMetadata\n const outputTokens =\n usage?.candidatesTokenCount === undefined\n ? undefined\n : usage.candidatesTokenCount + (usage.thoughtsTokenCount ?? 0)\n return new ImageResponse({\n images,\n usage:\n usage === undefined\n ? undefined\n : new Usage({\n inputTokens: usage.promptTokenCount,\n outputTokens,\n nonCachedInputTokens: ProviderShared.subtractTokens(\n usage.promptTokenCount,\n usage.cachedContentTokenCount,\n ),\n cacheReadInputTokens: usage.cachedContentTokenCount,\n reasoningTokens: usage.thoughtsTokenCount,\n totalTokens: ProviderShared.totalTokens(usage.promptTokenCount, outputTokens, usage.totalTokenCount),\n providerMetadata: { google: usage },\n }),\n providerMetadata: {\n google: {\n modelVersion: decoded.modelVersion,\n responseId: decoded.responseId,\n promptFeedback: decoded.promptFeedback,\n candidates: candidateMetadata,\n },\n },\n })\n }),\n }\n return ImageModel.make<GoogleImageOptions>({ id: input.id, provider: \"google\", route, http: input.http })\n}\n\nconst googleImagePart = (image: ImageInput): Effect.Effect<Record<string, unknown>, LLMError> => {\n if (image.type === \"bytes\")\n return Effect.succeed({ inlineData: { mimeType: image.mediaType, data: Encoding.encodeBase64(image.data) } })\n if (image.type === \"file-uri\") return Effect.succeed({ fileData: { mimeType: image.mediaType, fileUri: image.uri } })\n if (image.type === \"url\")\n return ImageInputs.decodeDataUrl(image.url, ADAPTER).pipe(\n Effect.flatMap((decoded) => {\n if (decoded === undefined)\n return Effect.fail(\n ImageInputs.invalid(\n ADAPTER,\n \"Google generateContent does not fetch public image URLs; use bytes, a data URL, or a Gemini file URI\",\n ),\n )\n return Effect.succeed({\n inlineData: { mimeType: decoded.mediaType, data: Encoding.encodeBase64(decoded.data) },\n })\n }),\n )\n return Effect.fail(\n ImageInputs.invalid(ADAPTER, \"Google generateContent requires Gemini file URIs rather than provider file IDs\"),\n )\n}\n\nexport const GoogleImages = {\n model,\n} as const\n", | ||
| "import type { RouteDefaultsInput } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport type { ProviderAuthOption } from \"../route/auth-options\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { HttpOptions, ProviderID, mergeHttpOptions, type ModelID, type ProviderOptions } from \"../schema\"\nimport { Gemini } from \"../protocols/gemini\"\nimport { GoogleImages } from \"../protocols/google-images\"\n\nexport type { GoogleImageOptions } from \"../protocols/google-images\"\n\nexport const id = ProviderID.make(\"google\")\n\nexport const routes = [Gemini.route]\n\nexport type Config = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n }\n\nexport interface Settings extends ProviderPackage.Settings {\n readonly apiKey?: string\n readonly baseURL?: string\n readonly providerOptions?: ProviderOptions\n}\n\nconst auth = (options: ProviderAuthOption<\"optional\">) => {\n if (\"auth\" in options && options.auth) return options.auth\n return Auth.optional(\"apiKey\" in options ? options.apiKey : undefined, \"apiKey\")\n .orElse(Auth.config(\"GOOGLE_GENERATIVE_AI_API_KEY\"))\n .pipe(Auth.header(\"x-goog-api-key\"))\n}\n\nconst configuredRoute = (input: Config) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n return Gemini.route.with({ ...rest, endpoint: { baseURL }, auth: auth(input) })\n}\n\nexport const configure = (input: Config = {}) => {\n const route = configuredRoute(input)\n const image = (modelID: string | ModelID) =>\n GoogleImages.model({\n id: modelID,\n auth: auth(input),\n baseURL: input.baseURL,\n headers: input.headers,\n http: mergeHttpOptions(input.http === undefined ? undefined : HttpOptions.make(input.http)),\n })\n return {\n id,\n model: (modelID: string | ModelID) => route.model({ id: modelID }),\n image,\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure({\n apiKey: settings.apiKey,\n baseURL: settings.baseURL,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n providerOptions: settings.providerOptions,\n }).model(modelID)\n\nexport const image = provider.image\n" | ||
| ], | ||
| "mappings": ";ytBAwBA,SAAM,OAAU,cACV,OAAc,SAAI,SAAY,OAAe,gBAAW,OACjD,OAAmB,mDAK1B,GAAiB,EAAO,OAAO,CACnC,KAAM,EAAO,OACb,QAAS,EAAO,SAAS,EAAO,OAAO,EACvC,iBAAkB,EAAO,SAAS,EAAO,MAAM,CACjD,CAAC,EAEK,GAAuB,EAAO,OAAO,CACzC,WAAY,EAAO,OAAO,CACxB,SAAU,EAAO,OACjB,KAAM,EAAO,MACf,CAAC,CACH,CAAC,EAEK,GAAyB,EAAO,OAAO,CAC3C,aAAc,EAAO,OAAO,CAC1B,KAAM,EAAO,OACb,KAAM,EAAO,OACf,CAAC,EACD,iBAAkB,EAAO,SAAS,EAAO,MAAM,CACjD,CAAC,EAEK,GAA6B,EAAO,OAAO,CAC/C,iBAAkB,EAAO,OAAO,CAC9B,KAAM,EAAO,OACb,SAAU,EAAO,OACnB,CAAC,CACH,CAAC,EAEK,GAAoB,EAAO,MAAM,CACr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AQ,EAAG,KAAM,GAAK,CAAK,CAAE,CAAC,GAGnE,EAAY,CAAC,EAAgB,CAAC,IAAM,CAC/C,IAAM,EAAQ,GAAgB,CAAK,EASnC,MAAO,CACL,MACA,MAAO,CAAC,IAA8B,EAAM,MAAM,CAAE,GAAI,CAAQ,CAAC,EACjE,MAXY,CAAC,IACb,GAAa,MAAM,CACjB,GAAI,EACJ,KAAM,GAAK,CAAK,EAChB,QAAS,EAAM,QACf,QAAS,EAAM,QACf,KAAM,EAAiB,EAAM,OAAS,OAAY,OAAY,GAAY,KAAK,EAAM,IAAI,CAAC,CAC5F,CAAC,EAKD,WACF,GAGW,GAAW,EAAU,EACrB,GAAuD,CAAC,EAAS,IAC5E,EAAU,CACR,OAAQ,EAAS,OACjB,QAAS,EAAS,QAClB,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,OACjB,gBAAiB,EAAS,eAC5B,CAAC,EAAE,MAAM,CAAO,EAEL,GAAQ,GAAS", | ||
| "debugId": "3E7E3E066066763F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/openai-images.ts", "../ai/src/providers/openai.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Encoding, Schema } from \"effect\"\nimport { Headers, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\"\nimport {\n ImageModel,\n GeneratedImage,\n ImageResponse,\n type ImageInput,\n type ImageRequestFor,\n type ImageRoute,\n} from \"../image\"\nimport { Auth, type Definition as AuthDefinition } from \"../route/auth\"\nimport {\n InvalidProviderOutputReason,\n LLMError,\n Usage,\n mergeHttpOptions,\n mergeJsonRecords,\n type HttpOptions,\n} from \"../schema\"\nimport { ProviderShared } from \"./shared\"\nimport { ImageInputs } from \"./utils/image-input\"\nimport { OpenAIImage } from \"./utils/openai-image\"\n\nconst ADAPTER = \"openai-images\"\nexport const DEFAULT_BASE_URL = \"https://api.openai.com/v1\"\nexport const PATH = \"/images/generations\"\nexport const EDIT_PATH = \"/images/edits\"\n\nexport type OpenAIImageString<Known extends string> = Known | (string & {})\n\nexport type OpenAIImageOptions = {\n readonly mask?: ImageInput\n readonly n?: number\n readonly size?: OpenAIImageString<\n \"auto\" | \"256x256\" | \"512x512\" | \"1024x1024\" | \"1536x1024\" | \"1024x1536\" | \"1792x1024\" | \"1024x1792\"\n >\n readonly quality?: OpenAIImageString<\"auto\" | \"low\" | \"medium\" | \"high\" | \"standard\" | \"hd\">\n readonly background?: OpenAIImageString<\"auto\" | \"opaque\" | \"transparent\">\n readonly moderation?: OpenAIImageString<\"auto\" | \"low\">\n readonly outputFormat?: OpenAIImageString<\"png\" | \"jpeg\" | \"webp\">\n readonly outputCompression?: number\n} & Record<string, unknown>\n\nexport type OpenAIImageBody = Record<string, unknown> & {\n readonly model: string\n readonly prompt: string\n}\n\nconst OpenAIImageResponse = Schema.Struct({\n data: Schema.Array(\n Schema.Struct({\n b64_json: Schema.optional(Schema.String),\n url: Schema.optional(Schema.String),\n revised_prompt: Schema.optional(Schema.String),\n }),\n ),\n output_format: Schema.optional(Schema.String),\n usage: Schema.optional(\n Schema.Struct({\n input_tokens: Schema.optional(Schema.Number),\n output_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n input_tokens_details: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n output_tokens_details: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n }),\n ),\n})\n\nexport interface ModelInput {\n readonly id: string\n readonly auth: AuthDefinition\n readonly baseURL?: string\n readonly headers?: Record<string, string>\n readonly http?: HttpOptions\n}\n\nconst nativeOptions = (options: OpenAIImageOptions | undefined) => {\n if (!options) return undefined\n const { mask: _, outputFormat, outputCompression, ...native } = options\n return {\n output_format: outputFormat,\n output_compression: outputCompression,\n ...native,\n }\n}\n\nconst invalidOutput = (message: string) =>\n new LLMError({\n module: ADAPTER,\n method: \"generate\",\n reason: new InvalidProviderOutputReason({ message, route: ADAPTER }),\n })\n\nconst applyQuery = (url: string, query: Record<string, string> | undefined) => {\n if (!query) return url\n const next = new URL(url)\n Object.entries(query).forEach(([key, value]) => next.searchParams.set(key, value))\n return next.toString()\n}\n\nexport const model = (input: ModelInput) => {\n const route: ImageRoute<OpenAIImageOptions> = {\n id: ADAPTER,\n generate: Effect.fn(\"OpenAIImages.generate\")(function* (request: ImageRequestFor<OpenAIImageOptions>, execute) {\n const mask = request.options?.mask\n if (mask !== undefined && (request.images?.length ?? 0) === 0)\n return yield* ImageInputs.invalid(ADAPTER, \"An OpenAI image mask requires at least one input image\")\n const http = mergeHttpOptions(request.model.http, request.http)\n const sourceImages = request.images ?? []\n const multipartImages = yield* Effect.forEach(sourceImages, (image) => {\n if (image.type === \"bytes\") return Effect.succeed({ data: image.data, mediaType: image.mediaType })\n if (image.type === \"url\") return ImageInputs.decodeDataUrl(image.url, ADAPTER)\n return Effect.succeed(undefined)\n })\n const multipartMask =\n mask === undefined\n ? undefined\n : mask.type === \"bytes\"\n ? { data: mask.data, mediaType: mask.mediaType }\n : mask.type === \"url\"\n ? yield* ImageInputs.decodeDataUrl(mask.url, ADAPTER)\n : undefined\n const useMultipart =\n sourceImages.length > 0 &&\n multipartImages.every((image) => image !== undefined) &&\n (mask === undefined || multipartMask !== undefined)\n const path = sourceImages.length === 0 ? PATH : EDIT_PATH\n const url = applyQuery(`${(input.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\")}${path}`, http?.query)\n\n if (useMultipart) {\n const form = new FormData()\n form.append(\"model\", request.model.id)\n form.append(\"prompt\", request.prompt)\n Object.entries(mergeJsonRecords(nativeOptions(request.options), http?.body) ?? {}).forEach(([key, value]) => {\n if ([\"model\", \"prompt\", \"image\", \"image[]\", \"images\", \"mask\"].includes(key)) return\n form.append(key, typeof value === \"string\" ? value : ProviderShared.encodeJson(value))\n })\n multipartImages.forEach((image, index) => {\n if (image === undefined) return\n form.append(\"image[]\", imageBlob(image.data, image.mediaType), `image-${index}`)\n })\n if (multipartMask !== undefined)\n form.append(\"mask\", imageBlob(multipartMask.data, multipartMask.mediaType), \"mask\")\n const headers = yield* Auth.toEffect(input.auth)({\n request,\n method: \"POST\",\n url,\n body: \"[multipart/form-data]\",\n headers: Headers.remove(Headers.fromInput({ ...input.headers, ...http?.headers }), \"content-type\"),\n })\n const response = yield* execute(\n HttpClientRequest.post(url).pipe(HttpClientRequest.setHeaders(headers), HttpClientRequest.bodyFormData(form)),\n )\n return yield* parseResponse(response, request.options, http?.body)\n }\n\n const references = sourceImages.map((image) => {\n if (image.type === \"bytes\") return { image_url: ImageInputs.dataUrl(image) }\n if (image.type === \"url\") return { image_url: image.url }\n if (image.type === \"file-id\") return { file_id: image.id }\n return undefined\n })\n if (references.some((image) => image === undefined))\n return yield* ImageInputs.invalid(ADAPTER, \"OpenAI Images accepts image URLs, data URLs, bytes, and file IDs\")\n const maskReference =\n mask === undefined\n ? undefined\n : mask.type === \"bytes\"\n ? { image_url: ImageInputs.dataUrl(mask) }\n : mask.type === \"url\"\n ? { image_url: mask.url }\n : mask.type === \"file-id\"\n ? { file_id: mask.id }\n : undefined\n if (mask !== undefined && maskReference === undefined)\n return yield* ImageInputs.invalid(ADAPTER, \"OpenAI Images accepts masks as URLs, data URLs, bytes, or file IDs\")\n const requestBody = mergeJsonRecords(\n {\n model: request.model.id,\n prompt: request.prompt,\n images: references.length === 0 ? undefined : references,\n mask: maskReference,\n },\n nativeOptions(request.options),\n http?.body,\n ) as OpenAIImageBody\n const text = ProviderShared.encodeJson(requestBody)\n const headers = yield* Auth.toEffect(input.auth)({\n request,\n method: \"POST\",\n url,\n body: text,\n headers: Headers.fromInput({ ...input.headers, ...http?.headers }),\n })\n const response = yield* execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(text, \"application/json\"),\n ),\n )\n return yield* parseResponse(response, request.options, http?.body)\n }),\n }\n return ImageModel.make<OpenAIImageOptions>({ id: input.id, provider: \"openai\", route, http: input.http })\n}\n\nconst parseResponse = Effect.fn(\"OpenAIImages.parseResponse\")(function* (\n response: HttpClientResponse.HttpClientResponse,\n options: OpenAIImageOptions | undefined,\n overlay: Record<string, unknown> | undefined,\n) {\n const payload = yield* response.json.pipe(\n Effect.mapError(() => invalidOutput(\"Failed to read the OpenAI Images response\")),\n )\n const decoded = yield* Schema.decodeUnknownEffect(OpenAIImageResponse)(payload).pipe(\n Effect.mapError(() => invalidOutput(\"OpenAI Images returned an invalid response\")),\n )\n const requestBody = mergeJsonRecords(nativeOptions(options), overlay)\n const format =\n decoded.output_format ?? (typeof requestBody?.output_format === \"string\" ? requestBody.output_format : \"png\")\n const images = yield* Effect.forEach(decoded.data, (item, index) => {\n if (item.b64_json)\n return Effect.fromResult(Encoding.decodeBase64(item.b64_json)).pipe(\n Effect.mapError(() => invalidOutput(`OpenAI Images result ${index} contains invalid base64 data`)),\n Effect.map(\n (data) =>\n new GeneratedImage({\n mediaType: `image/${format}`,\n data,\n providerMetadata:\n item.revised_prompt === undefined ? undefined : { openai: { revisedPrompt: item.revised_prompt } },\n }),\n ),\n )\n if (item.url)\n return Effect.succeed(\n new GeneratedImage({\n mediaType: `image/${format}`,\n data: item.url,\n providerMetadata:\n item.revised_prompt === undefined ? undefined : { openai: { revisedPrompt: item.revised_prompt } },\n }),\n )\n return Effect.fail(invalidOutput(`OpenAI Images result ${index} has neither image data nor a URL`))\n })\n if (images.length === 0) return yield* invalidOutput(\"OpenAI Images returned no images\")\n return new ImageResponse({\n images,\n usage:\n decoded.usage === undefined\n ? undefined\n : new Usage({\n inputTokens: decoded.usage.input_tokens,\n outputTokens: decoded.usage.output_tokens,\n totalTokens: decoded.usage.total_tokens,\n providerMetadata: { openai: decoded.usage },\n }),\n providerMetadata: { openai: { outputFormat: format } },\n })\n})\n\nconst imageBlob = (data: Uint8Array, mediaType: string) => {\n const buffer = new ArrayBuffer(data.byteLength)\n new Uint8Array(buffer).set(data)\n return new Blob([buffer], { type: mediaType })\n}\n\nexport const OpenAIImages = {\n model,\n} as const\n", | ||
| "import { AuthOptions, type ProviderAuthOption } from \"../route/auth-options\"\nimport type { Route, RouteDefaultsInput } from \"../route/client\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { HttpOptions, ProviderID, ToolDefinition, mergeHttpOptions, type ModelID } from \"../schema\"\nimport * as OpenAIChat from \"../protocols/openai-chat\"\nimport * as OpenAIResponses from \"../protocols/openai-responses\"\nimport { withOpenAIOptions, type OpenAIProviderOptionsInput } from \"./openai-options\"\nimport { OpenAIImages, type OpenAIImageString } from \"../protocols/openai-images\"\n\nexport type { OpenAIOptionsInput, OpenAIResponseIncludable } from \"./openai-options\"\nexport type { OpenAIImageOptions } from \"../protocols/openai-images\"\n\nexport const id = ProviderID.make(\"openai\")\n\nexport const routes = [OpenAIResponses.route, OpenAIResponses.webSocketRoute, OpenAIChat.route]\n\n// This provider facade wraps the lower-level Responses and Chat model factories\n// with OpenAI-specific conveniences: typed options, API-key sugar, env fallback,\n// and default option normalization.\nexport type Config = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n readonly queryParams?: Record<string, string>\n readonly providerOptions?: OpenAIProviderOptionsInput\n }\n\nexport interface ImageGenerationOptions {\n readonly action?: OpenAIImageString<\"auto\" | \"generate\" | \"edit\">\n readonly background?: OpenAIImageString<\"auto\" | \"opaque\" | \"transparent\">\n readonly inputFidelity?: OpenAIImageString<\"low\" | \"high\">\n readonly outputCompression?: number\n readonly outputFormat?: OpenAIImageString<\"png\" | \"jpeg\" | \"webp\">\n readonly partialImages?: number\n readonly quality?: OpenAIImageString<\"auto\" | \"low\" | \"medium\" | \"high\" | \"standard\" | \"hd\">\n readonly size?: OpenAIImageString<\n \"auto\" | \"256x256\" | \"512x512\" | \"1024x1024\" | \"1536x1024\" | \"1024x1536\" | \"1792x1024\" | \"1024x1792\"\n >\n}\n\nexport const imageGeneration = (options: ImageGenerationOptions = {}) =>\n ToolDefinition.make({\n name: \"image_generation\",\n description: \"Generate or edit an image using OpenAI's hosted image generation tool.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n native: {\n openai: {\n type: \"image_generation\",\n action: options.action,\n background: options.background,\n input_fidelity: options.inputFidelity,\n output_compression: options.outputCompression,\n output_format: options.outputFormat,\n partial_images: options.partialImages,\n quality: options.quality,\n size: options.size,\n },\n },\n })\n\nexport interface Settings extends ProviderPackage.Settings {\n readonly apiKey?: string\n readonly baseURL?: string\n readonly organization?: string\n readonly project?: string\n readonly queryParams?: Readonly<Record<string, string>>\n readonly transport?: \"http\" | \"websocket\"\n readonly providerOptions?: OpenAIProviderOptionsInput\n}\n\nconst auth = (options: ProviderAuthOption<\"optional\">) => AuthOptions.bearer(options, \"OPENAI_API_KEY\")\n\nconst defaults = (input: Config) => {\n const { apiKey: _, auth: _auth, baseURL: _baseURL, queryParams: _queryParams, ...rest } = input\n return rest\n}\n\nconst configuredRoute = <Body, Prepared>(route: Route<Body, Prepared>, input: Config) =>\n route.with({\n auth: auth(input),\n endpoint: { baseURL: input.baseURL, query: input.queryParams },\n })\n\nexport const configure = (input: Config = {}) => {\n const responsesRoute = configuredRoute(OpenAIResponses.route, input)\n const responsesWebSocketRoute = configuredRoute(OpenAIResponses.webSocketRoute, input)\n const chatRoute = configuredRoute(OpenAIChat.route, input)\n const modelDefaults = defaults(input)\n const responses = (id: string | ModelID) =>\n responsesRoute.with(withOpenAIOptions(id, modelDefaults, { textVerbosity: true })).model({ id })\n const responsesWebSocket = (id: string | ModelID) =>\n responsesWebSocketRoute.with(withOpenAIOptions(id, modelDefaults, { textVerbosity: true })).model({ id })\n const chat = (id: string | ModelID) => chatRoute.with(withOpenAIOptions(id, modelDefaults)).model({ id })\n const image = (modelID: string | ModelID) =>\n OpenAIImages.model({\n id: modelID,\n auth: auth(input),\n baseURL: input.baseURL,\n headers: input.headers,\n http: mergeHttpOptions(\n input.http === undefined ? undefined : HttpOptions.make(input.http),\n input.queryParams === undefined ? undefined : new HttpOptions({ query: input.queryParams }),\n ),\n })\n\n return {\n id,\n model: responses,\n responses,\n responsesWebSocket,\n chat,\n image,\n configure,\n }\n}\n\nexport const provider = configure()\n\nconst config = (settings: Settings): Config => {\n const headers = {\n ...(settings.organization === undefined ? {} : { \"OpenAI-Organization\": settings.organization }),\n ...(settings.project === undefined ? {} : { \"OpenAI-Project\": settings.project }),\n ...settings.headers,\n }\n return {\n apiKey: settings.apiKey,\n baseURL: settings.baseURL,\n headers: Object.keys(headers).length === 0 ? undefined : headers,\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n providerOptions: settings.providerOptions,\n queryParams: settings.queryParams === undefined ? undefined : { ...settings.queryParams },\n }\n}\n\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) => {\n const configured = configure(config(settings))\n if (settings.transport === undefined || settings.transport === \"http\") return configured.responses(modelID)\n if (settings.transport === \"websocket\") return configured.responsesWebSocket(modelID)\n throw new Error(`Unsupported OpenAI Responses transport: ${String(settings.transport)}`)\n}\n\nexport const chatModel: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure(config(settings)).chat(modelID)\nexport const responses = provider.responses\nexport const responsesWebSocket = provider.responsesWebSocket\nexport const chat = provider.chat\nexport const image = provider.image\n" | ||
| ], | ||
| "mappings": ";oiBAuBA,SAAM,OAAU,qBACH,QAAmB,iCACnB,QAAO,2BACP,QAAY,gBAsBnB,GAAsB,EAAO,OAAO,CACxC,KAAM,EAAO,MACX,EAAO,OAAO,CACZ,SAAU,EAAO,SAAS,EAAO,MAAM,EACvC,IAAK,EAAO,SAAS,EAAO,MAAM,EAClC,eAAgB,EAAO,SAAS,EAAO,MAAM,CAC/C,CAAC,CACH,EACA,cAAe,EAAO,SAAS,EAAO,MAAM,EAC5C,MAAO,EAAO,SACZ,EAAO,OAAO,CACZ,aAAc,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E,OAAQ,EAAS,OACjB,gBAAiB,EAAS,gBAC1B,YAAa,EAAS,cAAgB,OAAY,OAAY,IAAK,EAAS,WAAY,CAC1F,GAGW,GAAuD,CAAC,EAAS,IAAa,CACzF,IAAM,EAAa,EAAU,EAAO,CAAQ,CAAC,EAC7C,GAAI,EAAS,YAAc,QAAa,EAAS,YAAc,OAAQ,OAAO,EAAW,UAAU,CAAO,EAC1G,GAAI,EAAS,YAAc,YAAa,OAAO,EAAW,mBAAmB,CAAO,EACpF,MAAU,MAAM,2CAA2C,OAAO,EAAS,SAAS,GAAG,GAG5E,GAA2D,CAAC,EAAS,IAChF,EAAU,EAAO,CAAQ,CAAC,EAAE,KAAK,CAAO,EAC7B,GAAY,EAAS,UACrB,GAAqB,EAAS,mBAC9B,GAAO,EAAS,KAChB,GAAQ,EAAS", | ||
| "debugId": "23C76EAD48E9C42264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+cerebras@2.0.41+d6123d32214422cb/node_modules/@ai-sdk/cerebras/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/cerebras-provider.ts\nimport { OpenAICompatibleChatLanguageModel } from \"@ai-sdk/openai-compatible\";\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\n\n// src/version.ts\nvar VERSION = true ? \"2.0.41\" : \"0.0.0-test\";\n\n// src/cerebras-provider.ts\nvar cerebrasErrorSchema = z.object({\n message: z.string(),\n type: z.string(),\n param: z.string(),\n code: z.string()\n});\nvar cerebrasErrorStructure = {\n errorSchema: cerebrasErrorSchema,\n errorToMessage: (data) => data.message\n};\nfunction createCerebras(options = {}) {\n var _a;\n const baseURL = withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.cerebras.ai/v1\"\n );\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"CEREBRAS_API_KEY\",\n description: \"Cerebras API key\"\n })}`,\n ...options.headers\n },\n `ai-sdk/cerebras/${VERSION}`\n );\n const createLanguageModel = (modelId) => {\n return new OpenAICompatibleChatLanguageModel(modelId, {\n provider: `cerebras.chat`,\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch,\n errorStructure: cerebrasErrorStructure,\n supportsStructuredOutputs: true\n });\n };\n const provider = (modelId) => createLanguageModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.languageModel = createLanguageModel;\n provider.chat = createLanguageModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar cerebras = createCerebras();\nexport {\n VERSION,\n cerebras,\n createCerebras\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";yVAaA,SAAI,OAAiB,cAGjB,OAAsB,OAAE,YAAO,MACjC,QAAS,EAAE,OAAO,EAClB,KAAM,EAAE,OAAO,EACf,MAAO,EAAE,OAAO,EAChB,KAAM,EAAE,OAAO,CACjB,CAAC,EACG,EAAyB,CAC3B,YAAa,EACb,eAAgB,CAAC,IAAS,EAAK,OACjC,EACA,SAAS,CAAc,CAAC,EAAU,CAAC,EAAG,CACpC,IAAI,EACJ,IAAM,EAAU,GACb,EAAK,EAAQ,UAAY,KAAO,EAAK,4BACxC,EACM,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,mBACzB,YAAa,kBACf,CAAC,OACE,EAAQ,OACb,EACA,mBAAmB,GACrB,EACM,EAAsB,CAAC,IAAY,CACvC,OAAO,IAAI,EAAkC,EAAS,CACpD,SAAU,gBACV,IAAK,EAAG,UAAW,GAAG,IAAU,IAChC,QAAS,EACT,MAAO,EAAQ,MACf,eAAgB,EAChB,0BAA2B,EAC7B,CAAC,GAEG,EAAW,CAAC,IAAY,EAAoB,CAAO,EAWzD,OAVA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,KAAO,EAChB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,EAAW,EAAe", | ||
| "debugId": "7C0C45F8A4BED66E64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "B22977C5D69FA8F964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "CD9B9D4B34667D6764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/logout.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.logout,\n Effect.fn(\"cli.mcp.logout\")(function* (input) {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n yield* Effect.forEach(\n credentials,\n (connection) => Effect.promise(() => client.credential.remove({ credentialID: connection.id, location })),\n { discard: true },\n )\n process.stdout.write(`Removed OAuth credentials for ${input.name}` + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";66BAAA,mBAAS,gBAST,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,YAC/B,OAAO,QAAG,qBAAgB,OAAE,cAAU,MAAC,OAAO,CAC5C,IAAM,EAAU,MAAO,EAAc,QAAQ,EAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EAAa,CAChB,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,IAAM,EAAc,EAAY,YAAY,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACnG,GAAI,EAAY,SAAW,EAAG,CAC5B,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,MAAO,EAAO,QACZ,EACA,CAAC,IAAe,EAAO,QAAQ,IAAM,EAAO,WAAW,OAAO,CAAE,aAAc,EAAW,GAAI,UAAS,CAAC,CAAC,EACxG,CAAE,QAAS,EAAK,CAClB,EACA,QAAQ,OAAO,MAAM,iCAAiC,EAAM,OAAS,CAAG,EACzE,CACH", | ||
| "debugId": "D55DC034FDF4FCEA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/set.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.set,\n Effect.fn(\"cli.service.set\")(function* (input) {\n yield* ServiceConfig.set(input.key, input.value)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";k0BAKA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,SACnC,OAAO,QAAG,sBAAiB,OAAE,cAAU,MAAC,OAAO,MAC7C,WAAO,OAAc,SAAI,OAAM,SAAK,OAAM,KAAK,EAChD,CACH", | ||
| "debugId": "217B0F21A34BBE0E64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/agents.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.agents,\n Effect.fn(\"cli.debug.agents\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.agent.list({ location: { directory: process.cwd() } }))\n process.stdout.write(\n JSON.stringify(\n response.data.toSorted((a, b) => a.id.localeCompare(b.id)),\n null,\n 2,\n ) + EOL,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";83BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,WAAM,cAAS,YACjC,OAAO,QAAG,uBAAkB,OAAE,cAAU,OAAG,MACzC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EAC1G,QAAQ,OAAO,MACb,KAAK,UACH,EAAS,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzD,KACA,CACF,EAAI,CACN,EACD,CACH", | ||
| "debugId": "97096986A07B4DC964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/utils/cache.ts"], | ||
| "sourcesContent": [ | ||
| "// Shared helpers for provider cache-marker lowering. Anthropic and Bedrock\n// both enforce a 4-breakpoint cap per request and accept the same `5m`/`1h`\n// TTL buckets, so the counter and TTL mapping live here.\n\nexport interface Breakpoints {\n remaining: number\n dropped: number\n}\n\nexport const newBreakpoints = (cap: number): Breakpoints => ({ remaining: cap, dropped: 0 })\n\n// Returns `\"1h\"` for any `ttlSeconds >= 3600`, otherwise `undefined` (the\n// provider default 5m). Anthropic & Bedrock both treat anything shorter than\n// an hour as 5m.\nexport const ttlBucket = (ttlSeconds: number | undefined): \"1h\" | undefined =>\n ttlSeconds !== undefined && ttlSeconds >= 3600 ? \"1h\" : undefined\n" | ||
| ], | ||
| "mappings": ";AASO,IAAM,EAAiB,CAAC,KAA8B,CAAE,UAAW,EAAK,QAAS,CAAE,GAK7E,EAAY,CAAC,IACxB,IAAe,QAAa,GAAc,KAAO,KAAO", | ||
| "debugId": "354589B05AF7929E64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+togetherai@2.0.41+d6123d32214422cb/node_modules/@ai-sdk/togetherai/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/togetherai-provider.ts\nimport {\n OpenAICompatibleChatLanguageModel,\n OpenAICompatibleCompletionLanguageModel,\n OpenAICompatibleEmbeddingModel\n} from \"@ai-sdk/openai-compatible\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/reranking/togetherai-reranking-model.ts\nimport {\n combineHeaders,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\n\n// src/reranking/togetherai-reranking-api.ts\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\nvar togetheraiErrorSchema = lazySchema(\n () => zodSchema(\n z.object({\n error: z.object({\n message: z.string()\n })\n })\n )\n);\nvar togetheraiRerankingResponseSchema = lazySchema(\n () => zodSchema(\n z.object({\n id: z.string().nullish(),\n model: z.string().nullish(),\n results: z.array(\n z.object({\n index: z.number(),\n relevance_score: z.number()\n })\n ),\n usage: z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number(),\n total_tokens: z.number()\n })\n })\n )\n);\n\n// src/reranking/togetherai-reranking-options.ts\nimport { lazySchema as lazySchema2, zodSchema as zodSchema2 } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar togetheraiRerankingModelOptionsSchema = lazySchema2(\n () => zodSchema2(\n z2.object({\n rankFields: z2.array(z2.string()).optional()\n })\n )\n);\n\n// src/reranking/togetherai-reranking-model.ts\nvar TogetherAIRerankingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n // see https://docs.together.ai/reference/rerank-1\n async doRerank({\n documents,\n headers,\n query,\n topN,\n abortSignal,\n providerOptions\n }) {\n var _a, _b;\n const rerankingOptions = await parseProviderOptions({\n provider: \"togetherai\",\n providerOptions,\n schema: togetheraiRerankingModelOptionsSchema\n });\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi({\n url: `${this.config.baseURL}/rerank`,\n headers: combineHeaders(this.config.headers(), headers),\n body: {\n model: this.modelId,\n documents: documents.values,\n query,\n top_n: topN,\n rank_fields: rerankingOptions == null ? void 0 : rerankingOptions.rankFields,\n return_documents: false\n // reduce response size\n },\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: togetheraiErrorSchema,\n errorToMessage: (data) => data.error.message\n }),\n successfulResponseHandler: createJsonResponseHandler(\n togetheraiRerankingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n ranking: response.results.map((result) => ({\n index: result.index,\n relevanceScore: result.relevance_score\n })),\n response: {\n id: (_a = response.id) != null ? _a : void 0,\n modelId: (_b = response.model) != null ? _b : void 0,\n headers: responseHeaders,\n body: rawValue\n }\n };\n }\n};\n\n// src/togetherai-image-model.ts\nimport {\n combineHeaders as combineHeaders2,\n convertImageModelFileToDataUri,\n createJsonResponseHandler as createJsonResponseHandler2,\n createJsonErrorResponseHandler as createJsonErrorResponseHandler2,\n lazySchema as lazySchema3,\n parseProviderOptions as parseProviderOptions2,\n postJsonToApi as postJsonToApi2,\n zodSchema as zodSchema3\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\nvar TogetherAIImageModel = class {\n constructor(modelId, config) {\n this.modelId = modelId;\n this.config = config;\n this.specificationVersion = \"v3\";\n this.maxImagesPerCall = 1;\n }\n get provider() {\n return this.config.provider;\n }\n async doGenerate({\n prompt,\n n,\n size,\n seed,\n providerOptions,\n headers,\n abortSignal,\n files,\n mask\n }) {\n var _a, _b, _c;\n const warnings = [];\n if (mask != null) {\n throw new Error(\n \"Together AI does not support mask-based image editing. Use FLUX Kontext models (e.g., black-forest-labs/FLUX.1-kontext-pro) with a reference image and descriptive prompt instead.\"\n );\n }\n if (size != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"aspectRatio\",\n details: \"This model does not support the `aspectRatio` option. Use `size` instead.\"\n });\n }\n const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();\n const togetheraiOptions = await parseProviderOptions2({\n provider: \"togetherai\",\n providerOptions,\n schema: togetheraiImageModelOptionsSchema\n });\n let imageUrl;\n if (files != null && files.length > 0) {\n imageUrl = convertImageModelFileToDataUri(files[0]);\n if (files.length > 1) {\n warnings.push({\n type: \"other\",\n message: \"Together AI only supports a single input image. Additional images are ignored.\"\n });\n }\n }\n const splitSize = size == null ? void 0 : size.split(\"x\");\n const { value: response, responseHeaders } = await postJsonToApi2({\n url: `${this.config.baseURL}/images/generations`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n prompt,\n seed,\n ...n > 1 ? { n } : {},\n ...splitSize && {\n width: parseInt(splitSize[0]),\n height: parseInt(splitSize[1])\n },\n ...imageUrl != null ? { image_url: imageUrl } : {},\n response_format: \"base64\",\n ...togetheraiOptions != null ? togetheraiOptions : {}\n },\n failedResponseHandler: createJsonErrorResponseHandler2({\n errorSchema: togetheraiErrorSchema2,\n errorToMessage: (data) => data.error.message\n }),\n successfulResponseHandler: createJsonResponseHandler2(\n togetheraiImageResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n images: response.data.map((item) => item.b64_json),\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders\n }\n };\n }\n};\nvar togetheraiImageResponseSchema = z3.object({\n data: z3.array(\n z3.object({\n b64_json: z3.string()\n })\n )\n});\nvar togetheraiErrorSchema2 = z3.object({\n error: z3.object({\n message: z3.string()\n })\n});\nvar togetheraiImageModelOptionsSchema = lazySchema3(\n () => zodSchema3(\n z3.object({\n /**\n * Number of generation steps. Higher values can improve quality.\n */\n steps: z3.number().nullish(),\n /**\n * Guidance scale for image generation.\n */\n guidance: z3.number().nullish(),\n /**\n * Negative prompt to guide what to avoid.\n */\n negative_prompt: z3.string().nullish(),\n /**\n * Disable the safety checker for image generation.\n * When true, the API will not reject images flagged as potentially NSFW.\n * Not available for Flux Schnell Free and Flux Pro models.\n */\n disable_safety_checker: z3.boolean().nullish()\n }).passthrough()\n )\n);\n\n// src/version.ts\nvar VERSION = true ? \"2.0.41\" : \"0.0.0-test\";\n\n// src/togetherai-provider.ts\nfunction loadDeprecatedApiKey() {\n if (typeof process === \"undefined\") {\n return void 0;\n }\n if (typeof process.env.TOGETHER_API_KEY === \"string\") {\n return void 0;\n }\n const key = process.env.TOGETHER_AI_API_KEY;\n if (typeof key === \"string\") {\n console.warn(\n \"TOGETHER_AI_API_KEY is deprecated and will be removed in a future release. Please use TOGETHER_API_KEY instead.\"\n );\n }\n return key;\n}\nfunction createTogetherAI(options = {}) {\n var _a;\n const baseURL = withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.together.xyz/v1/\"\n );\n const getHeaders = () => {\n var _a2;\n return withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: (_a2 = options.apiKey) != null ? _a2 : loadDeprecatedApiKey(),\n environmentVariableName: \"TOGETHER_API_KEY\",\n description: \"TogetherAI\"\n })}`,\n ...options.headers\n },\n `ai-sdk/togetherai/${VERSION}`\n );\n };\n const getCommonModelConfig = (modelType) => ({\n provider: `togetherai.${modelType}`,\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createChatModel = (modelId) => {\n return new OpenAICompatibleChatLanguageModel(\n modelId,\n getCommonModelConfig(\"chat\")\n );\n };\n const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(\n modelId,\n getCommonModelConfig(\"completion\")\n );\n const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(\n modelId,\n getCommonModelConfig(\"embedding\")\n );\n const createImageModel = (modelId) => new TogetherAIImageModel(modelId, {\n ...getCommonModelConfig(\"image\"),\n baseURL: baseURL != null ? baseURL : \"https://api.together.xyz/v1/\"\n });\n const createRerankingModel = (modelId) => new TogetherAIRerankingModel(modelId, {\n ...getCommonModelConfig(\"reranking\"),\n baseURL: baseURL != null ? baseURL : \"https://api.together.xyz/v1/\"\n });\n const provider = (modelId) => createChatModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.completionModel = createCompletionModel;\n provider.languageModel = createChatModel;\n provider.chatModel = createChatModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.image = createImageModel;\n provider.imageModel = createImageModel;\n provider.reranking = createRerankingModel;\n provider.rerankingModel = createRerankingModel;\n return provider;\n}\nvar togetherai = createTogetherAI();\nexport {\n VERSION,\n createTogetherAI,\n togetherai\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";4ZAwBA,SAAI,OAAwB,OAC1B,SAAM,OACJ,OAAE,YAAO,CACP,MAAO,EAAE,OAAO,CACd,QAAS,EAAE,OAAO,CACpB,CAAC,CACH,CAAC,CACH,CACF,EACI,EAAoC,EACtC,IAAM,EACJ,EAAE,OAAO,CACP,GAAI,EAAE,OAAO,EAAE,QAAQ,EACvB,MAAO,EAAE,OAAO,EAAE,QAAQ,EAC1B,QAAS,EAAE,MACT,EAAE,OAAO,CACP,MAAO,EAAE,OAAO,EAChB,gBAAiB,EAAE,OAAO,CAC5B,CAAC,CACH,EACA,MAAO,EAAE,OAAO,CACd,cAAe,EAAE,OAAO,EACxB,kBAAmB,EAAE,OAAO,EAC5B,aAAc,EAAE,OAAO,CACzB,CAAC,CACH,CAAC,CACH,CACF,EAKI,EAAwC,EAC1C,I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,CACnC,EACM,EAAuB,CAAC,IAAY,IAAI,EAC5C,EACA,EAAqB,WAAW,CAClC,EACM,EAAmB,CAAC,IAAY,IAAI,EAAqB,EAAS,IACnE,EAAqB,OAAO,EAC/B,QAAS,GAAW,KAAO,EAAU,8BACvC,CAAC,EACK,EAAuB,CAAC,IAAY,IAAI,EAAyB,EAAS,IAC3E,EAAqB,WAAW,EACnC,QAAS,GAAW,KAAO,EAAU,8BACvC,CAAC,EACK,EAAW,CAAC,IAAY,EAAgB,CAAO,EAWrD,OAVA,EAAS,qBAAuB,KAChC,EAAS,gBAAkB,EAC3B,EAAS,cAAgB,EACzB,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,mBAAqB,EAC9B,EAAS,MAAQ,EACjB,EAAS,WAAa,EACtB,EAAS,UAAY,EACrB,EAAS,eAAiB,EACnB,EAET,IAAI,GAAa,EAAiB", | ||
| "debugId": "17887359E9EE760B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/run/run.ts", "src/run/noninteractive.ts", "src/run/ui.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient, type SessionMessageAssistantTool } from \"@opencode-ai/client/promise\"\nimport { FSUtil } from \"@opencode-ai/util/fs-util\"\nimport { open } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { readStdin } from \"../util/io\"\nimport { ServerConnection } from \"../services/server-connection\"\nimport { parseSessionTargetModel, resolveSessionTarget } from \"../session-target\"\nimport { toolInlineInfo } from \"@opencode-ai/tui/mini/tool\"\nimport { runNonInteractivePrompt } from \"./noninteractive\"\nimport { UI } from \"./ui\"\n\nexport type RunCommandInput = {\n server: ServerConnection.Resolved\n message: string[]\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n format: \"default\" | \"json\"\n file: string[]\n title?: string\n thinking?: boolean\n auto?: boolean\n}\n\ntype FilePart = {\n url: string\n filename: string\n mime: string\n}\n\ntype Prepared = {\n directory?: string\n message: string\n files: FilePart[]\n}\n\ntype ExecutionOptions = {\n root?: string\n directory?: string\n useServerDirectory?: boolean\n variant?: string\n attached?: boolean\n compatibility?: \"v1\"\n}\n\nclass RunTargetError extends Error {\n constructor(\n message: string,\n readonly sessionID?: string,\n ) {\n super(message)\n }\n}\n\nconst ATTACH_FILE_MAX_BYTES = 10 * 1024 * 1024\n\nexport function runNonInteractive(input: RunCommandInput) {\n return runNonInteractiveWithOptions(input, {})\n}\n\n/** @internal Used only by the V1 command boundary. */\nexport function runNonInteractiveWithOptions(input: RunCommandInput, options: ExecutionOptions) {\n return run(input, options).catch((error) => reportRunError(input, errorMessage(error)))\n}\n\nasync function run(input: RunCommandInput, options: ExecutionOptions) {\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n const root = options.root ?? process.env.PWD ?? process.cwd()\n const local = localDirectory(root)\n const directory = options.useServerDirectory ? undefined : (options.directory ?? local)\n const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin())\n if (!message?.trim()) fail(\"You must provide a message\")\n const files = await Promise.all(input.file.map((file) => prepareFile(file, root, options)))\n const prepared = { directory, message, files }\n return execute(input, prepared, input.server.endpoint, options)\n}\n\nasync function execute(input: RunCommandInput, prepared: Prepared, endpoint: Endpoint, options: ExecutionOptions) {\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const explicit = parseRunModel(input.model)\n const target = await resolveSessionTarget({\n client,\n location: prepared.directory ? { directory: prepared.directory } : undefined,\n continue: input.continue,\n session: input.session,\n fork: input.fork,\n model: explicit\n ? { providerID: explicit.model.providerID, id: explicit.model.modelID, variant: explicit.variant }\n : undefined,\n agent: input.agent,\n prepare: async (next) => {\n const selected =\n next.model ??\n (options.variant\n ? await client.model\n .default({ location: { directory: next.location.directory, workspace: next.location.workspaceID } })\n .then((result) => result.data)\n : undefined)\n const model = selected\n ? {\n providerID: selected.providerID,\n id: selected.id,\n variant: options.variant ?? (\"variant\" in selected ? selected.variant : undefined),\n }\n : undefined\n if ((options.variant ?? explicit?.variant) && !model)\n throw new RunTargetError(\"Cannot select a variant before selecting a model\", next.session?.id)\n return { model, agent: next.agent }\n },\n }).catch((error) => {\n if (!(error instanceof RunTargetError)) throw error\n reportRunError(input, error.message, error.sessionID)\n return undefined\n })\n if (!target) return\n const model = target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined\n const variant = target.model?.variant\n if (!target.resume && input.title !== undefined) {\n await client.session.rename({\n sessionID: target.session.id,\n title: input.title || prepared.message.slice(0, 50) + (prepared.message.length > 50 ? \"...\" : \"\"),\n })\n }\n\n await runNonInteractivePrompt({\n client,\n sessionID: target.session.id,\n location: target.location,\n message: prepared.message,\n files: prepared.files,\n agent: target.agent,\n model,\n variant,\n thinking: input.thinking ?? false,\n format: input.format,\n auto: input.auto ?? false,\n attached: options.attached ?? true,\n compatibility: options.compatibility,\n renderTool: (part) => renderTool(part, target.location.directory),\n renderToolError: (part) => renderToolError(part, target.location.directory),\n }).catch((error) => reportRunError(input, errorMessage(error), target.session.id))\n}\n\nexport function mergeInput(message: string | undefined, piped: string | undefined) {\n if (!message) return piped || undefined\n if (!piped) return message\n return message + \"\\n\" + piped\n}\n\nfunction formatMessage(message: string[]) {\n const value = message.map((part) => (part.includes(\" \") ? `\"${part.replace(/\"/g, '\\\\\"')}\"` : part)).join(\" \")\n return value || undefined\n}\n\nfunction localDirectory(root: string) {\n try {\n process.chdir(root)\n return process.cwd()\n } catch {\n fail(`Failed to change directory to ${root}`)\n }\n}\n\nexport function parseRunModel(value?: string) {\n const ref = parseSessionTargetModel(value)\n if (!ref) return\n return {\n model: { providerID: ref.providerID, modelID: ref.id },\n variant: ref.variant,\n }\n}\n\nasync function prepareFile(input: string, directory: string, options: ExecutionOptions): Promise<FilePart> {\n const file = path.resolve(directory, input)\n const handle = await open(file, \"r\").catch(() => fail(`File not found: ${input}`))\n try {\n const stat = await handle.stat()\n if (options.compatibility === \"v1\" && options.attached && stat.isDirectory())\n fail(`Cannot attach local directory without a shared filesystem: ${input}`)\n if (!stat.isFile() || stat.size > ATTACH_FILE_MAX_BYTES)\n fail(`Cannot attach a directory, special file, or file larger than 10 MiB: ${input}`)\n const content = Buffer.alloc(Number(stat.size))\n let offset = 0\n while (offset < content.length) {\n const read = await handle.read(content, offset, content.length - offset, offset)\n if (read.bytesRead === 0) break\n offset += read.bytesRead\n }\n const bytes = content.subarray(0, offset)\n const detected = FSUtil.mimeType(file)\n const text = bytes.toString(\"utf8\")\n const mime =\n detected.startsWith(\"image/\") || detected === \"application/pdf\"\n ? detected\n : !isBinaryContent(bytes) && Buffer.from(text, \"utf8\").equals(bytes)\n ? \"text/plain\"\n : detected\n return {\n url: `data:${mime};base64,${bytes.toString(\"base64\")}`,\n filename: path.basename(file),\n mime,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction isBinaryContent(bytes: Uint8Array) {\n if (bytes.length === 0) return false\n if (bytes.includes(0)) return true\n return bytes.reduce((count, byte) => count + Number(byte < 9 || (byte > 13 && byte < 32)), 0) / bytes.length > 0.3\n}\n\nasync function renderTool(part: SessionMessageAssistantTool, directory: string) {\n const info = toolInlineInfo(part, directory)\n if (info.mode === \"block\") {\n UI.empty()\n UI.println(UI.Style.TEXT_NORMAL + info.icon, UI.Style.TEXT_NORMAL + info.title)\n if (info.body?.trim()) UI.println(info.body)\n UI.empty()\n return\n }\n UI.println(\n UI.Style.TEXT_NORMAL + info.icon,\n UI.Style.TEXT_NORMAL + info.title,\n info.description ? UI.Style.TEXT_DIM + info.description + UI.Style.TEXT_NORMAL : \"\",\n )\n}\n\nasync function renderToolError(part: SessionMessageAssistantTool, directory: string) {\n const info = toolInlineInfo(part, directory)\n UI.println(UI.Style.TEXT_NORMAL + \"✗\", UI.Style.TEXT_NORMAL + `${info.title} failed`)\n}\n\nfunction warning(message: string) {\n UI.println(UI.Style.TEXT_WARNING_BOLD + \"!\", UI.Style.TEXT_NORMAL, message)\n}\n\nfunction errorMessage(error: unknown) {\n if (error instanceof Error) return error.message\n if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\")\n return error.message\n return String(error)\n}\n\n/** @internal Used by the V1 command boundary before a Session exists. */\nexport function reportRunError(input: Pick<RunCommandInput, \"format\">, message: string, sessionID?: string) {\n process.exitCode = 1\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify({\n type: \"error\",\n timestamp: Date.now(),\n sessionID: sessionID ?? \"\",\n error: { type: \"unknown\", message },\n }) + \"\\n\",\n )\n return\n }\n UI.error(message)\n}\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n", | ||
| "import type {\n EventSubscribeOutput,\n JsonValue,\n LLMToolContent,\n LocationRef,\n OpenCodeClient,\n SessionMessageAssistantTool,\n SessionMessageInfo,\n} from \"@opencode-ai/client/promise\"\nimport { SessionMessage } from \"@opencode-ai/schema/session-message\"\nimport { EOL } from \"node:os\"\nimport { readFile } from \"node:fs/promises\"\nimport { toolOutputText, type MiniToolPart } from \"@opencode-ai/tui/mini/tool\"\nimport { UI } from \"./ui\"\n\ntype Model = {\n providerID: string\n modelID: string\n}\n\ntype File = {\n url: string\n filename: string\n mime: string\n}\n\ntype Input = {\n client: OpenCodeClient\n sessionID: string\n location: LocationRef\n message: string\n files: File[]\n agent?: string\n model?: Model\n variant?: string\n thinking: boolean\n format: \"default\" | \"json\"\n auto: boolean\n /** True when the client is attached to a shared server rather than an exclusive in-process one. */\n attached: boolean\n compatibility?: \"v1\"\n renderTool: (part: SessionMessageAssistantTool) => Promise<void>\n renderToolError: (part: SessionMessageAssistantTool) => Promise<void>\n}\n\ntype StartedPart = {\n id: string\n timestamp: number\n}\n\ntype ToolState = StartedPart & {\n assistantMessageID: string\n tool: string\n input: Record<string, JsonValue>\n raw?: string\n provider?: unknown\n providerState?: SessionMessageAssistantTool[\"providerState\"]\n structured: Record<string, JsonValue>\n content: LLMToolContent[]\n}\n\ntype V2Event = EventSubscribeOutput\ntype FormRequest = Extract<V2Event, { type: \"form.created\" }>[\"data\"][\"form\"]\n\n// MCP elicitations are temporarily owned by the \"global\" sentinel instead of a real\n// session. An exclusive local process may treat them as this run's blockers; an\n// attached client must not cancel input that may belong to another session.\nconst GLOBAL_FORM_SESSION_ID = \"global\"\n\nexport async function runNonInteractivePrompt(input: Input) {\n const controller = new AbortController()\n const stream = input.client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()\n const connected = await stream.next()\n if (connected.done) throw new Error(\"Event stream disconnected before prompt admission\")\n\n const messageID = SessionMessage.ID.create()\n const starts = new Map<string, StartedPart>()\n const tools = new Map<string, ToolState>()\n const renderedText = new Map<string, string>()\n const renderedReasoning = new Map<string, string>()\n const renderedTools = new Set<string>()\n let submitted = false\n let promoted = false\n let emittedError = false\n let permissionRejected = false\n let formCancelled = false\n let interrupted = false\n let v1InvalidOutput = false\n let prePromotionError: { message: string; [key: string]: unknown } | undefined\n let finalizing = false\n let admission: AbortController | undefined\n let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined\n\n const emit = (type: string, timestamp: number, data: Record<string, unknown>) => {\n if (input.format !== \"json\") return false\n process.stdout.write(JSON.stringify({ type, timestamp, sessionID: input.sessionID, ...data }) + EOL)\n return true\n }\n\n const writeText = (part: { text: string; [key: string]: unknown }, timestamp: number) => {\n if (emit(\"text\", timestamp, { part })) return\n const text = part.text.trim()\n if (!text) return\n if (!process.stdout.isTTY) {\n process.stdout.write(text + EOL)\n return\n }\n UI.empty()\n UI.println(text)\n UI.empty()\n }\n\n const writeReasoning = (part: { text: string; [key: string]: unknown }, timestamp: number) => {\n if (emit(\"reasoning\", timestamp, { part })) return\n const text = part.text.trim()\n if (!text) return\n const line = `Thinking: ${text}`\n if (!process.stdout.isTTY) return void process.stdout.write(line + EOL)\n UI.empty()\n UI.println(`${UI.Style.TEXT_DIM}\\u001b[3m${line}\\u001b[0m${UI.Style.TEXT_NORMAL}`)\n UI.empty()\n }\n\n const flushStep = () => {\n if (!pendingStep) return\n const value = pendingStep\n pendingStep = undefined\n if (!emit(\"step_start\", value.timestamp, { part: value.part }) && input.format !== \"json\") {\n UI.empty()\n UI.println(value.label)\n UI.empty()\n }\n }\n\n const replyPermission = async (request: { id: string; action: string; resources: ReadonlyArray<string> }) => {\n if (!input.auto) {\n permissionRejected = true\n UI.println(\n UI.Style.TEXT_WARNING_BOLD + \"!\",\n UI.Style.TEXT_NORMAL +\n `permission requested: ${request.action} (${request.resources.join(\", \")}); auto-rejecting`,\n )\n }\n await input.client.permission\n .reply({\n sessionID: input.sessionID,\n requestID: request.id,\n reply: input.auto ? \"once\" : \"reject\",\n })\n .catch(() => {})\n if (!input.auto) {\n await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n }\n\n const cancelForm = async (request: Pick<FormRequest, \"id\" | \"sessionID\">) => {\n try {\n await input.client.form.cancel(\n { sessionID: request.sessionID, formID: request.id },\n ...formRequestOptions(request.sessionID === GLOBAL_FORM_SESSION_ID ? input.location : undefined),\n )\n } catch (error) {\n if (!formAlreadySettled(error)) throw error\n }\n formCancelled = true\n }\n\n const consume = async () => {\n while (!controller.signal.aborted) {\n const next = await stream.next().catch((error) => {\n if (!emittedError) throw error\n return { done: true as const, value: undefined }\n })\n if (next.done) {\n if (emittedError) return\n throw new Error(\"Event stream disconnected during prompt execution\")\n }\n const event = next.value\n\n if (event.type === \"permission.v2.asked\" && submitted && event.data.sessionID === input.sessionID) {\n await replyPermission(event.data)\n continue\n }\n if (\n event.type === \"form.created\" &&\n submitted &&\n (event.data.form.sessionID === input.sessionID ||\n (!input.attached &&\n event.data.form.sessionID === GLOBAL_FORM_SESSION_ID &&\n sameLocation(event.location, input.location)))\n ) {\n await cancelForm(event.data.form)\n continue\n }\n if (!(\"sessionID\" in event.data) || event.data.sessionID !== input.sessionID) continue\n const time = toMillis(\"created\" in event ? event.created : undefined)\n\n if (event.type === \"session.input.promoted\") {\n if (event.data.inputID === messageID) {\n promoted = true\n prePromotionError = undefined\n continue\n }\n }\n if (\n event.type === \"session.execution.interrupted\" &&\n event.data.reason === \"user\" &&\n (interrupted || permissionRejected || formCancelled)\n ) {\n return\n }\n if (!promoted && event.type === \"session.execution.failed\") {\n prePromotionError = event.data.error\n if (finalizing) return\n continue\n }\n if (\n !promoted &&\n finalizing &&\n (event.type === \"session.execution.succeeded\" || event.type === \"session.execution.interrupted\")\n )\n return\n if (!promoted) continue\n if (finalizing && !event.type.startsWith(\"session.execution.\")) continue\n\n if (event.type === \"session.step.started\") {\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-start\",\n snapshot: event.data.snapshot,\n }\n if (input.compatibility === \"v1\") {\n pendingStep = {\n timestamp: time,\n part,\n label: `> ${event.data.agent} · ${event.data.model.id}`,\n }\n continue\n }\n if (!emit(\"step_start\", time, { part }) && input.format !== \"json\") {\n UI.empty()\n UI.println(`> ${event.data.agent} · ${event.data.model.id}`)\n UI.empty()\n }\n continue\n }\n\n if (event.type === \"session.text.started\") {\n flushStep()\n starts.set(`text\\u0000${contentKey(event.data.assistantMessageID, event.data.ordinal)}`, {\n id: partID(event.id),\n timestamp: time,\n })\n continue\n }\n if (event.type === \"session.text.ended\") {\n const key = contentKey(event.data.assistantMessageID, event.data.ordinal)\n const started = starts.get(`text\\u0000${key}`)\n starts.delete(`text\\u0000${key}`)\n const part = {\n id: started?.id ?? partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"text\",\n text: event.data.text,\n time: { start: started?.timestamp ?? time, end: time },\n }\n renderedText.set(key, event.data.text)\n writeText(part, time)\n continue\n }\n\n if (event.type === \"session.reasoning.started\") {\n flushStep()\n starts.set(`reasoning\\u0000${contentKey(event.data.assistantMessageID, event.data.ordinal)}`, {\n id: partID(event.id),\n timestamp: time,\n })\n continue\n }\n if (event.type === \"session.reasoning.ended\" && input.thinking) {\n const key = contentKey(event.data.assistantMessageID, event.data.ordinal)\n const started = starts.get(`reasoning\\u0000${key}`)\n starts.delete(`reasoning\\u0000${key}`)\n const part = {\n id: started?.id ?? partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"reasoning\",\n text: event.data.text,\n metadata: event.data.state,\n time: { start: started?.timestamp ?? time, end: time },\n }\n renderedReasoning.set(key, event.data.text)\n writeReasoning(part, time)\n continue\n }\n\n if (event.type === \"session.tool.input.started\") {\n flushStep()\n tools.set(toolKey(event.data.assistantMessageID, event.data.callID), {\n id: partID(event.id),\n timestamp: time,\n assistantMessageID: event.data.assistantMessageID,\n tool: event.data.name,\n input: {},\n structured: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.input.ended\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))\n if (current) current.raw = event.data.text\n continue\n }\n if (event.type === \"session.tool.input.delta\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))\n if (current) current.raw = (current.raw ?? \"\") + event.data.delta\n continue\n }\n if (event.type === \"session.tool.called\") {\n flushStep()\n const key = toolKey(event.data.assistantMessageID, event.data.callID)\n const current = tools.get(key)\n tools.set(key, {\n id: current?.id ?? partID(event.id),\n timestamp: current?.timestamp ?? time,\n assistantMessageID: event.data.assistantMessageID,\n tool: current?.tool ?? \"tool\",\n input: event.data.input,\n raw: current?.raw,\n provider: { executed: event.data.executed, state: event.data.state },\n providerState: event.data.state,\n structured: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.progress\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))\n if (current) {\n current.structured = event.data.structured\n current.content = event.data.content\n }\n continue\n }\n if (event.type === \"session.tool.success\") {\n const key = toolKey(event.data.assistantMessageID, event.data.callID)\n const current = tools.get(key) ?? fallbackTool(event)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.callID,\n name: current.tool,\n executed: event.data.executed,\n providerState: current.providerState,\n providerResultState: event.data.resultState,\n state: {\n status: \"completed\",\n input: current.input,\n structured: event.data.structured,\n content: event.data.content,\n result: event.data.result,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n id: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n callID: event.data.callID,\n tool: current.tool,\n state: {\n status: \"completed\",\n input: current.input,\n output: toolOutputText(current.tool, event.data.content),\n title: current.tool,\n metadata: {\n structured: event.data.structured,\n content: event.data.content,\n result: event.data.result,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(key)\n renderedTools.add(key)\n if (!emit(\"tool_use\", time, { part })) await input.renderTool(tool)\n continue\n }\n if (event.type === \"session.tool.failed\") {\n const key = toolKey(event.data.assistantMessageID, event.data.callID)\n const current = tools.get(key) ?? fallbackTool(event)\n const error = event.data.error.message\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.callID,\n name: current.tool,\n executed: event.data.executed,\n providerState: current.providerState,\n providerResultState: event.data.resultState,\n state: {\n status: \"error\",\n input: current.input,\n structured: current.structured,\n content: current.content,\n error: event.data.error,\n result: event.data.result,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n id: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n callID: event.data.callID,\n tool: current.tool,\n state: {\n status: \"error\",\n input: current.input,\n error,\n metadata: {\n result: event.data.result,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(key)\n renderedTools.add(key)\n if (input.compatibility === \"v1\" && (permissionRejected || formCancelled)) continue\n if (!emit(\"tool_use\", time, { part })) {\n if (toolOutputText(current.tool, current.content).trim())\n await input.renderTool({\n ...tool,\n state: {\n status: \"completed\",\n input: current.input,\n structured: current.structured,\n content: current.content,\n result: event.data.result,\n },\n })\n await input.renderToolError(tool)\n UI.error(error)\n }\n continue\n }\n\n if (event.type === \"session.step.ended\") {\n flushStep()\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-finish\",\n reason: event.data.finish,\n snapshot: event.data.snapshot,\n cost: event.data.cost,\n tokens: event.data.tokens,\n }\n emit(\"step_finish\", time, { part })\n continue\n }\n if (event.type === \"session.step.failed\") {\n if (\n input.compatibility === \"v1\" &&\n event.data.error.message === \"Provider stream ended without a terminal finish event\"\n ) {\n pendingStep = undefined\n v1InvalidOutput = true\n continue\n }\n if (interrupted || permissionRejected || formCancelled) continue\n flushStep()\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", time, { error: event.data.error })) UI.error(event.data.error.message)\n continue\n }\n if (event.type === \"session.execution.failed\") {\n if (input.compatibility === \"v1\" && (v1InvalidOutput || permissionRejected || formCancelled)) return\n flushStep()\n if (!emittedError && !formCancelled) {\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", time, { error: event.data.error })) UI.error(event.data.error.message)\n }\n return\n }\n if (event.type === \"session.execution.interrupted\") {\n if (input.compatibility === \"v1\" && (permissionRejected || formCancelled)) return\n if (event.data.reason === \"user\" && interrupted) process.exitCode = 130\n if (event.data.reason !== \"user\" && !emittedError) {\n emittedError = true\n process.exitCode = 1\n const error = { type: \"aborted\" as const, message: `Session interrupted: ${event.data.reason}` }\n if (!emit(\"error\", time, { error })) UI.error(error.message)\n }\n return\n }\n if (event.type === \"session.execution.succeeded\") return\n }\n }\n\n const projectedMessages = async () => {\n const messages: SessionMessageInfo[] = []\n let cursor: string | undefined\n while (true) {\n const page = await input.client.message.list(\n cursor\n ? { sessionID: input.sessionID, limit: 200, cursor }\n : { sessionID: input.sessionID, limit: 200, order: \"desc\" },\n )\n for (const message of page.data) {\n if (message.id === messageID) return { found: true, messages: messages.toReversed() }\n messages.push(message)\n }\n cursor = page.cursor.next ?? undefined\n if (!cursor) return { found: false, messages: [] }\n }\n }\n\n const reconcile = async () => {\n const projected = await projectedMessages()\n for (const message of projected.messages) {\n if (message.type !== \"assistant\") continue\n const timestamp = message.time.completed ?? message.time.created\n let textOrdinal = 0\n let reasoningOrdinal = 0\n for (const item of message.content) {\n if (item.type === \"text\") {\n const ordinal = textOrdinal++\n const key = contentKey(message.id, ordinal)\n const rendered = renderedText.get(key) ?? \"\"\n if (rendered === item.text || !item.text.startsWith(rendered)) continue\n const text = item.text.slice(rendered.length)\n writeText(\n {\n id: projectedPartID(message.id, `text-${ordinal}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"text\",\n text,\n time: { start: message.time.created, end: timestamp },\n },\n timestamp,\n )\n renderedText.set(key, item.text)\n continue\n }\n if (item.type === \"reasoning\") {\n const ordinal = reasoningOrdinal++\n if (!input.thinking) continue\n const key = contentKey(message.id, ordinal)\n const rendered = renderedReasoning.get(key) ?? \"\"\n if (rendered === item.text || !item.text.startsWith(rendered)) continue\n const text = item.text.slice(rendered.length)\n const part = {\n id: projectedPartID(message.id, `reasoning-${ordinal}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"reasoning\",\n text,\n metadata: item.state,\n time: { start: message.time.created, end: timestamp },\n }\n renderedReasoning.set(key, item.text)\n writeReasoning(part, timestamp)\n continue\n }\n\n const key = toolKey(message.id, item.id)\n if (renderedTools.has(key) || item.state.status === \"streaming\" || item.state.status === \"running\") continue\n const part: MiniToolPart = {\n id: projectedPartID(message.id, `tool-${item.id}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"tool\",\n callID: item.id,\n tool: item.name,\n state:\n item.state.status === \"completed\"\n ? {\n status: \"completed\",\n input: item.state.input,\n output: toolOutputText(item.name, item.state.content),\n title: item.name,\n metadata: { structured: item.state.structured, content: item.state.content, result: item.state.result },\n time: { start: item.time.ran ?? item.time.created, end: item.time.completed ?? timestamp },\n }\n : {\n status: \"error\",\n input: item.state.input,\n error: item.state.error.message,\n metadata: { structured: item.state.structured, content: item.state.content, result: item.state.result },\n time: { start: item.time.ran ?? item.time.created, end: item.time.completed ?? timestamp },\n },\n }\n renderedTools.add(key)\n if (emit(\"tool_use\", timestamp, { part })) continue\n if (item.state.status === \"completed\") {\n await input.renderTool(item)\n continue\n }\n if (toolOutputText(item.name, item.state.content).trim()) {\n await input.renderTool({ ...item, state: { ...item.state, status: \"completed\" } })\n }\n await input.renderToolError(item)\n UI.error(item.state.error.message)\n }\n\n if (message.error && !emittedError) {\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", timestamp, { error: message.error })) UI.error(message.error.message)\n }\n }\n return {\n found: projected.found,\n responded: projected.messages.some((message) => message.type === \"assistant\"),\n }\n }\n\n const interrupt = () => {\n if (interrupted) process.exit(130)\n interrupted = true\n process.exitCode = 130\n admission?.abort()\n void input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n process.on(\"SIGINT\", interrupt)\n\n let completed: Promise<void> | undefined\n try {\n if (input.agent) {\n await input.client.session.switchAgent({ sessionID: input.sessionID, agent: input.agent })\n }\n const selected = input.model\n ? { providerID: input.model.providerID, id: input.model.modelID, variant: input.variant }\n : input.variant\n ? await input.client.session\n .get({ sessionID: input.sessionID })\n .then((result) => result.model)\n .then(async (model) => {\n if (model) return { ...model, variant: input.variant }\n const result = await input.client.model.default()\n const fallback = result.data\n return fallback ? { providerID: fallback.providerID, id: fallback.id, variant: input.variant } : undefined\n })\n : undefined\n if (input.variant && !selected) throw new Error(\"Cannot select a variant before selecting a model\")\n if (selected) {\n await input.client.session.switchModel({ sessionID: input.sessionID, model: selected })\n }\n\n const prepared = await Promise.all(input.files.map(prepareFile))\n if (interrupted) return\n submitted = true\n completed = consume()\n admission = new AbortController()\n const response = await input.client.session\n .prompt(\n {\n sessionID: input.sessionID,\n id: messageID,\n text: [input.message, ...prepared.flatMap((file) => (file.text ? [file.text] : []))].join(\"\\n\\n\"),\n files: prepared.flatMap((file) => (file.attachment ? [file.attachment] : [])),\n delivery: \"steer\",\n },\n { signal: admission.signal },\n )\n .catch(async (error) => {\n if (interrupted) {\n await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n controller.abort()\n await completed?.catch(() => {})\n if (interrupted || emittedError) return undefined\n throw error\n })\n admission = undefined\n if (!response) return\n if (interrupted) await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n\n const [permissions, forms, globals] = await Promise.all([\n input.client.permission.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.client.form.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.attached\n ? Promise.resolve(undefined)\n : input.client.form.request\n .list({\n location: { directory: input.location.directory, workspace: input.location.workspaceID },\n })\n .catch(() => undefined),\n ])\n await Promise.all([\n ...(permissions ?? []).map(replyPermission),\n ...(forms ?? []).map(cancelForm),\n ...(globals && sameLocation(globals.location, input.location)\n ? globals.data.filter((form) => form.sessionID === GLOBAL_FORM_SESSION_ID).map(cancelForm)\n : []),\n ])\n if (input.compatibility === \"v1\") {\n await completed\n return\n }\n\n const waiting = input.client.session.wait({ sessionID: input.sessionID })\n await Promise.race([waiting, completed.then(() => waiting)])\n finalizing = true\n const projected = await reconcile()\n if (\n !projected.responded &&\n !interrupted &&\n !permissionRejected &&\n !formCancelled &&\n !emittedError &&\n !prePromotionError\n ) {\n await completed\n }\n if (!projected.found && !interrupted && !permissionRejected && !formCancelled && !emittedError) {\n const error = prePromotionError ?? { type: \"unknown\", message: \"Prompt was not promoted\" }\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", Date.now(), { error })) UI.error(error.message)\n }\n } finally {\n process.off(\"SIGINT\", interrupt)\n controller.abort()\n if (input.compatibility === \"v1\") await stream.return?.(undefined).catch(() => {})\n else void stream.return?.(undefined).catch(() => {})\n }\n}\n\nfunction sameLocation(left: LocationRef | undefined, right: LocationRef) {\n return !!left && left.directory === right.directory && left.workspaceID === right.workspaceID\n}\n\nfunction formRequestOptions(location: LocationRef | undefined): [] | [{ headers: Record<string, string> }] {\n if (!location) return []\n return [\n {\n headers: {\n \"x-opencode-directory\": encodeURIComponent(location.directory),\n ...(location.workspaceID ? { \"x-opencode-workspace\": location.workspaceID } : {}),\n },\n },\n ]\n}\n\nfunction formAlreadySettled(error: unknown) {\n return !!error && typeof error === \"object\" && Reflect.get(error, \"_tag\") === \"FormAlreadySettledError\"\n}\n\nfunction partID(eventID: string) {\n return `prt_${eventID.replace(/^evt_/, \"\")}`\n}\n\nfunction toolKey(messageID: string, callID: string) {\n return `${messageID}\\u0000${callID}`\n}\n\nfunction contentKey(messageID: string, ordinal: number) {\n return `${messageID}\\u0000${ordinal}`\n}\n\nfunction projectedPartID(messageID: string, part: string) {\n return `prt_${messageID.replace(/^msg_/, \"\")}_${part}`\n}\n\nfunction fallbackTool(event: {\n id: string\n created: number\n data: { assistantMessageID: string; callID: string }\n}): ToolState {\n return {\n id: partID(event.id),\n timestamp: toMillis(event.created),\n assistantMessageID: event.data.assistantMessageID,\n tool: \"tool\",\n input: {},\n structured: {},\n content: [],\n }\n}\n\nfunction toMillis(value: unknown) {\n if (typeof value === \"number\") return value\n if (typeof value === \"string\") return new Date(value).getTime()\n return Date.now()\n}\n\nasync function prepareFile(file: File) {\n if (file.mime !== \"text/plain\") {\n const uri = file.url.startsWith(\"data:\")\n ? file.url\n : `data:${file.mime};base64,${(await readFile(new URL(file.url))).toString(\"base64\")}`\n return { attachment: { uri, name: file.filename } }\n }\n const content = file.url.startsWith(\"data:\")\n ? Buffer.from(file.url.slice(file.url.indexOf(\",\") + 1), \"base64\").toString(\"utf8\")\n : await readFile(new URL(file.url), \"utf8\")\n return { text: `<file name=\"${file.filename}\">\\n${content}\\n</file>` }\n}\n", | ||
| "import { EOL } from \"node:os\"\n\nexport const Style = {\n TEXT_DIM: \"\\x1b[90m\",\n TEXT_NORMAL: \"\\x1b[0m\",\n TEXT_WARNING_BOLD: \"\\x1b[93m\\x1b[1m\",\n TEXT_DANGER_BOLD: \"\\x1b[91m\\x1b[1m\",\n}\n\nexport function println(...message: string[]) {\n process.stderr.write(message.join(\" \") + EOL)\n}\n\nlet blank = false\n\nexport function empty() {\n if (blank) return\n println(Style.TEXT_NORMAL)\n blank = true\n}\n\nexport function error(message: string) {\n if (message.startsWith(\"Error: \")) message = message.slice(\"Error: \".length)\n println(Style.TEXT_DANGER_BOLD + \"Error: \" + Style.TEXT_NORMAL + message)\n}\n\nexport * as UI from \"./ui\"\n" | ||
| ], | ||
| "mappings": ";o/BAGA,oBAAS,0BACT,0BCMA,mBAAS,gBACT,wBAAS,wGCXT,mBAAS,iBAEF,SAAM,OAAQ,MACnB,cAAU,gBACV,iBAAa,eACb,uBAAmB,uBACnB,sBAAkB,sBACpB,OAEO,cAAS,MAAO,SAAI,OAAmB,CAC5C,QAAQ,OAAO,MAAM,EAAQ,KAAK,GAAG,EAAI,EAAG,EAG9C,IAAI,GAAQ,GAEL,SAAS,EAAK,EAAG,CACtB,GAAI,GAAO,OACX,EAAQ,EAAM,WAAW,EACzB,GAAQ,GAGH,SAAS,EAAK,CAAC,EAAiB,CACrC,GAAI,EAAQ,WAAW,SAAS,EAAG,EAAU,EAAQ,MAAM,CAAgB,EAC3E,EAAQ,EAAM,iBAAmB,UAAY,EAAM,YAAc,CAAO,ED4C1E,IAAM,EAAyB,SAE/B,eAAsB,EAAuB,CAAC,EAAc,CAC1D,IAAM,EAAa,IAAI,gBACjB,EAAS,EAAM,OAAO,MAAM,UAAU,CAAE,OAAQ,EAAW,MAAO,CAAC,EAAE,OAAO,eAAe,EAEjG,IADkB,MAAM,EAAO,KAAK,GACtB,KAAM,MAAU,MAAM,mDAAmD,EAEvF,IAAM,EAAY,GAAe,GAAG,OAAO,EACrC,EAAS,IAAI,IACb,EAAQ,IAAI,IACZ,EAAe,IAAI,IACnB,EAAoB,IAAI,IACxB,EAAgB,IAAI,IACtB,EAAY,GACZ,EAAW,GACX,EAAe,GACf,EAAqB,GACrB,EAAgB,GAChB,EAAc,GACd,EAAkB,GAClB,EACA,EAAa,GAC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
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/pair.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode } from \"@opencode-ai/client/promise\"\nimport { renderUnicodeCompact } from \"uqr\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServiceConfig } from \"../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.pair,\n Effect.fn(\"cli.pair\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const password = yield* ServiceConfig.password()\n const server = yield* Effect.tryPromise(() =>\n OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.get(),\n )\n const info = { urls: server.urls, username: \"opencode\", password }\n process.stdout.write(\n [\n \"\",\n ` URLs ${info.urls[0] ?? \"(none)\"}`,\n ...info.urls.slice(1).map((url) => ` ${url}`),\n ` Username ${info.username}`,\n ` Password ${info.password}`,\n \"\",\n \" Scan to pair\",\n \"\",\n renderUnicodeCompact(JSON.stringify(info), { border: 2 })\n .split(EOL)\n .map((line) => \" \" + line)\n .join(EOL),\n \"\",\n ].join(EOL) + EOL,\n )\n\n const hostname = new URL(endpoint.url).hostname\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(hostname)) return\n process.stderr.write(\n ` Run \\`opencode service set hostname 0.0.0.0\\` to access the service remotely.${EOL}${EOL}`,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";66BAAA,mBAAS,gBAST,SAAe,SAAQ,aACrB,OAAS,cAAS,UAClB,OAAO,QAAG,eAAU,OAAE,cAAU,OAAG,MACjC,SAAM,OAAW,WAAO,OAAQ,YAAO,WAAO,OAAc,aAAQ,MAAC,EAC/D,EAAW,MAAO,EAAc,SAAS,EAIzC,EAAO,CAAE,MAHA,MAAO,EAAO,WAAW,IACtC,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAAE,OAAO,IAAI,CAC1F,GAC4B,KAAM,SAAU,WAAY,UAAS,EACjE,QAAQ,OAAO,MACb,CACE,GACA,eAAe,EAAK,KAAK,IAAM,WAC/B,GAAG,EAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,IAAQ,eAAe,GAAK,EACvD,eAAe,EAAK,WACpB,eAAe,EAAK,WACpB,GACA,iBACA,GACA,EAAqB,KAAK,UAAU,CAAI,EAAG,CAAE,OAAQ,CAAE,CAAC,EACrD,MAAM,CAAG,EACT,IAAI,CAAC,IAAS,KAAO,CAAI,EACzB,KAAK,CAAG,EACX,EACF,EAAE,KAAK,CAAG,EAAI,CAChB,EAEA,IAAM,EAAW,IAAI,IAAI,EAAS,GAAG,EAAE,SACvC,GAAI,CAAC,CAAC,YAAa,YAAa,OAAO,EAAE,SAAS,CAAQ,EAAG,OAC7D,QAAQ,OAAO,MACb,kFAAkF,IAAM,GAC1F,EACD,CACH", | ||
| "debugId": "4CE250B634AF740E64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/openai-compatible-profile.ts"], | ||
| "sourcesContent": [ | ||
| "export interface OpenAICompatibleProfile {\n readonly provider: string\n readonly baseURL: string\n}\n\nexport const profiles = {\n baseten: { provider: \"baseten\", baseURL: \"https://inference.baseten.co/v1\" },\n cerebras: { provider: \"cerebras\", baseURL: \"https://api.cerebras.ai/v1\" },\n deepinfra: { provider: \"deepinfra\", baseURL: \"https://api.deepinfra.com/v1/openai\" },\n deepseek: { provider: \"deepseek\", baseURL: \"https://api.deepseek.com/v1\" },\n fireworks: { provider: \"fireworks\", baseURL: \"https://api.fireworks.ai/inference/v1\" },\n groq: { provider: \"groq\", baseURL: \"https://api.groq.com/openai/v1\" },\n openrouter: { provider: \"openrouter\", baseURL: \"https://openrouter.ai/api/v1\" },\n togetherai: { provider: \"togetherai\", baseURL: \"https://api.together.xyz/v1\" },\n xai: { provider: \"xai\", baseURL: \"https://api.x.ai/v1\" },\n} as const satisfies Record<string, OpenAICompatibleProfile>\n\nexport const byProvider: Record<string, OpenAICompatibleProfile> = Object.fromEntries(\n Object.values(profiles).map((profile) => [profile.provider, profile]),\n)\n" | ||
| ], | ||
| "mappings": ";AAKO,IAAM,EAAW,CACtB,QAAS,CAAE,SAAU,UAAW,QAAS,iCAAkC,EAC3E,SAAU,CAAE,SAAU,WAAY,QAAS,4BAA6B,EACxE,UAAW,CAAE,SAAU,YAAa,QAAS,qCAAsC,EACnF,SAAU,CAAE,SAAU,WAAY,QAAS,6BAA8B,EACzE,UAAW,CAAE,SAAU,YAAa,QAAS,uCAAwC,EACrF,KAAM,CAAE,SAAU,OAAQ,QAAS,gCAAiC,EACpE,WAAY,CAAE,SAAU,aAAc,QAAS,8BAA+B,EAC9E,WAAY,CAAE,SAAU,aAAc,QAAS,6BAA8B,EAC7E,IAAK,CAAE,SAAU,MAAO,QAAS,qBAAsB,CACzD,EAEa,EAAsD,OAAO,YACxE,OAAO,OAAO,CAAQ,EAAE,IAAI,CAAC,IAAY,CAAC,EAAQ,SAAU,CAAO,CAAC,CACtE", | ||
| "debugId": "593BF0511FB46FF064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/node-http.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.4.10/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js"], | ||
| "sourcesContent": [ | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { retry } from \"./remoteProvider/retry\";\nexport const ENV_CMDS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nexport const ENV_CMDS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nexport const ENV_CMDS_AUTH_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromContainerMetadata = (init = {}) => {\n const { timeout, maxRetries } = providerConfigFromInit(init);\n return () => retry(async () => {\n const requestOptions = await getCmdsUri({ logger: init.logger });\n const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));\n if (!isImdsCredentials(credsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credsResponse);\n }, maxRetries);\n};\nconst requestFromEcsImds = async (timeout, options) => {\n if (process.env[ENV_CMDS_AUTH_TOKEN]) {\n options.headers = {\n ...options.headers,\n Authorization: process.env[ENV_CMDS_AUTH_TOKEN],\n };\n }\n const buffer = await httpRequest({\n ...options,\n timeout,\n });\n return buffer.toString();\n};\nconst CMDS_IP = \"169.254.170.2\";\nconst GREENGRASS_HOSTS = new Set([\"localhost\", \"127.0.0.1\"]);\nconst GREENGRASS_PROTOCOLS = new Set([\"http:\", \"https:\"]);\nconst getCmdsUri = async ({ logger }) => {\n if (process.env[ENV_CMDS_RELATIVE_URI]) {\n return {\n hostname: CMDS_IP,\n path: process.env[ENV_CMDS_RELATIVE_URI],\n };\n }\n if (process.env[ENV_CMDS_FULL_URI]) {\n let parsed;\n try {\n parsed = new URL(process.env[ENV_CMDS_FULL_URI]);\n }\n catch {\n throw new CredentialsProviderError(`${process.env[ENV_CMDS_FULL_URI]} is not a valid container metadata service URL`, { tryNextLink: false, logger });\n }\n if (!parsed.hostname || !GREENGRASS_HOSTS.has(parsed.hostname)) {\n throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {\n tryNextLink: false,\n logger,\n });\n }\n if (!parsed.protocol || !GREENGRASS_PROTOCOLS.has(parsed.protocol)) {\n throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {\n tryNextLink: false,\n logger,\n });\n }\n return {\n protocol: parsed.protocol,\n hostname: parsed.hostname,\n path: parsed.pathname + parsed.search,\n port: parsed.port ? parseInt(parsed.port, 10) : undefined,\n };\n }\n throw new CredentialsProviderError(\"The container metadata credential provider cannot be used unless\" +\n ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` +\n \" variable is set\", {\n tryNextLink: false,\n logger,\n });\n};\n", | ||
| "export const isImdsCredentials = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.AccessKeyId === \"string\" &&\n typeof arg.SecretAccessKey === \"string\" &&\n typeof arg.Token === \"string\" &&\n typeof arg.Expiration === \"string\";\nexport const fromImdsCredentials = (creds) => ({\n accessKeyId: creds.AccessKeyId,\n secretAccessKey: creds.SecretAccessKey,\n sessionToken: creds.Token,\n expiration: new Date(creds.Expiration),\n ...(creds.AccountId && { accountId: creds.AccountId }),\n});\n", | ||
| "export const DEFAULT_TIMEOUT = 1000;\nexport const DEFAULT_MAX_RETRIES = 0;\nexport const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout });\n", | ||
| "import { ProviderError } from \"@smithy/core/config\";\nimport { node_http } from \"./node-http\";\nexport function httpRequest(options) {\n return new Promise((resolve, reject) => {\n const req = node_http.request({\n method: \"GET\",\n ...options,\n hostname: options.hostname?.replace(/^\\[(.+)\\]$/, \"$1\"),\n });\n req.on(\"error\", (err) => {\n reject(Object.assign(new ProviderError(\"Unable to connect to instance metadata service\"), err));\n req.destroy();\n });\n req.on(\"timeout\", () => {\n reject(new ProviderError(\"TimeoutError from instance metadata service\"));\n req.destroy();\n });\n req.on(\"response\", (res) => {\n const { statusCode = 400 } = res;\n if (statusCode < 200 || 300 <= statusCode) {\n reject(Object.assign(new ProviderError(\"Error response received from instance metadata service\"), { statusCode }));\n req.destroy();\n }\n const chunks = [];\n res.on(\"data\", (chunk) => {\n chunks.push(chunk);\n });\n res.on(\"end\", () => {\n resolve(Buffer.concat(chunks));\n req.destroy();\n });\n });\n req.end();\n });\n}\n", | ||
| "import node_http from \"node:http\";\nexport { node_http };\n", | ||
| "export const retry = (toRetry, maxRetries) => {\n let promise = toRetry();\n for (let i = 0; i < maxRetries; i++) {\n promise = promise.catch(toRetry);\n }\n return promise;\n};\n", | ||
| "import { CredentialsProviderError, loadConfig } from \"@smithy/core/config\";\nimport { InstanceMetadataV1FallbackError } from \"./error/InstanceMetadataV1FallbackError\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { retry } from \"./remoteProvider/retry\";\nimport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nimport { staticStabilityProvider } from \"./utils/staticStabilityProvider\";\nconst IMDS_PATH = \"/latest/meta-data/iam/security-credentials/\";\nconst IMDS_TOKEN_PATH = \"/latest/api/token\";\nconst AWS_EC2_METADATA_V1_DISABLED = \"AWS_EC2_METADATA_V1_DISABLED\";\nconst PROFILE_AWS_EC2_METADATA_V1_DISABLED = \"ec2_metadata_v1_disabled\";\nconst X_AWS_EC2_METADATA_TOKEN = \"x-aws-ec2-metadata-token\";\nexport const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger });\nconst getInstanceMetadataProvider = (init = {}) => {\n let disableFetchToken = false;\n const { logger, profile } = init;\n const { timeout, maxRetries } = providerConfigFromInit(init);\n const getCredentials = async (maxRetries, options) => {\n const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;\n if (isImdsV1Fallback) {\n let fallbackBlockedFromProfile = false;\n let fallbackBlockedFromProcessEnv = false;\n const configValue = await loadConfig({\n environmentVariableSelector: (env) => {\n const envValue = env[AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProcessEnv = !!envValue && envValue !== \"false\";\n if (envValue === undefined) {\n throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger });\n }\n return fallbackBlockedFromProcessEnv;\n },\n configFileSelector: (profile) => {\n const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProfile = !!profileValue && profileValue !== \"false\";\n return fallbackBlockedFromProfile;\n },\n default: false,\n }, {\n profile,\n })();\n if (init.ec2MetadataV1Disabled || configValue) {\n const causes = [];\n if (init.ec2MetadataV1Disabled)\n causes.push(\"credential provider initialization (runtime option ec2MetadataV1Disabled)\");\n if (fallbackBlockedFromProfile)\n causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);\n if (fallbackBlockedFromProcessEnv)\n causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);\n throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(\", \")}].`);\n }\n }\n const imdsProfile = (await retry(async () => {\n let profile;\n try {\n profile = await getProfile(options);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return profile;\n }, maxRetries)).trim();\n return retry(async () => {\n let creds;\n try {\n creds = await getCredentialsFromProfile(imdsProfile, options, init);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return creds;\n }, maxRetries);\n };\n return async () => {\n const endpoint = await getInstanceMetadataEndpoint();\n if (disableFetchToken) {\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (no token fetch)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n else {\n let token;\n try {\n token = (await getMetadataToken({ ...endpoint, timeout })).toString();\n }\n catch (error) {\n if (error?.statusCode === 400) {\n throw Object.assign(error, {\n message: \"EC2 Metadata token request returned error\",\n });\n }\n else if (error.message === \"TimeoutError\" || [403, 404, 405].includes(error.statusCode)) {\n disableFetchToken = true;\n }\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (initial)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n return getCredentials(maxRetries, {\n ...endpoint,\n headers: {\n [X_AWS_EC2_METADATA_TOKEN]: token,\n },\n timeout,\n });\n }\n };\n};\nconst getMetadataToken = async (options) => httpRequest({\n ...options,\n path: IMDS_TOKEN_PATH,\n method: \"PUT\",\n headers: {\n \"x-aws-ec2-metadata-token-ttl-seconds\": \"21600\",\n },\n});\nconst getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString();\nconst getCredentialsFromProfile = async (profile, options, init) => {\n const credentialsResponse = JSON.parse((await httpRequest({\n ...options,\n path: IMDS_PATH + profile,\n })).toString());\n if (!isImdsCredentials(credentialsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credentialsResponse);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nexport class InstanceMetadataV1FallbackError extends CredentialsProviderError {\n tryNextLink;\n name = \"InstanceMetadataV1FallbackError\";\n constructor(message, tryNextLink = true) {\n super(message, tryNextLink);\n this.tryNextLink = tryNextLink;\n Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype);\n }\n}\n", | ||
| "import { loadConfig } from \"@smithy/core/config\";\nimport { parseUrl } from \"@smithy/core/protocols\";\nimport { Endpoint as InstanceMetadataEndpoint } from \"../config/Endpoint\";\nimport { ENDPOINT_CONFIG_OPTIONS } from \"../config/EndpointConfigOptions\";\nimport { EndpointMode } from \"../config/EndpointMode\";\nimport { ENDPOINT_MODE_CONFIG_OPTIONS, } from \"../config/EndpointModeConfigOptions\";\nexport const getInstanceMetadataEndpoint = async () => parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig()));\nconst getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)();\nconst getFromEndpointModeConfig = async () => {\n const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();\n switch (endpointMode) {\n case EndpointMode.IPv4:\n return InstanceMetadataEndpoint.IPv4;\n case EndpointMode.IPv6:\n return InstanceMetadataEndpoint.IPv6;\n default:\n throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`);\n }\n};\n", | ||
| "export var Endpoint;\n(function (Endpoint) {\n Endpoint[\"IPv4\"] = \"http://169.254.169.254\";\n Endpoint[\"IPv6\"] = \"http://[fd00:ec2::254]\";\n})(Endpoint || (Endpoint = {}));\n", | ||
| "export const ENV_ENDPOINT_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT\";\nexport const CONFIG_ENDPOINT_NAME = \"ec2_metadata_service_endpoint\";\nexport const ENDPOINT_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],\n default: undefined,\n};\n", | ||
| "export var EndpointMode;\n(function (EndpointMode) {\n EndpointMode[\"IPv4\"] = \"IPv4\";\n EndpointMode[\"IPv6\"] = \"IPv6\";\n})(EndpointMode || (EndpointMode = {}));\n", | ||
| "import { EndpointMode } from \"./EndpointMode\";\nexport const ENV_ENDPOINT_MODE_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE\";\nexport const CONFIG_ENDPOINT_MODE_NAME = \"ec2_metadata_service_endpoint_mode\";\nexport const ENDPOINT_MODE_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],\n default: EndpointMode.IPv4,\n};\n", | ||
| "const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;\nconst STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;\nconst STATIC_STABILITY_DOC_URL = \"https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html\";\nexport const getExtendedInstanceMetadataCredentials = (credentials, logger) => {\n const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS +\n Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);\n const newExpiration = new Date(Date.now() + refreshInterval * 1000);\n logger.warn(\"Attempting credential expiration extension due to a credential service availability issue. A refresh of these \" +\n `credentials will be attempted after ${new Date(newExpiration)}.\\nFor more information, please visit: ` +\n STATIC_STABILITY_DOC_URL);\n const originalExpiration = credentials.originalExpiration ?? credentials.expiration;\n return {\n ...credentials,\n ...(originalExpiration ? { originalExpiration } : {}),\n expiration: newExpiration,\n };\n};\n", | ||
| "import { getExtendedInstanceMetadataCredentials } from \"./getExtendedInstanceMetadataCredentials\";\nexport const staticStabilityProvider = (provider, options = {}) => {\n const logger = options?.logger || console;\n let pastCredentials;\n return async () => {\n let credentials;\n try {\n credentials = await provider();\n if (credentials.expiration && credentials.expiration.getTime() < Date.now()) {\n credentials = getExtendedInstanceMetadataCredentials(credentials, logger);\n }\n }\n catch (e) {\n if (pastCredentials) {\n logger.warn(\"Credential renew failed: \", e);\n credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger);\n }\n else {\n throw e;\n }\n }\n pastCredentials = credentials;\n return credentials;\n };\n};\n" | ||
| ], | ||
| "mappings": ";mJAAA,oBCAO,SAAM,EAAoB,CAAC,IAAQ,QAAQ,CAAG,GACjD,OAAO,IAAQ,UACf,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,kBAAoB,UAC/B,OAAO,EAAI,QAAU,UACrB,OAAO,EAAI,aAAe,SACjB,EAAsB,CAAC,KAAW,CAC3C,YAAa,EAAM,YACnB,gBAAiB,EAAM,gBACvB,aAAc,EAAM,MACpB,WAAY,IAAI,KAAK,EAAM,UAAU,KACjC,EAAM,WAAa,CAAE,UAAW,EAAM,SAAU,CACxD,GCZO,IAAM,EAAkB,KAClB,EAAsB,EACtB,EAAyB,EAAG,aADN,EACwC,U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Y,IACjD,EACH,KAAM,GACN,OAAQ,MACR,QAAS,CACL,uCAAwC,OAC5C,CACJ,CAAC,EACK,GAAa,MAAO,KAAa,MAAM,EAAY,IAAK,EAAS,KAAM,CAAU,CAAC,GAAG,SAAS,EAC9F,GAA4B,MAAO,EAAS,EAAS,IAAS,CAChE,IAAM,EAAsB,KAAK,OAAO,MAAM,EAAY,IACnD,EACH,KAAM,EAAY,CACtB,CAAC,GAAG,SAAS,CAAC,EACd,GAAI,CAAC,EAAkB,CAAmB,EACtC,MAAM,IAAI,2BAAyB,4DAA6D,CAC5F,OAAQ,EAAK,MACjB,CAAC,EAEL,OAAO,EAAoB,CAAmB", | ||
| "debugId": "F9D2FD2D8D3C4AFE64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/ui/timeline.tsx", "src/commands/handlers/console/login.ts"], | ||
| "sourcesContent": [ | ||
| "import { createComponent as _$createComponent } from \"@opentui/solid\";\nimport { effect as _$effect } from \"@opentui/solid\";\nimport { createTextNode as _$createTextNode } from \"@opentui/solid\";\nimport { insertNode as _$insertNode } from \"@opentui/solid\";\nimport { insert as _$insert } from \"@opentui/solid\";\nimport { setProp as _$setProp } from \"@opentui/solid\";\nimport { createElement as _$createElement } from \"@opentui/solid\";\n/** @jsxImportSource @opentui/solid */\nimport { createCliRenderer, RGBA } from \"@opentui/core\";\nimport { createScrollbackWriter, render, useKeyboard } from \"@opentui/solid\";\nimport { registerOpencodeSpinner } from \"@opencode-ai/tui/component/register-spinner\";\nimport { Show, createSignal } from \"solid-js\";\nregisterOpencodeSpinner();\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst IDLE_TIMEOUT = 1_000;\nconst COLORS = {\n accent: RGBA.fromIndex(6),\n error: RGBA.fromIndex(1),\n foreground: RGBA.defaultForeground(),\n muted: RGBA.fromIndex(8),\n success: RGBA.fromIndex(2)\n};\nconst ROWS = {\n intro: {\n marker: \"┌\",\n color: COLORS.muted,\n connector: true\n },\n item: {\n marker: \"●\",\n color: COLORS.accent,\n connector: true\n },\n success: {\n marker: \"◇\",\n color: COLORS.success,\n connector: true\n },\n failure: {\n marker: \"■\",\n color: COLORS.error,\n connector: false\n },\n outro: {\n marker: \"└\",\n color: COLORS.muted,\n connector: false\n }\n};\nfunction row(kind, value) {\n const style = ROWS[kind];\n return createScrollbackWriter(() => (() => {\n var _el$ = _$createElement(\"box\"),\n _el$2 = _$createElement(\"box\"),\n _el$3 = _$createElement(\"text\"),\n _el$4 = _$createElement(\"text\");\n _$insertNode(_el$, _el$2);\n _$setProp(_el$, \"width\", \"100%\");\n _$setProp(_el$, \"minHeight\", 1);\n _$setProp(_el$, \"flexDirection\", \"column\");\n _$insertNode(_el$2, _el$3);\n _$insertNode(_el$2, _el$4);\n _$setProp(_el$2, \"width\", \"100%\");\n _$setProp(_el$2, \"minHeight\", 1);\n _$setProp(_el$2, \"flexDirection\", \"row\");\n _$setProp(_el$2, \"gap\", 1);\n _$setProp(_el$3, \"flexShrink\", 0);\n _$insert(_el$3, () => style.marker);\n _$setProp(_el$4, \"wrapMode\", \"word\");\n _$insert(_el$4, value);\n _$insert(_el$, _$createComponent(Show, {\n get when() {\n return style.connector;\n },\n get children() {\n var _el$5 = _$createElement(\"text\");\n _$insertNode(_el$5, _$createTextNode(`│`));\n _$effect(_$p => _$setProp(_el$5, \"fg\", COLORS.muted, _$p));\n return _el$5;\n }\n }), null);\n _$effect(_p$ => {\n var _v$ = style.color,\n _v$2 = COLORS.foreground;\n _v$ !== _p$.e && (_p$.e = _$setProp(_el$3, \"fg\", _v$, _p$.e));\n _v$2 !== _p$.t && (_p$.t = _$setProp(_el$4, \"fg\", _v$2, _p$.t));\n return _p$;\n }, {\n e: undefined,\n t: undefined\n });\n return _el$;\n })(), {\n startOnNewLine: true,\n trailingNewline: !style.connector\n });\n}\nfunction TimelineFooter(props) {\n useKeyboard(event => {\n if (event.name !== \"escape\" && !(event.ctrl && event.name === \"c\")) return;\n event.preventDefault();\n props.cancel();\n });\n return (() => {\n var _el$7 = _$createElement(\"box\");\n _$setProp(_el$7, \"width\", \"100%\");\n _$setProp(_el$7, \"height\", 1);\n _$setProp(_el$7, \"flexDirection\", \"row\");\n _$setProp(_el$7, \"gap\", 1);\n _$insert(_el$7, _$createComponent(Show, {\n get when() {\n return props.pending();\n },\n children: text => [(() => {\n var _el$8 = _$createElement(\"spinner\");\n _$setProp(_el$8, \"frames\", SPINNER_FRAMES);\n _$setProp(_el$8, \"interval\", 80);\n _$effect(_$p => _$setProp(_el$8, \"color\", COLORS.accent, _$p));\n return _el$8;\n })(), (() => {\n var _el$9 = _$createElement(\"text\");\n _$setProp(_el$9, \"wrapMode\", \"none\");\n _$setProp(_el$9, \"truncate\", true);\n _$insert(_el$9, text);\n _$effect(_$p => _$setProp(_el$9, \"fg\", COLORS.foreground, _$p));\n return _el$9;\n })()]\n }));\n return _el$7;\n })();\n}\nfunction bounded(task) {\n return new Promise(resolve => {\n const timer = setTimeout(resolve, IDLE_TIMEOUT);\n timer.unref();\n const finish = () => {\n clearTimeout(timer);\n resolve();\n };\n void task.then(finish, finish);\n });\n}\nasync function shutdown(renderer) {\n await bounded(renderer.idle());\n try {\n renderer.externalOutputMode = \"passthrough\";\n } finally {\n try {\n renderer.screenMode = \"main-screen\";\n } finally {\n if (!renderer.isDestroyed) renderer.destroy();\n }\n }\n}\nexport async function createTimelineHost() {\n const stdout = process.stdout;\n const controller = new AbortController();\n const signals = [\"SIGINT\", \"SIGHUP\", \"SIGQUIT\"];\n const cancel = () => {\n if (!controller.signal.aborted) controller.abort();\n };\n signals.forEach(signal => process.on(signal, cancel));\n if (!stdout.isTTY || !process.stdin.isTTY) {\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = async (kind, text) => {\n if (closed) throw new Error(\"timeline closed\");\n if (writing) throw new Error(\"timeline write already in progress\");\n writing = true;\n try {\n const style = kind === \"pending\" ? undefined : ROWS[kind];\n const marker = kind === \"pending\" ? \".\" : ROWS[kind].marker;\n const connector = style?.connector ? \"│\\n\" : \"\";\n active = new Promise((resolve, reject) => {\n stdout.write(`${marker} ${text}\\n${connector}`, error => error ? reject(error) : resolve());\n });\n await active;\n } finally {\n writing = false;\n active = undefined;\n }\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n signals.forEach(signal => process.off(signal, cancel));\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n }\n let renderer;\n try {\n // Start on a fresh row so delayed SSH cursor reports cannot make\n // split-footer overwrite the shell command.\n process.stdout.write(\"\\n\");\n renderer = await createCliRenderer({\n stdin: process.stdin,\n useMouse: false,\n autoFocus: false,\n openConsoleOnError: false,\n exitOnCtrlC: false,\n exitSignals: [],\n screenMode: \"split-footer\",\n footerHeight: 1,\n externalOutputMode: \"capture-stdout\",\n consoleMode: \"disabled\",\n clearOnShutdown: false\n });\n const activeRenderer = renderer;\n const [pending, setPending] = createSignal();\n const renderTask = render(() => _$createComponent(TimelineFooter, {\n pending: pending,\n cancel: cancel\n }), activeRenderer);\n void renderTask.catch(cancel);\n await bounded(activeRenderer.idle());\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = (kind, text) => {\n if (closed) return Promise.reject(new Error(\"timeline closed\"));\n if (writing) return Promise.reject(new Error(\"timeline write already in progress\"));\n writing = true;\n active = (async () => {\n if (kind === \"pending\") {\n setPending(text);\n activeRenderer.requestRender();\n } else {\n if (kind === \"success\" || kind === \"failure\" || kind === \"outro\") setPending(undefined);\n activeRenderer.writeToScrollback(row(kind, text));\n activeRenderer.requestRender();\n }\n await bounded(activeRenderer.idle());\n })().finally(() => {\n writing = false;\n active = undefined;\n });\n return active;\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n try {\n await shutdown(activeRenderer);\n await bounded(renderTask);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n } catch (error) {\n try {\n if (renderer) await shutdown(renderer);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n throw error;\n }\n}", | ||
| "import { Cause, Effect, Exit, Option } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { AppProcess } from \"@opencode-ai/util/process\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { createTimelineHost, type TimelineHost } from \"../../../ui/timeline\"\n\nconst integrationID = \"opencode\"\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.console.commands.login,\n Effect.fn(\"cli.console.login\")(function* (input) {\n const timeline = yield* Effect.acquireRelease(\n Effect.promise(() => createTimelineHost()),\n (value) => request(() => value.close()).pipe(Effect.ignore),\n )\n const exit = yield* login(timeline, Option.getOrUndefined(input.url)).pipe(\n Effect.raceFirst(AppProcess.waitForAbort(timeline.signal)),\n Effect.exit,\n )\n if (Exit.isSuccess(exit)) return\n\n const cancelled = timeline.signal.aborted\n yield* request(() => timeline.failure(cancelled ? \"Authorization cancelled\" : errorMessage(exit.cause))).pipe(\n Effect.ignore,\n )\n process.exitCode = cancelled ? 130 : 1\n }),\n)\n\nconst login = Effect.fn(\"cli.console.login.run\")(function* (timeline: TimelineHost, server?: string) {\n yield* request(() => timeline.intro(\"Log in\"))\n yield* request(() => timeline.pending(\"Connecting to OpenCode...\"))\n\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const found = yield* request((signal) => client.integration.get({ integrationID, location }, { signal }))\n const integration = yield* required(found.data, \"OpenCode Console integration is unavailable\")\n const method = yield* required(\n integration.methods.find((candidate) => candidate.type === \"oauth\"),\n \"OpenCode Console login is unavailable\",\n )\n\n yield* request(() => timeline.pending(\"Starting authorization...\"))\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n {\n integrationID,\n methodID: method.id,\n inputs: server ? { server } : {},\n location,\n },\n { signal },\n ),\n )\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n if (attempt.mode !== \"auto\") yield* Effect.fail(new Error(\"OpenCode Console requires a device login\"))\n\n yield* request(() => timeline.item(`Go to: ${attempt.url}`))\n yield* request(() => timeline.item(attempt.instructions))\n yield* request(async () => {\n const { default: open } = await import(\"open\")\n await open(attempt.url)\n }).pipe(Effect.ignore)\n yield* request(() => timeline.pending(\"Waiting for authorization...\"))\n\n const status = yield* waitForConsoleLogin(client, integrationID, attempt.attemptID)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") yield* Effect.fail(new Error(\"Device code expired\"))\n\n yield* request(() => timeline.success(\"Connected to OpenCode Console\"))\n yield* request(() => timeline.outro(\"Done\"))\n})\n\nconst waitForConsoleLogin = Effect.fn(\"cli.console.login.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.oauth.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n yield* Effect.sleep(500)\n }\n})\n\nfunction request<A>(task: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: task,\n catch: (cause) => cause,\n })\n}\n\nfunction required<A>(value: A | null | undefined, message: string) {\n return value === null || value === undefined ? Effect.fail(new Error(message)) : Effect.succeed(value)\n}\n\nfunction errorMessage(cause: Cause.Cause<unknown>) {\n const error = Cause.squash(cause)\n if (error instanceof Error) return error.message\n if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\") {\n return error.message\n }\n return String(error)\n}\n" | ||
| ], | ||
| "mappings": ";0lCAYA,OAAwB,OACxB,SAAM,OAAiB,MAAC,cAAI,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,aAAG,OACjE,QAAe,UACf,OAAS,MACb,YAAQ,OAAK,eAAU,MAAC,EACxB,MAAO,EAAK,UAAU,CAAC,EACvB,WAAY,EAAK,kBAAkB,EACnC,MAAO,EAAK,UAAU,CAAC,EACvB,QAAS,EAAK,UAAU,CAAC,CAC3B,EACM,EAAO,CACX,MAAO,CACL,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,EACA,KAAM,CACJ,OAAQ,SACR,MAAO,EAAO,OACd,UAAW,EACb,EACA,QAAS,CACP,OAAQ,SACR,MAAO,EAAO,QACd,UAAW,EACb,EACA,QAAS,CACP,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,EACA,MAAO,CACL,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,CACF,EACA,SAAS,EAAG,CAAC,EAAM,EAAO,CACxB,IAAM,EAAQ,EAAK,GACnB,OAAO,EAAuB,KAAO,IAAM,CACzC,IAAI,EAAO,EAAgB,KAAK,EAC9B,EAAQ,EAAgB,KAAK,EAC7B,EAAQ,EAAgB,MAAM,EAC9B,EAAQ,EAAgB,MAAM,EAoChC,OAnCA,EAAa,EAAM,CAAK,EACxB,EAAU,EAAM,QAAS,MAAM,EAC/B,EAAU,EAAM,YAAa,CAAC,EAC9B,EAAU,EAAM,gBAAiB,QAAQ,EACzC,EAAa,EAAO,CAAK,E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AG,CAAE,QAAO,CAAC,CACpF,EACA,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,MAAO,EAAO,MAAM,GAAG,GAE1B,EAED,SAAS,CAAU,CAAC,EAA2C,CAC7D,OAAO,EAAO,WAAW,CACvB,IAAK,EACL,MAAO,CAAC,IAAU,CACpB,CAAC,EAGH,SAAS,CAAW,CAAC,EAA6B,EAAiB,CACjE,OAAO,IAAU,MAAQ,IAAU,OAAY,EAAO,KAAS,MAAM,CAAO,CAAC,EAAI,EAAO,QAAQ,CAAK,EAGvG,SAAS,EAAY,CAAC,EAA6B,CACjD,IAAM,EAAQ,EAAM,OAAO,CAAK,EAChC,GAAI,aAAiB,MAAO,OAAO,EAAM,QACzC,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,OAAO,EAAM,UAAY,SAChG,OAAO,EAAM,QAEf,OAAO,OAAO,CAAK", | ||
| "debugId": "E44573A494AAEBD264756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "D75D6721B7B1FF5864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "AEAE44FECE20DB8364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/get.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.get,\n Effect.fn(\"cli.service.get\")(function* (input) {\n process.stdout.write((yield* ServiceConfig.get(Option.getOrUndefined(input.key))) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";00BAAA,mBAAS,gBAMT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,SACnC,OAAO,QAAG,sBAAiB,OAAE,cAAU,MAAC,OAAO,MAC7C,aAAQ,YAAO,YAAO,WAAO,EAAc,IAAI,EAAO,eAAe,EAAM,GAAG,CAAC,GAAK,CAAG,EACxF,CACH", | ||
| "debugId": "0238A6B004869E8164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/azure.ts"], | ||
| "sourcesContent": [ | ||
| "import { Auth } from \"../route/auth\"\nimport { type AtLeastOne, type ProviderAuthOption } from \"../route/auth-options\"\nimport type { Route as RouteDef, RouteDefaultsInput } from \"../route/client\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { ProviderID, type ModelID } from \"../schema\"\nimport * as OpenAIChat from \"../protocols/openai-chat\"\nimport * as OpenAIResponses from \"../protocols/openai-responses\"\nimport { withOpenAIOptions, type OpenAIProviderOptionsInput } from \"./openai-options\"\n\nexport const id = ProviderID.make(\"azure\")\nconst routeAuth = Auth.remove(\"authorization\")\n\n// Azure needs the customer's resource URL; supply either `resourceName`\n// (helper builds the URL) or `baseURL` directly.\ntype AzureURL = AtLeastOne<{ readonly resourceName: string; readonly baseURL: string }>\n\nexport type ModelOptions = AzureURL &\n RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly apiVersion?: string\n readonly queryParams?: Record<string, string>\n readonly useCompletionUrls?: boolean\n readonly providerOptions?: OpenAIProviderOptionsInput\n }\nexport type Config = ModelOptions\n\nexport type Settings = ProviderPackage.Settings &\n AzureURL & {\n readonly apiKey?: string\n readonly apiVersion?: string\n readonly queryParams?: Readonly<Record<string, string>>\n readonly providerOptions?: OpenAIProviderOptionsInput\n }\n\nconst resourceBaseURL = (resourceName: string) => `https://${resourceName.trim()}.openai.azure.com/openai/v1`\n\nconst responsesRoute = OpenAIResponses.route.with({\n id: \"azure-openai-responses\",\n provider: id,\n auth: routeAuth,\n endpoint: {\n query: { \"api-version\": \"v1\" },\n },\n})\n\nconst chatRoute = OpenAIChat.route.with({\n id: \"azure-openai-chat\",\n provider: id,\n auth: routeAuth,\n endpoint: {\n query: { \"api-version\": \"v1\" },\n },\n})\n\nexport const routes = [responsesRoute, chatRoute]\n\nconst defaults = (input: Config) => {\n const {\n apiKey: _,\n apiVersion: _apiVersion,\n resourceName: _resourceName,\n useCompletionUrls: _useCompletionUrls,\n baseURL: _baseURL,\n queryParams: _queryParams,\n ...rest\n } = input\n if (\"auth\" in rest) {\n const { auth: _, ...withoutAuth } = rest\n return withoutAuth\n }\n return rest\n}\n\nconst auth = (input: Config) => {\n if (\"auth\" in input && input.auth) return input.auth\n return Auth.remove(\"authorization\").andThen(\n Auth.optional(\"apiKey\" in input ? input.apiKey : undefined, \"apiKey\")\n .orElse(Auth.config(\"AZURE_OPENAI_API_KEY\"))\n .pipe(Auth.header(\"api-key\")),\n )\n}\n\nconst configuredRoute = <Body, Prepared>(route: RouteDef<Body, Prepared>, input: Config) =>\n route.with({\n auth: auth(input),\n endpoint: {\n // AtLeastOne guarantees at least one is set; baseURL wins if both are.\n baseURL: input.baseURL ?? resourceBaseURL(input.resourceName!),\n query: {\n ...(input.apiVersion ? { \"api-version\": input.apiVersion } : {}),\n ...input.queryParams,\n },\n },\n })\n\nexport const configure = (input: Config) => {\n const configuredResponsesRoute = configuredRoute(responsesRoute, input)\n const configuredChatRoute = configuredRoute(chatRoute, input)\n const modelDefaults = defaults(input)\n\n const responses = (modelID: string | ModelID) =>\n configuredResponsesRoute.with(withOpenAIOptions(modelID, modelDefaults)).model({ id: modelID })\n\n const chat = (modelID: string | ModelID) =>\n configuredChatRoute.with(withOpenAIOptions(modelID, modelDefaults)).model({ id: modelID })\n\n return {\n id,\n model: (modelID: string | ModelID) => (input.useCompletionUrls === true ? chat(modelID) : responses(modelID)),\n responses,\n chat,\n configure,\n }\n}\n\nexport const provider = {\n id,\n configure,\n}\n\nconst config = (settings: Settings): Config => {\n const common = {\n apiKey: settings.apiKey,\n apiVersion: settings.apiVersion,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n providerOptions: settings.providerOptions,\n queryParams: settings.queryParams === undefined ? undefined : { ...settings.queryParams },\n }\n if (settings.baseURL !== undefined) return { ...common, baseURL: settings.baseURL }\n if (settings.resourceName !== undefined) return { ...common, resourceName: settings.resourceName }\n throw new Error(\"Azure requires resourceName or baseURL\")\n}\n\nexport const responsesModel: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure(config(settings)).responses(modelID)\nexport const chatModel: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure(config(settings)).chat(modelID)\nexport const model = responsesModel\n" | ||
| ], | ||
| "mappings": ";yMASO,SAAM,OAAK,OAAW,KAAK,OAAO,EACnC,EAAY,EAAK,OAAO,eAAe,EAwBvC,EAAkB,CAAC,IAAyB,WAAW,EAAa,KAAK,+BAEzE,EAAiC,EAAM,KAAK,CAChD,GAAI,yBACJ,SAAU,EACV,KAAM,EACN,SAAU,CACR,MAAO,CAAE,cAAe,IAAK,CAC/B,CACF,CAAC,EAEK,EAAuB,EAAM,KAAK,CACtC,GAAI,oBACJ,SAAU,EACV,KAAM,EACN,SAAU,CACR,MAAO,CAAE,cAAe,IAAK,CAC/B,CACF,CAAC,EAEY,EAAS,CAAC,EAAgB,CAAS,EAE1C,EAAW,CAAC,IAAkB,CAClC,IACE,OAAQ,EACR,WAAY,EACZ,aAAc,EACd,kBAAmB,EACnB,QAAS,EACT,YAAa,KACV,GACD,EACJ,GAAI,SAAU,EAAM,CAClB,IAAQ,KAAM,KAAM,GAAgB,EACpC,OAAO,EAET,OAAO,GAGH,EAAO,CAAC,IAAkB,CAC9B,GAAI,SAAU,GAAS,EAAM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O,IAAK,EAAQ,QAAS,EAAS,OAAQ,EAClF,GAAI,EAAS,eAAiB,OAAW,MAAO,IAAK,EAAQ,aAAc,EAAS,YAAa,EACjG,MAAU,MAAM,wCAAwC,GAG7C,EAAgE,CAAC,EAAS,IACrF,EAAU,EAAO,CAAQ,CAAC,EAAE,UAAU,CAAO,EAClC,EAA2D,CAAC,EAAS,IAChF,EAAU,EAAO,CAAQ,CAAC,EAAE,KAAK,CAAO,EAC7B,EAAQ", | ||
| "debugId": "756178589AFEE7D264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/utils/openai-options.ts", "../ai/src/protocols/openai-chat.ts"], | ||
| "sourcesContent": [ | ||
| "import { Schema } from \"effect\"\nimport type { LLMRequest, TextVerbosity as TextVerbosityValue } from \"../../schema\"\nimport { ReasoningEfforts, TextVerbosity } from \"../../schema\"\n\nexport const OpenAIReasoningEfforts = ReasoningEfforts\nexport type OpenAIReasoningEffort = string\n\n// Mirrors OpenAI's `ResponseIncludable` union from the official SDK. Keep this\n// in lockstep with `openai-node/src/resources/responses/responses.ts`.\nexport const OpenAIResponseIncludables = [\n \"file_search_call.results\",\n \"web_search_call.results\",\n \"web_search_call.action.sources\",\n \"message.input_image.image_url\",\n \"computer_call_output.output.image_url\",\n \"code_interpreter_call.outputs\",\n \"reasoning.encrypted_content\",\n \"message.output_text.logprobs\",\n] as const\nexport type OpenAIResponseIncludable = (typeof OpenAIResponseIncludables)[number]\nexport const OpenAIServiceTiers = [\"auto\", \"default\", \"flex\", \"priority\"] as const\nexport type OpenAIServiceTier = (typeof OpenAIServiceTiers)[number]\n\nconst TEXT_VERBOSITY = new Set<string>([\"low\", \"medium\", \"high\"])\nconst INCLUDABLES = new Set<string>(OpenAIResponseIncludables)\nconst SERVICE_TIERS = new Set<string>(OpenAIServiceTiers)\n\nexport const OpenAIReasoningEffort = Schema.String\nexport const OpenAITextVerbosity = TextVerbosity\nexport const OpenAIResponseIncludable = Schema.Literals(OpenAIResponseIncludables)\nexport const OpenAIServiceTier = Schema.Literals(OpenAIServiceTiers)\n\nexport const isReasoningEffort = (effort: unknown): effort is OpenAIReasoningEffort => typeof effort === \"string\"\n\nconst isTextVerbosity = (value: unknown): value is TextVerbosityValue =>\n typeof value === \"string\" && TEXT_VERBOSITY.has(value)\n\nconst options = (request: LLMRequest) => request.providerOptions?.openai\n\nexport const store = (request: LLMRequest): boolean | undefined => {\n const value = options(request)?.store\n return typeof value === \"boolean\" ? value : undefined\n}\n\nexport const reasoningEffort = (request: LLMRequest): string | undefined => {\n const value = options(request)?.reasoningEffort\n return typeof value === \"string\" ? value : undefined\n}\n\nexport const reasoningSummary = (request: LLMRequest): \"auto\" | undefined =>\n options(request)?.reasoningSummary === \"auto\" ? \"auto\" : undefined\n\n// Resolve the OpenAI Responses `include` field. Filters out unknown\n// includable values defensively so a typo in upstream config drops the\n// invalid entry instead of poisoning the wire body. An empty array (either\n// passed directly or produced by filtering) is treated as \"no include\" and\n// returns undefined so the request body omits the field entirely.\nexport const include = (request: LLMRequest): ReadonlyArray<OpenAIResponseIncludable> | undefined => {\n const value = options(request)?.include\n if (!Array.isArray(value)) return undefined\n const filtered = value.filter((entry): entry is OpenAIResponseIncludable => INCLUDABLES.has(entry))\n return filtered.length > 0 ? filtered : undefined\n}\n\nexport const promptCacheKey = (request: LLMRequest) => {\n const value = options(request)?.promptCacheKey\n return typeof value === \"string\" ? value : undefined\n}\n\nexport const textVerbosity = (request: LLMRequest) => {\n const value = options(request)?.textVerbosity\n return isTextVerbosity(value) ? value : undefined\n}\n\nexport const serviceTier = (request: LLMRequest) => {\n const value = options(request)?.serviceTier\n return typeof value === \"string\" && SERVICE_TIERS.has(value) ? (value as OpenAIServiceTier) : undefined\n}\n\nexport const instructions = (request: LLMRequest) => {\n const value = options(request)?.instructions\n return typeof value === \"string\" ? value : undefined\n}\n\nexport * as OpenAIOptions from \"./openai-options\"\n", | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { HttpTransport } from \"../route/transport\"\nimport { Protocol } from \"../route/protocol\"\nimport {\n LLMEvent,\n Usage,\n type FinishReason,\n type JsonSchema,\n type LLMRequest,\n type MediaPart,\n type ReasoningPart,\n type TextPart,\n type ToolCallPart,\n type ToolDefinition,\n type ToolContent,\n} from \"../schema\"\nimport { isRecord, JsonObject, optionalArray, optionalNull, ProviderShared } from \"./shared\"\nimport { OpenAIOptions } from \"./utils/openai-options\"\nimport { Lifecycle } from \"./utils/lifecycle\"\nimport { ToolSchemaProjection } from \"./utils/tool-schema\"\nimport { ToolStream } from \"./utils/tool-stream\"\n\nconst ADAPTER = \"openai-chat\"\nconst IMAGE_MIMES = new Set<string>(ProviderShared.IMAGE_MIMES)\nconst RESERVED_REASONING_FIELDS = new Set([\"role\", \"content\", \"tool_calls\"])\nexport const DEFAULT_BASE_URL = \"https://api.openai.com/v1\"\nexport const PATH = \"/chat/completions\"\n\n// =============================================================================\n// Request Body Schema\n// =============================================================================\n// The body schema is the provider-native JSON body. `fromRequest` below builds\n// this shape from the common `LLMRequest`, then `Route.make` validates and\n// JSON-encodes it before transport.\nconst OpenAIChatFunction = Schema.Struct({\n name: Schema.String,\n description: Schema.String,\n parameters: JsonObject,\n})\n\nconst OpenAIChatTool = Schema.Struct({\n type: Schema.tag(\"function\"),\n function: OpenAIChatFunction,\n})\ntype OpenAIChatTool = Schema.Schema.Type<typeof OpenAIChatTool>\n\nconst OpenAIChatAssistantToolCall = Schema.Struct({\n id: Schema.String,\n type: Schema.tag(\"function\"),\n function: Schema.Struct({\n name: Schema.String,\n arguments: Schema.String,\n }),\n})\ntype OpenAIChatAssistantToolCall = Schema.Schema.Type<typeof OpenAIChatAssistantToolCall>\n\nconst OpenAIChatUserContent = Schema.Union([\n Schema.Struct({ type: Schema.Literal(\"text\"), text: Schema.String }),\n Schema.Struct({\n type: Schema.Literal(\"image_url\"),\n image_url: Schema.Struct({ url: Schema.String }),\n }),\n])\n\nconst OpenAIChatMessage = Schema.Union([\n Schema.Struct({ role: Schema.Literal(\"system\"), content: Schema.String }),\n Schema.Struct({\n role: Schema.Literal(\"user\"),\n content: Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContent)]),\n }),\n Schema.StructWithRest(\n Schema.Struct({\n role: Schema.Literal(\"assistant\"),\n content: Schema.NullOr(Schema.String),\n tool_calls: optionalArray(OpenAIChatAssistantToolCall),\n reasoning_content: Schema.optional(Schema.String),\n reasoning: Schema.optional(Schema.String),\n reasoning_text: Schema.optional(Schema.String),\n reasoning_details: Schema.optional(Schema.Unknown),\n }),\n [Schema.Record(Schema.String, Schema.Unknown)],\n ),\n Schema.Struct({ role: Schema.Literal(\"tool\"), tool_call_id: Schema.String, content: Schema.String }),\n]).pipe(Schema.toTaggedUnion(\"role\"))\ntype OpenAIChatMessage = Schema.Schema.Type<typeof OpenAIChatMessage>\n\nconst OpenAIChatToolChoice = Schema.Union([\n Schema.Literals([\"auto\", \"none\", \"required\"]),\n Schema.Struct({\n type: Schema.tag(\"function\"),\n function: Schema.Struct({ name: Schema.String }),\n }),\n])\n\nexport const bodyFields = {\n model: Schema.String,\n messages: Schema.Array(OpenAIChatMessage),\n tools: optionalArray(OpenAIChatTool),\n tool_choice: Schema.optional(OpenAIChatToolChoice),\n stream: Schema.Literal(true),\n stream_options: Schema.optional(Schema.Struct({ include_usage: Schema.Boolean })),\n store: Schema.optional(Schema.Boolean),\n reasoning_effort: Schema.optional(OpenAIOptions.OpenAIReasoningEffort),\n max_tokens: Schema.optional(Schema.Number),\n temperature: Schema.optional(Schema.Number),\n top_p: Schema.optional(Schema.Number),\n frequency_penalty: Schema.optional(Schema.Number),\n presence_penalty: Schema.optional(Schema.Number),\n seed: Schema.optional(Schema.Number),\n stop: optionalArray(Schema.String),\n}\nconst OpenAIChatBody = Schema.Struct(bodyFields)\nexport type OpenAIChatBody = Schema.Schema.Type<typeof OpenAIChatBody>\n\n// =============================================================================\n// Streaming Event Schema\n// =============================================================================\n// The event schema is one decoded SSE `data:` payload. `Framing.sse` splits the\n// byte stream into strings, then `Protocol.jsonEvent` decodes each string into\n// this provider-native event shape.\nconst OpenAIChatUsage = Schema.Struct({\n prompt_tokens: Schema.optional(Schema.Number),\n completion_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n prompt_tokens_details: optionalNull(\n Schema.Struct({\n cached_tokens: Schema.optional(Schema.Number),\n }),\n ),\n completion_tokens_details: optionalNull(\n Schema.Struct({\n reasoning_tokens: Schema.optional(Schema.Number),\n }),\n ),\n})\n\nconst OpenAIChatToolCallDeltaFunction = Schema.Struct({\n name: optionalNull(Schema.String),\n arguments: optionalNull(Schema.String),\n})\n\nconst OpenAIChatToolCallDelta = Schema.Struct({\n index: Schema.Number,\n id: optionalNull(Schema.String),\n function: optionalNull(OpenAIChatToolCallDeltaFunction),\n})\ntype OpenAIChatToolCallDelta = Schema.Schema.Type<typeof OpenAIChatToolCallDelta>\n\nconst OpenAIChatDelta = Schema.StructWithRest(\n Schema.Struct({\n content: optionalNull(Schema.String),\n reasoning_content: optionalNull(Schema.String),\n reasoning: optionalNull(Schema.String),\n reasoning_text: optionalNull(Schema.String),\n reasoning_details: optionalNull(Schema.Unknown),\n tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),\n }),\n [Schema.Record(Schema.String, Schema.Unknown)],\n)\n\nconst OpenAIChatChoice = Schema.Struct({\n delta: optionalNull(OpenAIChatDelta),\n finish_reason: optionalNull(Schema.String),\n})\n\nexport const OpenAIChatEvent = Schema.Struct({\n choices: Schema.Array(OpenAIChatChoice),\n usage: optionalNull(OpenAIChatUsage),\n})\nexport type OpenAIChatEvent = Schema.Schema.Type<typeof OpenAIChatEvent>\ntype OpenAIChatRequestMessage = LLMRequest[\"messages\"][number]\n\ninterface PendingToolDelta {\n readonly id?: string\n readonly name?: string\n readonly input: string\n}\n\nexport interface ParserState {\n readonly tools: ToolStream.State<number>\n readonly pendingTools: Partial<Record<number, PendingToolDelta>>\n readonly toolCallEvents: ReadonlyArray<LLMEvent>\n readonly usage?: Usage\n readonly finishReason?: FinishReason\n readonly lifecycle: Lifecycle.State\n readonly reasoningField?: string\n readonly reasoningDetails: Array<unknown>\n readonly reasoningDetailsObserved: boolean\n readonly reasoningEmitted: boolean\n}\n\n// =============================================================================\n// Request Lowering\n// =============================================================================\n// Lowering is the only place that knows how common LLM messages map onto the\n// OpenAI Chat wire format. Keep provider quirks here instead of leaking native\n// fields into `LLMRequest`.\nconst lowerTool = (tool: ToolDefinition, inputSchema: JsonSchema): OpenAIChatTool => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: ToolSchemaProjection.openAI(inputSchema),\n },\n})\n\nconst lowerToolChoice = (toolChoice: NonNullable<LLMRequest[\"toolChoice\"]>) =>\n ProviderShared.matchToolChoice(\"OpenAI Chat\", toolChoice, {\n auto: () => \"auto\" as const,\n none: () => \"none\" as const,\n required: () => \"required\" as const,\n tool: (name) => ({ type: \"function\" as const, function: { name } }),\n })\n\nconst lowerToolCall = (part: ToolCallPart): OpenAIChatAssistantToolCall => ({\n id: part.id,\n type: \"function\",\n function: {\n name: part.name,\n arguments: ProviderShared.encodeJson(part.input),\n },\n})\n\nconst lowerMedia = Effect.fn(\"OpenAIChat.lowerMedia\")(function* (part: MediaPart) {\n const media = yield* ProviderShared.validateMedia(\"OpenAI Chat\", part, IMAGE_MIMES)\n return { type: \"image_url\" as const, image_url: { url: media.dataUrl } }\n})\n\nconst openAICompatibleReasoningContent = (native: unknown) =>\n isRecord(native) && typeof native.reasoning_content === \"string\" ? native.reasoning_content : undefined\n\nconst reasoningField = (part: ReasoningPart) => {\n const field = part.providerMetadata?.openai?.reasoningField\n return typeof field === \"string\" ? field : undefined\n}\n\nconst reasoningDetails = (parts: ReadonlyArray<ReasoningPart>, native: unknown) => {\n const observed = parts.flatMap((part) => {\n const details = part.providerMetadata?.openai?.reasoningDetails\n return Array.isArray(details) ? details : []\n })\n if (parts.some((part) => Array.isArray(part.providerMetadata?.openai?.reasoningDetails))) return observed\n if (isRecord(native) && Array.isArray(native.reasoning_details)) return native.reasoning_details\n}\n\nconst lowerUserMessage = Effect.fn(\"OpenAIChat.lowerUserMessage\")(function* (message: OpenAIChatRequestMessage) {\n const content: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"text\", text: part.text })\n continue\n }\n if (part.type === \"media\") {\n content.push(yield* lowerMedia(part))\n continue\n }\n return yield* ProviderShared.unsupportedContent(\"OpenAI Chat\", \"user\", [\"text\", \"media\"])\n }\n if (content.every((part) => part.type === \"text\"))\n return { role: \"user\" as const, content: content.map((part) => part.text).join(\"\") }\n return { role: \"user\" as const, content }\n})\n\nconst lowerAssistantMessage = Effect.fn(\"OpenAIChat.lowerAssistantMessage\")(function* (\n message: OpenAIChatRequestMessage,\n configuredField?: string,\n) {\n const content: TextPart[] = []\n const reasoning: ReasoningPart[] = []\n const toolCalls: OpenAIChatAssistantToolCall[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"text\", \"reasoning\", \"tool-call\"]))\n return yield* ProviderShared.unsupportedContent(\"OpenAI Chat\", \"assistant\", [\"text\", \"reasoning\", \"tool-call\"])\n if (part.type === \"text\") {\n content.push(part)\n continue\n }\n if (part.type === \"reasoning\") {\n reasoning.push(part)\n continue\n }\n if (part.type === \"tool-call\") {\n toolCalls.push(lowerToolCall(part))\n continue\n }\n }\n const text = reasoning.map((part) => part.text).join(\"\")\n const details = reasoningDetails(reasoning, message.native?.openaiCompatible)\n const observedField = reasoning.map(reasoningField).find((value) => value !== undefined)\n const nativeReasoning = openAICompatibleReasoningContent(message.native?.openaiCompatible)\n const fullyStructured = reasoning.every((part) => Array.isArray(part.providerMetadata?.openai?.reasoningDetails))\n const field = (() => {\n if (configuredField !== undefined) return configuredField\n if (reasoning.length === 0) return undefined\n if (observedField !== undefined) return observedField\n if (nativeReasoning !== undefined) return \"reasoning_content\"\n if (!fullyStructured) return \"reasoning_content\"\n })()\n const reasoningText = (() => {\n if (configuredField !== undefined) return reasoning.length === 0 ? (nativeReasoning ?? \"\") : text\n if (reasoning.length === 0) return nativeReasoning\n return text\n })()\n const result = {\n role: \"assistant\" as const,\n content: content.length === 0 ? null : ProviderShared.joinText(content),\n tool_calls: toolCalls.length === 0 ? undefined : toolCalls,\n reasoning_details: details,\n }\n if (field === undefined || reasoningText === undefined) return result\n return { ...result, [field]: reasoningText }\n})\n\nconst lowerToolMessages = Effect.fn(\"OpenAIChat.lowerToolMessages\")(function* (message: OpenAIChatRequestMessage) {\n const messages: OpenAIChatMessage[] = []\n const images: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"tool-result\"]))\n return yield* ProviderShared.unsupportedContent(\"OpenAI Chat\", \"tool\", [\"tool-result\"])\n if (part.result.type !== \"content\") {\n messages.push({ role: \"tool\", tool_call_id: part.id, content: ProviderShared.toolResultText(part) })\n continue\n }\n const content: ReadonlyArray<ToolContent> = part.result.value\n const text = content.filter((item) => item.type === \"text\").map((item) => item.text)\n messages.push({ role: \"tool\", tool_call_id: part.id, content: text.join(\"\\n\") })\n const files = content.filter((item) => item.type === \"file\")\n images.push(\n ...(yield* Effect.forEach(files, (item) =>\n lowerMedia({ type: \"media\", mediaType: item.mime, data: item.uri, filename: item.name }),\n )),\n )\n }\n return { messages, images }\n})\n\nconst lowerMessage = Effect.fn(\"OpenAIChat.lowerMessage\")(function* (\n message: OpenAIChatRequestMessage,\n reasoningField?: string,\n) {\n if (message.role === \"user\") return [yield* lowerUserMessage(message)]\n if (message.role === \"assistant\") return [yield* lowerAssistantMessage(message, reasoningField)]\n return (yield* lowerToolMessages(message)).messages\n})\n\nconst lowerMessages = Effect.fn(\"OpenAIChat.lowerMessages\")(function* (request: LLMRequest) {\n const system: OpenAIChatMessage[] =\n request.system.length === 0 ? [] : [{ role: \"system\", content: ProviderShared.joinText(request.system) }]\n const messages = [...system]\n const pendingImages: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []\n const flushImages = () => {\n if (pendingImages.length === 0) return\n messages.push({ role: \"user\", content: pendingImages.splice(0) })\n }\n for (const message of request.messages) {\n if (message.role === \"system\") {\n const part = yield* ProviderShared.wrappedSystemUpdate(\"OpenAI Chat\", message)\n if (pendingImages.length > 0) {\n messages.push({ role: \"user\", content: [...pendingImages.splice(0), { type: \"text\", text: part.text }] })\n continue\n }\n const previous = messages.at(-1)\n if (previous?.role === \"user\" && typeof previous.content === \"string\")\n messages[messages.length - 1] = { role: \"user\", content: `${previous.content}\\n${part.text}` }\n else if (previous?.role === \"user\" && Array.isArray(previous.content))\n messages[messages.length - 1] = {\n role: \"user\",\n content: [...previous.content, { type: \"text\", text: part.text }],\n }\n else messages.push({ role: \"user\", content: part.text })\n continue\n }\n if (message.role === \"tool\") {\n const lowered = yield* lowerToolMessages(message)\n messages.push(...lowered.messages)\n pendingImages.push(...lowered.images)\n continue\n }\n flushImages()\n messages.push(...(yield* lowerMessage(message, request.model.compatibility?.reasoningField)))\n }\n flushImages()\n return messages\n})\n\nconst lowerOptions = Effect.fn(\"OpenAIChat.lowerOptions\")(function* (request: LLMRequest) {\n const store = OpenAIOptions.store(request)\n const reasoningEffort = OpenAIOptions.reasoningEffort(request)\n return {\n ...(store !== undefined ? { store } : {}),\n ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),\n }\n})\n\nconst fromRequest = Effect.fn(\"OpenAIChat.fromRequest\")(function* (request: LLMRequest) {\n // `fromRequest` returns the provider body only. Endpoint, auth, framing,\n // validation, and HTTP execution are composed by `Route.make`.\n const reasoningField = request.model.compatibility?.reasoningField\n if (reasoningField && RESERVED_REASONING_FIELDS.has(reasoningField))\n return yield* ProviderShared.invalidRequest(\n `OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`,\n )\n const generation = request.generation\n const toolSchemaCompatibility = request.model.compatibility?.toolSchema\n return {\n model: request.model.id,\n messages: yield* lowerMessages(request),\n tools:\n request.tools.length === 0\n ? undefined\n : request.tools.map((tool) =>\n lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),\n ),\n tool_choice: request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,\n stream: true as const,\n stream_options: { include_usage: true },\n max_tokens: generation?.maxTokens,\n temperature: generation?.temperature,\n top_p: generation?.topP,\n frequency_penalty: generation?.frequencyPenalty,\n presence_penalty: generation?.presencePenalty,\n seed: generation?.seed,\n stop: generation?.stop,\n ...(yield* lowerOptions(request)),\n }\n})\n\n// =============================================================================\n// Stream Parsing\n// =============================================================================\n// Streaming parsers are small state machines: every event returns a new state\n// plus the common `LLMEvent`s produced by that event. Tool calls are accumulated\n// because OpenAI streams JSON arguments across multiple deltas.\nconst mapFinishReason = (reason: string | null | undefined): FinishReason => {\n if (reason === \"stop\") return \"stop\"\n if (reason === \"length\") return \"length\"\n if (reason === \"content_filter\") return \"content-filter\"\n if (reason === \"function_call\" || reason === \"tool_calls\") return \"tool-calls\"\n return \"unknown\"\n}\n\n// OpenAI Chat reports `prompt_tokens` (inclusive total) with a\n// `cached_tokens` subset, and `completion_tokens` (inclusive total) with\n// a `reasoning_tokens` subset. We pass the inclusive totals through and\n// derive the non-cached breakdown so the `LLM.Usage` contract is\n// satisfied on both sides.\nconst mapUsage = (usage: OpenAIChatEvent[\"usage\"]): Usage | undefined => {\n if (!usage) return undefined\n const cached = usage.prompt_tokens_details?.cached_tokens\n const reasoning = usage.completion_tokens_details?.reasoning_tokens\n const nonCached = ProviderShared.subtractTokens(usage.prompt_tokens, cached)\n return new Usage({\n inputTokens: usage.prompt_tokens,\n outputTokens: usage.completion_tokens,\n nonCachedInputTokens: nonCached,\n cacheReadInputTokens: cached,\n reasoningTokens: reasoning,\n totalTokens: ProviderShared.totalTokens(usage.prompt_tokens, usage.completion_tokens, usage.total_tokens),\n providerMetadata: { openai: usage },\n })\n}\n\nconst reasoningDelta = (\n delta: Schema.Schema.Type<typeof OpenAIChatDelta> | null | undefined,\n configuredField?: string,\n) => {\n if (!delta) return undefined\n const fields = new Set([configuredField, \"reasoning_content\", \"reasoning\", \"reasoning_text\"])\n for (const field of fields) {\n if (field === undefined) continue\n const text = delta[field]\n if (typeof text === \"string\" && text.length > 0) return { field, text }\n }\n return undefined\n}\n\nconst detailText = (details: ReadonlyArray<unknown>) => {\n const text = details.flatMap((detail) => {\n if (!isRecord(detail)) return []\n if (detail.type === \"reasoning.text\" && typeof detail.text === \"string\" && detail.text) return [detail.text]\n if (detail.type === \"reasoning.summary\" && typeof detail.summary === \"string\" && detail.summary)\n return [detail.summary]\n return []\n })\n if (text.length > 0) return text.join(\"\")\n}\n\nconst appendReasoningDetails = (result: Array<unknown>, details: ReadonlyArray<unknown>) => {\n for (const detail of details) {\n const previous = result.at(-1)\n if (\n !isRecord(previous) ||\n previous.type !== \"reasoning.text\" ||\n !isRecord(detail) ||\n detail.type !== \"reasoning.text\" ||\n conflictingReasoningTextDetails(previous, detail)\n ) {\n result.push(detail)\n continue\n }\n result[result.length - 1] = {\n ...previous,\n ...Object.fromEntries(Object.entries(detail).filter((entry) => entry[1] !== undefined)),\n text: `${typeof previous.text === \"string\" ? previous.text : \"\"}${typeof detail.text === \"string\" ? detail.text : \"\"}`,\n signature: mergeDetailValue(previous.signature, detail.signature),\n format: mergeDetailValue(previous.format, detail.format),\n }\n }\n}\n\nconst mergeDetailValue = (previous: unknown, current: unknown) =>\n previous || current || (previous !== undefined ? previous : current)\n\nconst conflictingReasoningTextDetails = (previous: Record<string, unknown>, current: Record<string, unknown>) =>\n conflictingDetailValue(previous.id, current.id) ||\n conflictingDetailValue(previous.index, current.index) ||\n conflictingDetailValue(previous.format, current.format) ||\n (Boolean(previous.signature) && Boolean(current.signature) && previous.signature !== current.signature)\n\nconst conflictingDetailValue = (previous: unknown, current: unknown) =>\n previous !== undefined && previous !== null && current !== undefined && current !== null && previous !== current\n\nconst reasoningMetadata = (field: ParserState[\"reasoningField\"], details?: ReadonlyArray<unknown>) => ({\n openai: {\n ...(field ? { reasoningField: field } : {}),\n ...(details ? { reasoningDetails: details } : {}),\n },\n})\n\nconst step = (state: ParserState, event: OpenAIChatEvent) =>\n Effect.gen(function* () {\n const events: LLMEvent[] = []\n const usage = mapUsage(event.usage) ?? state.usage\n const choice = event.choices[0]\n const finishReason = choice?.finish_reason ? mapFinishReason(choice.finish_reason) : state.finishReason\n const delta = choice?.delta\n const toolDeltas = delta?.tool_calls ?? []\n let tools = state.tools\n let pendingTools = state.pendingTools\n\n let lifecycle = state.lifecycle\n\n const reasoning = reasoningDelta(delta, state.reasoningField)\n const reasoningField = state.reasoningField ?? (!state.lifecycle.text.has(\"text-0\") ? reasoning?.field : undefined)\n const detailDelta = Array.isArray(delta?.reasoning_details) ? delta.reasoning_details : undefined\n if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)\n const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined\n const deltaMetadata = reasoningMetadata(reasoningField)\n const text = detailDelta?.length ? (detailText(detailDelta) ?? reasoning?.text) : reasoning?.text\n if (!state.lifecycle.text.has(\"text-0\") && text !== undefined)\n lifecycle = Lifecycle.reasoningDelta(lifecycle, events, \"reasoning-0\", text, deltaMetadata)\n else if (\n reasoningDetailsObserved &&\n !lifecycle.reasoning.has(\"reasoning-0\") &&\n (Boolean(delta?.content) || toolDeltas.length > 0)\n )\n lifecycle = Lifecycle.reasoningStart(lifecycle, events, \"reasoning-0\", deltaMetadata)\n const reasoningEmitted = state.reasoningEmitted || lifecycle.reasoning.has(\"reasoning-0\")\n\n if (delta?.content) {\n lifecycle = Lifecycle.reasoningEnd(\n lifecycle,\n events,\n \"reasoning-0\",\n reasoningMetadata(reasoningField, reasoningDetailsObserved ? state.reasoningDetails : undefined),\n )\n lifecycle = Lifecycle.textDelta(lifecycle, events, \"text-0\", delta.content)\n }\n\n for (const tool of toolDeltas) {\n const current = tools[tool.index]\n const pending = pendingTools[tool.index]\n const id = current?.id ?? pending?.id ?? (tool.id || undefined)\n const name = current?.name ?? pending?.name ?? (tool.function?.name || undefined)\n const text = `${pending?.input ?? \"\"}${tool.function?.arguments ?? \"\"}`\n if (!current && (!id || !name)) {\n pendingTools = { ...pendingTools, [tool.index]: { id: id || undefined, name: name || undefined, input: text } }\n continue\n }\n if (pending) {\n pendingTools = { ...pendingTools }\n delete pendingTools[tool.index]\n }\n const result = ToolStream.appendOrStart(\n ADAPTER,\n tools,\n tool.index,\n { id: id || undefined, name: name || undefined, text },\n \"OpenAI Chat tool call delta is missing id or name\",\n )\n if (ToolStream.isError(result)) return yield* result\n tools = result.tools\n if (result.events.length) lifecycle = Lifecycle.stepStart(lifecycle, events)\n events.push(...result.events)\n }\n\n if (finishReason !== undefined && state.finishReason === undefined && Object.keys(pendingTools).length > 0)\n return yield* ProviderShared.eventError(ADAPTER, \"OpenAI Chat tool call delta is missing id or name\")\n\n // Finalize accumulated tool inputs eagerly when finish_reason arrives so\n // valid calls and malformed local calls settle independently.\n const finished =\n finishReason !== undefined && state.finishReason === undefined && Object.keys(tools).length > 0\n ? yield* ToolStream.finishAll(ADAPTER, tools)\n : undefined\n\n return [\n {\n tools: finished?.tools ?? tools,\n pendingTools,\n toolCallEvents: finished?.events ?? state.toolCallEvents,\n usage,\n finishReason,\n lifecycle,\n reasoningField,\n reasoningDetails: state.reasoningDetails,\n reasoningDetailsObserved,\n reasoningEmitted,\n },\n events,\n ] as const\n })\n\nconst finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {\n const events: LLMEvent[] = []\n const hasToolCalls = state.toolCallEvents.length > 0\n const reason = state.finishReason === \"stop\" && hasToolCalls ? \"tool-calls\" : state.finishReason\n const metadata = reasoningMetadata(\n state.reasoningField,\n state.reasoningDetailsObserved ? state.reasoningDetails : undefined,\n )\n const started =\n state.reasoningDetailsObserved && !state.reasoningEmitted\n ? Lifecycle.reasoningStart(state.lifecycle, events, \"reasoning-0\", reasoningMetadata(state.reasoningField))\n : state.lifecycle\n const ended = Lifecycle.reasoningEnd(started, events, \"reasoning-0\", metadata)\n const lifecycle = state.toolCallEvents.length ? Lifecycle.stepStart(ended, events) : ended\n events.push(...state.toolCallEvents)\n if (reason) Lifecycle.finish(lifecycle, events, { reason, usage: state.usage })\n return events\n}\n\n// =============================================================================\n// Protocol And OpenAI Route\n// =============================================================================\n/**\n * The OpenAI Chat protocol — request body construction, body schema, and the\n * streaming-event state machine. Reused by every route that speaks OpenAI Chat\n * over HTTP+SSE: native OpenAI, DeepSeek, TogetherAI, Cerebras, Baseten,\n * Fireworks, DeepInfra, and (once added) Azure OpenAI Chat.\n */\nexport const protocol = Protocol.make({\n id: ADAPTER,\n body: {\n schema: OpenAIChatBody,\n from: fromRequest,\n },\n stream: {\n event: Protocol.jsonEvent(OpenAIChatEvent),\n initial: (request) => ({\n tools: ToolStream.empty<number>(),\n pendingTools: {},\n toolCallEvents: [],\n lifecycle: Lifecycle.initial(),\n reasoningField: request.model.compatibility?.reasoningField,\n reasoningDetails: [],\n reasoningDetailsObserved: false,\n reasoningEmitted: false,\n }),\n step,\n onHalt: finishEvents,\n },\n})\n\nexport const httpTransport = HttpTransport.sseJson.with<OpenAIChatBody>()\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: \"openai\",\n providerMetadataKey: \"openai\",\n protocol,\n endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),\n auth: Auth.none,\n transport: httpTransport,\n})\n\nexport * as OpenAIChat from \"./openai-chat\"\n" | ||
| ], | ||
| "mappings": ";6tBAIO,SAAM,QAAyB,OAKzB,EAA4B,CACvC,2BACA,0BACA,iCACA,gCACA,wCACA,gCACA,8BACA,8BACF,EAEa,EAAqB,CAAC,OAAQ,UAAW,OAAQ,UAAU,EAGlE,GAAiB,IAAI,IAAY,CAAC,MAAO,SAAU,MAAM,CAAC,EAC1D,GAAc,IAAI,IA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U,OAAO,EAAW,EAAQ,CAAE,SAAQ,MAAO,EAAM,KAAM,CAAC,EAC9E,OAAO,GAYI,GAAW,EAAS,KAAK,CACpC,GAAI,EACJ,KAAM,CACJ,OAAQ,GACR,KAAM,EACR,EACA,OAAQ,CACN,MAAO,EAAS,UAAU,EAAe,EACzC,QAAS,CAAC,KAAa,CACrB,MAAO,EAAW,MAAc,EAChC,aAAc,CAAC,EACf,eAAgB,CAAC,EACjB,UAAW,EAAU,QAAQ,EAC7B,eAAgB,EAAQ,MAAM,eAAe,eAC7C,iBAAkB,CAAC,EACnB,yBAA0B,GAC1B,iBAAkB,EACpB,GACA,QACA,OAAQ,EACV,CACF,CAAC,EAEY,GAAgB,EAAc,QAAQ,KAAqB,EAE3D,GAAQ,EAAM,KAAK,CAC9B,GAAI,EACJ,SAAU,SACV,oBAAqB,SACrB,YACA,SAAU,EAAS,KAAK,GAAM,CAAE,QAAS,EAAiB,CAAC,EAC3D,KAAM,EAAK,KACX,UAAW,EACb,CAAC", | ||
| "debugId": "FD8EBE5B1E7A823F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "D88D496B8E7D934864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/aws4fetch@1.0.20/node_modules/aws4fetch/dist/aws4fetch.esm.mjs"], | ||
| "sourcesContent": [ | ||
| "/**\n * @license MIT <https://opensource.org/licenses/MIT>\n * @copyright Michael Hart 2024\n */\nconst encoder = new TextEncoder();\nconst HOST_SERVICES = {\n appstream2: 'appstream',\n cloudhsmv2: 'cloudhsm',\n email: 'ses',\n marketplace: 'aws-marketplace',\n mobile: 'AWSMobileHubService',\n pinpoint: 'mobiletargeting',\n queue: 'sqs',\n 'git-codecommit': 'codecommit',\n 'mturk-requester-sandbox': 'mturk-requester',\n 'personalize-runtime': 'personalize',\n};\nconst UNSIGNABLE_HEADERS = new Set([\n 'authorization',\n 'content-type',\n 'content-length',\n 'user-agent',\n 'presigned-expires',\n 'expect',\n 'x-amzn-trace-id',\n 'range',\n 'connection',\n]);\nclass AwsClient {\n constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n this.service = service;\n this.region = region;\n this.cache = cache || new Map();\n this.retries = retries != null ? retries : 10;\n this.initRetryMs = initRetryMs || 50;\n }\n async sign(input, init) {\n if (input instanceof Request) {\n const { method, url, headers, body } = input;\n init = Object.assign({ method, url, headers }, init);\n if (init.body == null && headers.has('Content-Type')) {\n init.body = body != null && headers.has('X-Amz-Content-Sha256') ? body : await input.clone().arrayBuffer();\n }\n input = url;\n }\n const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));\n const signed = Object.assign({}, init, await signer.sign());\n delete signed.aws;\n try {\n return new Request(signed.url.toString(), signed)\n } catch (e) {\n if (e instanceof TypeError) {\n return new Request(signed.url.toString(), Object.assign({ duplex: 'half' }, signed))\n }\n throw e\n }\n }\n async fetch(input, init) {\n for (let i = 0; i <= this.retries; i++) {\n const fetched = fetch(await this.sign(input, init));\n if (i === this.retries) {\n return fetched\n }\n const res = await fetched;\n if (res.status < 500 && res.status !== 429) {\n return res\n }\n await new Promise(resolve => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));\n }\n throw new Error('An unknown error occurred, ensure retries is not negative')\n }\n}\nclass AwsV4Signer {\n constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {\n if (url == null) throw new TypeError('url is a required option')\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.method = method || (body ? 'POST' : 'GET');\n this.url = new URL(url);\n this.headers = new Headers(headers || {});\n this.body = body;\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n let guessedService, guessedRegion;\n if (!service || !region) {\n[guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);\n }\n this.service = service || guessedService || '';\n this.region = region || guessedRegion || 'us-east-1';\n this.cache = cache || new Map();\n this.datetime = datetime || new Date().toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n this.signQuery = signQuery;\n this.appendSessionToken = appendSessionToken || this.service === 'iotdevicegateway';\n this.headers.delete('Host');\n if (this.service === 's3' && !this.signQuery && !this.headers.has('X-Amz-Content-Sha256')) {\n this.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD');\n }\n const params = this.signQuery ? this.url.searchParams : this.headers;\n params.set('X-Amz-Date', this.datetime);\n if (this.sessionToken && !this.appendSessionToken) {\n params.set('X-Amz-Security-Token', this.sessionToken);\n }\n this.signableHeaders = ['host', ...this.headers.keys()]\n .filter(header => allHeaders || !UNSIGNABLE_HEADERS.has(header))\n .sort();\n this.signedHeaders = this.signableHeaders.join(';');\n this.canonicalHeaders = this.signableHeaders\n .map(header => header + ':' + (header === 'host' ? this.url.host : (this.headers.get(header) || '').replace(/\\s+/g, ' ')))\n .join('\\n');\n this.credentialString = [this.datetime.slice(0, 8), this.region, this.service, 'aws4_request'].join('/');\n if (this.signQuery) {\n if (this.service === 's3' && !params.has('X-Amz-Expires')) {\n params.set('X-Amz-Expires', '86400');\n }\n params.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256');\n params.set('X-Amz-Credential', this.accessKeyId + '/' + this.credentialString);\n params.set('X-Amz-SignedHeaders', this.signedHeaders);\n }\n if (this.service === 's3') {\n try {\n this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\\+/g, ' '));\n } catch (e) {\n this.encodedPath = this.url.pathname;\n }\n } else {\n this.encodedPath = this.url.pathname.replace(/\\/+/g, '/');\n }\n if (!singleEncode) {\n this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, '/');\n }\n this.encodedPath = encodeRfc3986(this.encodedPath);\n const seenKeys = new Set();\n this.encodedSearch = [...this.url.searchParams]\n .filter(([k]) => {\n if (!k) return false\n if (this.service === 's3') {\n if (seenKeys.has(k)) return false\n seenKeys.add(k);\n }\n return true\n })\n .map(pair => pair.map(p => encodeRfc3986(encodeURIComponent(p))))\n .sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0)\n .map(pair => pair.join('='))\n .join('&');\n }\n async sign() {\n if (this.signQuery) {\n this.url.searchParams.set('X-Amz-Signature', await this.signature());\n if (this.sessionToken && this.appendSessionToken) {\n this.url.searchParams.set('X-Amz-Security-Token', this.sessionToken);\n }\n } else {\n this.headers.set('Authorization', await this.authHeader());\n }\n return {\n method: this.method,\n url: this.url,\n headers: this.headers,\n body: this.body,\n }\n }\n async authHeader() {\n return [\n 'AWS4-HMAC-SHA256 Credential=' + this.accessKeyId + '/' + this.credentialString,\n 'SignedHeaders=' + this.signedHeaders,\n 'Signature=' + (await this.signature()),\n ].join(', ')\n }\n async signature() {\n const date = this.datetime.slice(0, 8);\n const cacheKey = [this.secretAccessKey, date, this.region, this.service].join();\n let kCredentials = this.cache.get(cacheKey);\n if (!kCredentials) {\n const kDate = await hmac('AWS4' + this.secretAccessKey, date);\n const kRegion = await hmac(kDate, this.region);\n const kService = await hmac(kRegion, this.service);\n kCredentials = await hmac(kService, 'aws4_request');\n this.cache.set(cacheKey, kCredentials);\n }\n return buf2hex(await hmac(kCredentials, await this.stringToSign()))\n }\n async stringToSign() {\n return [\n 'AWS4-HMAC-SHA256',\n this.datetime,\n this.credentialString,\n buf2hex(await hash(await this.canonicalString())),\n ].join('\\n')\n }\n async canonicalString() {\n return [\n this.method.toUpperCase(),\n this.encodedPath,\n this.encodedSearch,\n this.canonicalHeaders + '\\n',\n this.signedHeaders,\n await this.hexBodyHash(),\n ].join('\\n')\n }\n async hexBodyHash() {\n let hashHeader = this.headers.get('X-Amz-Content-Sha256') || (this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null);\n if (hashHeader == null) {\n if (this.body && typeof this.body !== 'string' && !('byteLength' in this.body)) {\n throw new Error('body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header')\n }\n hashHeader = buf2hex(await hash(this.body || ''));\n }\n return hashHeader\n }\n}\nasync function hmac(key, string) {\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n typeof key === 'string' ? encoder.encode(key) : key,\n { name: 'HMAC', hash: { name: 'SHA-256' } },\n false,\n ['sign'],\n );\n return crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string))\n}\nasync function hash(content) {\n return crypto.subtle.digest('SHA-256', typeof content === 'string' ? encoder.encode(content) : content)\n}\nconst HEX_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nfunction buf2hex(arrayBuffer) {\n const buffer = new Uint8Array(arrayBuffer);\n let out = '';\n for (let idx = 0; idx < buffer.length; idx++) {\n const n = buffer[idx];\n out += HEX_CHARS[(n >>> 4) & 0xF];\n out += HEX_CHARS[n & 0xF];\n }\n return out\n}\nfunction encodeRfc3986(urlEncodedStr) {\n return urlEncodedStr.replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n}\nfunction guessServiceRegion(url, headers) {\n const { hostname, pathname } = url;\n if (hostname.endsWith('.on.aws')) {\n const match = hostname.match(/^[^.]{1,63}\\.lambda-url\\.([^.]{1,63})\\.on\\.aws$/);\n return match != null ? ['lambda', match[1] || ''] : ['', '']\n }\n if (hostname.endsWith('.r2.cloudflarestorage.com')) {\n return ['s3', 'auto']\n }\n if (hostname.endsWith('.backblazeb2.com')) {\n const match = hostname.match(/^(?:[^.]{1,63}\\.)?s3\\.([^.]{1,63})\\.backblazeb2\\.com$/);\n return match != null ? ['s3', match[1] || ''] : ['', '']\n }\n const match = hostname.replace('dualstack.', '').match(/([^.]{1,63})\\.(?:([^.]{0,63})\\.)?amazonaws\\.com(?:\\.cn)?$/);\n let service = (match && match[1]) || '';\n let region = match && match[2];\n if (region === 'us-gov') {\n region = 'us-gov-west-1';\n } else if (region === 's3' || region === 's3-accelerate') {\n region = 'us-east-1';\n service = 's3';\n } else if (service === 'iot') {\n if (hostname.startsWith('iot.')) {\n service = 'execute-api';\n } else if (hostname.startsWith('data.jobs.iot.')) {\n service = 'iot-jobs-data';\n } else {\n service = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata';\n }\n } else if (service === 'autoscaling') {\n const targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0];\n if (targetPrefix === 'AnyScaleFrontendService') {\n service = 'application-autoscaling';\n } else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') {\n service = 'autoscaling-plans';\n }\n } else if (region == null && service.startsWith('s3-')) {\n region = service.slice(3).replace(/^fips-|^external-1/, '');\n service = 's3';\n } else if (service.endsWith('-fips')) {\n service = service.slice(0, -5);\n } else if (region && /-\\d$/.test(service) && !/-\\d$/.test(region)) {\n[service, region] = [region, service];\n }\n return [HOST_SERVICES[service] || service, region || '']\n}\n\nexport { AwsClient, AwsV4Signer };\n" | ||
| ], | ||
| "mappings": ";AAIA,IAAM,EAAU,IAAI,YACd,EAAgB,CACpB,WAAY,YACZ,WAAY,WACZ,MAAO,MACP,YAAa,kBACb,OAAQ,sBACR,SAAU,kBACV,MAAO,MACP,iBAAkB,aAClB,0BAA2B,kBAC3B,sBAAuB,aACzB,EACM,EAAqB,IAAI,IAAI,CACjC,gBACA,eACA,iBACA,aACA,oBACA,SACA,kBACA,QACA,YACF,CAAC,EAkDD,MAAM,CAAY,CAChB,WAAW,EAAG,SAAQ,MAAK,UAAS,OAAM,c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S,OAAO,EACjC,EAAU,EAAQ,MAAM,EAAG,EAAE,EACxB,QAAI,GAAU,OAAO,KAAK,CAAO,GAAK,CAAC,OAAO,KAAK,CAAM,EAClE,CAAC,EAAS,CAAM,EAAI,CAAC,EAAQ,CAAO,EAElC,MAAO,CAAC,EAAc,IAAY,EAAS,GAAU,EAAE", | ||
| "debugId": "2383788C954031E964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@smithy+node-http-handler@4.9.7/node_modules/@smithy/node-http-handler/dist-cjs/index.js"], | ||
| "sourcesContent": [ | ||
| "const { buildQueryString, HttpResponse } = require(\"@smithy/core/protocols\");\nconst node_https = require(\"node:https\");\nconst { Readable } = require(\"node:stream\");\nconst http2 = require(\"node:http2\");\nconst { streamCollector } = require(\"@smithy/core/serde\");\nexports.streamCollector = streamCollector;\n\nfunction buildAbortError(abortSignal) {\n const reason = abortSignal && typeof abortSignal === \"object\" && \"reason\" in abortSignal\n ? abortSignal.reason\n : undefined;\n if (reason) {\n if (reason instanceof Error) {\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n abortError.cause = reason;\n return abortError;\n }\n const abortError = new Error(String(reason));\n abortError.name = \"AbortError\";\n return abortError;\n }\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n return abortError;\n}\n\nconst NODEJS_TIMEOUT_ERROR_CODES = [\"ECONNRESET\", \"EPIPE\", \"ETIMEDOUT\"];\n\nconst getTransformedHeaders = (headers) => {\n const transformedHeaders = {};\n for (const name in headers) {\n const headerValues = headers[name];\n transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(\",\") : headerValues;\n }\n return transformedHeaders;\n};\n\nconst timing = {\n setTimeout: (cb, ms) => setTimeout(cb, ms),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n};\n\nconst DEFER_EVENT_LISTENER_TIME$2 = 1000;\nconst setConnectionTimeout = (request, reject, timeoutInMs = 0) => {\n if (!timeoutInMs) {\n return -1;\n }\n const registerTimeout = (offset) => {\n const timeoutId = timing.setTimeout(() => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), {\n name: \"TimeoutError\",\n }));\n }, timeoutInMs - offset);\n const doWithSocket = (socket) => {\n if (socket?.connecting) {\n socket.on(\"connect\", () => {\n timing.clearTimeout(timeoutId);\n });\n }\n else {\n timing.clearTimeout(timeoutId);\n }\n };\n if (request.socket) {\n doWithSocket(request.socket);\n }\n else {\n request.on(\"socket\", doWithSocket);\n }\n };\n if (timeoutInMs < 2000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2);\n};\n\nconst setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => {\n if (timeoutInMs) {\n return timing.setTimeout(() => {\n let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? \"ERROR\" : \"WARN\"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;\n if (throwOnRequestTimeout) {\n const error = Object.assign(new Error(msg), {\n name: \"TimeoutError\",\n code: \"ETIMEDOUT\",\n });\n req.destroy(error);\n reject(error);\n }\n else {\n msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;\n logger?.warn?.(msg);\n }\n }, timeoutInMs);\n }\n return -1;\n};\n\nconst DEFER_EVENT_LISTENER_TIME$1 = 3000;\nconst setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => {\n if (keepAlive !== true) {\n return -1;\n }\n const registerListener = () => {\n if (request.socket) {\n request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n }\n else {\n request.on(\"socket\", (socket) => {\n socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n });\n }\n };\n if (deferTimeMs === 0) {\n registerListener();\n return 0;\n }\n return timing.setTimeout(registerListener, deferTimeMs);\n};\n\nconst DEFER_EVENT_LISTENER_TIME = 3000;\nconst setSocketTimeout = (request, reject, timeoutInMs = 0) => {\n const registerTimeout = (offset) => {\n const timeout = timeoutInMs - offset;\n const onTimeout = () => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: \"TimeoutError\" }));\n };\n if (request.socket) {\n request.socket.setTimeout(timeout, onTimeout);\n request.on(\"close\", () => request.socket?.removeListener(\"timeout\", onTimeout));\n }\n else {\n request.setTimeout(timeout, onTimeout);\n }\n };\n if (0 < timeoutInMs && timeoutInMs < 6000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);\n};\n\nconst MIN_WAIT_TIME = 6_000;\nasync function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {\n const headers = request.headers;\n const expect = headers ? headers.Expect || headers.expect : undefined;\n let timeoutId = -1;\n let sendBody = true;\n if (!externalAgent && expect === \"100-continue\") {\n sendBody = await Promise.race([\n new Promise((resolve) => {\n timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));\n }),\n new Promise((resolve) => {\n httpRequest.on(\"continue\", () => {\n timing.clearTimeout(timeoutId);\n resolve(true);\n });\n httpRequest.on(\"response\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n httpRequest.on(\"error\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n }),\n ]);\n }\n if (sendBody) {\n writeBody(httpRequest, request.body);\n }\n}\nfunction writeBody(httpRequest, body) {\n if (body instanceof Readable) {\n body.pipe(httpRequest);\n return;\n }\n if (body) {\n const isBuffer = Buffer.isBuffer(body);\n const isString = typeof body === \"string\";\n if (isBuffer || isString) {\n if (isBuffer && body.byteLength === 0) {\n httpRequest.end();\n }\n else {\n httpRequest.end(body);\n }\n return;\n }\n const uint8 = body;\n if (typeof uint8 === \"object\" &&\n uint8.buffer &&\n typeof uint8.byteOffset === \"number\" &&\n typeof uint8.byteLength === \"number\") {\n httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));\n return;\n }\n httpRequest.end(Buffer.from(body));\n return;\n }\n httpRequest.end();\n}\n\nconst DEFAULT_REQUEST_TIMEOUT = 0;\nlet hAgent = undefined;\nlet hRequest = undefined;\nclass NodeHttpHandler {\n config;\n configProvider;\n socketWarningTimestamp = 0;\n externalAgent = false;\n metadata = { handlerProtocol: \"http/1.1\" };\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttpHandler(instanceOrOptions);\n }\n static checkSocketUsage(agent, socketWarningTimestamp, logger = console) {\n const { sockets, requests, maxSockets } = agent;\n if (typeof maxSockets !== \"number\" || maxSockets === Infinity) {\n return socketWarningTimestamp;\n }\n const interval = 15_000;\n if (Date.now() - interval < socketWarningTimestamp) {\n return socketWarningTimestamp;\n }\n if (sockets && requests) {\n for (const origin in sockets) {\n const socketsInUse = sockets[origin]?.length ?? 0;\n const requestsEnqueued = requests[origin]?.length ?? 0;\n if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {\n logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.\nSee https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html\nor increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);\n return Date.now();\n }\n }\n }\n return socketWarningTimestamp;\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((_options) => {\n resolve(this.resolveDefaultConfig(_options));\n })\n .catch(reject);\n }\n else {\n resolve(this.resolveDefaultConfig(options));\n }\n });\n }\n destroy() {\n this.config?.httpAgent?.destroy();\n this.config?.httpsAgent?.destroy();\n }\n async handle(request, { abortSignal, requestTimeout } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n }\n const config = this.config;\n const isSSL = request.protocol === \"https:\";\n if (!isSSL && !this.config.httpAgent) {\n this.config.httpAgent = await this.config.httpAgentProvider();\n }\n return new Promise((_resolve, _reject) => {\n let writeRequestBodyPromise = undefined;\n let socketWarningTimeoutId = -1;\n let connectionTimeoutId = -1;\n let requestTimeoutId = -1;\n let socketTimeoutId = -1;\n let keepAliveTimeoutId = -1;\n const clearTimeouts = () => {\n timing.clearTimeout(socketWarningTimeoutId);\n timing.clearTimeout(connectionTimeoutId);\n timing.clearTimeout(requestTimeoutId);\n timing.clearTimeout(socketTimeoutId);\n timing.clearTimeout(keepAliveTimeoutId);\n };\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n clearTimeouts();\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n clearTimeouts();\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n return;\n }\n const headers = request.headers;\n const expectContinue = headers ? (headers.Expect ?? headers.expect) === \"100-continue\" : false;\n let agent = isSSL ? config.httpsAgent : config.httpAgent;\n if (expectContinue && !this.externalAgent) {\n agent = new (isSSL ? node_https.Agent : hAgent)({\n keepAlive: false,\n maxSockets: Infinity,\n });\n }\n socketWarningTimeoutId = timing.setTimeout(() => {\n this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config.logger);\n }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2000) + (config.connectionTimeout ?? 1000));\n const queryString = request.query ? buildQueryString(request.query) : \"\";\n let auth = undefined;\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}`;\n }\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n let hostname = request.hostname ?? \"\";\n if (hostname[0] === \"[\" && hostname.endsWith(\"]\")) {\n hostname = request.hostname.slice(1, -1);\n }\n else {\n hostname = request.hostname;\n }\n const nodeHttpsOptions = {\n headers: request.headers,\n host: hostname,\n method: request.method,\n path,\n port: request.port,\n agent,\n auth,\n };\n const requestFunc = isSSL ? node_https.request : hRequest;\n const req = requestFunc(nodeHttpsOptions, (res) => {\n const httpResponse = new HttpResponse({\n statusCode: res.statusCode || -1,\n reason: res.statusMessage,\n headers: getTransformedHeaders(res.headers),\n body: res,\n });\n resolve({ response: httpResponse });\n });\n req.on(\"error\", (err) => {\n if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {\n reject(Object.assign(err, { name: \"TimeoutError\" }));\n }\n else {\n reject(err);\n }\n });\n if (abortSignal) {\n const onAbort = () => {\n req.destroy();\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n req.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout;\n connectionTimeoutId = setConnectionTimeout(req, reject, config.connectionTimeout);\n requestTimeoutId = setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, config.logger ?? console);\n socketTimeoutId = setSocketTimeout(req, reject, config.socketTimeout);\n const httpAgent = nodeHttpsOptions.agent;\n if (typeof httpAgent === \"object\" && \"keepAlive\" in httpAgent) {\n keepAliveTimeoutId = setSocketKeepAlive(req, {\n keepAlive: httpAgent.keepAlive,\n keepAliveMsecs: httpAgent.keepAliveMsecs,\n });\n }\n writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => {\n clearTimeouts();\n return _reject(e);\n });\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n resolveDefaultConfig(options) {\n const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger, } = options || {};\n const keepAlive = true;\n const maxSockets = 50;\n return {\n connectionTimeout,\n requestTimeout,\n socketTimeout,\n socketAcquisitionWarningTimeout,\n throwOnRequestTimeout,\n httpAgentProvider: async () => {\n const node_http = require('node:http');\n const { Agent, request } = node_http.default ?? node_http;\n hRequest = request;\n hAgent = Agent;\n if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpAgent;\n }\n return new hAgent({ keepAlive, maxSockets, ...httpAgent });\n },\n httpsAgent: (() => {\n if (httpsAgent instanceof node_https.Agent || typeof httpsAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpsAgent;\n }\n return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent });\n })(),\n logger,\n };\n }\n}\n\nconst ids = new Uint16Array(1);\nclass ClientHttp2SessionRef {\n id = ids[0]++;\n total = 0;\n max = 0;\n session;\n refs = 0;\n constructor(session) {\n session.unref();\n this.session = session;\n }\n retain() {\n if (this.session.destroyed) {\n throw new Error(\"@smithy/node-http-handler - cannot acquire reference to destroyed session.\");\n }\n this.refs += 1;\n this.total += 1;\n this.max = Math.max(this.refs, this.max);\n this.session.ref();\n }\n free() {\n if (this.session.destroyed) {\n return;\n }\n this.refs -= 1;\n if (this.refs === 0) {\n this.session.unref();\n }\n if (this.refs < 0) {\n throw new Error(\"@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.\");\n }\n }\n deref() {\n return this.session;\n }\n close() {\n if (!this.session.closed) {\n this.session.close();\n }\n }\n destroy() {\n this.refs = 0;\n if (!this.session.destroyed) {\n this.session.destroy();\n }\n }\n useCount() {\n return this.refs;\n }\n}\n\nclass NodeHttp2ConnectionPool {\n sessions = [];\n maxConcurrency = 0;\n constructor(sessions) {\n this.sessions = (sessions ?? []).map((session) => new ClientHttp2SessionRef(session));\n }\n poll() {\n let cleanup = false;\n for (const session of this.sessions) {\n if (session.deref().destroyed) {\n cleanup = true;\n continue;\n }\n if (!this.maxConcurrency || session.useCount() < this.maxConcurrency) {\n return session;\n }\n }\n if (cleanup) {\n for (const session of this.sessions) {\n if (session.deref().destroyed) {\n this.remove(session);\n }\n }\n }\n }\n offerLast(ref) {\n this.sessions.push(ref);\n }\n remove(ref) {\n const ix = this.sessions.indexOf(ref);\n if (ix > -1) {\n this.sessions.splice(ix, 1);\n }\n }\n [Symbol.iterator]() {\n return this.sessions[Symbol.iterator]();\n }\n setMaxConcurrency(maxConcurrency) {\n this.maxConcurrency = maxConcurrency;\n }\n destroy(ref) {\n this.remove(ref);\n ref.destroy();\n }\n}\n\nclass NodeHttp2ConnectionManager {\n config;\n connectOptions;\n connectionPools = new Map();\n constructor(config) {\n this.config = config;\n if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {\n throw new RangeError(\"maxConcurrency must be greater than zero.\");\n }\n }\n lease(requestContext, connectionConfiguration) {\n const url = this.getUrlString(requestContext);\n const pool = this.getPool(url);\n if (!this.config.disableConcurrency && !connectionConfiguration.isEventStream) {\n const available = pool.poll();\n if (available) {\n available.retain();\n return available;\n }\n }\n const ref = new ClientHttp2SessionRef(this.connect(url));\n const session = ref.deref();\n if (this.config.maxConcurrency) {\n session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => {\n if (err) {\n throw new Error(\"Fail to set maxConcurrentStreams to \" +\n this.config.maxConcurrency +\n \"when creating new session for \" +\n requestContext.destination.toString());\n }\n });\n }\n const graceful = () => {\n this.removeFromPoolAndClose(url, ref);\n };\n const ensureDestroyed = () => {\n this.removeFromPoolAndCheckedDestroy(url, ref);\n };\n session.on(\"goaway\", graceful);\n session.on(\"error\", ensureDestroyed);\n session.on(\"frameError\", ensureDestroyed);\n session.on(\"close\", ensureDestroyed);\n if (connectionConfiguration.requestTimeout) {\n session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed);\n }\n pool.offerLast(ref);\n ref.retain();\n return ref;\n }\n release(_requestContext, ref) {\n ref.free();\n }\n createIsolatedSession(requestContext, connectionConfiguration) {\n const url = this.getUrlString(requestContext);\n const ref = new ClientHttp2SessionRef(this.connect(url));\n const session = ref.deref();\n session.settings({ maxConcurrentStreams: 1 });\n const ensureDestroyed = () => {\n ref.destroy();\n };\n session.on(\"error\", ensureDestroyed);\n session.on(\"frameError\", ensureDestroyed);\n session.on(\"close\", ensureDestroyed);\n if (connectionConfiguration.requestTimeout) {\n session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed);\n }\n ref.retain();\n return ref;\n }\n destroy() {\n for (const [url, connectionPool] of this.connectionPools) {\n for (const session of [...connectionPool]) {\n session.destroy();\n }\n this.connectionPools.delete(url);\n }\n }\n setMaxConcurrentStreams(maxConcurrentStreams) {\n if (maxConcurrentStreams && maxConcurrentStreams <= 0) {\n throw new RangeError(\"maxConcurrentStreams must be greater than zero.\");\n }\n this.config.maxConcurrency = maxConcurrentStreams;\n for (const pool of this.connectionPools.values()) {\n pool.setMaxConcurrency(maxConcurrentStreams);\n }\n }\n setDisableConcurrentStreams(disableConcurrentStreams) {\n this.config.disableConcurrency = disableConcurrentStreams;\n }\n setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions) {\n this.connectOptions = nodeHttp2ConnectOptions;\n }\n debug() {\n const pools = {};\n for (const [url, pool] of this.connectionPools) {\n const sessions = [];\n for (const ref of pool) {\n sessions.push({\n id: ref.id,\n active: ref.useCount(),\n maxConcurrent: ref.max,\n totalRequests: ref.total,\n });\n }\n pools[url] = { sessions };\n }\n return pools;\n }\n removeFromPoolAndClose(authority, ref) {\n this.connectionPools.get(authority)?.remove(ref);\n ref.close();\n }\n removeFromPoolAndCheckedDestroy(authority, ref) {\n this.connectionPools.get(authority)?.remove(ref);\n ref.destroy();\n }\n getPool(url) {\n if (!this.connectionPools.has(url)) {\n const pool = new NodeHttp2ConnectionPool();\n if (this.config.maxConcurrency) {\n pool.setMaxConcurrency(this.config.maxConcurrency);\n }\n this.connectionPools.set(url, pool);\n }\n return this.connectionPools.get(url);\n }\n getUrlString(request) {\n return request.destination.toString();\n }\n connect(url) {\n return this.connectOptions === undefined ? http2.connect(url) : http2.connect(url, this.connectOptions);\n }\n}\n\nconst { constants } = http2;\nclass NodeHttp2Handler {\n config;\n configProvider;\n metadata = { handlerProtocol: \"h2\" };\n connectionManager = new NodeHttp2ConnectionManager({});\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttp2Handler(instanceOrOptions);\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((opts) => {\n resolve(opts || {});\n })\n .catch(reject);\n }\n else {\n resolve(options || {});\n }\n });\n }\n destroy() {\n this.connectionManager.destroy();\n }\n async handle(request, { abortSignal, requestTimeout, isEventStream } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n const { disableConcurrentStreams, maxConcurrentStreams, nodeHttp2ConnectOptions } = this.config;\n this.connectionManager.setDisableConcurrentStreams(disableConcurrentStreams ?? false);\n if (maxConcurrentStreams) {\n this.connectionManager.setMaxConcurrentStreams(maxConcurrentStreams);\n }\n if (nodeHttp2ConnectOptions) {\n this.connectionManager.setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions);\n }\n }\n const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config;\n const useIsolatedSession = disableConcurrentStreams || isEventStream;\n const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout;\n return new Promise((_resolve, _reject) => {\n let fulfilled = false;\n let writeRequestBodyPromise = undefined;\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n fulfilled = true;\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n return;\n }\n const { hostname, method, port, protocol, query } = request;\n let auth = \"\";\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}@`;\n }\n const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : \"\"}`;\n const requestContext = { destination: new URL(authority) };\n const connectConfig = {\n requestTimeout: this.config?.sessionTimeout,\n isEventStream,\n };\n const ref = useIsolatedSession\n ? this.connectionManager.createIsolatedSession(requestContext, connectConfig)\n : this.connectionManager.lease(requestContext, connectConfig);\n const session = ref.deref();\n const rejectWithDestroy = (err) => {\n if (useIsolatedSession) {\n ref.destroy();\n }\n fulfilled = true;\n reject(err);\n };\n const queryString = query ? buildQueryString(query) : \"\";\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n const clientHttp2Stream = session.request({\n ...request.headers,\n [constants.HTTP2_HEADER_PATH]: path,\n [constants.HTTP2_HEADER_METHOD]: method,\n });\n if (effectiveRequestTimeout) {\n clientHttp2Stream.setTimeout(effectiveRequestTimeout, () => {\n clientHttp2Stream.close();\n const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`);\n timeoutError.name = \"TimeoutError\";\n rejectWithDestroy(timeoutError);\n });\n }\n if (abortSignal) {\n const onAbort = () => {\n clientHttp2Stream.close();\n const abortError = buildAbortError(abortSignal);\n rejectWithDestroy(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n clientHttp2Stream.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n clientHttp2Stream.on(\"frameError\", (type, code, id) => {\n rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));\n });\n clientHttp2Stream.on(\"error\", rejectWithDestroy);\n clientHttp2Stream.on(\"aborted\", () => {\n rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${clientHttp2Stream.rstCode}.`));\n });\n clientHttp2Stream.on(\"response\", (headers) => {\n const httpResponse = new HttpResponse({\n statusCode: headers[\":status\"] ?? -1,\n headers: getTransformedHeaders(headers),\n body: clientHttp2Stream,\n });\n fulfilled = true;\n resolve({ response: httpResponse });\n if (useIsolatedSession) {\n session.close();\n }\n });\n clientHttp2Stream.on(\"close\", () => {\n if (useIsolatedSession) {\n ref.destroy();\n }\n else {\n this.connectionManager.release(requestContext, ref);\n }\n if (!fulfilled) {\n rejectWithDestroy(new Error(\"Unexpected error: http2 request did not get a response\"));\n }\n });\n writeRequestBodyPromise = writeRequestBody(clientHttp2Stream, request, effectiveRequestTimeout);\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n}\n\nexports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT;\nexports.NodeHttp2Handler = NodeHttp2Handler;\nexports.NodeHttpHandler = NodeHttpHandler;\n" | ||
| ], | ||
| "mappings": ";2KAAA,SAAQ,wBAAkB,qBACpB,cACE,yBACF,cACE,wBACA,mBAAkB,GAE1B,SAAS,CAAe,CAAC,EAAa,CAClC,IAAM,EAAS,GAAe,OAAO,IAAgB,UAAY,WAAY,EACvE,EAAY,OACZ,OACN,GAAI,EAAQ,CACR,GAAI,aAAkB,MAAO,CACzB,IAAM,EAAiB,MAAM,iBAAiB,EAG9C,OAFA,EAAW,KAAO,aAClB,EAAW,MAAQ,EACZ,EAEX,IAAM,EA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hC,GAAI,OAAO,EAAY,mBAAqB,WAAY,CACpD,IAAM,EAAS,EACf,EAAO,iBAAiB,QAAS,EAAS,CAAE,KAAM,EAAK,CAAC,EACxD,EAAkB,KAAK,QAAS,IAAM,EAAO,oBAAoB,QAAS,CAAO,CAAC,EAGlF,OAAY,QAAU,EAG9B,EAAkB,GAAG,aAAc,CAAC,EAAM,EAAM,IAAO,CACnD,EAAsB,MAAM,iBAAiB,kBAAqB,0BAA2B,IAAO,CAAC,EACxG,EACD,EAAkB,GAAG,QAAS,CAAiB,EAC/C,EAAkB,GAAG,UAAW,IAAM,CAClC,EAAsB,MAAM,6EAA6E,EAAkB,UAAU,CAAC,EACzI,EACD,EAAkB,GAAG,WAAY,CAAC,IAAY,CAC1C,IAAM,EAAe,IAAI,EAAa,CAClC,WAAY,EAAQ,YAAc,GAClC,QAAS,EAAsB,CAAO,EACtC,KAAM,CACV,CAAC,EAGD,GAFA,EAAY,GACZ,EAAQ,CAAE,SAAU,CAAa,CAAC,EAC9B,EACA,EAAQ,MAAM,EAErB,EACD,EAAkB,GAAG,QAAS,IAAM,CAChC,GAAI,EACA,EAAI,QAAQ,EAGZ,UAAK,kBAAkB,QAAQ,EAAgB,CAAG,EAEtD,GAAI,CAAC,EACD,EAAsB,MAAM,wDAAwD,CAAC,EAE5F,EACD,EAA0B,EAAiB,EAAmB,EAAS,CAAuB,EACjG,EAEL,sBAAsB,CAAC,EAAK,EAAO,CAC/B,KAAK,OAAS,OACd,KAAK,eAAiB,KAAK,eAAe,KAAK,CAAC,IAAW,CACvD,MAAO,IACA,GACF,GAAM,CACX,EACH,EAEL,kBAAkB,EAAG,CACjB,OAAO,KAAK,QAAU,CAAC,EAE/B,CAEQ,2BAA0B,GAC1B,oBAAmB,EACnB,mBAAkB", | ||
| "debugId": "ECE52110C76691C864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+vercel@2.0.39+d6123d32214422cb/node_modules/@ai-sdk/vercel/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/vercel-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport { OpenAICompatibleChatLanguageModel } from \"@ai-sdk/openai-compatible\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/version.ts\nvar VERSION = true ? \"2.0.39\" : \"0.0.0-test\";\n\n// src/vercel-provider.ts\nfunction createVercel(options = {}) {\n var _a;\n const baseURL = withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.v0.dev/v1\"\n );\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"VERCEL_API_KEY\",\n description: \"Vercel\"\n })}`,\n ...options.headers\n },\n `ai-sdk/vercel/${VERSION}`\n );\n const getCommonModelConfig = (modelType) => ({\n provider: `vercel.${modelType}`,\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createChatModel = (modelId) => {\n return new OpenAICompatibleChatLanguageModel(modelId, {\n ...getCommonModelConfig(\"chat\")\n });\n };\n const provider = (modelId) => createChatModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar vercel = createVercel();\nexport {\n VERSION,\n createVercel,\n vercel\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";4UAYA,SAAI,OAAiB,cAGrB,cAAS,MAAY,MAAC,OAAU,CAAC,EAAG,CAClC,IAAI,EACJ,IAAM,EAAU,GACb,EAAK,EAAQ,UAAY,KAAO,EAAK,uBACxC,EACM,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,iBACzB,YAAa,QACf,CAAC,OACE,EAAQ,OACb,EACA,iBAAiB,GACnB,EACM,EAAuB,CAAC,KAAe,CAC3C,SAAU,UAAU,IACpB,IAAK,EAAG,UAAW,GAAG,IAAU,IAChC,QAAS,EACT,MAAO,EAAQ,KACjB,GACM,EAAkB,CAAC,IAAY,CACnC,OAAO,IAAI,EAAkC,EAAS,IACjD,EAAqB,MAAM,CAChC,CAAC,GAEG,EAAW,CAAC,IAAY,EAAgB,CAAO,EAUrD,OATA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,EAAS,EAAa", | ||
| "debugId": "196A5B8C5BF11B9464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "8C2E101EFA5FCAC064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/version.ts"], | ||
| "sourcesContent": [ | ||
| "declare const OPENCODE_VERSION: string\ndeclare const OPENCODE_CHANNEL: string\n\nconst version = typeof OPENCODE_VERSION === \"string\" ? OPENCODE_VERSION : \"local\"\nconst channel = typeof OPENCODE_CHANNEL === \"string\" ? OPENCODE_CHANNEL : \"local\"\n\nexport { version as OPENCODE_VERSION, channel as OPENCODE_CHANNEL }\nexport const OPENCODE_LOCAL = channel === \"local\"\n" | ||
| ], | ||
| "mappings": ";AAGA,IAAM,EAAiD,mBACjD,EAAiD,OAGhD,IAAM,EAAiB", | ||
| "debugId": "8E89F6FE80BD5CA664756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "7A113230590D497C64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/services/service-config.ts"], | ||
| "sourcesContent": [ | ||
| "import { Global } from \"@opencode-ai/util/global\"\nimport { OPENCODE_CHANNEL, OPENCODE_VERSION } from \"../version\"\nimport { Hash } from \"@opencode-ai/util/hash\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, FileSystem, Option, Schema } from \"effect\"\nimport { randomBytes } from \"crypto\"\nimport path from \"path\"\nimport { selfCommand } from \"../util/process\"\n\n// The CLI's service configuration file, plus the Service.EnsureOptions binding that\n// points the client package's service operations at this CLI: which\n// registration file (by channel), which version, and how to spawn opencode.\n\nexport const Info = Schema.Struct({\n hostname: Schema.optional(Schema.String),\n port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),\n password: Schema.optional(Schema.String),\n})\nexport type Info = typeof Info.Type\n\nconst keys = [\"hostname\", \"port\", \"password\"] as const\ntype Key = (typeof keys)[number]\n\nconst decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))\nconst decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info))\n\nexport function filename(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"next\") return \"service.json\"\n return `service-${channel.replace(/[^a-zA-Z0-9._-]/g, \"-\")}.json`\n}\n\nexport function defaultPort(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"next\") return 0xc0de\n if (channel === \"local\") return 0xc0df\n return 10_000 + (Number.parseInt(Hash.fast(channel).slice(0, 8), 16) % 50_000)\n}\n\nexport function legacyFilename(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"local\") return\n return `service-${Hash.fast(channel)}.json`\n}\n\nexport function versionBelongsToChannel(\n version: string | undefined,\n channel = OPENCODE_CHANNEL,\n installedVersion = OPENCODE_VERSION,\n) {\n if (version === undefined) return false\n if (version === installedVersion) return true\n const prefix = `0.0.0-${channel}-`\n if (!version.startsWith(prefix)) return false\n return /^\\d+(?:\\.\\d+)?$/.test(version.slice(prefix.length))\n}\n\nexport const migrateRegistration = Effect.fnUntraced(function* (\n legacy: string,\n file: string,\n channel = OPENCODE_CHANNEL,\n installedVersion = OPENCODE_VERSION,\n) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(legacy).pipe(Effect.option)\n if (Option.isNone(text)) return\n const registration = yield* decodeRegistration(text.value).pipe(Effect.option)\n if (Option.isNone(registration)) return\n if (!versionBelongsToChannel(registration.value.version, channel, installedVersion)) return\n yield* fs.writeFileString(file, text.value, { flag: \"wx\", mode: 0o600 }).pipe(Effect.ignore)\n})\n\nexport const migrateConfig = Effect.fnUntraced(function* (legacy: string, file: string) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(legacy).pipe(Effect.option)\n if (Option.isNone(text)) return\n if (Option.isNone(yield* decodeInfo(text.value).pipe(Effect.option))) return\n yield* fs.writeFileString(file, text.value, { flag: \"wx\", mode: 0o600 }).pipe(Effect.ignore)\n})\n\nfunction configKey(key: string): Key {\n if (key === \"hostname\" || key === \"port\" || key === \"password\") return key\n throw new Error(`Unknown service config key: ${key}`)\n}\n\nconst paths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem\n const global = yield* Global.Service\n const name = filename()\n const legacy = legacyFilename()\n const file = path.join(global.state, name)\n return {\n fs,\n file,\n legacyConfigFile: legacy ? path.join(global.config, legacy) : undefined,\n legacyRegistrationFiles: [\n ...(legacy ? [path.join(global.state, legacy)] : []),\n ...(name !== \"service.json\" && OPENCODE_CHANNEL !== \"local\" ? [path.join(global.state, \"service.json\")] : []),\n ],\n configFile: path.join(global.config, name),\n }\n})\n\nexport const options = Effect.fnUntraced(function* () {\n const { file, legacyRegistrationFiles } = yield* paths\n yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))\n return {\n file,\n version: OPENCODE_VERSION,\n command: [...selfCommand(), \"serve\", \"--service\"],\n }\n})\n\nexport const read = Effect.fn(\"cli.service-config.read\")(function* () {\n const { fs, configFile, legacyConfigFile } = yield* paths\n if (legacyConfigFile) yield* migrateConfig(legacyConfigFile, configFile)\n return yield* fs.readFileString(configFile).pipe(\n Effect.flatMap(decodeInfo),\n Effect.catch(() => Effect.succeed({} as Info)),\n )\n})\n\nconst write = Effect.fn(\"cli.service-config.write\")(function* (value: Info) {\n const { fs, configFile } = yield* paths\n const temp = configFile + \".tmp\"\n yield* fs.makeDirectory(path.dirname(configFile), { recursive: true })\n yield* fs.writeFileString(temp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n yield* fs.rename(temp, configFile)\n})\n\nexport const password = Effect.fn(\"cli.service-config.password\")(function* (value?: string) {\n const existing = yield* read()\n if (value === undefined && existing.password) return existing.password\n const next = value ?? randomBytes(32).toString(\"base64url\")\n\n // Keep one private credential across server restarts so discovered clients\n // can reconnect without exposing a password flag or environment variable.\n yield* write({ ...existing, password: next })\n return next\n})\n\nexport const get = Effect.fn(\"cli.service-config.get\")(function* (key?: string) {\n if (key === undefined) {\n const { password: _password, ...safe } = yield* read()\n return JSON.stringify(safe, null, 2)\n }\n switch (configKey(key)) {\n case \"hostname\": {\n return (yield* read()).hostname ?? \"\"\n }\n case \"port\": {\n const port = (yield* read()).port\n return port === undefined ? \"\" : String(port)\n }\n case \"password\": {\n return yield* password()\n }\n }\n throw new Error(`Unknown service config key: ${key}`)\n})\n\nexport const set = Effect.fn(\"cli.service-config.set\")(function* (key: string, value: string) {\n switch (configKey(key)) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), hostname: value })\n return\n }\n case \"port\": {\n const port = Number(value)\n if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error(\"Port must be between 1 and 65535\")\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), port })\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n yield* password(value)\n return\n }\n }\n})\n\nexport const unset = Effect.fn(\"cli.service-config.unset\")(function* (key: string) {\n switch (configKey(key)) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n const { hostname: _hostname, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"port\": {\n yield* Service.stop(yield* options())\n const { port: _port, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n const { password: _password, ...next } = yield* read()\n yield* write(next)\n return\n }\n }\n})\n\nexport * as ServiceConfig from \"./service-config\"\n" | ||
| ], | ||
| "mappings": ";gkBAKA,2BAAS,oBACT,yBAOO,SAAM,OAAO,EAAO,OAAO,CAChC,SAAU,EAAO,SAAS,EAAO,MAAM,EACvC,KAAM,EAAO,SAAS,EAAO,IAAI,MAAM,EAAO,uBAAuB,CAAC,EAAG,EAAO,oBAAoB,KAAM,CAAC,CAAC,EAC5G,SAAU,EAAO,SAAS,EAAO,MAAM,CACzC,CAAC,EAMD,IAAM,EAAa,EAAO,oBAAoB,EAAO,eAAe,CAAI,CAAC,EACnE,EAAqB,EAAO,oBAAoB,EAAO,eAAe,EAAQ,IAAI,CAAC,EAElF,SAAS,CAAQ,CAAC,EAAU,EAAkB,CACnD,GAAI,IAAY,UAAY,IAAY,OAAQ,MAAO,eACvD,MAAO,WAAW,EAAQ,QAAQ,mBAAoB,GAAG,SAGpD,SAAS,CAAW,CAAC,EAAU,EAAkB,CACtD,GAAI,IAAY,UAAY,IAAY,OAAQ,MAAO,OACvD,GAAI,IAAY,QAAS,MAAO,OAChC,MAAO,KAAU,OAAO,SAAS,EAAK,KAAK,CAAO,EAAE,MAAM,EAAG,CAAC,EAAG,EAAE,EAAI,MAGlE,SAAS,CAAc,CAAC,EAAU,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,IAAM,MAAO,EAAK,EAAI,MAAK,CAAC,EACzC,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,MAAO,EAAS,CAAK,EACrB,MACF,GAEH,EAEY,EAAQ,EAAO,GAAG,0BAA0B,EAAE,SAAU,CAAC,EAAa,CACjF,OAAQ,EAAU,CAAG,OACd,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,KACK,OAAQ,CACX,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,KAAM,KAAU,GAAS,MAAO,EAAK,EAC7C,MAAO,EAAM,CAAI,EACjB,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,GAEH", | ||
| "debugId": "F078B3565094F56F64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/services/server-connection.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint, type EnsureOptions } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, isUnauthorizedError, OpenCode } from \"@opencode-ai/client/promise\"\nimport { OPENCODE_VERSION } from \"../version\"\nimport { Effect, Redacted } from \"effect\"\nimport { Env } from \"../env\"\nimport { ServiceConfig } from \"./service-config\"\nimport { Standalone } from \"./standalone\"\n\nexport type Args = {\n readonly server?: string\n readonly standalone?: boolean\n readonly mismatch?: \"replace\" | \"ignore\" | \"error\"\n readonly onStart?: EnsureOptions[\"onStart\"]\n}\n\nexport type Resolved = {\n readonly endpoint: Endpoint\n readonly service?: ReturnType<typeof managedService>\n}\n\nexport const resolve = Effect.fn(\"cli.server-connection.resolve\")(function* (args: Args) {\n if (args.server !== undefined && args.standalone)\n return yield* Effect.fail(new Error(\"--server and --standalone cannot be combined\"))\n if (args.server !== undefined) {\n const password = yield* Env.password\n const endpoint = {\n url: args.server,\n auth: password ? { type: \"basic\" as const, username: \"opencode\", password: Redacted.value(password) } : undefined,\n } satisfies Endpoint\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const health = yield* Effect.tryPromise({\n try: () => client.health.get({ signal: AbortSignal.timeout(5_000) }),\n catch: (cause) => connectError(endpoint, cause),\n })\n if (health.version !== OPENCODE_VERSION)\n process.stderr.write(\n `Warning: Server at ${endpoint.url} has version ${health.version}; this client is ${OPENCODE_VERSION}. Continuing anyway.\\n`,\n )\n return { endpoint } satisfies Resolved\n }\n if (args.standalone) {\n return { endpoint: yield* Standalone.start() } satisfies Resolved\n }\n\n const options = yield* ServiceConfig.options()\n return {\n endpoint: yield* resolveManaged({ ...options, onStart: args.onStart }, args.mismatch ?? \"replace\"),\n service: managedService(options),\n } satisfies Resolved\n})\n\nfunction managedService(options: EnsureOptions) {\n const reconnectOptions = { ...options, version: undefined }\n return {\n reconnect: () => Service.ensure(reconnectOptions),\n restart: () =>\n Effect.gen(function* () {\n yield* Service.stop(options)\n yield* Service.ensure(reconnectOptions)\n }),\n }\n}\n\nconst resolveManaged = Effect.fnUntraced(function* (\n options: EnsureOptions,\n mismatch: NonNullable<Args[\"mismatch\"]>,\n) {\n if (mismatch === \"replace\") return yield* Service.ensure(options)\n if (mismatch === \"ignore\") return yield* Service.ensure({ ...options, version: undefined })\n\n const compatible = yield* Service.discover(options)\n if (compatible !== undefined) return compatible\n const existing = yield* Service.discover({ ...options, version: undefined })\n if (existing !== undefined)\n return yield* Effect.fail(new Error(\"Background server version does not match this client\"))\n return yield* Service.ensure(options)\n})\n\nfunction connectError(endpoint: Endpoint, cause: unknown) {\n if (isUnauthorizedError(cause)) {\n return new Error(\n endpoint.auth === undefined\n ? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`\n : `Server at ${endpoint.url} rejected the password`,\n { cause },\n )\n }\n if (cause instanceof ClientError && cause.reason === \"Transport\")\n return new Error(`Could not reach server at ${endpoint.url}`, { cause })\n return new Error(`Server at ${endpoint.url} did not provide a compatible V2 health response`, { cause })\n}\n\nexport * as ServerConnection from \"./server-connection\"\n" | ||
| ], | ||
| "mappings": ";0cAoBO,SAAM,OAAU,OAAO,QAAG,oCAA+B,OAAE,cAAU,CAAC,EAAY,CACvF,GAAI,EAAK,SAAW,QAAa,EAAK,WACpC,OAAO,MAAO,EAAO,KAAS,MAAM,8CAA8C,CAAC,EACrF,GAAI,EAAK,SAAW,OAAW,CAC7B,IAAM,EAAW,MAAO,EAAI,SACtB,EAAW,CACf,IAAK,EAAK,OACV,KAAM,EAAW,CAAE,KAAM,QAAkB,SAAU,WAAY,SAAU,EAAS,MAAM,CAAQ,CAAE,EAAI,MAC1G,EACM,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAS,MAAO,EAAO,WAAW,CACtC,IAAK,IAAM,EAAO,OAAO,IAAI,CAAE,OAAQ,YAAY,QAAQ,IAAK,CAAE,CAAC,EACnE,MAAO,CAAC,IAAU,EAAa,EAAU,CAAK,CAChD,CAAC,EACD,GAAI,EAAO,UAAY,EACrB,QAAQ,OAAO,MACb,sBAAsB,EAAS,mBAAmB,EAAO,2BAA2B;AAAA,CACtF,EACF,MAAO,CAAE,UAAS,EAEpB,GAAI,EAAK,WACP,MAAO,CAAE,SAAU,MAAO,EAAW,MAAM,CAAE,EAG/C,IAAM,EAAU,MAAO,EAAc,QAAQ,EAC7C,MAAO,CACL,SAAU,MAAO,EAAe,IAAK,EAAS,QAAS,EAAK,OAAQ,EAAG,EAAK,UAAY,SAAS,EACjG,QAAS,EAAe,CAAO,CACjC,EACD,EAED,SAAS,CAAc,CAAC,EAAwB,CAC9C,IAAM,EAAmB,IAAK,EAAS,QAAS,MAAU,EAC1D,MAAO,CACL,UAAW,IAAM,EAAQ,OAAO,CAAgB,EAChD,QAAS,IACP,EAAO,IAAI,SAAU,EAAG,CACtB,MAAO,EAAQ,KAAK,CAAO,EAC3B,MAAO,EAAQ,OAAO,CAAgB,EACvC,CACL,EAGF,IAAM,EAAiB,EAAO,WAAW,SAAU,CACjD,EACA,EACA,CACA,GAAI,IAAa,UAAW,OAAO,MAAO,EAAQ,OAAO,CAAO,EAChE,GAAI,IAAa,SAAU,OAAO,MAAO,EAAQ,OAAO,IAAK,EAAS,QAAS,MAAU,CAAC,EAE1F,IAAM,EAAa,MAAO,EAAQ,SAAS,CAAO,EAClD,GAAI,IAAe,OAAW,OAAO,EAErC,IADiB,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,KAC1D,OACf,OAAO,MAAO,EAAO,KAAS,MAAM,sDAAsD,CAAC,EAC7F,OAAO,MAAO,EAAQ,OAAO,CAAO,EACrC,EAED,SAAS,CAAY,CAAC,EAAoB,EAAgB,CACxD,GAAI,EAAoB,CAAK,EAC3B,OAAW,MACT,EAAS,OAAS,OACd,aAAa,EAAS,iDACtB,aAAa,EAAS,4BAC1B,CAAE,OAAM,CACV,EAEF,GAAI,aAAiB,GAAe,EAAM,SAAW,YACnD,OAAW,MAAM,6BAA6B,EAAS,MAAO,CAAE,OAAM,CAAC,EACzE,OAAW,MAAM,aAAa,EAAS,sDAAuD,CAAE,OAAM,CAAC", | ||
| "debugId": "9CED01F2E9A5836864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/anthropic-compatible.ts", "../ai/src/providers/anthropic.ts"], | ||
| "sourcesContent": [ | ||
| "import type { ProviderPackage } from \"../provider-package\"\nimport { AnthropicMessages } from \"../protocols/anthropic-messages\"\nimport { Auth } from \"../route/auth\"\nimport type { ProviderAuthOption } from \"../route/auth-options\"\nimport type { RouteDefaultsInput } from \"../route/client\"\nimport { ProviderID, type ModelID } from \"../schema\"\n\nexport const id = ProviderID.make(\"anthropic-compatible\")\n\nexport type Config = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly provider?: string\n readonly baseURL: string\n }\n\nexport type Settings = ProviderPackage.Settings &\n (\n | { readonly apiKey?: string; readonly authToken?: never }\n | { readonly apiKey?: never; readonly authToken?: string }\n ) & {\n readonly baseURL: string\n readonly provider?: string\n }\n\nexport const routes = [AnthropicMessages.route]\n\nconst auth = (input: ProviderAuthOption<\"optional\">) => {\n if (\"auth\" in input && input.auth) return input.auth\n return Auth.optional(\"apiKey\" in input ? input.apiKey : undefined, \"apiKey\").pipe(Auth.header(\"x-api-key\"))\n}\n\nexport const configure = (input: Config) => {\n if (!input.baseURL) throw new Error(\"Anthropic-compatible providers require a baseURL\")\n const provider = input.provider ?? \"anthropic-compatible\"\n const { provider: _, baseURL, apiKey: _apiKey, auth: _auth, ...rest } = input\n const route = AnthropicMessages.route.with({\n ...rest,\n provider,\n endpoint: { baseURL },\n auth: auth(input),\n })\n return {\n id: ProviderID.make(provider),\n model: (modelID: string | ModelID) => route.model({ id: modelID }),\n configure,\n }\n}\n\nexport const provider = {\n id,\n configure,\n}\n\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) => {\n if (settings.apiKey !== undefined && settings.authToken !== undefined)\n throw new Error(\"Anthropic-compatible apiKey cannot be combined with authToken\")\n return configure({\n ...(settings.authToken === undefined ? { apiKey: settings.apiKey } : { auth: Auth.bearer(settings.authToken) }),\n baseURL: settings.baseURL,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n provider: settings.provider,\n }).model(modelID)\n}\n\nexport * as AnthropicCompatible from \"./anthropic-compatible\"\n", | ||
| "import type { RouteDefaultsInput } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport type { ProviderAuthOption } from \"../route/auth-options\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { ProviderID, type ModelID } from \"../schema\"\nimport { AnthropicMessages } from \"../protocols/anthropic-messages\"\nimport { AnthropicCompatible } from \"./anthropic-compatible\"\n\nexport const id = ProviderID.make(\"anthropic\")\n\nexport const routes = [AnthropicMessages.route]\n\nexport type Config = RouteDefaultsInput & ProviderAuthOption<\"optional\"> & { readonly baseURL?: string }\n\nexport type Settings = ProviderPackage.Settings &\n (\n | { readonly apiKey?: string; readonly authToken?: never }\n | { readonly apiKey?: never; readonly authToken?: string }\n ) & {\n readonly baseURL?: string\n }\n\nconst auth = (options: ProviderAuthOption<\"optional\">) => {\n if (\"auth\" in options && options.auth) return options.auth\n return Auth.optional(\"apiKey\" in options ? options.apiKey : undefined, \"apiKey\")\n .orElse(Auth.config(\"ANTHROPIC_API_KEY\"))\n .pipe(Auth.header(\"x-api-key\"))\n}\n\nexport const configure = (input: Config = {}) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n const compatible = AnthropicCompatible.configure({\n ...rest,\n auth: auth(input),\n baseURL: baseURL ?? AnthropicMessages.DEFAULT_BASE_URL,\n provider: id,\n })\n return {\n id,\n model: (modelID: string | ModelID) => compatible.model(modelID),\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) => {\n if (settings.apiKey !== undefined && settings.authToken !== undefined)\n throw new Error(\"Anthropic apiKey cannot be combined with authToken\")\n return configure({\n ...(settings.authToken === undefined ? { apiKey: settings.apiKey } : { auth: Auth.bearer(settings.authToken) }),\n baseURL: settings.baseURL,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n }).model(modelID)\n}\n" | ||
| ], | ||
| "mappings": ";ujBAOO,SAAM,OAAK,OAAW,UAAK,2BAAsB,OAiB3C,OAAS,MAAC,OAAkB,UAAK,OAExC,EAAO,CAAC,IAA0C,CACtD,GAAI,SAAU,GAAS,EAAM,KAAM,OAA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AAC,GAGrB,EAAY,CAAC,EAAgB,CAAC,IAAM,CAC/C,IAAQ,OAAQ,EAAG,KAAM,EAAO,aAAY,GAAS,EAC/C,EAAa,EAAoB,UAAU,IAC5C,EACH,KAAM,EAAK,CAAK,EAChB,QAAS,GAAW,EAAkB,iBACtC,SAAU,CACZ,CAAC,EACD,MAAO,CACL,KACA,MAAO,CAAC,IAA8B,EAAW,MAAM,CAAO,EAC9D,WACF,GAGW,EAAW,EAAU,EACrB,EAAuD,CAAC,EAAS,IAAa,CACzF,GAAI,EAAS,SAAW,QAAa,EAAS,YAAc,OAC1D,MAAU,MAAM,oDAAoD,EACtE,OAAO,EAAU,IACX,EAAS,YAAc,OAAY,CAAE,OAAQ,EAAS,MAAO,EAAI,CAAE,KAAM,EAAK,OAAO,EAAS,SAAS,CAAE,EAC7G,QAAS,EAAS,QAClB,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,MACnB,CAAC,EAAE,MAAM,CAAO", | ||
| "debugId": "80CA2F96F9027F3B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/createCredentialChain.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/resolveLogins.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/IndexedDbStorage.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/InMemoryStorage.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.58/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/localStorage.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentity.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentityPool.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromContainerMetadata.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromEnv.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromIni.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromInstanceMetadata.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.70/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.70/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.70/node_modules/@aws-sdk/credential-provider-node/dist-es/runtime/memoize-chain.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromNodeProviderChain.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromProcess.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromSSO.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.base.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTokenFile.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromWebToken.js"], | ||
| "sourcesContent": [ | ||
| "import { ProviderError } from \"@smithy/core/config\";\nexport const createCredentialChain = (...credentialProviders) => {\n let expireAfter = -1;\n const baseFunction = async (awsIdentityProperties) => {\n const credentials = await propertyProviderChain(...credentialProviders)(awsIdentityProperties);\n if (!credentials.expiration && expireAfter !== -1) {\n credentials.expiration = new Date(Date.now() + expireAfter);\n }\n return credentials;\n };\n const withOptions = Object.assign(baseFunction, {\n expireAfter(milliseconds) {\n if (milliseconds < 5 * 60_000) {\n throw new Error(\"@aws-sdk/credential-providers - createCredentialChain(...).expireAfter(ms) may not be called with a duration lower than five minutes.\");\n }\n expireAfter = milliseconds;\n return withOptions;\n },\n });\n return withOptions;\n};\nexport const propertyProviderChain = (...providers) => async (awsIdentityProperties) => {\n if (providers.length === 0) {\n throw new ProviderError(\"No providers in chain\", { tryNextLink: false });\n }\n let lastProviderError;\n for (const provider of providers) {\n try {\n return await provider(awsIdentityProperties);\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { resolveLogins } from \"./resolveLogins\";\nexport function fromCognitoIdentity(parameters) {\n return async (awsIdentityProperties) => {\n parameters.logger?.debug(\"@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity\");\n const { GetCredentialsForIdentityCommand, CognitoIdentityClient } = await import(\"./loadCognitoIdentity.js\");\n const fromConfigs = (property) => parameters.clientConfig?.[property] ??\n parameters.parentClientConfig?.[property] ??\n awsIdentityProperties?.callerClientConfig?.[property];\n const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken, } = throwOnMissingCredentials(parameters.logger), } = await (parameters.client ??\n new CognitoIdentityClient(Object.assign({}, parameters.clientConfig ?? {}, {\n region: fromConfigs(\"region\"),\n profile: fromConfigs(\"profile\"),\n userAgentAppId: fromConfigs(\"userAgentAppId\"),\n }))).send(new GetCredentialsForIdentityCommand({\n CustomRoleArn: parameters.customRoleArn,\n IdentityId: parameters.identityId,\n Logins: parameters.logins ? await resolveLogins(parameters.logins) : undefined,\n }));\n return {\n identityId: parameters.identityId,\n accessKeyId: AccessKeyId,\n secretAccessKey: SecretKey,\n sessionToken: SessionToken,\n expiration: Expiration,\n };\n };\n}\nfunction throwOnMissingAccessKeyId(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no access key ID\", { logger });\n}\nfunction throwOnMissingCredentials(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no credentials\", { logger });\n}\nfunction throwOnMissingSecretKey(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no secret key\", { logger });\n}\n", | ||
| "export function resolveLogins(logins) {\n return Promise.all(Object.keys(logins).reduce((arr, name) => {\n const tokenOrProvider = logins[name];\n if (typeof tokenOrProvider === \"string\") {\n arr.push([name, tokenOrProvider]);\n }\n else {\n arr.push(tokenOrProvider().then((token) => [name, token]));\n }\n return arr;\n }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins, [key, value]) => {\n logins[key] = value;\n return logins;\n }, {}));\n}\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { fromCognitoIdentity } from \"./fromCognitoIdentity\";\nimport { localStorage } from \"./localStorage\";\nimport { resolveLogins } from \"./resolveLogins\";\nexport function fromCognitoIdentityPool({ accountId, cache = localStorage(), client, clientConfig, customRoleArn, identityPoolId, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? \"ANONYMOUS\" : undefined, logger, parentClientConfig, }) {\n logger?.debug(\"@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity\");\n const cacheKey = userIdentifier\n ? `aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}`\n : undefined;\n let provider = async (awsIdentityProperties) => {\n const { GetIdCommand, CognitoIdentityClient } = await import(\"./loadCognitoIdentity.js\");\n const fromConfigs = (property) => clientConfig?.[property] ??\n parentClientConfig?.[property] ??\n awsIdentityProperties?.callerClientConfig?.[property];\n const _client = client ??\n new CognitoIdentityClient(Object.assign({}, clientConfig ?? {}, {\n region: fromConfigs(\"region\"),\n profile: fromConfigs(\"profile\"),\n userAgentAppId: fromConfigs(\"userAgentAppId\"),\n }));\n let identityId = (cacheKey && (await cache.getItem(cacheKey)));\n if (!identityId) {\n const { IdentityId = throwOnMissingId(logger) } = await _client.send(new GetIdCommand({\n AccountId: accountId,\n IdentityPoolId: identityPoolId,\n Logins: logins ? await resolveLogins(logins) : undefined,\n }));\n identityId = IdentityId;\n if (cacheKey) {\n Promise.resolve(cache.setItem(cacheKey, identityId)).catch(() => { });\n }\n }\n provider = fromCognitoIdentity({\n client: _client,\n customRoleArn,\n logins,\n identityId,\n });\n return provider(awsIdentityProperties);\n };\n return (awsIdentityProperties) => provider(awsIdentityProperties).catch(async (err) => {\n if (cacheKey) {\n Promise.resolve(cache.removeItem(cacheKey)).catch(() => { });\n }\n throw err;\n });\n}\nfunction throwOnMissingId(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no identity ID\", { logger });\n}\n", | ||
| "const STORE_NAME = \"IdentityIds\";\nexport class IndexedDbStorage {\n dbName;\n constructor(dbName = \"aws:cognito-identity-ids\") {\n this.dbName = dbName;\n }\n getItem(key) {\n return this.withObjectStore(\"readonly\", (store) => {\n const req = store.get(key);\n return new Promise((resolve) => {\n req.onerror = () => resolve(null);\n req.onsuccess = () => resolve(req.result ? req.result.value : null);\n });\n }).catch(() => null);\n }\n removeItem(key) {\n return this.withObjectStore(\"readwrite\", (store) => {\n const req = store.delete(key);\n return new Promise((resolve, reject) => {\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve();\n });\n });\n }\n setItem(id, value) {\n return this.withObjectStore(\"readwrite\", (store) => {\n const req = store.put({ id, value });\n return new Promise((resolve, reject) => {\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve();\n });\n });\n }\n getDb() {\n const openDbRequest = self.indexedDB.open(this.dbName, 1);\n return new Promise((resolve, reject) => {\n openDbRequest.onsuccess = () => {\n resolve(openDbRequest.result);\n };\n openDbRequest.onerror = () => {\n reject(openDbRequest.error);\n };\n openDbRequest.onblocked = () => {\n reject(new Error(\"Unable to access DB\"));\n };\n openDbRequest.onupgradeneeded = () => {\n const db = openDbRequest.result;\n db.onerror = () => {\n reject(new Error(\"Failed to create object store\"));\n };\n db.createObjectStore(STORE_NAME, { keyPath: \"id\" });\n };\n });\n }\n withObjectStore(mode, action) {\n return this.getDb().then((db) => {\n const tx = db.transaction(STORE_NAME, mode);\n tx.oncomplete = () => db.close();\n return new Promise((resolve, reject) => {\n tx.onerror = () => reject(tx.error);\n resolve(action(tx.objectStore(STORE_NAME)));\n }).catch((err) => {\n db.close();\n throw err;\n });\n });\n }\n}\n", | ||
| "export class InMemoryStorage {\n store;\n constructor(store = {}) {\n this.store = store;\n }\n getItem(key) {\n if (key in this.store) {\n return this.store[key];\n }\n return null;\n }\n removeItem(key) {\n delete this.store[key];\n }\n setItem(key, value) {\n this.store[key] = value;\n }\n}\n", | ||
| "import { IndexedDbStorage } from \"./IndexedDbStorage\";\nimport { InMemoryStorage } from \"./InMemoryStorage\";\nconst inMemoryStorage = new InMemoryStorage();\nexport function localStorage() {\n if (typeof self === \"object\" && self.indexedDB) {\n return new IndexedDbStorage();\n }\n if (typeof window === \"object\" && window.localStorage) {\n return window.localStorage;\n }\n return inMemoryStorage;\n}\n", | ||
| "import { fromCognitoIdentity as _fromCognitoIdentity } from \"@aws-sdk/credential-provider-cognito-identity\";\nexport const fromCognitoIdentity = (options) => _fromCognitoIdentity({\n ...options,\n});\n", | ||
| "import { fromCognitoIdentityPool as _fromCognitoIdentityPool } from \"@aws-sdk/credential-provider-cognito-identity\";\nexport const fromCognitoIdentityPool = (options) => _fromCognitoIdentityPool({\n ...options,\n});\n", | ||
| "import { fromContainerMetadata as _fromContainerMetadata } from \"@smithy/credential-provider-imds\";\nexport const fromContainerMetadata = (init) => {\n init?.logger?.debug(\"@smithy/credential-provider-imds\", \"fromContainerMetadata\");\n return _fromContainerMetadata(init);\n};\n", | ||
| "import { fromEnv as _fromEnv } from \"@aws-sdk/credential-provider-env\";\nexport const fromEnv = (init) => _fromEnv(init);\n", | ||
| "import { fromIni as _fromIni } from \"@aws-sdk/credential-provider-ini\";\nexport const fromIni = (init = {}) => _fromIni({\n ...init,\n});\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromInstanceMetadata as _fromInstanceMetadata } from \"@smithy/credential-provider-imds\";\nexport const fromInstanceMetadata = (init) => {\n init?.logger?.debug(\"@smithy/credential-provider-imds\", \"fromInstanceMetadata\");\n return async () => _fromInstanceMetadata(init)().then((creds) => setCredentialFeature(creds, \"CREDENTIALS_IMDS\", \"0\"));\n};\n", | ||
| "import { fromLoginCredentials as _fromLoginCredentials, } from \"@aws-sdk/credential-provider-login\";\nexport const fromLoginCredentials = (init) => _fromLoginCredentials({\n ...init,\n});\n", | ||
| "import { ENV_KEY, ENV_SECRET, fromEnv } from \"@aws-sdk/credential-provider-env\";\nimport { CredentialsProviderError, ENV_PROFILE } from \"@smithy/core/config\";\nimport { remoteProvider } from \"./remoteProvider\";\nimport { memoizeChain } from \"./runtime/memoize-chain\";\nlet multipleCredentialSourceWarningEmitted = false;\nexport const defaultProvider = (init = {}) => memoizeChain([\n async () => {\n const profile = init.profile ?? process.env[ENV_PROFILE];\n if (profile) {\n const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET];\n if (envStaticCredentialsAreSet) {\n if (!multipleCredentialSourceWarningEmitted) {\n const warnFn = init.logger?.warn && init.logger?.constructor?.name !== \"NoOpLogger\"\n ? init.logger.warn.bind(init.logger)\n : console.warn;\n warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:\n Multiple credential sources detected: \n Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.\n This SDK will proceed with the AWS_PROFILE value.\n \n However, a future version may change this behavior to prefer the ENV static credentials.\n Please ensure that your environment only sets either the AWS_PROFILE or the\n AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.\n`);\n multipleCredentialSourceWarningEmitted = true;\n }\n }\n throw new CredentialsProviderError(\"AWS_PROFILE is set, skipping fromEnv provider.\", {\n logger: init.logger,\n tryNextLink: true,\n });\n }\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromEnv\");\n return fromEnv(init)();\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n throw new CredentialsProviderError(\"Skipping SSO provider in default chain (inputs do not include SSO fields).\", { logger: init.logger });\n }\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromIni\");\n const { fromIni } = await import(\"@aws-sdk/credential-provider-ini\");\n return fromIni(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromProcess\");\n const { fromProcess } = await import(\"@aws-sdk/credential-provider-process\");\n return fromProcess(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile\");\n const { fromTokenFile } = await import(\"@aws-sdk/credential-provider-web-identity\");\n return fromTokenFile(init)(awsIdentityProperties);\n },\n async () => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::remoteProvider\");\n return (await remoteProvider(init))();\n },\n async () => {\n throw new CredentialsProviderError(\"Could not load credentials from any providers\", {\n tryNextLink: false,\n logger: init.logger,\n });\n },\n], credentialsTreatedAsExpired);\nexport const credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined;\nexport const credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000;\n", | ||
| "import { chain, CredentialsProviderError } from \"@smithy/core/config\";\nexport const ENV_IMDS_DISABLED = \"AWS_EC2_METADATA_DISABLED\";\nexport const remoteProvider = async (init) => {\n const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata\");\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n return chain(fromHttp(init), fromContainerMetadata(init));\n }\n if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== \"false\") {\n return async () => {\n throw new CredentialsProviderError(\"EC2 Instance Metadata Service access disabled\", { logger: init.logger });\n };\n }\n init.logger?.debug(\"@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata\");\n return fromInstanceMetadata(init);\n};\n", | ||
| "export function memoizeChain(providers, treatAsExpired) {\n const chain = internalCreateChain(providers);\n let activeLock;\n let passiveLock;\n let credentials;\n let forceRefreshLock;\n const provider = async (options) => {\n if (options?.forceRefresh) {\n if (!forceRefreshLock) {\n forceRefreshLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n forceRefreshLock = undefined;\n });\n }\n await forceRefreshLock;\n return credentials;\n }\n if (credentials?.expiration) {\n if (credentials?.expiration?.getTime() < Date.now()) {\n credentials = undefined;\n }\n }\n if (activeLock) {\n await activeLock;\n }\n else if (!credentials || treatAsExpired?.(credentials)) {\n if (credentials) {\n if (!passiveLock) {\n passiveLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n passiveLock = undefined;\n });\n }\n }\n else {\n activeLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n activeLock = undefined;\n });\n return provider(options);\n }\n }\n return credentials;\n };\n return provider;\n}\nexport const internalCreateChain = (providers) => async (awsIdentityProperties) => {\n let lastProviderError;\n for (const provider of providers) {\n try {\n return await provider(awsIdentityProperties);\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n", | ||
| "import { defaultProvider } from \"@aws-sdk/credential-provider-node\";\nexport const fromNodeProviderChain = (init = {}) => defaultProvider({\n ...init,\n});\n", | ||
| "import { fromProcess as _fromProcess } from \"@aws-sdk/credential-provider-process\";\nexport const fromProcess = (init) => _fromProcess(init);\n", | ||
| "import { fromSSO as _fromSSO } from \"@aws-sdk/credential-provider-sso\";\nexport const fromSSO = (init = {}) => {\n return _fromSSO({ ...init });\n};\n", | ||
| "import { loadConfig, NODE_REGION_CONFIG_FILE_OPTIONS } from \"@smithy/core/config\";\nimport { fromNodeProviderChain } from \"./fromNodeProviderChain\";\nimport { fromTemporaryCredentials as fromTemporaryCredentialsBase } from \"./fromTemporaryCredentials.base\";\nexport const fromTemporaryCredentials = (options) => {\n return fromTemporaryCredentialsBase(options, fromNodeProviderChain, async ({ profile = process.env.AWS_PROFILE }) => loadConfig({\n environmentVariableSelector: (env) => env.AWS_REGION,\n configFileSelector: (profileData) => {\n return profileData.region;\n },\n default: () => undefined,\n }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, profile })());\n};\n", | ||
| "import { normalizeProvider } from \"@smithy/core\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nconst ASSUME_ROLE_DEFAULT_REGION = \"us-east-1\";\nexport const fromTemporaryCredentials = (options, credentialDefaultProvider, regionProvider) => {\n let stsClient;\n return async (awsIdentityProperties = {}) => {\n const { callerClientConfig } = awsIdentityProperties;\n const profile = options.clientConfig?.profile ?? callerClientConfig?.profile;\n const logger = options.logger ?? callerClientConfig?.logger;\n logger?.debug(\"@aws-sdk/credential-providers - fromTemporaryCredentials (STS)\");\n const params = { ...options.params, RoleSessionName: options.params.RoleSessionName ?? \"aws-sdk-js-\" + Date.now() };\n if (params?.SerialNumber) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Temporary credential requires multi-factor authentication, but no MFA code callback was provided.`, {\n tryNextLink: false,\n logger,\n });\n }\n params.TokenCode = await options.mfaCodeProvider(params?.SerialNumber);\n }\n const { AssumeRoleCommand, STSClient } = await import(\"./loadSts.js\");\n if (!stsClient) {\n const defaultCredentialsOrError = typeof credentialDefaultProvider === \"function\" ? credentialDefaultProvider() : undefined;\n const credentialSources = [\n options.masterCredentials,\n options.clientConfig?.credentials,\n void callerClientConfig?.credentials,\n callerClientConfig?.credentialDefaultProvider?.(),\n defaultCredentialsOrError,\n ];\n let credentialSource = \"STS client default credentials\";\n if (credentialSources[0]) {\n credentialSource = \"options.masterCredentials\";\n }\n else if (credentialSources[1]) {\n credentialSource = \"options.clientConfig.credentials\";\n }\n else if (credentialSources[2]) {\n credentialSource = \"caller client's credentials\";\n throw new Error(\"fromTemporaryCredentials recursion in callerClientConfig.credentials\");\n }\n else if (credentialSources[3]) {\n credentialSource = \"caller client's credentialDefaultProvider\";\n }\n else if (credentialSources[4]) {\n credentialSource = \"AWS SDK default credentials\";\n }\n const regionSources = [\n options.clientConfig?.region,\n callerClientConfig?.region,\n await regionProvider?.({\n profile,\n }),\n ASSUME_ROLE_DEFAULT_REGION,\n ];\n let regionSource = \"default partition's default region\";\n if (regionSources[0]) {\n regionSource = \"options.clientConfig.region\";\n }\n else if (regionSources[1]) {\n regionSource = \"caller client's region\";\n }\n else if (regionSources[2]) {\n regionSource = \"file or env region\";\n }\n const requestHandlerSources = [\n filterRequestHandler(options.clientConfig?.requestHandler),\n filterRequestHandler(callerClientConfig?.requestHandler),\n ];\n let requestHandlerSource = \"STS default requestHandler\";\n if (requestHandlerSources[0]) {\n requestHandlerSource = \"options.clientConfig.requestHandler\";\n }\n else if (requestHandlerSources[1]) {\n requestHandlerSource = \"caller client's requestHandler\";\n }\n logger?.debug?.(`@aws-sdk/credential-providers - fromTemporaryCredentials STS client init with ` +\n `${regionSource}=${await normalizeProvider(coalesce(regionSources))()}, ${credentialSource}, ${requestHandlerSource}.`);\n stsClient = new STSClient({\n userAgentAppId: callerClientConfig?.userAgentAppId,\n ...options.clientConfig,\n credentials: coalesce(credentialSources),\n logger,\n profile,\n region: coalesce(regionSources),\n requestHandler: coalesce(requestHandlerSources),\n });\n }\n if (options.clientPlugins) {\n for (const plugin of options.clientPlugins) {\n stsClient.middlewareStack.use(plugin);\n }\n }\n const { Credentials } = await stsClient.send(new AssumeRoleCommand(params));\n if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {\n throw new CredentialsProviderError(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`, {\n logger,\n });\n }\n return {\n accessKeyId: Credentials.AccessKeyId,\n secretAccessKey: Credentials.SecretAccessKey,\n sessionToken: Credentials.SessionToken,\n expiration: Credentials.Expiration,\n credentialScope: Credentials.CredentialScope,\n };\n };\n};\nconst filterRequestHandler = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\" ? undefined : requestHandler;\n};\nconst coalesce = (args) => {\n for (const item of args) {\n if (item !== undefined) {\n return item;\n }\n }\n};\n", | ||
| "import { fromTokenFile as _fromTokenFile } from \"@aws-sdk/credential-provider-web-identity\";\nexport const fromTokenFile = (init = {}) => _fromTokenFile({\n ...init,\n});\n", | ||
| "import { fromWebToken as _fromWebToken } from \"@aws-sdk/credential-provider-web-identity\";\nexport const fromWebToken = (init) => _fromWebToken({\n ...init,\n});\n" | ||
| ], | ||
| "mappings": ";moBAAA,oBACa,QAAwB,SAAI,SAAwB,MAC7D,SAAI,OAAc,QAQZ,OAAc,YAAO,YAPN,WAAO,IAA0B,CAClD,IAAM,EAAc,MAAM,GAAsB,GAAG,CAAmB,EAAE,CAAqB,EAC7F,GAAI,CAAC,EAAY,YAAc,IAAgB,GAC3C,EAAY,WAAa,IAAI,KAAK,KAAK,IAAI,EAAI,CAAW,EAE9D,OAAO,GAEqC,CAC5C,WAAW,CAAC,EAAc,CACtB,GAAI,EAAe,OACf,MAAU,MAAM,uIAAuI,EAG3J,OADA,EAAc,EACP,EAEf,CAAC,EACD,OAAO,GAEE,GAAwB,IAAI,IAAc,MAAO,IAA0B,CACpF,GAAI,EAAU,SAAW,EACrB,MAAM,IAAI,gBAAc,wBAAyB,CAAE,YAAa,EAAM,CAAC,EAE3E,IAAI,EACJ,QAAW,KAAY,EACnB,GAAI,CACA,OAAO,MAAM,EAAS,CAAqB,EAE/C,MAAO,EAAK,CAER,GADA,EAAoB,EAChB,GAAK,YACL,SAEJ,MAAM,EAGd,MAAM,GCtCV,eCAO,SAAS,CAAa,CAAC,EAAQ,CAClC,OAAO,QAAQ,IAAI,OAAO,KAAK,CAAM,EAAE,OAAO,CAAC,EAAK,IAAS,CACzD,IAAM,EAAkB,EAAO,GAC/B,GAAI,OAAO,IAAoB,SAC3B,EAAI,KAAK,CAAC,EAAM,CAAe,CAAC,EAGhC,OAAI,KAAK,EAAgB,EAAE,KAAK,CAAC,IAAU,CAAC,EAAM,CAAK,CAAC,CAAC,EAE7D,OAAO,GACR,CAAC,CAAC,CAAC,E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gBAC7B,aAAc,EAAY,aAC1B,WAAY,EAAY,WACxB,gBAAiB,EAAY,eACjC,IAGF,EAAuB,CAAC,IAAmB,CAC7C,OAAO,GAAgB,UAAU,kBAAoB,KAAO,OAAY,GAEtE,EAAW,CAAC,IAAS,CACvB,QAAW,KAAQ,EACf,GAAI,IAAS,OACT,OAAO,GD/GZ,IAAM,GAA2B,CAAC,IAAY,CACjD,OAAO,GAA6B,EAAS,EAAuB,OAAS,UAAU,QAAQ,IAAI,eAAkB,aAAW,CAC5H,4BAA6B,CAAC,IAAQ,EAAI,WAC1C,mBAAoB,CAAC,IAAgB,CACjC,OAAO,EAAY,QAEvB,QAAS,IAAG,CAAG,OACnB,EAAG,IAAK,kCAAiC,SAAQ,CAAC,EAAE,CAAC,GETlD,IAAM,GAAgB,CAAC,EAAO,CAAC,IAAM,GAAe,IACpD,CACP,CAAC,ECFM,IAAM,GAAe,CAAC,IAAS,GAAc,IAC7C,CACP,CAAC", | ||
| "debugId": "FE4ED48C1635C7A764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "72451AEC09E6FEBB64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+deepinfra@2.0.41+d6123d32214422cb/node_modules/@ai-sdk/deepinfra/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/deepinfra-provider.ts\nimport {\n OpenAICompatibleCompletionLanguageModel,\n OpenAICompatibleEmbeddingModel\n} from \"@ai-sdk/openai-compatible\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/deepinfra-image-model.ts\nimport {\n combineHeaders,\n convertBase64ToUint8Array,\n convertToFormData,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n downloadBlob,\n postFormDataToApi,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\nvar DeepInfraImageModel = class {\n constructor(modelId, config) {\n this.modelId = modelId;\n this.config = config;\n this.specificationVersion = \"v3\";\n this.maxImagesPerCall = 1;\n }\n get provider() {\n return this.config.provider;\n }\n async doGenerate({\n prompt,\n n,\n size,\n aspectRatio,\n seed,\n providerOptions,\n headers,\n abortSignal,\n files,\n mask\n }) {\n var _a, _b, _c, _d, _e;\n const warnings = [];\n const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();\n if (files != null && files.length > 0) {\n const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi({\n url: this.getEditUrl(),\n headers: combineHeaders(this.config.headers(), headers),\n formData: convertToFormData(\n {\n model: this.modelId,\n prompt,\n image: await Promise.all(files.map((file) => fileToBlob(file))),\n mask: mask != null ? await fileToBlob(mask) : void 0,\n n,\n size,\n ...(_d = providerOptions.deepinfra) != null ? _d : {}\n },\n { useArrayBrackets: false }\n ),\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: deepInfraEditErrorSchema,\n errorToMessage: (error) => {\n var _a2, _b2;\n return (_b2 = (_a2 = error.error) == null ? void 0 : _a2.message) != null ? _b2 : \"Unknown error\";\n }\n }),\n successfulResponseHandler: createJsonResponseHandler(\n deepInfraEditResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n images: response2.data.map((item) => item.b64_json),\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders2\n }\n };\n }\n const splitSize = size == null ? void 0 : size.split(\"x\");\n const { value: response, responseHeaders } = await postJsonToApi({\n url: `${this.config.baseURL}/${this.modelId}`,\n headers: combineHeaders(this.config.headers(), headers),\n body: {\n prompt,\n num_images: n,\n ...aspectRatio && { aspect_ratio: aspectRatio },\n ...splitSize && { width: splitSize[0], height: splitSize[1] },\n ...seed != null && { seed },\n ...(_e = providerOptions.deepinfra) != null ? _e : {}\n },\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: deepInfraErrorSchema,\n errorToMessage: (error) => error.detail.error\n }),\n successfulResponseHandler: createJsonResponseHandler(\n deepInfraImageResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n images: response.images.map(\n (image) => image.replace(/^data:image\\/\\w+;base64,/, \"\")\n ),\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders\n }\n };\n }\n getEditUrl() {\n const baseUrl = this.config.baseURL.replace(\"/inference\", \"/openai\");\n return `${baseUrl}/images/edits`;\n }\n};\nvar deepInfraErrorSchema = z.object({\n detail: z.object({\n error: z.string()\n })\n});\nvar deepInfraImageResponseSchema = z.object({\n images: z.array(z.string())\n});\nvar deepInfraEditErrorSchema = z.object({\n error: z.object({\n message: z.string()\n }).optional()\n});\nvar deepInfraEditResponseSchema = z.object({\n data: z.array(z.object({ b64_json: z.string() }))\n});\nasync function fileToBlob(file) {\n if (file.type === \"url\") {\n return downloadBlob(file.url);\n }\n const data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array(file.data);\n return new Blob([data], { type: file.mediaType });\n}\n\n// src/deepinfra-chat-language-model.ts\nimport { OpenAICompatibleChatLanguageModel } from \"@ai-sdk/openai-compatible\";\nvar DeepInfraChatLanguageModel = class extends OpenAICompatibleChatLanguageModel {\n constructor(modelId, config) {\n super(modelId, config);\n }\n /**\n * Fixes incorrect token usage for Gemini/Gemma models from DeepInfra.\n *\n * DeepInfra's API returns completion_tokens that don't include reasoning_tokens\n * for Gemini/Gemma models, which violates the OpenAI-compatible spec.\n * According to the spec, completion_tokens should include reasoning_tokens.\n *\n * Example of incorrect data from DeepInfra:\n * {\n * \"completion_tokens\": 84, // text-only tokens\n * \"completion_tokens_details\": {\n * \"reasoning_tokens\": 1081 // reasoning tokens not included above\n * }\n * }\n *\n * This would result in negative text tokens: 84 - 1081 = -997\n *\n * The fix: If reasoning_tokens > completion_tokens, add reasoning_tokens\n * to completion_tokens: 84 + 1081 = 1165\n */\n fixUsageForGeminiModels(usage) {\n var _a, _b;\n if (!usage || !((_a = usage.completion_tokens_details) == null ? void 0 : _a.reasoning_tokens)) {\n return usage;\n }\n const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;\n const reasoningTokens = usage.completion_tokens_details.reasoning_tokens;\n if (reasoningTokens > completionTokens) {\n const correctedCompletionTokens = completionTokens + reasoningTokens;\n return {\n ...usage,\n // Add reasoning_tokens to completion_tokens to get the correct total\n completion_tokens: correctedCompletionTokens,\n // Update total_tokens if present\n total_tokens: usage.total_tokens != null ? usage.total_tokens + reasoningTokens : void 0\n };\n }\n return usage;\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g;\n const result = await super.doGenerate(options);\n if ((_a = result.usage) == null ? void 0 : _a.raw) {\n const fixedRawUsage = this.fixUsageForGeminiModels(result.usage.raw);\n if (fixedRawUsage !== result.usage.raw) {\n const promptTokens = (_b = fixedRawUsage.prompt_tokens) != null ? _b : 0;\n const completionTokens = (_c = fixedRawUsage.completion_tokens) != null ? _c : 0;\n const cacheReadTokens = (_e = (_d = fixedRawUsage.prompt_tokens_details) == null ? void 0 : _d.cached_tokens) != null ? _e : 0;\n const reasoningTokens = (_g = (_f = fixedRawUsage.completion_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : 0;\n return {\n ...result,\n usage: {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens - reasoningTokens,\n reasoning: reasoningTokens\n },\n raw: fixedRawUsage\n }\n };\n }\n }\n return result;\n }\n async doStream(options) {\n const result = await super.doStream(options);\n const originalStream = result.stream;\n const fixUsage = this.fixUsageForGeminiModels.bind(this);\n const transformedStream = new ReadableStream({\n async start(controller) {\n var _a, _b, _c, _d, _e, _f, _g;\n const reader = originalStream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value.type === \"finish\" && ((_a = value.usage) == null ? void 0 : _a.raw)) {\n const fixedRawUsage = fixUsage(value.usage.raw);\n if (fixedRawUsage !== value.usage.raw) {\n const promptTokens = (_b = fixedRawUsage.prompt_tokens) != null ? _b : 0;\n const completionTokens = (_c = fixedRawUsage.completion_tokens) != null ? _c : 0;\n const cacheReadTokens = (_e = (_d = fixedRawUsage.prompt_tokens_details) == null ? void 0 : _d.cached_tokens) != null ? _e : 0;\n const reasoningTokens = (_g = (_f = fixedRawUsage.completion_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : 0;\n controller.enqueue({\n ...value,\n usage: {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens - reasoningTokens,\n reasoning: reasoningTokens\n },\n raw: fixedRawUsage\n }\n });\n } else {\n controller.enqueue(value);\n }\n } else {\n controller.enqueue(value);\n }\n }\n controller.close();\n } catch (error) {\n controller.error(error);\n }\n }\n });\n return {\n ...result,\n stream: transformedStream\n };\n }\n};\n\n// src/version.ts\nvar VERSION = true ? \"2.0.41\" : \"0.0.0-test\";\n\n// src/deepinfra-provider.ts\nfunction createDeepInfra(options = {}) {\n var _a;\n const baseURL = withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.deepinfra.com/v1\"\n );\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"DEEPINFRA_API_KEY\",\n description: \"DeepInfra's API key\"\n })}`,\n ...options.headers\n },\n `ai-sdk/deepinfra/${VERSION}`\n );\n const getCommonModelConfig = (modelType) => ({\n provider: `deepinfra.${modelType}`,\n url: ({ path }) => `${baseURL}/openai${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createChatModel = (modelId) => {\n return new DeepInfraChatLanguageModel(\n modelId,\n getCommonModelConfig(\"chat\")\n );\n };\n const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(\n modelId,\n getCommonModelConfig(\"completion\")\n );\n const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(\n modelId,\n getCommonModelConfig(\"embedding\")\n );\n const createImageModel = (modelId) => new DeepInfraImageModel(modelId, {\n ...getCommonModelConfig(\"image\"),\n baseURL: baseURL ? `${baseURL}/inference` : \"https://api.deepinfra.com/v1/inference\"\n });\n const provider = (modelId) => createChatModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.completionModel = createCompletionModel;\n provider.chatModel = createChatModel;\n provider.image = createImageModel;\n provider.imageModel = createImageModel;\n provider.languageModel = createChatModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n return provider;\n}\nvar deepinfra = createDeepInfra();\nexport {\n VERSION,\n createDeepInfra,\n deepinfra\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";4ZAuBA,SAAI,OAAsB,UAAM,MAC9B,gBAAW,MAAC,OAAS,EAAQ,CAC3B,KAAK,QAAU,EACf,KAAK,OAAS,EACd,KAAK,qBAAuB,KAC5B,KAAK,iBAAmB,KAEtB,SAAQ,EAAG,CACb,OAAO,KAAK,OAAO,cAEf,WAAU,EACd,SACA,IACA,OACA,cACA,OACA,kBACA,UACA,cACA,QACA,QACC,CACD,IAAI,EAAI,EAAI,EAAI,EAAI,EACpB,IAAM,EAAW,CAAC,EACZ,GAAe,GAAM,GAAM,EAAK,KAAK,OAAO,YAAc,KAAY,OAAI,EAAG,cAAgB,KAAY,OAAI,EAAG,KAAK,CAAE,IAAM,KAAO,EAAqB,IAAI,KACnK,GAAI,GAAS,MAAQ,EAAM,OAAS,EAAG,CACrC,IAAQ,MAAO,EAAW,gBAAiB,GAAqB,MAAM,EAAkB,CACtF,IAAK,KAAK,WAAW,EACrB,QAA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,IAClE,EAAqB,OAAO,EAC/B,QAAS,EAAU,GAAG,cAAsB,wCAC9C,CAAC,EACK,EAAW,CAAC,IAAY,EAAgB,CAAO,EASrD,OARA,EAAS,qBAAuB,KAChC,EAAS,gBAAkB,EAC3B,EAAS,UAAY,EACrB,EAAS,MAAQ,EACjB,EAAS,WAAa,EACtB,EAAS,cAAgB,EACzB,EAAS,eAAiB,EAC1B,EAAS,mBAAqB,EACvB,EAET,IAAI,GAAY,EAAgB", | ||
| "debugId": "62827775947AE6A164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.list,\n Effect.fn(\"cli.plugin.list\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.plugin.list({ location: { directory: process.cwd() } }))\n const plugins = response.data.toSorted((a, b) => a.id.localeCompare(b.id))\n if (plugins.length === 0) {\n process.stdout.write(\"No plugins loaded\" + EOL)\n return\n }\n process.stdout.write(plugins.map((plugin) => plugin.id).join(EOL) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";83BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,YAAO,cAAS,UAClC,OAAO,QAAG,sBAAiB,OAAE,cAAU,OAAG,MACxC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAClF,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzE,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,oBAAsB,CAAG,EAC9C,OAEF,QAAQ,OAAO,MAAM,EAAQ,IAAI,CAAC,IAAW,EAAO,EAAE,EAAE,KAAK,CAAG,EAAI,CAAG,EACxE,CACH", | ||
| "debugId": "A98FFAF5C52FCEBD64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/anthropic-messages.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route } from \"../route/client\"\nimport { Auth } from \"../route/auth\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Framing } from \"../route/framing\"\nimport { Protocol } from \"../route/protocol\"\nimport {\n LLMError,\n LLMEvent,\n Usage,\n type CacheHint,\n type FinishReason,\n type JsonSchema,\n type LLMRequest,\n type MediaPart,\n type ProviderMetadata,\n type ToolCallPart,\n type ToolDefinition,\n type ToolContent,\n type ToolResultPart,\n} from \"../schema\"\nimport { JsonObject, optionalArray, optionalNull, ProviderShared } from \"./shared\"\nimport { classifyProviderFailure } from \"../provider-error\"\nimport * as Cache from \"./utils/cache\"\nimport { Lifecycle } from \"./utils/lifecycle\"\nimport { ToolSchemaProjection } from \"./utils/tool-schema\"\nimport { ToolStream } from \"./utils/tool-stream\"\n\nconst ADAPTER = \"anthropic-messages\"\nexport const DEFAULT_BASE_URL = \"https://api.anthropic.com/v1\"\nexport const PATH = \"/messages\"\n\n// =============================================================================\n// Request Body Schema\n// =============================================================================\nconst AnthropicCacheControl = Schema.Struct({\n type: Schema.tag(\"ephemeral\"),\n ttl: Schema.optional(Schema.Literals([\"5m\", \"1h\"])),\n})\n\nconst AnthropicTextBlock = Schema.Struct({\n type: Schema.tag(\"text\"),\n text: Schema.String,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicTextBlock = Schema.Schema.Type<typeof AnthropicTextBlock>\n\nconst AnthropicImageBlock = Schema.Struct({\n type: Schema.tag(\"image\"),\n source: Schema.Struct({\n type: Schema.tag(\"base64\"),\n media_type: Schema.String,\n data: Schema.String,\n }),\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicImageBlock = Schema.Schema.Type<typeof AnthropicImageBlock>\n\nconst AnthropicThinkingBlock = Schema.Struct({\n type: Schema.tag(\"thinking\"),\n thinking: Schema.String,\n signature: Schema.optional(Schema.String),\n cache_control: Schema.optional(AnthropicCacheControl),\n})\n\nconst AnthropicToolUseBlock = Schema.Struct({\n type: Schema.tag(\"tool_use\"),\n id: Schema.String,\n name: Schema.String,\n input: Schema.Unknown,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicToolUseBlock = Schema.Schema.Type<typeof AnthropicToolUseBlock>\n\nconst AnthropicServerToolUseBlock = Schema.Struct({\n type: Schema.tag(\"server_tool_use\"),\n id: Schema.String,\n name: Schema.String,\n input: Schema.Unknown,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicServerToolUseBlock = Schema.Schema.Type<typeof AnthropicServerToolUseBlock>\n\n// Server tool result blocks: web_search_tool_result, code_execution_tool_result,\n// and web_fetch_tool_result. The provider executes the tool and inlines the\n// structured result into the assistant turn — there is no client tool_result\n// round-trip. We round-trip the structured `content` payload as opaque JSON so\n// the next request can echo it back when continuing the conversation.\nconst AnthropicServerToolResultType = Schema.Literals([\n \"web_search_tool_result\",\n \"code_execution_tool_result\",\n \"web_fetch_tool_result\",\n])\ntype AnthropicServerToolResultType = Schema.Schema.Type<typeof AnthropicServerToolResultType>\n\nconst AnthropicServerToolResultBlock = Schema.Struct({\n type: AnthropicServerToolResultType,\n tool_use_id: Schema.String,\n content: Schema.Unknown,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicServerToolResultBlock = Schema.Schema.Type<typeof AnthropicServerToolResultBlock>\n\n// Anthropic accepts either a plain string or an ordered array of text/image\n// blocks inside `tool_result.content`. The array form is required when a tool\n// returns image bytes (screenshot, image search, etc.) so they can be passed\n// to the model as proper image inputs instead of being JSON-stringified into\n// the prompt — which silently inflates context by megabytes and can push the\n// conversation over the model's token limit.\nconst AnthropicToolResultContent = Schema.Union([AnthropicTextBlock, AnthropicImageBlock])\n\nconst AnthropicToolResultBlock = Schema.Struct({\n type: Schema.tag(\"tool_result\"),\n tool_use_id: Schema.String,\n content: Schema.Union([Schema.String, Schema.Array(AnthropicToolResultContent)]),\n is_error: Schema.optional(Schema.Boolean),\n cache_control: Schema.optional(AnthropicCacheControl),\n})\n\nconst AnthropicUserBlock = Schema.Union([AnthropicTextBlock, AnthropicImageBlock, AnthropicToolResultBlock])\ntype AnthropicUserBlock = Schema.Schema.Type<typeof AnthropicUserBlock>\nconst AnthropicAssistantBlock = Schema.Union([\n AnthropicTextBlock,\n AnthropicThinkingBlock,\n AnthropicToolUseBlock,\n AnthropicServerToolUseBlock,\n AnthropicServerToolResultBlock,\n])\ntype AnthropicAssistantBlock = Schema.Schema.Type<typeof AnthropicAssistantBlock>\ntype AnthropicToolResultBlock = Schema.Schema.Type<typeof AnthropicToolResultBlock>\n\nconst AnthropicMessage = Schema.Union([\n Schema.Struct({ role: Schema.Literal(\"user\"), content: Schema.Array(AnthropicUserBlock) }),\n Schema.Struct({ role: Schema.Literal(\"assistant\"), content: Schema.Array(AnthropicAssistantBlock) }),\n Schema.Struct({ role: Schema.Literal(\"system\"), content: Schema.Array(AnthropicTextBlock) }),\n]).pipe(Schema.toTaggedUnion(\"role\"))\ntype AnthropicMessage = Schema.Schema.Type<typeof AnthropicMessage>\n\nconst AnthropicTool = Schema.Struct({\n name: Schema.String,\n description: Schema.String,\n input_schema: JsonObject,\n cache_control: Schema.optional(AnthropicCacheControl),\n})\ntype AnthropicTool = Schema.Schema.Type<typeof AnthropicTool>\n\nconst AnthropicToolChoice = Schema.Union([\n Schema.Struct({ type: Schema.Literals([\"auto\", \"any\"]) }),\n Schema.Struct({ type: Schema.tag(\"tool\"), name: Schema.String }),\n])\n\nconst AnthropicThinking = Schema.Union([\n Schema.Struct({\n type: Schema.tag(\"enabled\"),\n budget_tokens: Schema.Number,\n }),\n Schema.Struct({\n type: Schema.tag(\"adaptive\"),\n display: Schema.optional(Schema.Literals([\"summarized\", \"omitted\"])),\n }),\n Schema.Struct({\n type: Schema.tag(\"disabled\"),\n }),\n])\n\nconst AnthropicOutputConfig = Schema.Struct({\n effort: Schema.optional(Schema.String),\n})\n\nconst AnthropicBodyFields = {\n model: Schema.String,\n system: optionalArray(AnthropicTextBlock),\n messages: Schema.Array(AnthropicMessage),\n tools: optionalArray(AnthropicTool),\n tool_choice: Schema.optional(AnthropicToolChoice),\n stream: Schema.Literal(true),\n max_tokens: Schema.Number,\n temperature: Schema.optional(Schema.Number),\n top_p: Schema.optional(Schema.Number),\n top_k: Schema.optional(Schema.Number),\n stop_sequences: optionalArray(Schema.String),\n thinking: Schema.optional(AnthropicThinking),\n output_config: Schema.optional(AnthropicOutputConfig),\n}\nexport const AnthropicMessagesBody = Schema.Struct(AnthropicBodyFields)\nexport type AnthropicMessagesBody = Schema.Schema.Type<typeof AnthropicMessagesBody>\n\nconst AnthropicUsage = Schema.Struct({\n input_tokens: Schema.optional(Schema.Number),\n output_tokens: Schema.optional(Schema.Number),\n cache_creation_input_tokens: optionalNull(Schema.Number),\n cache_read_input_tokens: optionalNull(Schema.Number),\n})\ntype AnthropicUsage = Schema.Schema.Type<typeof AnthropicUsage>\n\nconst AnthropicStreamBlock = Schema.Struct({\n type: Schema.String,\n id: Schema.optional(Schema.String),\n name: Schema.optional(Schema.String),\n text: Schema.optional(Schema.String),\n thinking: Schema.optional(Schema.String),\n signature: Schema.optional(Schema.String),\n input: Schema.optional(Schema.Unknown),\n // *_tool_result blocks arrive whole as content_block_start (no streaming\n // delta) with the structured payload in `content` and the originating\n // server_tool_use id in `tool_use_id`.\n tool_use_id: Schema.optional(Schema.String),\n content: Schema.optional(Schema.Unknown),\n})\n\nconst AnthropicStreamDelta = Schema.Struct({\n type: Schema.optional(Schema.String),\n text: Schema.optional(Schema.String),\n thinking: Schema.optional(Schema.String),\n partial_json: Schema.optional(Schema.String),\n signature: Schema.optional(Schema.String),\n stop_reason: optionalNull(Schema.String),\n stop_sequence: optionalNull(Schema.String),\n})\n\nconst AnthropicEvent = Schema.Struct({\n type: Schema.String,\n index: Schema.optional(Schema.Number),\n message: Schema.optional(Schema.Struct({ usage: Schema.optional(AnthropicUsage) })),\n content_block: Schema.optional(AnthropicStreamBlock),\n delta: Schema.optional(AnthropicStreamDelta),\n usage: Schema.optional(AnthropicUsage),\n // `type` and `message` are both required per Anthropic's spec, but\n // OpenAI-compatible proxies and gateway translations occasionally drop one\n // or the other; mark them optional so a partial payload still parses and\n // the parser can fall back to whichever field is populated.\n error: Schema.optional(\n Schema.Struct({ type: Schema.optional(Schema.String), message: Schema.optional(Schema.String) }),\n ),\n})\ntype AnthropicEvent = Schema.Schema.Type<typeof AnthropicEvent>\n\ninterface ParserState {\n readonly tools: ToolStream.State<number>\n readonly usage?: Usage\n readonly lifecycle: Lifecycle.State\n}\n\nconst invalid = ProviderShared.invalidRequest\n\n// =============================================================================\n// Request Lowering\n// =============================================================================\n// Anthropic accepts at most 4 explicit cache_control breakpoints per request,\n// across `tools`, `system`, and `messages`. Beyond the cap the API returns a\n// 400 — so the lowering layer counts emitted markers and silently drops any\n// that exceed it.\nconst ANTHROPIC_BREAKPOINT_CAP = 4\n\nconst EPHEMERAL_5M = { type: \"ephemeral\" as const }\nconst EPHEMERAL_1H = { type: \"ephemeral\" as const, ttl: \"1h\" as const }\n\nconst cacheControl = (breakpoints: Cache.Breakpoints, cache: CacheHint | undefined) => {\n if (cache?.type !== \"ephemeral\" && cache?.type !== \"persistent\") return undefined\n if (breakpoints.remaining <= 0) {\n breakpoints.dropped += 1\n return undefined\n }\n breakpoints.remaining -= 1\n return Cache.ttlBucket(cache.ttlSeconds) === \"1h\" ? EPHEMERAL_1H : EPHEMERAL_5M\n}\n\nconst anthropicMetadata = (metadata: Record<string, unknown>): ProviderMetadata => ({ anthropic: metadata })\n\nconst signatureFromMetadata = (metadata: ProviderMetadata | undefined): string | undefined => {\n const anthropic = metadata?.anthropic\n if (!ProviderShared.isRecord(anthropic)) return undefined\n return typeof anthropic.signature === \"string\" ? anthropic.signature : undefined\n}\n\nconst lowerTool = (breakpoints: Cache.Breakpoints, tool: ToolDefinition, inputSchema: JsonSchema): AnthropicTool => ({\n name: tool.name,\n description: tool.description,\n input_schema: inputSchema,\n cache_control: cacheControl(breakpoints, tool.cache),\n})\n\nconst lowerToolChoice = (toolChoice: NonNullable<LLMRequest[\"toolChoice\"]>) =>\n ProviderShared.matchToolChoice(\"Anthropic Messages\", toolChoice, {\n auto: () => ({ type: \"auto\" as const }),\n none: () => undefined,\n required: () => ({ type: \"any\" as const }),\n tool: (name) => ({ type: \"tool\" as const, name }),\n })\n\nconst lowerToolCall = (part: ToolCallPart): AnthropicToolUseBlock => ({\n type: \"tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n})\n\nconst lowerServerToolCall = (part: ToolCallPart): AnthropicServerToolUseBlock => ({\n type: \"server_tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n})\n\n// Server tool result blocks are typed by name. Anthropic ships three today;\n// extend this list when new server tools land. The block content is the\n// structured payload returned by the provider, which we round-trip as-is.\nconst serverToolResultType = (name: string): AnthropicServerToolResultType | undefined => {\n if (name === \"web_search\") return \"web_search_tool_result\"\n if (name === \"code_execution\") return \"code_execution_tool_result\"\n if (name === \"web_fetch\") return \"web_fetch_tool_result\"\n return undefined\n}\n\nconst lowerServerToolResult = Effect.fn(\"AnthropicMessages.lowerServerToolResult\")(function* (part: ToolResultPart) {\n const wireType = serverToolResultType(part.name)\n if (!wireType)\n return yield* invalid(`Anthropic Messages does not know how to round-trip server tool result for ${part.name}`)\n return { type: wireType, tool_use_id: part.id, content: part.result.value } satisfies AnthropicServerToolResultBlock\n})\n\nconst lowerImage = Effect.fn(\"AnthropicMessages.lowerImage\")(function* (part: MediaPart) {\n const media = yield* ProviderShared.validateMedia(\n \"Anthropic Messages\",\n part,\n new Set<string>(ProviderShared.IMAGE_MIMES),\n )\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: media.mime,\n data: media.base64,\n },\n } satisfies AnthropicImageBlock\n})\n\n// Tool results may carry structured text/images. Keep media as provider-native\n// content instead of JSON-stringifying base64 into a prompt string.\nconst lowerToolResultContentItem = Effect.fn(\"AnthropicMessages.lowerToolResultContentItem\")(function* (\n item: ToolContent,\n) {\n if (item.type === \"text\") return { type: \"text\" as const, text: item.text } satisfies AnthropicTextBlock\n const media = yield* ProviderShared.validateToolFile(\n \"Anthropic Messages\",\n item,\n new Set<string>(ProviderShared.IMAGE_MIMES),\n )\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: media.mime,\n data: media.base64,\n },\n } satisfies AnthropicImageBlock\n})\n\nconst lowerToolResultContent = Effect.fn(\"AnthropicMessages.lowerToolResultContent\")(function* (part: ToolResultPart) {\n // Text / json / error results stay as a string for backward compatibility\n // with existing cassettes and provider expectations.\n if (part.result.type !== \"content\") return ProviderShared.toolResultText(part)\n // Preserve the narrowed array element type when compiled through a consumer package.\n const content: ReadonlyArray<ToolContent> = part.result.value\n return yield* Effect.forEach(content, lowerToolResultContentItem)\n})\n\n// Mid-conversation system messages are a native Claude API feature only for\n// Opus 4.8. Other Anthropic models intentionally use the same visible wrapped-\n// user fallback as non-Anthropic routes rather than sending a role they reject.\nconst supportsNativeSystemUpdates = (request: LLMRequest) => String(request.model.id) === \"claude-opus-4-8\"\n\nconst endsInServerToolUse = (message: LLMRequest[\"messages\"][number]) => {\n const last = message.content.at(-1)\n return message.role === \"assistant\" && last?.type === \"tool-call\" && last.providerExecuted === true\n}\n\nconst canUseNativeSystemUpdate = (messages: LLMRequest[\"messages\"], index: number) => {\n const previous = messages[index - 1]\n const next = messages[index + 1]\n return (\n previous !== undefined &&\n previous.role !== \"system\" &&\n (previous.role === \"user\" || previous.role === \"tool\" || endsInServerToolUse(previous)) &&\n next?.role !== \"system\" &&\n (next === undefined || next.role === \"assistant\")\n )\n}\n\nconst splitsLocalToolResults = (messages: LLMRequest[\"messages\"], index: number) => {\n const pending = new Set<string>()\n for (const message of messages.slice(0, index)) {\n for (const part of message.content) {\n if (message.role === \"assistant\" && part.type === \"tool-call\" && part.providerExecuted !== true)\n pending.add(part.id)\n if (message.role === \"tool\" && part.type === \"tool-result\") pending.delete(part.id)\n }\n }\n return pending.size > 0\n}\n\nconst lowerNativeSystemUpdate = Effect.fn(\"AnthropicMessages.lowerNativeSystemUpdate\")(function* (\n message: LLMRequest[\"messages\"][number],\n breakpoints: Cache.Breakpoints,\n) {\n const content = yield* ProviderShared.systemUpdateText(\"Anthropic Messages\", message)\n return {\n role: \"system\" as const,\n content: content.map((part) => ({\n type: \"text\" as const,\n text: part.text,\n cache_control: cacheControl(breakpoints, part.cache),\n })),\n }\n})\n\nconst lowerMessages = Effect.fn(\"AnthropicMessages.lowerMessages\")(function* (\n request: LLMRequest,\n breakpoints: Cache.Breakpoints,\n) {\n const messages: AnthropicMessage[] = []\n\n for (const [index, message] of request.messages.entries()) {\n if (message.role === \"system\") {\n if (splitsLocalToolResults(request.messages, index))\n return yield* invalid(\"Anthropic Messages system updates cannot split a local tool call from its tool result\")\n if (supportsNativeSystemUpdates(request) && canUseNativeSystemUpdate(request.messages, index)) {\n messages.push(yield* lowerNativeSystemUpdate(message, breakpoints))\n continue\n }\n const part = yield* ProviderShared.wrappedSystemUpdate(\"Anthropic Messages\", message)\n const block = { type: \"text\" as const, text: part.text, cache_control: cacheControl(breakpoints, part.cache) }\n const previous = messages.at(-1)\n if (previous?.role === \"user\")\n messages[messages.length - 1] = { role: \"user\", content: [...previous.content, block] }\n else messages.push({ role: \"user\", content: [block] })\n continue\n }\n\n if (message.role === \"user\") {\n const content: AnthropicUserBlock[] = []\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"text\", text: part.text, cache_control: cacheControl(breakpoints, part.cache) })\n continue\n }\n if (part.type === \"media\") {\n content.push(yield* lowerImage(part))\n continue\n }\n return yield* ProviderShared.unsupportedContent(\"Anthropic Messages\", \"user\", [\"text\", \"media\"])\n }\n messages.push({ role: \"user\", content })\n continue\n }\n\n if (message.role === \"assistant\") {\n const content: AnthropicAssistantBlock[] = []\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"text\", text: part.text, cache_control: cacheControl(breakpoints, part.cache) })\n continue\n }\n if (part.type === \"reasoning\") {\n content.push({\n type: \"thinking\",\n thinking: part.text,\n signature: part.encrypted ?? signatureFromMetadata(part.providerMetadata),\n })\n continue\n }\n if (part.type === \"tool-call\") {\n content.push(part.providerExecuted ? lowerServerToolCall(part) : lowerToolCall(part))\n continue\n }\n if (part.type === \"tool-result\" && part.providerExecuted) {\n content.push(yield* lowerServerToolResult(part))\n continue\n }\n return yield* invalid(\n `Anthropic Messages assistant messages only support text, reasoning, and tool-call content for now`,\n )\n }\n messages.push({ role: \"assistant\", content })\n continue\n }\n\n const content: AnthropicToolResultBlock[] = []\n for (const part of message.content) {\n if (!ProviderShared.supportsContent(part, [\"tool-result\"]))\n return yield* ProviderShared.unsupportedContent(\"Anthropic Messages\", \"tool\", [\"tool-result\"])\n content.push({\n type: \"tool_result\",\n tool_use_id: part.id,\n content: yield* lowerToolResultContent(part),\n is_error: part.result.type === \"error\" ? true : undefined,\n cache_control: cacheControl(breakpoints, part.cache),\n })\n }\n messages.push({ role: \"user\", content })\n }\n\n return messages\n})\n\nconst anthropicOptions = (request: LLMRequest) => request.providerOptions?.anthropic\n\nconst lowerThinking = Effect.fn(\"AnthropicMessages.lowerThinking\")(function* (request: LLMRequest) {\n const thinking = anthropicOptions(request)?.thinking\n if (!ProviderShared.isRecord(thinking)) return undefined\n if (thinking.type === \"adaptive\") {\n const display =\n thinking.display === \"summarized\"\n ? (\"summarized\" as const)\n : thinking.display === \"omitted\"\n ? (\"omitted\" as const)\n : undefined\n return { type: \"adaptive\" as const, ...(display === undefined ? {} : { display }) }\n }\n if (thinking.type === \"disabled\") return { type: \"disabled\" as const }\n if (thinking.type !== \"enabled\") return undefined\n const budget =\n typeof thinking.budgetTokens === \"number\"\n ? thinking.budgetTokens\n : typeof thinking.budget_tokens === \"number\"\n ? thinking.budget_tokens\n : undefined\n if (budget === undefined) return yield* invalid(\"Anthropic thinking provider option requires budgetTokens\")\n return { type: \"enabled\" as const, budget_tokens: budget }\n})\n\nconst outputConfig = (request: LLMRequest) => {\n const effort = anthropicOptions(request)?.effort\n return typeof effort === \"string\" ? { effort } : undefined\n}\n\nconst fromRequest = Effect.fn(\"AnthropicMessages.fromRequest\")(function* (request: LLMRequest) {\n const toolChoice = request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined\n const generation = request.generation\n const toolSchemaCompatibility = request.model.compatibility?.toolSchema\n const outputLimit = request.model.defaults?.limits?.output ?? request.model.route.defaults.limits?.output ?? 4096\n // Allocate the 4-breakpoint budget in invalidation order: tools → system →\n // messages. Tools live highest in the cache hierarchy, so when callers\n // over-mark we keep their tool hints and shed the message-tail ones first.\n const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP)\n const tools =\n request.tools.length === 0 || request.toolChoice?.type === \"none\"\n ? undefined\n : request.tools.map((tool) =>\n lowerTool(\n breakpoints,\n tool,\n ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility),\n ),\n )\n const system =\n request.system.length === 0\n ? undefined\n : request.system.map((part) => ({\n type: \"text\" as const,\n text: part.text,\n cache_control: cacheControl(breakpoints, part.cache),\n }))\n const messages = yield* lowerMessages(request, breakpoints)\n if (breakpoints.dropped > 0) {\n yield* Effect.logWarning(\n `Anthropic Messages: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${ANTHROPIC_BREAKPOINT_CAP} per request.`,\n )\n }\n return {\n model: request.model.id,\n system,\n messages,\n tools,\n tool_choice: toolChoice,\n stream: true as const,\n max_tokens: generation?.maxTokens ?? outputLimit,\n temperature: generation?.temperature,\n top_p: generation?.topP,\n top_k: generation?.topK,\n stop_sequences: generation?.stop,\n thinking: yield* lowerThinking(request),\n output_config: outputConfig(request),\n }\n})\n\n// =============================================================================\n// Stream Parsing\n// =============================================================================\nconst mapFinishReason = (reason: string | null | undefined): FinishReason => {\n if (reason === \"end_turn\" || reason === \"stop_sequence\" || reason === \"pause_turn\") return \"stop\"\n if (reason === \"max_tokens\") return \"length\"\n if (reason === \"tool_use\") return \"tool-calls\"\n if (reason === \"refusal\") return \"content-filter\"\n return \"unknown\"\n}\n\n// Anthropic reports the non-overlapping breakdown natively — its\n// `input_tokens` is the *non-cached* count per the Messages API docs, with\n// cache reads and writes as separate fields. We sum them to derive the\n// inclusive `inputTokens` the rest of the contract expects. Extended\n// thinking tokens are *not* broken out by Anthropic — they're billed as\n// part of `output_tokens`, so `reasoningTokens` stays `undefined` and\n// `outputTokens` carries the combined total.\nconst mapUsage = (usage: AnthropicUsage | undefined): Usage | undefined => {\n if (!usage) return undefined\n const nonCached = usage.input_tokens\n const cacheRead = usage.cache_read_input_tokens ?? undefined\n const cacheWrite = usage.cache_creation_input_tokens ?? undefined\n const inputTokens = ProviderShared.sumTokens(nonCached, cacheRead, cacheWrite)\n return new Usage({\n inputTokens,\n outputTokens: usage.output_tokens,\n nonCachedInputTokens: nonCached,\n cacheReadInputTokens: cacheRead,\n cacheWriteInputTokens: cacheWrite,\n totalTokens: ProviderShared.totalTokens(inputTokens, usage.output_tokens, undefined),\n providerMetadata: { anthropic: usage },\n })\n}\n\n// Anthropic emits usage on `message_start` and again on `message_delta` — the\n// final delta carries the authoritative totals. Right-biased merge: each\n// field prefers `right` when defined, falls back to `left`. `inputTokens` is\n// recomputed from the merged breakdown so the inclusive total stays\n// consistent with `nonCached + cacheRead + cacheWrite`.\nconst mergeUsage = (left: Usage | undefined, right: Usage | undefined) => {\n if (!left) return right\n if (!right) return left\n const nonCachedInputTokens = right.nonCachedInputTokens ?? left.nonCachedInputTokens\n const cacheReadInputTokens = right.cacheReadInputTokens ?? left.cacheReadInputTokens\n const cacheWriteInputTokens = right.cacheWriteInputTokens ?? left.cacheWriteInputTokens\n const inputTokens = ProviderShared.sumTokens(nonCachedInputTokens, cacheReadInputTokens, cacheWriteInputTokens)\n const outputTokens = right.outputTokens ?? left.outputTokens\n return new Usage({\n inputTokens,\n outputTokens,\n nonCachedInputTokens,\n cacheReadInputTokens,\n cacheWriteInputTokens,\n totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),\n providerMetadata: {\n anthropic: {\n ...left.providerMetadata?.[\"anthropic\"],\n ...right.providerMetadata?.[\"anthropic\"],\n },\n },\n })\n}\n\n// Server tool result blocks come whole in `content_block_start` (no streaming\n// delta sequence). We convert the payload to a `tool-result` event with\n// `providerExecuted: true`. The runtime appends it to the assistant message\n// for round-trip; downstream consumers can inspect `result.value` for the\n// structured payload.\nconst SERVER_TOOL_RESULT_NAMES: Record<AnthropicServerToolResultType, string> = {\n web_search_tool_result: \"web_search\",\n code_execution_tool_result: \"code_execution\",\n web_fetch_tool_result: \"web_fetch\",\n}\n\nconst isServerToolResultType = (type: string): type is AnthropicServerToolResultType => type in SERVER_TOOL_RESULT_NAMES\n\nconst serverToolResultEvent = (block: NonNullable<AnthropicEvent[\"content_block\"]>): LLMEvent | undefined => {\n if (!block.type || !isServerToolResultType(block.type)) return undefined\n const errorPayload =\n typeof block.content === \"object\" && block.content !== null && \"type\" in block.content\n ? String((block.content as Record<string, unknown>).type)\n : \"\"\n const isError = errorPayload.endsWith(\"_tool_result_error\")\n return LLMEvent.toolResult({\n id: block.tool_use_id ?? \"\",\n name: SERVER_TOOL_RESULT_NAMES[block.type],\n result: isError ? { type: \"error\", value: block.content } : { type: \"json\", value: block.content },\n providerExecuted: true,\n providerMetadata: anthropicMetadata({ blockType: block.type }),\n })\n}\n\ntype StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]\n\nconst NO_EVENTS: StepResult[\"1\"] = []\n\nconst onMessageStart = (state: ParserState, event: AnthropicEvent): StepResult => {\n const usage = mapUsage(event.message?.usage)\n return [usage ? { ...state, usage: mergeUsage(state.usage, usage) } : state, NO_EVENTS]\n}\n\nconst onContentBlockStart = (state: ParserState, event: AnthropicEvent): StepResult => {\n const block = event.content_block\n if (!block) return [state, NO_EVENTS]\n\n if ((block.type === \"tool_use\" || block.type === \"server_tool_use\") && event.index !== undefined) {\n const events: LLMEvent[] = []\n const lifecycle = Lifecycle.stepStart(state.lifecycle, events)\n return [\n {\n ...state,\n lifecycle,\n tools: ToolStream.start(state.tools, event.index, {\n id: block.id ?? String(event.index),\n name: block.name ?? \"\",\n providerExecuted: block.type === \"server_tool_use\",\n }),\n },\n [\n ...events,\n LLMEvent.toolInputStart({\n id: block.id ?? String(event.index),\n name: block.name ?? \"\",\n providerExecuted: block.type === \"server_tool_use\" ? true : undefined,\n }),\n ],\n ]\n }\n\n if (block.type === \"text\" && block.text) {\n const events: LLMEvent[] = []\n return [\n { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, `text-${event.index ?? 0}`, block.text) },\n events,\n ]\n }\n\n if (block.type === \"thinking\" && block.thinking) {\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${event.index ?? 0}`, block.thinking),\n },\n events,\n ]\n }\n\n const result = serverToolResultEvent(block)\n if (!result) return [state, NO_EVENTS]\n const events: LLMEvent[] = []\n return [{ ...state, lifecycle: Lifecycle.stepStart(state.lifecycle, events) }, [...events, result]]\n}\n\nconst onContentBlockDelta = Effect.fn(\"AnthropicMessages.onContentBlockDelta\")(function* (\n state: ParserState,\n event: AnthropicEvent,\n) {\n const delta = event.delta\n\n if (delta?.type === \"text_delta\" && delta.text) {\n const events: LLMEvent[] = []\n return [\n { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, `text-${event.index ?? 0}`, delta.text) },\n events,\n ] satisfies StepResult\n }\n\n if (delta?.type === \"thinking_delta\" && delta.thinking) {\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${event.index ?? 0}`, delta.thinking),\n },\n events,\n ] satisfies StepResult\n }\n\n if (delta?.type === \"signature_delta\" && delta.signature) {\n const events: LLMEvent[] = []\n return [\n {\n ...state,\n lifecycle: Lifecycle.reasoningEnd(\n state.lifecycle,\n events,\n `reasoning-${event.index ?? 0}`,\n anthropicMetadata({ signature: delta.signature }),\n ),\n },\n events,\n ] satisfies StepResult\n }\n\n if (delta?.type === \"input_json_delta\" && event.index !== undefined) {\n if (!delta.partial_json) return [state, NO_EVENTS] satisfies StepResult\n const result = ToolStream.appendExisting(\n ADAPTER,\n state.tools,\n event.index,\n delta.partial_json,\n \"Anthropic Messages tool argument delta is missing its tool call\",\n )\n if (ToolStream.isError(result)) return yield* result\n const events: LLMEvent[] = []\n const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle\n events.push(...result.events)\n return [{ ...state, lifecycle, tools: result.tools }, events] satisfies StepResult\n }\n\n return [state, NO_EVENTS] satisfies StepResult\n})\n\nconst onContentBlockStop = Effect.fn(\"AnthropicMessages.onContentBlockStop\")(function* (\n state: ParserState,\n event: AnthropicEvent,\n) {\n if (event.index === undefined) return [state, NO_EVENTS] satisfies StepResult\n const result = yield* ToolStream.finish(ADAPTER, state.tools, event.index)\n const events: LLMEvent[] = []\n const resultEvents = result.events ?? []\n const lifecycle = resultEvents.length\n ? Lifecycle.stepStart(state.lifecycle, events)\n : Lifecycle.reasoningEnd(\n Lifecycle.textEnd(state.lifecycle, events, `text-${event.index}`),\n events,\n `reasoning-${event.index}`,\n )\n events.push(...resultEvents)\n return [{ ...state, lifecycle, tools: result.tools }, events] satisfies StepResult\n})\n\nconst onMessageDelta = (state: ParserState, event: AnthropicEvent): StepResult => {\n const usage = mergeUsage(state.usage, mapUsage(event.usage))\n const events: LLMEvent[] = []\n const lifecycle = Lifecycle.finish(state.lifecycle, events, {\n reason: mapFinishReason(event.delta?.stop_reason),\n usage,\n providerMetadata: event.delta?.stop_sequence\n ? anthropicMetadata({ stopSequence: event.delta.stop_sequence })\n : undefined,\n })\n return [{ ...state, lifecycle, usage }, events]\n}\n\n// Prefix `error.type` so overloads, rate limits, and quota errors are visible\n// even when the provider message is generic or empty.\nconst providerErrorMessage = (event: AnthropicEvent): string => {\n const type = event.error?.type\n const message = event.error?.message\n if (type && message) return `${type}: ${message}`\n return message || type || \"Anthropic Messages stream error\"\n}\n\nconst onError = (event: AnthropicEvent) =>\n new LLMError({\n module: ADAPTER,\n method: \"stream\",\n reason: classifyProviderFailure({ message: providerErrorMessage(event), code: event.error?.type }),\n })\n\nconst step = (state: ParserState, event: AnthropicEvent) => {\n if (event.type === \"message_start\") return Effect.succeed(onMessageStart(state, event))\n if (event.type === \"content_block_start\") return Effect.succeed(onContentBlockStart(state, event))\n if (event.type === \"content_block_delta\") return onContentBlockDelta(state, event)\n if (event.type === \"content_block_stop\") return onContentBlockStop(state, event)\n if (event.type === \"message_delta\") return Effect.succeed(onMessageDelta(state, event))\n if (event.type === \"error\") return onError(event)\n return Effect.succeed<StepResult>([state, NO_EVENTS])\n}\n\n// =============================================================================\n// Protocol And Anthropic Route\n// =============================================================================\n/**\n * The Anthropic Messages protocol — request body construction, body schema,\n * and the streaming-event state machine. Used by native Anthropic Cloud and\n * (once registered) Vertex Anthropic / Bedrock-hosted Anthropic passthrough.\n */\nexport const protocol = Protocol.make({\n id: ADAPTER,\n body: {\n schema: AnthropicMessagesBody,\n from: fromRequest,\n },\n stream: {\n event: Protocol.jsonEvent(AnthropicEvent),\n initial: () => ({ tools: ToolStream.empty<number>(), lifecycle: Lifecycle.initial() }),\n step,\n },\n})\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: \"anthropic\",\n providerMetadataKey: \"anthropic\",\n protocol,\n endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),\n auth: Auth.none,\n framing: Framing.sse,\n headers: () => ({ \"anthropic-version\": \"2023-06-01\" }),\n})\n\nexport * as AnthropicMessages from \"./anthropic-messages\"\n" | ||
| ], | ||
| "mappings": ";kfA4BA,SAAM,OAAU,0BACH,OAAmB,+BACnB,EAAO,YAKd,EAAwB,EAAO,OAAO,CAC1C,KAAM,EAAO,IAAI,WAAW,EAC5B,IAAK,EAAO,SAAS,EAAO,SAAS,CAAC,KAAM,IAAI,CAAC,CAAC,CACpD,CAAC,EAEK,EAAqB,EAAO,OAAO,CACvC,KAAM,EAAO,IAAI,MAAM,EACvB,KAAM,EAAO,OACb,cAAe,EAAO,SAAS,CAAqB,CACtD,CAAC,EAGK,EAAsB,EAAO,OAAO,CACxC,KAAM,EAAO,IAAI,OAAO,EACxB,OAAQ,EAAO,OAAO,CACpB,KAAM,EAAO,IAAI,QAAQ,EACzB,WAAY,EAAO,OACnB,KAAM,EAAO,MACf,CAAC,EACD,cAAe,EAAO,SAAS,CAAqB,CACtD,CAAC,EAGK,EAAyB,EAAO,OAAO,CAC3C,KAAM,EAAO,IAAI,UAAU,EAC3B,SAAU,EAAO,OACjB,UAAW,EAAO,SAAS,EAAO,MAAM,EACxC,cAAe,EAAO,SAAS,CAAqB,CACtD,CAAC,EAEK,EAAwB,EAAO,OAAO,CAC1C,KAAM,EAAO,IAAI,UAAU,EAC3B,GAAI,EAAO,OACX,KAAM,EAAO,OACb,MAAO,EAAO,QACd,cAAe,EAAO,SAAS,CAAqB,CACtD,CAAC,EAGK,EAA8B,EAAO,OA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AAO,CAAK,EAC/E,GAAI,EAAM,OAAS,gBAAiB,OAAO,EAAO,QAAQ,GAAe,EAAO,CAAK,CAAC,EACtF,GAAI,EAAM,OAAS,QAAS,OAAO,GAAQ,CAAK,EAChD,OAAO,EAAO,QAAoB,CAAC,EAAO,CAAS,CAAC,GAWzC,EAAW,EAAS,KAAK,CACpC,GAAI,EACJ,KAAM,CACJ,OAAQ,EACR,KAAM,EACR,EACA,OAAQ,CACN,MAAO,EAAS,UAAU,EAAc,EACxC,QAAS,KAAO,CAAE,MAAO,EAAW,MAAc,EAAG,UAAW,EAAU,QAAQ,CAAE,GACpF,OACF,CACF,CAAC,EAEY,GAAQ,EAAM,KAAK,CAC9B,GAAI,EACJ,SAAU,YACV,oBAAqB,YACrB,WACA,SAAU,EAAS,KAAK,EAAM,CAAE,QAAS,CAAiB,CAAC,EAC3D,KAAM,EAAK,KACX,QAAS,EAAQ,IACjB,QAAS,KAAO,CAAE,oBAAqB,YAAa,EACtD,CAAC", | ||
| "debugId": "506541592F0D8D7C64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "7F5812F274797C0A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/protocols/xai-images.ts", "../ai/src/providers/xai.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Encoding, Schema } from \"effect\"\nimport { Headers, HttpClientRequest } from \"effect/unstable/http\"\nimport { GeneratedImage, ImageModel, ImageResponse, type ImageRequestFor, type ImageRoute } from \"../image\"\nimport { Auth, type Definition as AuthDefinition } from \"../route/auth\"\nimport {\n InvalidProviderOutputReason,\n LLMError,\n Usage,\n mergeHttpOptions,\n mergeJsonRecords,\n type HttpOptions,\n} from \"../schema\"\nimport { ProviderShared, optionalNull } from \"./shared\"\nimport { ImageInputs } from \"./utils/image-input\"\n\nconst ADAPTER = \"xai-images\"\nexport const DEFAULT_BASE_URL = \"https://api.x.ai/v1\"\nexport const PATH = \"/images/generations\"\nexport const EDIT_PATH = \"/images/edits\"\n\nexport type XAIImageString<Known extends string> = Known | (string & {})\n\nexport type XAIImageOptions = {\n readonly n?: number\n readonly aspectRatio?: XAIImageString<\n | \"1:1\"\n | \"3:4\"\n | \"4:3\"\n | \"9:16\"\n | \"16:9\"\n | \"2:3\"\n | \"3:2\"\n | \"9:19.5\"\n | \"19.5:9\"\n | \"9:20\"\n | \"20:9\"\n | \"1:2\"\n | \"2:1\"\n | \"auto\"\n >\n readonly aspect_ratio?: XAIImageString<\n | \"1:1\"\n | \"3:4\"\n | \"4:3\"\n | \"9:16\"\n | \"16:9\"\n | \"2:3\"\n | \"3:2\"\n | \"9:19.5\"\n | \"19.5:9\"\n | \"9:20\"\n | \"20:9\"\n | \"1:2\"\n | \"2:1\"\n | \"auto\"\n >\n readonly resolution?: XAIImageString<\"1k\" | \"2k\">\n readonly responseFormat?: XAIImageString<\"url\" | \"b64_json\">\n readonly response_format?: XAIImageString<\"url\" | \"b64_json\">\n} & Record<string, unknown>\n\ntype XAIImageBody = Record<string, unknown> & {\n readonly model: string\n readonly prompt: string\n}\n\nconst XAIImageResponse = Schema.Struct({\n data: Schema.Array(\n Schema.Struct({\n b64_json: optionalNull(Schema.String),\n url: optionalNull(Schema.String),\n revised_prompt: optionalNull(Schema.String),\n mime_type: optionalNull(Schema.String),\n }),\n ),\n usage: Schema.optional(Schema.Unknown),\n})\n\nexport interface ModelInput {\n readonly id: string\n readonly auth: AuthDefinition\n readonly baseURL?: string\n readonly headers?: Record<string, string>\n readonly http?: HttpOptions\n}\n\nconst nativeOptions = (options: XAIImageOptions | undefined) => {\n if (!options) return undefined\n const { aspectRatio, responseFormat, ...native } = options\n return {\n aspect_ratio: aspectRatio,\n response_format: responseFormat,\n ...native,\n }\n}\n\nconst invalidOutput = (message: string) =>\n new LLMError({\n module: ADAPTER,\n method: \"generate\",\n reason: new InvalidProviderOutputReason({ message, route: ADAPTER }),\n })\n\nconst applyQuery = (url: string, query: Record<string, string> | undefined) => {\n if (!query) return url\n const next = new URL(url)\n Object.entries(query).forEach(([key, value]) => next.searchParams.set(key, value))\n return next.toString()\n}\n\nexport const model = (input: ModelInput) => {\n const route: ImageRoute<XAIImageOptions> = {\n id: ADAPTER,\n generate: Effect.fn(\"XAIImages.generate\")(function* (request: ImageRequestFor<XAIImageOptions>, execute) {\n const http = mergeHttpOptions(request.model.http, request.http)\n const imageReferences = (request.images ?? []).map((image) => {\n if (image.type === \"bytes\") return { url: ImageInputs.dataUrl(image), type: \"image_url\" as const }\n if (image.type === \"url\") return { url: image.url, type: \"image_url\" as const }\n if (image.type === \"file-id\") return { file_id: image.id }\n return undefined\n })\n if (imageReferences.some((image) => image === undefined))\n return yield* ImageInputs.invalid(ADAPTER, \"xAI Images accepts image URLs, data URLs, bytes, and file IDs\")\n const requestBody = mergeJsonRecords(\n {\n model: request.model.id,\n prompt: request.prompt,\n image: imageReferences.length === 1 ? imageReferences[0] : undefined,\n images: imageReferences.length > 1 ? imageReferences : undefined,\n },\n nativeOptions(request.options),\n http?.body,\n ) as XAIImageBody\n const text = ProviderShared.encodeJson(requestBody)\n const url = applyQuery(\n `${(input.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\")}${imageReferences.length === 0 ? PATH : EDIT_PATH}`,\n http?.query,\n )\n const headers = yield* Auth.toEffect(input.auth)({\n request,\n method: \"POST\",\n url,\n body: text,\n headers: Headers.fromInput({ ...input.headers, ...http?.headers }),\n })\n const response = yield* execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(text, \"application/json\"),\n ),\n )\n const payload = yield* response.json.pipe(\n Effect.mapError(() => invalidOutput(\"Failed to read the xAI Images response\")),\n )\n const decoded = yield* Schema.decodeUnknownEffect(XAIImageResponse)(payload).pipe(\n Effect.mapError(() => invalidOutput(\"xAI Images returned an invalid response\")),\n )\n const images = yield* Effect.forEach(decoded.data, (item, index) => {\n const mediaType = item.mime_type ?? \"application/octet-stream\"\n if (item.b64_json)\n return Effect.fromResult(Encoding.decodeBase64(item.b64_json)).pipe(\n Effect.mapError(() => invalidOutput(`xAI Images result ${index} contains invalid base64 data`)),\n Effect.map(\n (data) =>\n new GeneratedImage({\n mediaType,\n data,\n providerMetadata:\n item.revised_prompt === undefined || item.revised_prompt === null\n ? undefined\n : { xai: { revisedPrompt: item.revised_prompt } },\n }),\n ),\n )\n if (item.url)\n return Effect.succeed(\n new GeneratedImage({\n mediaType,\n data: item.url,\n providerMetadata:\n item.revised_prompt === undefined || item.revised_prompt === null\n ? undefined\n : { xai: { revisedPrompt: item.revised_prompt } },\n }),\n )\n return Effect.fail(invalidOutput(`xAI Images result ${index} has neither image data nor a URL`))\n })\n if (images.length === 0) return yield* invalidOutput(\"xAI Images returned no images\")\n const usage = ProviderShared.isRecord(decoded.usage) ? decoded.usage : undefined\n return new ImageResponse({\n images,\n usage: usage === undefined ? undefined : new Usage({ providerMetadata: { xai: usage } }),\n providerMetadata: usage === undefined ? undefined : { xai: { usage } },\n })\n }),\n }\n return ImageModel.make<XAIImageOptions>({ id: input.id, provider: \"xai\", route, http: input.http })\n}\n\nexport const XAIImages = {\n model,\n} as const\n", | ||
| "import { AuthOptions, type ProviderAuthOption } from \"../route/auth-options\"\nimport type { RouteDefaultsInput } from \"../route/client\"\nimport { HttpOptions, ProviderID, type ModelID } from \"../schema\"\nimport * as OpenAICompatibleProfiles from \"./openai-compatible-profile\"\nimport * as OpenAICompatibleChat from \"../protocols/openai-compatible-chat\"\nimport * as OpenAIResponses from \"../protocols/openai-responses\"\nimport { XAIImages } from \"../protocols/xai-images\"\n\nexport const id = ProviderID.make(\"xai\")\n\nexport type ModelOptions = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n }\n\nexport type { XAIImageOptions } from \"../protocols/xai-images\"\n\nexport const routes = [OpenAIResponses.route, OpenAICompatibleChat.route]\n\nconst auth = (options: ProviderAuthOption<\"optional\">) => AuthOptions.bearer(options, \"XAI_API_KEY\")\n\nconst configuredResponsesRoute = (input: ModelOptions) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n return OpenAIResponses.route.with({\n ...rest,\n provider: id,\n endpoint: { baseURL: baseURL ?? OpenAICompatibleProfiles.profiles.xai.baseURL },\n auth: auth(input),\n })\n}\n\nconst configuredChatRoute = (input: ModelOptions) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n return OpenAICompatibleChat.route.with({\n ...rest,\n provider: id,\n endpoint: { baseURL: baseURL ?? OpenAICompatibleProfiles.profiles.xai.baseURL },\n auth: auth(input),\n })\n}\n\nexport const configure = (input: ModelOptions = {}) => {\n const responsesRoute = configuredResponsesRoute(input)\n const chatRoute = configuredChatRoute(input)\n const responses = (modelID: string | ModelID) => responsesRoute.model({ id: modelID })\n const chat = (modelID: string | ModelID) => chatRoute.model({ id: modelID })\n const image = (modelID: string | ModelID) =>\n XAIImages.model({\n id: modelID,\n auth: auth(input),\n baseURL: input.baseURL ?? OpenAICompatibleProfiles.profiles.xai.baseURL,\n headers: input.headers,\n http: input.http === undefined ? undefined : HttpOptions.make(input.http),\n })\n return {\n id,\n model: responses,\n responses,\n chat,\n image,\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model = provider.model\nexport const responses = provider.responses\nexport const chat = provider.chat\nexport const image = provider.image\n" | ||
| ], | ||
| "mappings": ";4yBAeA,SAAM,OAAU,kBACH,OAAmB,2BACnB,OAAO,2BACP,OAAY,qBAgDnB,OAAmB,OAAO,YAAO,MACrC,UAAM,OAAO,WACX,EAAO,OAAO,CACZ,SAAU,EAAa,EAAO,MAAM,EACpC,IAAK,EAAa,EAAO,MAAM,EAC/B,eAAgB,EAAa,EAAO,MAAM,EAC1C,UAAW,EAAa,EAAO,MAAM,CACvC,CAAC,CACH,EACA,MAAO,EAAO,SAAS,EAAO,OAAO,CACv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,CAAQ,CAAC,EAczE,MAbY,CAAC,IACb,EAAU,MAAM,CACd,GAAI,EACJ,KAAM,EAAK,CAAK,EAChB,QAAS,EAAM,SAAoC,EAAS,IAAI,QAChE,QAAS,EAAM,QACf,KAAM,EAAM,OAAS,OAAY,OAAY,EAAY,KAAK,EAAM,IAAI,CAC1E,CAAC,EAOD,WACF,GAGW,EAAW,EAAU,EACrB,GAAQ,EAAS,MACjB,GAAY,EAAS,UACrB,GAAO,EAAS,KAChB,GAAQ,EAAS", | ||
| "debugId": "11B67F6F2C51E41A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.33/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsJson1_1Protocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultCognitoIdentityHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"cognito-identity\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetCredentialsForIdentity\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n case \"GetId\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"cognito-identity\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.32\";\nvar packageInfo = {\n\tversion: version};\n\nconst m = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = \"stringEquals\", h = { [m]: \"Endpoint\" }, i = { [m]: d }, j = { [m]: \"Region\" }, k = {}, l = [j];\nconst _data = {\n conditions: [\n [c, [h]],\n [c, l],\n [\"aws.partition\", l, d],\n [e, [{ [m]: \"UseFIPS\" }, b]],\n [e, [{ fn: f, argv: [i, \"supportsFIPS\"] }, b]],\n [e, [{ [m]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [i, \"supportsDualStack\"] }, b]],\n [g, [{ fn: f, argv: [i, \"name\"] }, \"aws\"]],\n [g, [j, \"us-east-1\"]],\n [g, [j, \"us-east-2\"]],\n [g, [j, \"us-west-1\"]],\n [g, [j, \"us-west-2\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [h, k],\n [\"https://cognito-identity-fips.us-east-1.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-east-2.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-west-1.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-west-2.amazonaws.com\", k],\n [\"https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", k],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}\", k],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://cognito-identity.{Region}.amazonaws.com\", k],\n [\"https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}\", k],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}\", k],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 17, 3,\n 1, 4, r + 16,\n 2, 5, r + 16,\n 3, 9, 6,\n 5, 7, r + 15,\n 6, 8, r + 14,\n 7, r + 12, r + 13,\n 4, 11, 10,\n 5, r + 9, r + 11,\n 5, 12, r + 10,\n 6, 13, r + 9,\n 8, r + 4, 14,\n 9, r + 5, 15,\n 10, r + 6, 16,\n 11, r + 7, r + 8,\n 3, r + 1, 18,\n 5, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass CognitoIdentityServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, CognitoIdentityServiceException.prototype);\n }\n}\n\nclass ExternalServiceException extends CognitoIdentityServiceException {\n name = \"ExternalServiceException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ExternalServiceException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExternalServiceException.prototype);\n }\n}\nclass InternalErrorException extends CognitoIdentityServiceException {\n name = \"InternalErrorException\";\n $fault = \"server\";\n constructor(opts) {\n super({\n name: \"InternalErrorException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalErrorException.prototype);\n }\n}\nclass InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException {\n name = \"InvalidIdentityPoolConfigurationException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidIdentityPoolConfigurationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidIdentityPoolConfigurationException.prototype);\n }\n}\nclass InvalidParameterException extends CognitoIdentityServiceException {\n name = \"InvalidParameterException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidParameterException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidParameterException.prototype);\n }\n}\nclass NotAuthorizedException extends CognitoIdentityServiceException {\n name = \"NotAuthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"NotAuthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, NotAuthorizedException.prototype);\n }\n}\nclass ResourceConflictException extends CognitoIdentityServiceException {\n name = \"ResourceConflictException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceConflictException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceConflictException.prototype);\n }\n}\nclass ResourceNotFoundException extends CognitoIdentityServiceException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nclass TooManyRequestsException extends CognitoIdentityServiceException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nclass LimitExceededException extends CognitoIdentityServiceException {\n name = \"LimitExceededException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"LimitExceededException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, LimitExceededException.prototype);\n }\n}\n\nconst _AI = \"AccountId\";\nconst _AKI = \"AccessKeyId\";\nconst _C = \"Credentials\";\nconst _CRA = \"CustomRoleArn\";\nconst _E = \"Expiration\";\nconst _ESE = \"ExternalServiceException\";\nconst _GCFI = \"GetCredentialsForIdentity\";\nconst _GCFII = \"GetCredentialsForIdentityInput\";\nconst _GCFIR = \"GetCredentialsForIdentityResponse\";\nconst _GI = \"GetId\";\nconst _GII = \"GetIdInput\";\nconst _GIR = \"GetIdResponse\";\nconst _IEE = \"InternalErrorException\";\nconst _II = \"IdentityId\";\nconst _IIPCE = \"InvalidIdentityPoolConfigurationException\";\nconst _IPE = \"InvalidParameterException\";\nconst _IPI = \"IdentityPoolId\";\nconst _IPT = \"IdentityProviderToken\";\nconst _L = \"Logins\";\nconst _LEE = \"LimitExceededException\";\nconst _LM = \"LoginsMap\";\nconst _NAE = \"NotAuthorizedException\";\nconst _RCE = \"ResourceConflictException\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SK = \"SecretKey\";\nconst _SKS = \"SecretKeyString\";\nconst _ST = \"SessionToken\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _hE = \"httpError\";\nconst _m = \"message\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentity\";\nconst _se = \"server\";\nconst n0 = \"com.amazonaws.cognitoidentity\";\nconst _s_registry = TypeRegistry.for(_s);\nvar CognitoIdentityServiceException$ = [-3, _s, \"CognitoIdentityServiceException\", 0, [], []];\n_s_registry.registerError(CognitoIdentityServiceException$, CognitoIdentityServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar ExternalServiceException$ = [-3, n0, _ESE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(ExternalServiceException$, ExternalServiceException);\nvar InternalErrorException$ = [-3, n0, _IEE,\n { [_e]: _se },\n [_m],\n [0]\n];\nn0_registry.registerError(InternalErrorException$, InternalErrorException);\nvar InvalidIdentityPoolConfigurationException$ = [-3, n0, _IIPCE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidIdentityPoolConfigurationException$, InvalidIdentityPoolConfigurationException);\nvar InvalidParameterException$ = [-3, n0, _IPE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidParameterException$, InvalidParameterException);\nvar LimitExceededException$ = [-3, n0, _LEE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(LimitExceededException$, LimitExceededException);\nvar NotAuthorizedException$ = [-3, n0, _NAE,\n { [_e]: _c, [_hE]: 403 },\n [_m],\n [0]\n];\nn0_registry.registerError(NotAuthorizedException$, NotAuthorizedException);\nvar ResourceConflictException$ = [-3, n0, _RCE,\n { [_e]: _c, [_hE]: 409 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceConflictException$, ResourceConflictException);\nvar ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);\nvar TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nn0_registry.registerError(TooManyRequestsException$, TooManyRequestsException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar IdentityProviderToken = [0, n0, _IPT, 8, 0];\nvar SecretKeyString = [0, n0, _SKS, 8, 0];\nvar Credentials$ = [3, n0, _C,\n 0,\n [_AKI, _SK, _ST, _E],\n [0, [() => SecretKeyString, 0], 0, 4]\n];\nvar GetCredentialsForIdentityInput$ = [3, n0, _GCFII,\n 0,\n [_II, _L, _CRA],\n [0, [() => LoginsMap, 0], 0], 1\n];\nvar GetCredentialsForIdentityResponse$ = [3, n0, _GCFIR,\n 0,\n [_II, _C],\n [0, [() => Credentials$, 0]]\n];\nvar GetIdInput$ = [3, n0, _GII,\n 0,\n [_IPI, _AI, _L],\n [0, 0, [() => LoginsMap, 0]], 1\n];\nvar GetIdResponse$ = [3, n0, _GIR,\n 0,\n [_II],\n [0]\n];\nvar LoginsMap = [2, n0, _LM,\n 0, [0,\n 0],\n [() => IdentityProviderToken,\n 0]\n];\nvar GetCredentialsForIdentity$ = [9, n0, _GCFI,\n 0, () => GetCredentialsForIdentityInput$, () => GetCredentialsForIdentityResponse$\n];\nvar GetId$ = [9, n0, _GI,\n 0, () => GetIdInput$, () => GetIdResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2014-06-30\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultCognitoIdentityHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsJson1_1Protocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.cognitoidentity\",\n errorTypeRegistries,\n xmlNamespace: \"http://cognito-identity.amazonaws.com/doc/2014-06-30/\",\n version: \"2014-06-30\",\n serviceTarget: \"AWSCognitoIdentityService\",\n },\n serviceId: config?.serviceId ?? \"Cognito Identity\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass CognitoIdentityClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultCognitoIdentityHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"AWSCognitoIdentityService\", \"CognitoIdentityClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass GetCredentialsForIdentityCommand extends command(_ep0, _mw0, \"GetCredentialsForIdentity\", GetCredentialsForIdentity$) {\n}\n\nclass GetIdCommand extends command(_ep0, _mw0, \"GetId\", GetId$) {\n}\n\nconst commands = {\n GetCredentialsForIdentityCommand,\n GetIdCommand,\n};\nclass CognitoIdentity extends CognitoIdentityClient {\n}\ncreateAggregatedClient(commands, CognitoIdentity);\n\nexports.CognitoIdentity = CognitoIdentity;\nexports.CognitoIdentityClient = CognitoIdentityClient;\nexports.CognitoIdentityServiceException = CognitoIdentityServiceException;\nexports.CognitoIdentityServiceException$ = CognitoIdentityServiceException$;\nexports.Credentials$ = Credentials$;\nexports.ExternalServiceException = ExternalServiceException;\nexports.ExternalServiceException$ = ExternalServiceException$;\nexports.GetCredentialsForIdentity$ = GetCredentialsForIdentity$;\nexports.GetCredentialsForIdentityCommand = GetCredentialsForIdentityCommand;\nexports.GetCredentialsForIdentityInput$ = GetCredentialsForIdentityInput$;\nexports.GetCredentialsForIdentityResponse$ = GetCredentialsForIdentityResponse$;\nexports.GetId$ = GetId$;\nexports.GetIdCommand = GetIdCommand;\nexports.GetIdInput$ = GetIdInput$;\nexports.GetIdResponse$ = GetIdResponse$;\nexports.InternalErrorException = InternalErrorException;\nexports.InternalErrorException$ = InternalErrorException$;\nexports.InvalidIdentityPoolConfigurationException = InvalidIdentityPoolConfigurationException;\nexports.InvalidIdentityPoolConfigurationException$ = InvalidIdentityPoolConfigurationException$;\nexports.InvalidParameterException = InvalidParameterException;\nexports.InvalidParameterException$ = InvalidParameterException$;\nexports.LimitExceededException = LimitExceededException;\nexports.LimitExceededException$ = LimitExceededException$;\nexports.NotAuthorizedException = NotAuthorizedException;\nexports.NotAuthorizedException$ = NotAuthorizedException$;\nexports.ResourceConflictException = ResourceConflictException;\nexports.ResourceConflictException$ = ResourceConflictException$;\nexports.ResourceNotFoundException = ResourceNotFoundException;\nexports.ResourceNotFoundException$ = ResourceNotFoundException$;\nexports.TooManyRequestsException = TooManyRequestsException;\nexports.TooManyRequestsException$ = TooManyRequestsException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";8VAAA,SAAQ,6BAAs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"version": 3, | ||
| "sources": ["../ai/src/protocols/openai-compatible-chat.ts"], | ||
| "sourcesContent": [ | ||
| "import { Route, type RouteRoutedModelInput } from \"../route/client\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Framing } from \"../route/framing\"\nimport * as OpenAIChat from \"./openai-chat\"\n\nconst ADAPTER = \"openai-compatible-chat\"\n\nexport type OpenAICompatibleChatModelInput = RouteRoutedModelInput\n\n/**\n * Route for non-OpenAI providers that expose an OpenAI Chat-compatible\n * `/chat/completions` endpoint. Reuses `OpenAIChat.protocol` end-to-end and\n * overrides only the route id so providers can be resolved per-family without\n * colliding with native OpenAI. Provider helpers configure the route endpoint\n * before model selection.\n */\nexport const route = Route.make({\n id: ADAPTER,\n providerMetadataKey: \"openai\",\n protocol: OpenAIChat.protocol,\n endpoint: Endpoint.path(\"/chat/completions\"),\n framing: Framing.sse,\n})\n\nexport * as OpenAICompatibleChat from \"./openai-compatible-chat\"\n" | ||
| ], | ||
| "mappings": ";mHAKA,SAAM,EAAU,yBAWH,EAAQ,EAAM,KAAK,CAC9B,GAAI,EACJ,oBAAqB,SACrB,SAAqB,EACrB,SAAU,EAAS,KAAK,mBAAmB,EAC3C,QAAS,EAAQ,GACnB,CAAC", | ||
| "debugId": "724547B77B93B9C464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name: name14,\n message,\n cause\n }) {\n super(message);\n this[_a] = true;\n this.name = name14;\n this.cause = cause;\n }\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error) {\n return _AISDKError.hasMarker(error, marker);\n }\n static hasMarker(error, marker15) {\n const markerSymbol = Symbol.for(marker15);\n return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500),\n // server error\n data\n }) {\n super({ name, message, cause });\n this[_a2] = true;\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker2);\n }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n // used in isInstance\n constructor({ message = \"Empty response body\" } = {}) {\n super({ name: name2, message });\n this[_a3] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker3);\n }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n constructor({\n message,\n cause,\n argument\n }) {\n super({ name: name3, message, cause });\n this[_a4] = true;\n this.argument = argument;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker4);\n }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n constructor({\n prompt,\n message,\n cause\n }) {\n super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n this[_a5] = true;\n this.prompt = prompt;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker5);\n }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`\n }) {\n super({ name: name5, message });\n this[_a6] = true;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker6);\n }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n constructor({ text, cause }) {\n super({\n name: name6,\n message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a7] = true;\n this.text = text;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker7);\n }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name7, message });\n this[_a8] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker8);\n }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name8, message });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker9);\n }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n // used in isInstance\n constructor({\n message = \"No content generated.\"\n } = {}) {\n super({ name: name9, message });\n this[_a10] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker10);\n }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n constructor({\n errorName = name10,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`\n }) {\n super({ name: errorName, message });\n this[_a11] = true;\n this.modelId = modelId;\n this.modelType = modelType;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker11);\n }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n constructor(options) {\n super({\n name: name11,\n message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n });\n this[_a12] = true;\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker12);\n }\n};\n\n// src/errors/type-validation-error.ts\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n constructor({\n value,\n cause,\n context\n }) {\n let contextPrefix = \"Type validation failed\";\n if (context == null ? void 0 : context.field) {\n contextPrefix += ` for ${context.field}`;\n }\n if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n contextPrefix += \" (\";\n const parts = [];\n if (context.entityName) {\n parts.push(context.entityName);\n }\n if (context.entityId) {\n parts.push(`id: \"${context.entityId}\"`);\n }\n contextPrefix += parts.join(\", \");\n contextPrefix += \")\";\n }\n super({\n name: name12,\n message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\n this.context = context;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker13);\n }\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n context\n }) {\n var _a15, _b15, _c;\n if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {\n return cause;\n }\n return new _TypeValidationError({ value, cause, context });\n }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`\n }) {\n super({ name: name13, message });\n this[_a14] = true;\n this.functionality = functionality;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker14);\n }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n if (typeof value === \"object\") {\n return Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n }\n return false;\n}\nfunction isJSONArray(value) {\n return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n return value != null && typeof value === \"object\" && Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n}\nexport {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidArgumentError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n getErrorMessage,\n isJSONArray,\n isJSONObject,\n isJSONValue\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";AACA,IAAI,EAAS,kBACT,GAAS,OAAO,IAAI,CAAM,EAC1B,EAAI,EACJ,EAAa,MAAM,UAAqB,EAAK,MAAO,EAAK,GAAQ,EAAI,CASvE,WAAW,EACT,KAAM,EACN,UACA,SACC,CACD,MAAM,CAAO,EACb,KAAK,GAAM,GACX,KAAK,KAAO,EACZ,KAAK,MAAQ,QAOR,WAAU,CAAC,EAAO,CACvB,OAAO,EAAY,UAAU,EAAO,CAAM,QAErC,UAAS,CAAC,EAAO,EAAU,CAChC,IAAM,EAAe,OAAO,IAAI,CAAQ,EACxC,OAAO,GAAS,MAAQ,OAAO,IAAU,UAAY,KAAgB,GAAS,OAAO,EAAM,KAAkB,WAAa,EAAM,KAAkB,GAEtJ,EAGI,EAAO,kBACP,EAAU,mBAAmB,IAC7B,GAAU,OAAO,IAAI,CAAO,EAC5B,EAAK,EACL,GAAe,cAAe,EAAM,EAAY,EAAM,GAAS,EAAK,CACtE,WAAW,EACT,UACA,MACA,oBACA,aACA,kBACA,eACA,QACA,eAAc,GAAc,OAAS,IAAe,KACpD,IAAe,KACf,IAAe,KACf,GAAc,KAEd,SACC,CACD,MAAM,CAAE,OAAM,UAAS,OAAM,CAAC,EAC9B,KAAK,GAAO,GACZ,KAAK,IAAM,EACX,KAAK,kBAAoB,EACzB,KAAK,WAAa,EAClB,KAAK,gBAAkB,EACvB,KAAK,aAAe,EACpB,KAAK,YAAc,GACnB,KAAK,KAAO,SAEP,WAAU,CAAC,EAAO,CACvB,OAAO,EAAW,UAAU,EAAO,CAAO,EAE9C,EAGI,EAAQ,4BACR,EAAU,mBAAmB,IAC7B,GAAU,OAAO,IA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| ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode, type McpServer } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.list,\n Effect.fn(\"cli.mcp.list\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.mcp.list({ location: { directory: process.cwd() } }))\n const servers = response.data.toSorted((a, b) => a.name.localeCompare(b.name))\n if (servers.length === 0) {\n process.stdout.write(\"No MCP servers configured\" + EOL)\n return\n }\n const width = Math.max(...servers.map((server) => server.name.length))\n const lines = servers.map(\n (server) => `${icon(server.status)} ${server.name.padEnd(width)} ${describe(server.status)}`,\n )\n process.stdout.write(lines.join(EOL) + EOL)\n }),\n)\n\nfunction icon(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"connected\":\n return \"✓\"\n case \"needs_auth\":\n return \"⚠\"\n case \"failed\":\n case \"needs_client_registration\":\n return \"✗\"\n default:\n return \"○\"\n }\n}\n\nfunction describe(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"needs_auth\":\n return \"needs authentication\"\n case \"needs_client_registration\":\n return `needs client registration: ${status.error}`\n case \"failed\":\n return `failed: ${status.error}`\n default:\n return status.status\n }\n}\n" | ||
| ], | ||
| "mappings": ";83BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,UAC/B,OAAO,QAAG,mBAAc,OAAE,cAAU,OAAG,MACrC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,IAAI,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAC/E,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC,EAC7E,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,4BAA8B,CAAG,EACtD,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAQ,IAAI,CAAC,IAAW,EAAO,KAAK,MAAM,CAAC,EAC/D,EAAQ,EAAQ,IACpB,CAAC,IAAW,GAAG,EAAK,EAAO,MAAM,KAAK,EAAO,KAAK,OAAO,CAAK,MAAM,EAAS,EAAO,MAAM,GAC5F,EACA,QAAQ,OAAO,MAAM,EAAM,KAAK,CAAG,EAAI,CAAG,EAC3C,CACH,EAEA,SAAS,CAAI,CAAC,EAA6B,CACzC,OAAQ,EAAO,YACR,YACH,MAAO,aACJ,aACH,MAAO,aACJ,aACA,4BACH,MAAO,iBAEP,MAAO,UAIb,SAAS,CAAQ,CAAC,EAA6B,CAC7C,OAAQ,EAAO,YACR,aACH,MAAO,2BACJ,4BACH,MAAO,8BAA8B,EAAO,YACzC,SACH,MAAO,WAAW,EAAO,gBAEzB,OAAO,EAAO", | ||
| "debugId": "31632EC4E9C311F864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mini.ts"], | ||
| "sourcesContent": [ | ||
| "import { Context, Effect, FileSystem, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { Config } from \"../../config\"\nimport { resolve } from \"@opencode-ai/tui/config\"\n\nexport default Runtime.handler(Commands.commands.mini, (input) =>\n Effect.gen(function* () {\n const { runMini, validateMiniTerminal } = yield* Effect.promise(() => import(\"../../mini\"))\n yield* Effect.promise(async () => validateMiniTerminal())\n const serverURL = Option.getOrUndefined(input.server)\n const server = yield* ServerConnection.resolve({ server: serverURL, standalone: input.standalone })\n const config = yield* Config.Service\n const resolved = resolve(yield* config.get(), { terminalSuspend: process.platform !== \"win32\" })\n const fileSystem = yield* FileSystem.FileSystem\n const runServicePromise = Effect.runPromiseWith(Context.make(FileSystem.FileSystem, fileSystem))\n const service = server.service\n yield* Effect.promise(() =>\n runMini({\n server: {\n endpoint: server.endpoint,\n reconnect: service ? (signal) => runServicePromise(service.reconnect(), { signal }) : undefined,\n },\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n prompt: Option.getOrUndefined(input.prompt),\n replay: input.replay,\n replayLimit: Option.getOrUndefined(input.replayLimit),\n demo: input.demo,\n tuiConfig: resolved,\n config: {\n update: (update) => runServicePromise(config.update(update)),\n },\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";ogCAOA,SAAe,SAAQ,aAAQ,OAAS,cAAS,UAAM,MAAC,SACtD,OAAO,SAAI,cAAU,OAAG,MACtB,SAAQ,eAAS,6BAAyB,WAAO,OAAO,aAAQ,SAAa,wCAAa,OAC1F,WAAO,OAAO,aAAQ,cAAY,OAAqB,CAAC,EACxD,IAAM,EAAY,EAAO,eAAe,EAAM,MAAM,EAC9C,EAAS,MAAO,EAAiB,QAAQ,CAAE,OAAQ,EAAW,WAAY,EAAM,UAAW,CAAC,EAC5F,EAAS,MAAO,EAAO,QACvB,EAAW,EAAQ,MAAO,EAAO,IAAI,EAAG,CAAE,gBAAiB,EAA6B,CAAC,EACzF,EAAa,MAAO,EAAW,WAC/B,EAAoB,EAAO,eAAe,EAAQ,KAAK,EAAW,WAAY,CAAU,CAAC,EACzF,EAAU,EAAO,QACvB,MAAO,EAAO,QAAQ,IACpB,EAAQ,CACN,OAAQ,CACN,SAAU,EAAO,SACjB,UAAW,EAAU,CAAC,IAAW,EAAkB,EAAQ,UAAU,EAAG,CAAE,QAAO,CAAC,EAAI,MACxF,EACA,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,OAAQ,EAAM,OACd,YAAa,EAAO,eAAe,EAAM,WAAW,EACpD,KAAM,EAAM,KACZ,UAAW,EACX,OAAQ,CACN,OAAQ,CAAC,IAAW,EAAkB,EAAO,OAAO,CAAM,CAAC,CAC7D,CACF,CAAC,CACH,EACD,CACH", | ||
| "debugId": "B915ABB75B938B5764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/index.js", "../../node_modules/.bun/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/stream.js"], | ||
| "sourcesContent": [ | ||
| "class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nconst LF = 10, CR = 13, SPACE = 32;\nfunction noop(_arg) {\n}\nfunction createParser(config) {\n if (typeof config == \"function\")\n throw new TypeError(\n \"`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];\n let pendingFragmentsLength = 0, isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType, terminated = !1;\n function feed(chunk) {\n if (terminated)\n throw new Error(\n \"Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.\"\n );\n if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n const trailing2 = processLines(chunk);\n trailing2 !== \"\" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();\n return;\n }\n if (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();\n return;\n }\n pendingFragments.push(chunk);\n const input = pendingFragments.join(\"\");\n pendingFragments.length = 0, pendingFragmentsLength = 0;\n const trailing = processLines(input);\n trailing !== \"\" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();\n }\n function checkBufferSize() {\n maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, onError(\n new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: \"max-buffer-size-exceeded\"\n })\n )));\n }\n function processLines(chunk) {\n let searchIndex = 0;\n if (chunk.indexOf(\"\\r\") === -1) {\n let lfIndex = chunk.indexOf(`\n`, searchIndex);\n for (; lfIndex !== -1; ) {\n if (searchIndex === lfIndex) {\n dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n onEvent({ id, event: eventType, data: value }), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(\n chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n lfIndex\n ) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)\n break;\n parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n return;\n }\n if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n id = value2.includes(\"\\0\") ? void 0 : value2;\n return;\n }\n if (firstCharCode === 58) {\n if (onComment) {\n const line2 = chunk.slice(start, end);\n onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex === -1) {\n processField(line, \"\", line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value || void 0;\n break;\n case \"data\":\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n dataLines > 0 && onEvent({\n id,\n event: eventType,\n data\n }), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join(\"\");\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n isFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;\n }\n return { feed, reset };\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n", | ||
| "import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n typeof onError == \"function\" && onError(error), (onError === \"terminate\" || error.type === \"max-buffer-size-exceeded\") && controller.error(error);\n },\n onRetry,\n onComment,\n maxBufferSize\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n" | ||
| ], | ||
| "mappings": ";AAAA,MAAM,UAAmB,KAAM,CAC7B,WAAW,CAAC,EAAS,EAAS,CAC5B,MAAM,CAAO,EAAG,KAAK,KAAO,aAAc,KAAK,KAAO,EAAQ,KAAM,KAAK,MAAQ,EAAQ,MAAO,KAAK,MAAQ,EAAQ,MAAO,KAAK,KAAO,EAAQ,KAEpJ,CACA,IAAM,EAAK,GAAI,EAAK,GAAI,EAAQ,GAChC,SAAS,CAAI,CAAC,EAAM,EAEpB,SAAS,CAAY,CAAC,EAAQ,CAC5B,GAAI,OAAO,GAAU,WACnB,MAAU,UACR,iGACF,EACF,IAAQ,UAAU,EAAM,UAAU,EAAM,UAAU,EAAM,YAAW,iBAAkB,EAAQ,EAAmB,CAAC,EAC7G,EAAyB,EAAG,EAAe,GAAI,EAAI,EAAO,GAAI,EAAY,EAAG,EAAW,EAAa,GACzG,SAAS,CAAI,CAAC,EAAO,CACnB,GAAI,EACF,MAAU,MACR,yHACF,EACF,GAAI,IAAiB,EAAe,GAAI,EAAM,W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,WAAW,EAAI,CAAC,IAAM,GCxK1M,MAAM,UAAgC,eAAgB,CACpD,WAAW,EAAG,UAAS,UAAS,YAAW,iBAAkB,CAAC,EAAG,CAC/D,IAAI,EACJ,MAAM,CACJ,KAAK,CAAC,EAAY,CAChB,EAAS,EAAa,CACpB,QAAS,CAAC,IAAU,CAClB,EAAW,QAAQ,CAAK,GAE1B,OAAO,CAAC,EAAO,CACb,OAAO,GAAW,YAAc,EAAQ,CAAK,GAAI,IAAY,aAAe,EAAM,OAAS,6BAA+B,EAAW,MAAM,CAAK,GAElJ,UACA,YACA,eACF,CAAC,GAEH,SAAS,CAAC,EAAO,CACf,EAAO,KAAK,CAAK,EAErB,CAAC,EAEL", | ||
| "debugId": "93BA134ACC76793F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/ai-gateway-provider@3.1.2+a6631614dda8d488/node_modules/ai-gateway-provider/dist/providers/unified.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/providers/unified.ts\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nvar createUnified = (arg) => {\n return createOpenAICompatible({\n baseURL: \"https://gateway.ai.cloudflare.com/v1/compat\",\n // intercepted and replaced with actual base URL later\n name: \"Unified\",\n ...arg || {}\n });\n};\nvar unified = createUnified();\nexport {\n createUnified,\n unified\n};\n//# sourceMappingURL=unified.mjs.map" | ||
| ], | ||
| "mappings": ";kSAEA,SAAI,OAAgB,MAAC,SAAQ,MAC3B,YAAO,OAAuB,CAC5B,QAAS,8CAET,KAAM,aACH,GAAO,CAAC,CACb,CAAC,GAEC,EAAU,EAAc", | ||
| "debugId": "F0012135BBEDBB4664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/route/auth-options.ts"], | ||
| "sourcesContent": [ | ||
| "import type { Config, Redacted } from \"effect\"\nimport { Auth } from \"./auth\"\n\nexport type ApiKeyMode = \"optional\" | \"required\"\n\nexport type AuthOverride = {\n readonly auth: Auth.Definition\n readonly apiKey?: never\n}\n\nexport type OptionalApiKeyAuth = {\n readonly apiKey?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>>\n readonly auth?: never\n}\n\nexport type RequiredApiKeyAuth = {\n readonly apiKey: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>>\n readonly auth?: never\n}\n\nexport type ProviderAuthOption<Mode extends ApiKeyMode> =\n | AuthOverride\n | (Mode extends \"optional\" ? OptionalApiKeyAuth : RequiredApiKeyAuth)\n\nexport type ModelOptions<Base, Mode extends ApiKeyMode> = Omit<Base, \"apiKey\" | \"auth\"> & ProviderAuthOption<Mode>\n\nexport type ModelArgs<Base, Mode extends ApiKeyMode> = Mode extends \"optional\"\n ? readonly [options?: ModelOptions<Base, Mode>]\n : readonly [options: ModelOptions<Base, Mode>]\n\nexport type ModelFactory<Base, Mode extends ApiKeyMode, Model> = (id: string, ...args: ModelArgs<Base, Mode>) => Model\n\n/**\n * Require at least one of the keys in `T`. Use for option shapes where any\n * subset of fields is acceptable but at least one must be present (e.g. Azure\n * accepts `resourceName` or `baseURL`).\n */\nexport type AtLeastOne<T> = {\n [K in keyof T]: Required<Pick<T, K>> & Partial<Omit<T, K>>\n}[keyof T]\n\n/**\n * Standard bearer-auth resolution for providers: honor an explicit `auth`\n * override, otherwise resolve `apiKey` (option > config var) and apply it as\n * a bearer token.\n */\nexport const bearer = (\n options: ProviderAuthOption<\"optional\">,\n envVar: string | ReadonlyArray<string>,\n): Auth.Definition => {\n if (\"auth\" in options && options.auth) return options.auth\n return (Array.isArray(envVar) ? envVar : [envVar])\n .reduce(\n (auth, name) => auth.orElse(Auth.config(name)),\n Auth.optional(\"apiKey\" in options ? options.apiKey : undefined, \"apiKey\"),\n )\n .bearer()\n}\n\nexport * as AuthOptions from \"./auth-options\"\n" | ||
| ], | ||
| "mappings": ";kJA8CO,SAAM,EAAS,CACpB,EACA,IACoB,CACpB,GAAI,SAAU,GAAW,EAAQ,KAAM,OAAO,EAAQ,KACtD,OAAQ,MAAM,QAAQ,CAAM,EAAI,EAAS,CAAC,CAAM,GAC7C,OACC,CAAC,EAAM,IAAS,EAAK,OAAO,EAAK,OAAO,CAAI,CAAC,EAC7C,EAAK,SAAS,WAAY,EAAU,EAAQ,OAAS,OAAW,QAAQ,CAC1E,EACC,OAAO", | ||
| "debugId": "CD2B567F0C71AD4F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/server-process.ts", "src/commands/handlers/serve.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ServerProcess from \"./server-process\"\n\nimport { NodeServices } from \"@effect/platform-node\"\nimport { Service, type DiscoverOptions, type Info } from \"@opencode-ai/client/effect/service\"\nimport { LayerNode } from \"@opencode-ai/util/effect/layer-node\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { OPENCODE_CHANNEL, OPENCODE_VERSION } from \"./version\"\nimport { AppProcess } from \"@opencode-ai/util/process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport path from \"node:path\"\nimport { Effect, FileSystem, Logger, Option, Redacted, Schedule, Schema } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { Env } from \"./env\"\nimport { ServiceConfig } from \"./services/service-config\"\nimport { Updater } from \"./services/updater\"\n\nexport type Mode = \"default\" | \"service\" | \"stdio\"\n\nexport type Options = {\n readonly mode: Mode\n readonly hostname?: string\n readonly port?: number\n}\n\n// The process effect lives until server shutdown; tracing it would parent every request to one process-lifetime trace.\nexport const run = Effect.fnUntraced(function* (options: Options) {\n return yield* processEffect(options).pipe(\n Effect.provide(Updater.layer),\n Effect.provide(\n LayerNode.compile(LayerNode.group([Global.node, AppProcess.node]), [\n [\n Global.node,\n Global.layerWith(process.env.OPENCODE_CONFIG_DIR ? { config: process.env.OPENCODE_CONFIG_DIR } : {}),\n ],\n ]),\n ),\n Effect.provide(NodeServices.layer),\n )\n})\n\nconst processEffect = Effect.fnUntraced(function* (options: Options) {\n if (options.mode === \"service\") yield* Effect.sync(() => process.chdir(Global.Path.home))\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const serviceOptions = options.mode === \"service\" ? yield* ServiceConfig.options() : undefined\n const config = options.mode === \"service\" ? yield* ServiceConfig.read() : {}\n const hostname = options.hostname ?? config.hostname ?? \"127.0.0.1\"\n const port = options.port ?? config.port ?? (options.mode === \"service\" ? ServiceConfig.defaultPort() : undefined)\n if (\n serviceOptions !== undefined &&\n port !== undefined &&\n (yield* Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })) !== undefined\n )\n return\n const { start } = yield* Effect.promise(() => import(\"@opencode-ai/server/process\"))\n const environmentPassword = yield* Env.password\n // Keep the lease credential out of the environment inherited by tools.\n if (options.mode === \"stdio\") {\n delete process.env.OPENCODE_PASSWORD\n delete process.env.OPENCODE_SERVER_PASSWORD\n }\n const password =\n options.mode === \"service\"\n ? config.password || randomBytes(32).toString(\"base64url\")\n : environmentPassword\n ? Redacted.value(environmentPassword)\n : randomBytes(32).toString(\"base64url\")\n if (!password) return yield* Effect.fail(new Error(\"Missing server password\"))\n const instanceID = randomUUID()\n const server = yield* start(\n {\n app: {\n name: process.env.OPENCODE_CLIENT ?? \"cli\",\n version: OPENCODE_VERSION,\n channel: OPENCODE_CHANNEL,\n },\n hostname,\n port,\n password,\n simulation: truthy(process.env.OPENCODE_SIMULATE),\n database: {\n path:\n process.env.OPENCODE_DB ??\n ([\"latest\", \"beta\", \"prod\"].includes(OPENCODE_CHANNEL) ||\n process.env.OPENCODE_DISABLE_CHANNEL_DB === \"1\" ||\n process.env.OPENCODE_DISABLE_CHANNEL_DB === \"true\"\n ? \"opencode.db\"\n : `opencode-${OPENCODE_CHANNEL.replace(/[^a-zA-Z0-9._-]/g, \"-\")}.db`),\n },\n models: {\n url: process.env.OPENCODE_MODELS_URL,\n file: process.env.OPENCODE_MODELS_PATH,\n fetch: !truthy(process.env.OPENCODE_DISABLE_MODELS_FETCH),\n },\n observability: {\n endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,\n headers: process.env.OTEL_EXPORTER_OTLP_HEADERS,\n },\n config: {\n directory: process.env.OPENCODE_CONFIG_DIR,\n project: !truthy(\n process.env.OPENCODE_CONFIG_PROJECT_DISABLE ?? process.env.OPENCODE_DISABLE_PROJECT_CONFIG,\n ),\n file: process.env.OPENCODE_CONFIG,\n content: process.env.OPENCODE_CONFIG_CONTENT,\n },\n windows: {\n gitbash: process.env.OPENCODE_GIT_BASH_PATH,\n },\n fs: {\n filewatcher: !truthy(\n process.env.OPENCODE_FILEWATCHER_DISABLE ?? process.env.OPENCODE_DISABLE_FILEWATCHER,\n ),\n fff:\n process.env.OPENCODE_DISABLE_FFF === undefined\n ? process.platform !== \"win32\"\n : !truthy(process.env.OPENCODE_DISABLE_FFF),\n },\n },\n serviceOptions === undefined\n ? undefined\n : {\n instanceID,\n onListen: (address, shutdown) =>\n Effect.gen(function* () {\n if (!config.password) yield* ServiceConfig.password(password)\n return yield* register(address, password, instanceID, serviceOptions.file, shutdown)\n }),\n },\n ).pipe(\n Effect.provide(Logger.layer([], { mergeWithExisting: false })),\n Effect.catch((error) => {\n if (serviceOptions === undefined || port === undefined || !addressInUse(error)) return Effect.fail(error)\n return recognizeIncumbent(serviceOptions, hostname, port).pipe(\n Effect.flatMap((found) =>\n found\n ? Effect.void\n : Effect.fail(\n new Error(\n `Managed service port ${port} on ${hostname} is already in use by another process. ` +\n \"Configure another port with `opencode service set port <port>` and start the service again.\",\n { cause: error },\n ),\n ),\n ),\n )\n }),\n )\n if (server === undefined) return\n const url = HttpServer.formatAddress(server.address)\n console.log(options.mode === \"stdio\" ? JSON.stringify({ url }) : `server listening on ${url}`)\n if (options.mode === \"default\" && !environmentPassword) console.log(`server password ${password}`)\n const updater = yield* Updater.Service\n yield* updater.check().pipe(Effect.schedule(Schedule.spaced(\"10 minutes\")), Effect.forkScoped)\n return yield* options.mode === \"service\"\n ? server.shutdown\n : options.mode === \"stdio\"\n ? waitForStdinClose()\n : Effect.never\n }).pipe(Effect.annotateLogs({ role: \"server\" })),\n )\n})\n\nconst infoJson = Schema.fromJsonString(Service.Info)\nconst encodeInfo = Schema.encodeEffect(infoJson)\nconst decodeInfo = Schema.decodeUnknownEffect(infoJson)\n\nconst register = Effect.fnUntraced(function* (\n address: HttpServer.Address,\n password: string,\n id: string,\n file: string,\n shutdown: Effect.Effect<void>,\n) {\n const fs = yield* FileSystem.FileSystem\n const temp = file + \".\" + id + \".tmp\"\n yield* fs.makeDirectory(path.dirname(file), { recursive: true })\n const info = {\n id,\n version: OPENCODE_VERSION,\n url: HttpServer.formatAddress(address),\n pid: process.pid,\n password,\n }\n const encoded = yield* encodeInfo(info)\n const current = fs.readFileString(file).pipe(\n Effect.flatMap(decodeInfo),\n Effect.orElseSucceed(() => undefined),\n )\n const owns = (found: Info | undefined) =>\n found?.id === info.id &&\n found.version === info.version &&\n found.url === info.url &&\n found.pid === info.pid &&\n found.password === info.password\n yield* fs.writeFileString(temp, encoded, { mode: 0o600 }).pipe(Effect.andThen(fs.rename(temp, file)))\n yield* current.pipe(\n Effect.filterOrFail(owns),\n Effect.repeat(Schedule.spaced(\"5 seconds\")),\n Effect.ignore,\n Effect.andThen(shutdown),\n Effect.forkScoped,\n )\n return current.pipe(\n Effect.flatMap((found) => (owns(found) ? fs.remove(file) : Effect.void)),\n Effect.ignore,\n )\n})\n\nconst recognizeIncumbent = Effect.fnUntraced(function* (options: DiscoverOptions, hostname: string, port: number) {\n const found = yield* Service.incumbent({ ...options, url: serviceURL(hostname, port) }).pipe(\n Effect.filterOrFail((value) => value !== undefined),\n Effect.retry(Schedule.spaced(\"100 millis\")),\n Effect.timeoutOption(\"15 seconds\"),\n )\n return Option.isSome(found)\n})\n\nfunction serviceURL(hostname: string, port: number) {\n return `http://${hostname.includes(\":\") ? `[${hostname}]` : hostname}:${port}`\n}\n\nfunction truthy(value?: string) {\n return value === \"1\" || value?.toLowerCase() === \"true\"\n}\n\nfunction addressInUse(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false\n if (\"code\" in error && error.code === \"EADDRINUSE\") return true\n return \"cause\" in error && addressInUse(error.cause)\n}\n\nfunction waitForStdinClose() {\n return Effect.callback<void>((resume) => {\n const close = () => resume(Effect.void)\n process.stdin.once(\"end\", close)\n process.stdin.once(\"close\", close)\n process.stdin.resume()\n if (process.stdin.readableEnded || process.stdin.destroyed) close()\n return Effect.sync(() => {\n process.stdin.off(\"end\", close)\n process.stdin.off(\"close\", close)\n process.stdin.pause()\n })\n })\n}\n", | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerProcess } from \"../../server-process\"\n\nexport default Runtime.handler(\n Commands.commands.serve,\n Effect.fnUntraced(function* (input) {\n if (input.service && input.stdio) return yield* Effect.fail(new Error(\"--service and --stdio cannot be combined\"))\n return yield* ServerProcess.run({\n mode: input.service ? \"service\" : input.stdio ? \"stdio\" : \"default\",\n hostname: Option.getOrUndefined(input.hostname),\n port: Option.getOrUndefined(input.port),\n })\n }),\n)\n" | ||
| ], | ||
| "mappings": ";0kCAQA,2BAAS,qBAAa,oBACtB,yBAgBO,SAAM,OAAM,OAAO,gBAAW,cAAU,MAAC,OAAkB,MAChE,YAAO,WAAO,OAAc,MAAO,OAAE,UACnC,OAAO,aAAQ,OAAQ,UAAK,OAC5B,EAAO,QACL,EAAU,QAAQ,EAAU,MAAM,CAAC,EAAO,KAAM,EAAW,IAAI,CAAC,EAAG,CACjE,CACE,EAAO,KACP,EAAO,UAAU,QAAQ,IAAI,oBAAsB,CAAE,OAAQ,QAAQ,IAAI,mBAAoB,EAAI,CAAC,CAAC,CACrG,CACF,CAAC,CACH,EACA,EAAO,QAAQ,EAAa,KAAK,CACnC,EACD,EAEK,EAAgB,EAAO,WAAW,SAAU,CAAC,EAAkB,CACnE,GAAI,EAAQ,OAAS,UAAW,MAAO,EAAO,KAAK,IAAM,QAA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KAAQ,QACrB,EAAS,SAAS,MAClB,EAAO,WAAW,SAAU,CAAC,EAAO,CAClC,GAAI,EAAM,SAAW,EAAM,MAAO,OAAO,MAAO,EAAO,KAAS,MAAM,0CAA0C,CAAC,EACjH,OAAO,MAAO,EAAc,IAAI,CAC9B,KAAM,EAAM,QAAU,UAAY,EAAM,MAAQ,QAAU,UAC1D,SAAU,EAAO,eAAe,EAAM,QAAQ,EAC9C,KAAM,EAAO,eAAe,EAAM,IAAI,CACxC,CAAC,EACF,CACH", | ||
| "debugId": "0F18A970B4CBC59064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+perplexity@3.0.26+d6123d32214422cb/node_modules/@ai-sdk/perplexity/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/perplexity-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/perplexity-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\n\n// src/convert-perplexity-usage.ts\nfunction convertPerplexityUsage(usage) {\n var _a, _b, _c;\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;\n const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;\n const reasoningTokens = (_c = usage.reasoning_tokens) != null ? _c : 0;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens - reasoningTokens,\n reasoning: reasoningTokens\n },\n raw: usage\n };\n}\n\n// src/convert-to-perplexity-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertUint8ArrayToBase64 } from \"@ai-sdk/provider-utils\";\nfunction convertToPerplexityMessages(prompt) {\n const messages = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\":\n case \"assistant\": {\n const hasMultipartContent = content.some(\n (part) => part.type === \"file\" && part.mediaType.startsWith(\"image/\") || part.type === \"file\" && part.mediaType === \"application/pdf\"\n );\n const messageContent = content.map((part, index) => {\n var _a;\n switch (part.type) {\n case \"text\": {\n return {\n type: \"text\",\n text: part.text\n };\n }\n case \"file\": {\n if (part.mediaType === \"application/pdf\") {\n return part.data instanceof URL ? {\n type: \"file_url\",\n file_url: {\n url: part.data.toString()\n },\n file_name: part.filename\n } : {\n type: \"file_url\",\n file_url: {\n url: typeof part.data === \"string\" ? part.data : convertUint8ArrayToBase64(part.data)\n },\n file_name: part.filename || `document-${index}.pdf`\n };\n } else if (part.mediaType.startsWith(\"image/\")) {\n return part.data instanceof URL ? {\n type: \"image_url\",\n image_url: {\n url: part.data.toString()\n }\n } : {\n type: \"image_url\",\n image_url: {\n url: `data:${(_a = part.mediaType) != null ? _a : \"image/jpeg\"};base64,${typeof part.data === \"string\" ? part.data : convertUint8ArrayToBase64(part.data)}`\n }\n };\n }\n }\n }\n }).filter(Boolean);\n messages.push({\n role,\n content: hasMultipartContent ? messageContent : messageContent.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\")\n });\n break;\n }\n case \"tool\": {\n throw new UnsupportedFunctionalityError({\n functionality: \"Tool messages\"\n });\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/map-perplexity-finish-reason.ts\nfunction mapPerplexityFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n case \"length\":\n return finishReason;\n default:\n return \"other\";\n }\n}\n\n// src/perplexity-language-model.ts\nvar PerplexityLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.provider = \"perplexity\";\n this.supportedUrls = {\n // No URLs are supported.\n };\n this.modelId = modelId;\n this.config = config;\n }\n getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n providerOptions\n }) {\n var _a;\n const warnings = [];\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n if (stopSequences != null) {\n warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n }\n if (seed != null) {\n warnings.push({ type: \"unsupported\", feature: \"seed\" });\n }\n return {\n args: {\n // model id:\n model: this.modelId,\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n max_tokens: maxOutputTokens,\n presence_penalty: presencePenalty,\n temperature,\n top_k: topK,\n top_p: topP,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? {\n type: \"json_schema\",\n json_schema: { schema: responseFormat.schema }\n } : void 0,\n // provider extensions\n ...(_a = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a : {},\n // messages:\n messages: convertToPerplexityMessages(prompt)\n },\n warnings\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;\n const { args: body, warnings } = this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: perplexityErrorSchema,\n errorToMessage\n }),\n successfulResponseHandler: createJsonResponseHandler(\n perplexityResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n const text = choice.message.content;\n if (text.length > 0) {\n content.push({ type: \"text\", text });\n }\n if (response.citations != null) {\n for (const url of response.citations) {\n content.push({\n type: \"source\",\n sourceType: \"url\",\n id: this.config.generateId(),\n url\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapPerplexityFinishReason(choice.finish_reason),\n raw: (_a = choice.finish_reason) != null ? _a : void 0\n },\n usage: convertPerplexityUsage(response.usage),\n request: { body },\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n providerMetadata: {\n perplexity: {\n images: (_c = (_b = response.images) == null ? void 0 : _b.map((image) => ({\n imageUrl: image.image_url,\n originUrl: image.origin_url,\n height: image.height,\n width: image.width\n }))) != null ? _c : null,\n usage: {\n citationTokens: (_e = (_d = response.usage) == null ? void 0 : _d.citation_tokens) != null ? _e : null,\n numSearchQueries: (_g = (_f = response.usage) == null ? void 0 : _f.num_search_queries) != null ? _g : null\n },\n cost: ((_h = response.usage) == null ? void 0 : _h.cost) ? {\n inputTokensCost: (_i = response.usage.cost.input_tokens_cost) != null ? _i : null,\n outputTokensCost: (_j = response.usage.cost.output_tokens_cost) != null ? _j : null,\n requestCost: (_k = response.usage.cost.request_cost) != null ? _k : null,\n totalCost: (_l = response.usage.cost.total_cost) != null ? _l : null\n } : null\n }\n }\n };\n }\n async doStream(options) {\n const { args, warnings } = this.getArgs(options);\n const body = { ...args, stream: true };\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: perplexityErrorSchema,\n errorToMessage\n }),\n successfulResponseHandler: createEventSourceResponseHandler(\n perplexityChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n const providerMetadata = {\n perplexity: {\n usage: {\n citationTokens: null,\n numSearchQueries: null\n },\n cost: null,\n images: null\n }\n };\n let isFirstChunk = true;\n let isActive = false;\n const self = this;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b, _c, _d, _e, _f, _g;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (isFirstChunk) {\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n (_a = value.citations) == null ? void 0 : _a.forEach((url) => {\n controller.enqueue({\n type: \"source\",\n sourceType: \"url\",\n id: self.config.generateId(),\n url\n });\n });\n isFirstChunk = false;\n }\n if (value.usage != null) {\n usage = value.usage;\n providerMetadata.perplexity.usage = {\n citationTokens: (_b = value.usage.citation_tokens) != null ? _b : null,\n numSearchQueries: (_c = value.usage.num_search_queries) != null ? _c : null\n };\n providerMetadata.perplexity.cost = value.usage.cost ? {\n inputTokensCost: (_d = value.usage.cost.input_tokens_cost) != null ? _d : null,\n outputTokensCost: (_e = value.usage.cost.output_tokens_cost) != null ? _e : null,\n requestCost: (_f = value.usage.cost.request_cost) != null ? _f : null,\n totalCost: (_g = value.usage.cost.total_cost) != null ? _g : null\n } : null;\n }\n if (value.images != null) {\n providerMetadata.perplexity.images = value.images.map((image) => ({\n imageUrl: image.image_url,\n originUrl: image.origin_url,\n height: image.height,\n width: image.width\n }));\n }\n const choice = value.choices[0];\n if ((choice == null ? void 0 : choice.finish_reason) != null) {\n finishReason = {\n unified: mapPerplexityFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n if ((choice == null ? void 0 : choice.delta) == null) {\n return;\n }\n const delta = choice.delta;\n const textContent = delta.content;\n if (textContent != null) {\n if (!isActive) {\n controller.enqueue({ type: \"text-start\", id: \"0\" });\n isActive = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"0\",\n delta: textContent\n });\n }\n },\n flush(controller) {\n if (isActive) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertPerplexityUsage(usage),\n providerMetadata\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id,\n modelId: model,\n timestamp: new Date(created * 1e3)\n };\n}\nvar perplexityCostSchema = z.object({\n input_tokens_cost: z.number().nullish(),\n output_tokens_cost: z.number().nullish(),\n request_cost: z.number().nullish(),\n total_cost: z.number().nullish()\n});\nvar perplexityUsageSchema = z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number(),\n total_tokens: z.number().nullish(),\n citation_tokens: z.number().nullish(),\n num_search_queries: z.number().nullish(),\n reasoning_tokens: z.number().nullish(),\n cost: perplexityCostSchema.nullish()\n});\nvar perplexityImageSchema = z.object({\n image_url: z.string(),\n origin_url: z.string(),\n height: z.number(),\n width: z.number()\n});\nvar perplexityResponseSchema = z.object({\n id: z.string(),\n created: z.number(),\n model: z.string(),\n choices: z.array(\n z.object({\n message: z.object({\n role: z.literal(\"assistant\"),\n content: z.string()\n }),\n finish_reason: z.string().nullish()\n })\n ),\n citations: z.array(z.string()).nullish(),\n images: z.array(perplexityImageSchema).nullish(),\n usage: perplexityUsageSchema.nullish()\n});\nvar perplexityChunkSchema = z.object({\n id: z.string(),\n created: z.number(),\n model: z.string(),\n choices: z.array(\n z.object({\n delta: z.object({\n role: z.literal(\"assistant\"),\n content: z.string()\n }),\n finish_reason: z.string().nullish()\n })\n ),\n citations: z.array(z.string()).nullish(),\n images: z.array(perplexityImageSchema).nullish(),\n usage: perplexityUsageSchema.nullish()\n});\nvar perplexityErrorSchema = z.object({\n error: z.object({\n code: z.number(),\n message: z.string().nullish(),\n type: z.string().nullish()\n })\n});\nvar errorToMessage = (data) => {\n var _a, _b;\n return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : \"unknown error\";\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.26\" : \"0.0.0-test\";\n\n// src/perplexity-provider.ts\nfunction createPerplexity(options = {}) {\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"PERPLEXITY_API_KEY\",\n description: \"Perplexity\"\n })}`,\n ...options.headers\n },\n `ai-sdk/perplexity/${VERSION}`\n );\n const createLanguageModel = (modelId) => {\n var _a;\n return new PerplexityLanguageModel(modelId, {\n baseURL: withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.perplexity.ai\"\n ),\n headers: getHeaders,\n generateId,\n fetch: options.fetch\n });\n };\n const provider = (modelId) => createLanguageModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.languageModel = createLanguageModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar perplexity = createPerplexity();\nexport {\n VERSION,\n createPerplexity,\n perplexity\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";0WAsBA,cAAS,MAAsB,MAAC,OAAO,MACrC,SAAI,EAAI,EAAI,EACZ,GAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAY,OACZ,KAAW,OACX,UAAgB,MAClB,EACA,IAAU,MACZ,EAEF,IAAM,GAAgB,EAAK,EAAM,gBAAkB,KAAO,EAAK,EACzD,GAAoB,EAAK,EAAM,oBAAsB,KAAO,EAAK,EACjE,GAAmB,EAAK,EAAM,mBAAqB,KAAO,EAAK,EACrE,MAAO,CACL,YAAa,CACX,MAAO,EACP,QAAS,EACT,UAAgB,OAChB,WA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,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAa,EAAiB", | ||
| "debugId": "9E37ACECF15E98B664756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/plugin/sdk.ts", "../plugin/src/v2/effect/tool.ts", "../plugin/src/v2/effect/plugin.ts", "../schema/src/session.ts", "../schema/src/command.ts", "../schema/src/reference.ts"], | ||
| "sourcesContent": [ | ||
| "export * as SdkPlugins from \"./sdk\"\n\nimport type { Plugin } from \"@opencode-ai/plugin/v2/effect/plugin\"\nimport { Context, Effect, Layer } from \"effect\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { EventV2 } from \"../event\"\nimport type { PluginV2 } from \"../plugin\"\n\nexport const Updated = EventV2.ephemeral({ type: \"sdk.plugin.updated\", schema: {} })\n\n/**\n * Holds the plugins an embedder (the `@opencode-ai/sdk-next` host) contributes,\n * so `PluginSupervisor` can add them on every Location boot through the ordinary\n * generation path that `PluginSupervisor` uses for plugins discovered from\n * config. Registration publishes an unlocated update so every booted Location\n * reloads its plugin generation from the shared store.\n *\n * Each host-global layer owns one private store. Location graphs reuse that\n * layer through Effect's memoization, so separate hosts remain isolated while\n * every Location in one host sees the same registrations.\n */\nexport interface Interface {\n readonly register: (plugin: Plugin) => Effect.Effect<void>\n readonly all: () => readonly PluginV2.Versioned[]\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/SdkPlugins\") {}\n\nexport const layer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const events = yield* EventV2.Service\n const plugins = new Map<string, PluginV2.Versioned>()\n let revision = 0\n return Service.of({\n register: (plugin) =>\n Effect.sync(() => {\n plugins.set(plugin.id, { ...plugin, version: String(++revision) })\n }).pipe(Effect.andThen(events.publish(Updated, {})), Effect.asVoid),\n all: () => [...plugins.values()],\n })\n }),\n)\n\nexport const node = makeGlobalNode({ service: Service, layer, deps: [EventV2.node] })\n", | ||
| "export * as Tool from \"./tool.js\"\n\nimport { Agent } from \"@opencode-ai/schema/agent\"\nimport type { LLM } from \"@opencode-ai/schema/llm\"\nimport { Session } from \"@opencode-ai/schema/session\"\nimport { SessionMessage } from \"@opencode-ai/schema/session-message\"\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\"\nimport { Effect, JsonSchema, Schema } from \"effect\"\nimport type { Hooks, Transform } from \"./registration.js\"\n\nexport interface Context {\n readonly sessionID: Session.ID\n readonly agent: Agent.ID\n readonly messageID: SessionMessage.ID\n readonly callID: string\n readonly progress: (update: Progress) => Effect.Effect<void>\n}\n\nexport interface Progress {\n readonly structured: Readonly<Record<string, unknown>>\n readonly content?: ReadonlyArray<Content>\n}\n\nexport type StandardSchemaType<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output> &\n StandardJSONSchemaV1<Input, Output>\nexport type SchemaType<A> = Schema.Codec<A, any> | StandardSchemaType<any, A>\ntype IsAny<A> = 0 extends 1 & A ? true : false\nexport type InputValue<S> =\n IsAny<S> extends true\n ? any\n : S extends Schema.Codec<infer A, any>\n ? A\n : S extends StandardSchemaV1<any, infer A>\n ? A\n : never\nexport type OutputValue<S> =\n IsAny<S> extends true\n ? any\n : S extends Schema.Codec<infer A, any>\n ? A\n : S extends StandardSchemaV1<infer A, any>\n ? A\n : never\nexport type EncodedValue<S> =\n IsAny<S> extends true\n ? any\n : S extends Schema.Codec<any, infer A>\n ? A\n : S extends StandardSchemaV1<any, infer A>\n ? A\n : never\n\ntype ToolDefinition = {\n readonly name: string\n readonly description: string\n readonly inputSchema: JsonSchema.JsonSchema\n readonly outputSchema?: JsonSchema.JsonSchema\n}\n\ntype ToolCall = {\n readonly input: unknown\n readonly [key: string]: unknown\n}\n\ntype ToolResultValue =\n | { readonly type: \"json\"; readonly value: unknown }\n | { readonly type: \"text\"; readonly value: unknown }\n | { readonly type: \"error\"; readonly value: unknown }\n | { readonly type: \"content\"; readonly value: ReadonlyArray<LLM.ToolContent> }\n\ntype ToolOutput = {\n readonly structured: unknown\n readonly content: ReadonlyArray<LLM.ToolContent>\n}\n\nexport class Failure extends Schema.TaggedErrorClass<Failure>()(\"LLM.ToolFailure\", {\n message: Schema.String,\n error: Schema.optional(Schema.Defect()),\n metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n}) {}\n\nexport class RegistrationError extends Schema.TaggedErrorClass<RegistrationError>()(\"Tool.RegistrationError\", {\n name: Schema.String,\n message: Schema.String,\n}) {}\n\nexport type Content =\n | { readonly type: \"text\"; readonly text: string }\n | { readonly type: \"file\"; readonly data: string; readonly mime: string; readonly name?: string }\n\nexport type Definition<\n Input extends SchemaType<any>,\n Structured extends SchemaType<any>,\n Output extends SchemaType<any> = any,\n> = {\n readonly description: string\n readonly input: Input\n readonly output: Output\n readonly structured?: Structured\n readonly permission?: string\n readonly toStructuredOutput?: (input: {\n readonly input: InputValue<Input>\n readonly output: EncodedValue<Output>\n }) => OutputValue<Structured>\n readonly execute: (input: InputValue<Input>, context: Context) => Effect.Effect<OutputValue<Output>, Failure>\n readonly toModelOutput?: (input: {\n readonly input: InputValue<Input>\n readonly output: EncodedValue<Output>\n }) => ReadonlyArray<Content>\n}\n\nexport type DynamicOutput = {\n readonly structured: unknown\n readonly content: ReadonlyArray<Content>\n}\n\n/**\n * Config for a tool whose input shape is a raw JSON Schema not known at compile\n * time (MCP servers, plugin manifests). Input is passed through as `unknown`;\n * `execute` returns the already-projected structured value and model content.\n */\nexport type DynamicDefinition = {\n readonly description: string\n readonly jsonSchema: JsonSchema.JsonSchema\n readonly outputSchema?: JsonSchema.JsonSchema\n readonly permission?: string\n readonly execute: (input: unknown, context: Context) => Effect.Effect<DynamicOutput, Failure>\n}\n\nexport type AnyTool = Definition<any, any> | DynamicDefinition\n\nexport function make<\n Input extends SchemaType<any>,\n Output extends SchemaType<any>,\n Structured extends SchemaType<any> = Output,\n>(config: Definition<Input, Structured, Output>): Definition<Input, Structured, Output>\nexport function make(config: DynamicDefinition): DynamicDefinition\nexport function make(config: AnyTool): AnyTool\nexport function make(config: AnyTool): AnyTool {\n return config\n}\n\nfunction toModelContent(part: Content) {\n if (part.type === \"text\") return { type: \"text\" as const, text: part.text }\n return { type: \"file\" as const, uri: `data:${part.mime};base64,${part.data}`, mime: part.mime, name: part.name }\n}\n\nexport const validateName = (name: string) =>\n /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(name)\n ? Effect.void\n : Effect.fail(new RegistrationError({ name, message: `Invalid tool name: ${name}` }))\n\nexport const registrationEntries = (tools: Readonly<Record<string, AnyTool>>, namespace?: string) =>\n Object.entries(tools).map(([name, tool]) => {\n const normalized = name.replace(/[^a-zA-Z0-9_-]/g, \"_\")\n return {\n key: namespace === undefined ? normalized : `${namespace.replaceAll(\".\", \"_\")}_${normalized}`,\n name: normalized,\n namespace,\n tool,\n }\n })\n\nexport const validateNamespace = (namespace: string) =>\n namespace.split(\".\").every((segment) => /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(segment))\n ? Effect.void\n : Effect.fail(\n new RegistrationError({ name: namespace, message: `Invalid tool namespace: ${JSON.stringify(namespace)}` }),\n )\n\nexport const withPermission = <T extends AnyTool>(\n tool: T,\n permission: string,\n): Omit<T, \"permission\"> & {\n readonly permission: string\n} => ({ ...tool, permission })\n\nexport const permission = (tool: AnyTool, name: string) => tool.permission ?? name\n\nexport const definition = (name: string, tool: AnyTool): ToolDefinition =>\n \"jsonSchema\" in tool\n ? {\n name,\n description: tool.description,\n inputSchema: tool.jsonSchema,\n outputSchema: tool.outputSchema,\n }\n : {\n name,\n description: tool.description,\n inputSchema: inputJsonSchema(tool.input),\n outputSchema: outputJsonSchema(tool.structured ?? tool.output),\n }\n\nexport const settle = (tool: AnyTool, call: ToolCall, context: Context): Effect.Effect<ToolOutput, Failure> =>\n Effect.gen(function* () {\n if (\"jsonSchema\" in tool) {\n const output = yield* tool.execute(call.input, context)\n return { structured: output.structured, content: output.content.map(toModelContent) }\n }\n\n const input = yield* decodeInput(tool.input, call.input)\n const value = yield* tool.execute(input, context)\n const output = yield* encodeOutput(tool.output, value)\n const structured =\n tool.structured && tool.toStructuredOutput\n ? yield* encodeOutput(tool.structured, tool.toStructuredOutput({ input, output }))\n : output\n return {\n structured,\n content:\n tool.toModelOutput?.({ input, output }).map(toModelContent) ??\n (typeof output === \"string\" ? [{ type: \"text\" as const, text: output }] : []),\n }\n })\n\nfunction decodeInput(schema: SchemaType<any>, value: unknown): Effect.Effect<any, Failure> {\n if (Schema.isSchema(schema))\n return Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError((error) => new Failure({ message: `Invalid tool input: ${error.message}` })),\n )\n return validateStandard(schema, value, \"Invalid tool input\")\n}\n\nfunction encodeOutput(schema: SchemaType<any>, value: unknown): Effect.Effect<any, Failure> {\n if (Schema.isSchema(schema))\n return Schema.encodeEffect(schema)(value).pipe(\n Effect.mapError(\n (error) => new Failure({ message: `Tool returned an invalid value for its output schema: ${error.message}` }),\n ),\n )\n return validateStandard(schema, value, \"Tool returned an invalid value for its output schema\")\n}\n\nfunction validateStandard(schema: StandardSchemaType, value: unknown, prefix: string): Effect.Effect<unknown, Failure> {\n return Effect.gen(function* () {\n const pending = yield* Effect.try({\n try: () => schema[\"~standard\"].validate(value),\n catch: (error) => standardFailure(prefix, error),\n })\n const result =\n pending instanceof Promise\n ? yield* Effect.tryPromise({ try: () => pending, catch: (error) => standardFailure(prefix, error) })\n : pending\n if (result.issues)\n return yield* Effect.fail(\n new Failure({ message: `${prefix}: ${result.issues.map((issue) => issue.message).join(\", \")}` }),\n )\n return result.value\n })\n}\n\nfunction standardFailure(prefix: string, error: unknown) {\n return new Failure({ message: `${prefix}: ${error instanceof Error ? error.message : String(error)}` })\n}\n\nfunction inputJsonSchema(schema: SchemaType<any>): JsonSchema.JsonSchema {\n if (!Schema.isSchema(schema))\n return schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" }) as JsonSchema.JsonSchema\n return toJsonSchema(schema)\n}\n\nfunction outputJsonSchema(schema: SchemaType<any>): JsonSchema.JsonSchema {\n if (!Schema.isSchema(schema))\n return schema[\"~standard\"].jsonSchema.output({ target: \"draft-2020-12\" }) as JsonSchema.JsonSchema\n return toJsonSchema(schema)\n}\n\nfunction toJsonSchema(schema: Schema.Top): JsonSchema.JsonSchema {\n const document = Schema.toJsonSchemaDocument(schema)\n if (Object.keys(document.definitions).length === 0) return document.schema\n return { ...document.schema, $defs: document.definitions }\n}\n\nexport interface ToolExecuteBeforeEvent {\n readonly tool: string\n readonly sessionID: Session.ID\n readonly agent: Agent.ID\n readonly messageID: SessionMessage.ID\n readonly callID: string\n input: unknown\n}\n\nexport interface ToolExecuteAfterEvent {\n readonly tool: string\n readonly sessionID: Session.ID\n readonly agent: Agent.ID\n readonly messageID: SessionMessage.ID\n readonly callID: string\n readonly input: unknown\n result: ToolResultValue\n output?: ToolOutput\n outputPaths?: ReadonlyArray<string>\n}\n\nexport interface RegisterOptions {\n readonly namespace?: string\n /** Defaults to true. False exposes the tool directly to the provider. */\n readonly codemode?: boolean\n}\n\nexport interface ToolDraft {\n add(name: string, tool: AnyTool, options?: RegisterOptions): void\n}\n\nexport interface ToolHooks {\n readonly \"execute.before\": ToolExecuteBeforeEvent\n readonly \"execute.after\": ToolExecuteAfterEvent\n}\n\nexport interface ToolDomain {\n readonly transform: Transform<ToolDraft>\n readonly hook: Hooks<ToolHooks>\n}\n", | ||
| "import type { PluginApi } from \"@opencode-ai/client/effect/api\"\nimport type { Effect, Scope } from \"effect\"\nimport type { PluginOptions } from \"../options.js\"\nimport type { App } from \"../app.js\"\nimport type { AgentDomain } from \"./agent.js\"\nimport type { AISDKDomain } from \"./aisdk.js\"\nimport type { CatalogDomain } from \"./catalog.js\"\nimport type { CommandDomain } from \"./command.js\"\nimport type { EventDomain } from \"./event.js\"\nimport type { IntegrationDomain } from \"./integration.js\"\nimport type { ReferenceDomain } from \"./reference.js\"\nimport type { SessionDomain } from \"./session.js\"\nimport type { SkillDomain } from \"./skill.js\"\nimport type { ToolDomain } from \"./tool.js\"\n\nexport interface Context {\n readonly app: App\n readonly options: PluginOptions\n readonly agent: AgentDomain\n readonly aisdk: AISDKDomain\n readonly catalog: CatalogDomain\n readonly command: CommandDomain\n readonly event: EventDomain\n readonly integration: IntegrationDomain\n readonly plugin: PluginApi<unknown>\n readonly reference: ReferenceDomain\n readonly session: SessionDomain\n readonly skill: SkillDomain\n readonly tool: ToolDomain\n}\n\nexport interface Plugin<R = Scope.Scope> {\n readonly id: string\n readonly effect: (context: Context) => Effect.Effect<void, never, R>\n}\n\nexport function define<R = Scope.Scope>(plugin: Plugin<R>) {\n return plugin\n}\n", | ||
| "export * as Session from \"./session.js\"\n\nimport { Schema } from \"effect\"\nimport { Agent } from \"./agent.js\"\nimport { Location } from \"./location.js\"\nimport { Model } from \"./model.js\"\nimport { Project } from \"./project.js\"\nimport { DateTimeUtcFromMillis, optional, RelativePath } from \"./schema.js\"\nimport { SessionEvent } from \"./session-event.js\"\nimport { SessionID } from \"./session-id.js\"\nimport { SessionMessage } from \"./session-message.js\"\nimport { Money } from \"./money.js\"\nimport { TokenUsage } from \"./token-usage.js\"\nimport { Revert } from \"./session-revert.js\"\n\nexport const ID = SessionID\nexport type ID = SessionID\n\nexport const Event = SessionEvent\n\nexport { Revert }\n\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\nexport const Info = Schema.Struct({\n id: ID,\n parentID: ID.pipe(optional),\n fork: Schema.Struct({\n sessionID: ID,\n /** Messages before this exclusive boundary are copied into the fork. */\n messageID: SessionMessage.ID.pipe(optional),\n }).pipe(optional),\n projectID: Project.ID,\n agent: Agent.ID.pipe(optional),\n model: Model.Ref.pipe(optional),\n cost: Money.USD,\n tokens: TokenUsage.Info,\n time: Schema.Struct({\n created: DateTimeUtcFromMillis,\n updated: DateTimeUtcFromMillis,\n archived: DateTimeUtcFromMillis.pipe(optional),\n }),\n title: Schema.String,\n location: Location.Ref,\n subpath: RelativePath.pipe(optional),\n revert: Revert.pipe(optional),\n}).annotate({ identifier: \"Session.Info\" })\n\nexport const ListAnchor = Schema.Struct({\n id: ID,\n time: Schema.Finite,\n direction: Schema.Literals([\"previous\", \"next\"]),\n}).annotate({ identifier: \"Session.ListAnchor\" })\nexport interface ListAnchor extends Schema.Schema.Type<typeof ListAnchor> {}\n", | ||
| "export * as Command from \"./command.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.js\"\nimport { Model } from \"./model.js\"\nimport { Agent } from \"./agent.js\"\n\nconst Updated = ephemeral({ type: \"command.updated\", schema: {} })\n\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\nexport const Info = Schema.Struct({\n name: Schema.String,\n template: Schema.String,\n description: Schema.String.pipe(optional),\n agent: Agent.ID.pipe(optional),\n model: Model.Ref.pipe(optional),\n subtask: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Command.Info\" })\n\nexport const Event = {\n Updated,\n Definitions: inventory(Updated),\n}\n", | ||
| "export * as Reference from \"./reference.js\"\n\nimport { Schema } from \"effect\"\nimport { optional } from \"./schema.js\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { AbsolutePath } from \"./schema.js\"\n\nconst Updated = ephemeral({ type: \"reference.updated\", schema: {} })\nexport const Event = { Updated, Definitions: inventory(Updated) }\n\nexport interface LocalSource extends Schema.Schema.Type<typeof LocalSource> {}\nexport const LocalSource = Schema.Struct({\n type: Schema.Literal(\"local\"),\n path: AbsolutePath,\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Reference.LocalSource\" })\n\nexport interface GitSource extends Schema.Schema.Type<typeof GitSource> {}\nexport const GitSource = Schema.Struct({\n type: Schema.Literal(\"git\"),\n repository: Schema.String,\n branch: Schema.String.pipe(optional),\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Reference.GitSource\" })\n\nexport const Source = Schema.Union([LocalSource, GitSource])\n .pipe(Schema.toTaggedUnion(\"type\"))\n .annotate({ identifier: \"Reference.Source\" })\nexport type Source = typeof Source.Type\n\nexport const Info = Schema.Struct({\n name: Schema.String,\n path: AbsolutePath,\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n source: Source,\n}).annotate({ identifier: \"Reference.Info\" })\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\n" | ||
| ], | ||
| "mappings": ";kiBAQO,SAAM,OAAU,OAAQ,eAAU,MAAE,UAAM,qBAAsB,OAAQ,CAAC,CAAE,CAAC,EAkB5E,MAAM,UAAgB,EAAQ,QAA4B,EAAE,sBAAsB,CAAE,CAAC,CAErF,IAAM,EAAQ,EAAM,OACzB,EACA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAS,MAAO,EAAQ,QACxB,EAAU,IAAI,IAChB,EAAW,EACf,OAAO,EAAQ,GAAG,CAChB,SAAU,CAAC,IACT,EAAO,KAAK,IAAM,CAChB,EAAQ,IAAI,EAAO,GAAI,IAAK,EAAQ,QAAS,OAAO,EAAE,CAAQ,CAAE,CAAC,EAClE,EAAE,KAAK,EAAO,QAAQ,EAAO,QAAQ,EAAS,CAAC,CAAC,CAAC,EAAG,EAAO,MAAM,EACpE,IAAK,IAAM,CAAC,GAAG,EAAQ,OAAO,CAAC,CACjC,CAAC,EACF,CACH,EAEa,EAAO,EAAe,CAAE,QAAS,EAAS,QAAO,KAAM,CAAC,EAAQ,IAAI,CAAE,CAAC,6NC+B7E,MAAM,UAAgB,EAAO,iBAA0B,EAAE,kBAAmB,CACjF,QAAS,EAAO,OAChB,MA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C,CAAE,CAAC,EACtD,GAAQ,CAAE,UAAS,YAAa,EAAU,CAAO,CAAE,EAGnD,EAAc,EAAO,OAAO,CACvC,KAAM,EAAO,QAAQ,OAAO,EAC5B,KAAM,EACN,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,CACtC,CAAC,EAAE,SAAS,CAAE,WAAY,uBAAwB,CAAC,EAGtC,EAAY,EAAO,OAAO,CACrC,KAAM,EAAO,QAAQ,KAAK,EAC1B,WAAY,EAAO,OACnB,OAAQ,EAAO,OAAO,KAAK,CAAQ,EACnC,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,CACtC,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAEpC,EAAS,EAAO,MAAM,CAAC,EAAa,CAAS,CAAC,EACxD,KAAK,EAAO,cAAc,MAAM,CAAC,EACjC,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAGjC,GAAO,EAAO,OAAO,CAChC,KAAM,EAAO,OACb,KAAM,EACN,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,EACpC,OAAQ,CACV,CAAC,EAAE,SAAS,CAAE,WAAY,gBAAiB,CAAC", | ||
| "debugId": "B24B1C0698EB58AF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/openrouter.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Schema } from \"effect\"\nimport { Route, type RouteDefaultsInput } from \"../route/client\"\nimport { Endpoint } from \"../route/endpoint\"\nimport { Framing } from \"../route/framing\"\nimport { Protocol } from \"../route/protocol\"\nimport { AuthOptions, type ProviderAuthOption } from \"../route/auth-options\"\nimport { ProviderID, type ModelID, type ProviderOptions } from \"../schema\"\nimport * as OpenAICompatibleProfiles from \"./openai-compatible-profile\"\nimport * as OpenAIChat from \"../protocols/openai-chat\"\nimport { isRecord } from \"../protocols/shared\"\n\nexport const profile = OpenAICompatibleProfiles.profiles.openrouter\nexport const id = ProviderID.make(profile.provider)\nconst ADAPTER = \"openrouter\"\n\nexport interface OpenRouterOptions {\n readonly [key: string]: unknown\n readonly usage?: boolean | Record<string, unknown>\n readonly reasoning?: Record<string, unknown>\n readonly promptCacheKey?: string\n}\n\nexport type OpenRouterProviderOptionsInput = ProviderOptions & {\n readonly openrouter?: OpenRouterOptions\n}\n\nexport type ModelOptions = Omit<RouteDefaultsInput, \"providerOptions\"> &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n readonly providerOptions?: OpenRouterProviderOptionsInput\n }\n\nconst OpenRouterBody = Schema.StructWithRest(Schema.Struct(OpenAIChat.bodyFields), [\n Schema.Record(Schema.String, Schema.Any),\n])\nexport type OpenRouterBody = Schema.Schema.Type<typeof OpenRouterBody>\n\nexport const protocol = Protocol.make({\n id: \"openrouter-chat\",\n body: {\n schema: OpenRouterBody,\n from: (request) =>\n OpenAIChat.protocol.body.from(request).pipe(\n Effect.map((body) => {\n const sourceAssistants = request.messages.filter((message) => message.role === \"assistant\")\n let assistantIndex = 0\n const messages = body.messages.map((message) => {\n if (message.role !== \"assistant\") return message\n const source = sourceAssistants[assistantIndex++]\n const reasoning = source?.content\n .filter((part) => part.type === \"reasoning\")\n .map((part) => part.text)\n .join(\"\")\n const reasoningDetails = Array.isArray(message.reasoning_details) ? message.reasoning_details : undefined\n return {\n ...message,\n reasoning_content: undefined,\n reasoning_text: undefined,\n reasoning: reasoning && reasoningDetails && reasoningDetails.length > 0 ? reasoning : undefined,\n reasoning_details: reasoningDetails,\n }\n })\n return {\n ...body,\n messages,\n ...bodyOptions(request.providerOptions?.openrouter),\n } as OpenRouterBody\n }),\n ),\n },\n stream: OpenAIChat.protocol.stream,\n})\n\nconst bodyOptions = (input: unknown) => {\n const openrouter = isRecord(input) ? input : {}\n return {\n ...(openrouter.usage === true\n ? { usage: { include: true } }\n : isRecord(openrouter.usage)\n ? { usage: openrouter.usage }\n : {}),\n ...(isRecord(openrouter.reasoning) ? { reasoning: openrouter.reasoning } : {}),\n ...(typeof openrouter.promptCacheKey === \"string\" ? { prompt_cache_key: openrouter.promptCacheKey } : {}),\n }\n}\n\nexport const route = Route.make({\n id: ADAPTER,\n provider: profile.provider,\n protocol,\n endpoint: Endpoint.path(\"/chat/completions\", { baseURL: profile.baseURL }),\n framing: Framing.sse,\n})\n\nexport const routes = [route]\n\nconst configuredRoute = (input: ModelOptions) => {\n const { apiKey: _, auth: _auth, baseURL, ...rest } = input\n return route.with({\n ...rest,\n endpoint: { baseURL: baseURL ?? profile.baseURL },\n auth: AuthOptions.bearer(input, \"OPENROUTER_API_KEY\"),\n })\n}\n\nexport const configure = (input: ModelOptions = {}) => {\n const route = configuredRoute(input)\n return {\n id,\n model: (modelID: string | ModelID) => route.model({ id: modelID }),\n configure,\n }\n}\n\nexport const provider = configure()\nexport const model = provider.model\n" | ||
| ], | ||
| "mappings": ";wjBAWO,SAAM,OAAmC,OAAS,gBAC5C,OAAK,OAAW,UAAK,OAAQ,aAAQ,OAC5C,OAAU,kBAmBV,EAAiB,EAAO,eAAe,EAAO,OAAkB,CAAU,EAAG,CACjF,EAAO,OAAO,EAAO,OAAQ,EAAO,GAAG,CACzC,CAAC,EAGY,EAAW,EAAS,KAAK,CACpC,GAAI,kBACJ,KAAM,CACJ,OAAQ,EACR,KAAM,CAAC,IACM,EAAS,KAAK,KAAK,CAAO,EAAE,KACrC,EAAO,IAAI,CAAC,IAAS,CACnB,IAAM,EAAmB,EAAQ,SAAS,OAAO,CAAC,IAAY,EAAQ,OAAS,WAAW,EACtF,EAAiB,EACf,EAAW,EAAK,SAAS,IAAI,CAAC,IAAY,CAC9C,GAAI,EAAQ,OAAS,YAAa,OAAO,EAEzC,IAAM,EADS,EAAiB,MACN,QACvB,OAAO,CAAC,IAAS,EAAK,OAAS,WAAW,EAC1C,IAAI,CAAC,IAAS,EAAK,IAAI,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EAAQ,EAAS", | ||
| "debugId": "3FD38476CA3C338F64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/image/photon-wasm.bun.ts", "../core/src/image/photon.ts"], | ||
| "sourcesContent": [ | ||
| "// @ts-ignore Bun embeds static file imports when compiling the CLI.\nimport photonWasm from \"@silvia-odwyer/photon-node/photon_rs_bg.wasm\" with { type: \"file\" }\n\nexport default photonWasm\n", | ||
| "import photonWasm from \"#photon-wasm\"\nimport { Effect } from \"effect\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { FileSystem } from \"../filesystem\"\nimport { DecodeError, ResizerUnavailableError, SizeError } from \"../image\"\n\nconst JPEG_QUALITIES = [80, 85, 70, 55, 40]\n\nexport const make = Effect.gen(function* () {\n ;(globalThis as typeof globalThis & { __OPENCODE_PHOTON_WASM_PATH?: string }).__OPENCODE_PHOTON_WASM_PATH =\n path.isAbsolute(photonWasm) ? photonWasm : fileURLToPath(new URL(photonWasm, import.meta.url))\n const loadPhoton = yield* Effect.cached(\n Effect.tryPromise({\n try: () => import(\"@silvia-odwyer/photon-node\"),\n catch: () => new ResizerUnavailableError(),\n }),\n )\n return Effect.fn(\"Image.Photon.normalize\")(function* (\n resource: string,\n content: FileSystem.Content & { readonly encoding: \"base64\" },\n limits: {\n readonly autoResize: boolean\n readonly maxWidth: number\n readonly maxHeight: number\n readonly maxBase64Bytes: number\n },\n ) {\n const photon = yield* loadPhoton\n const decoded = yield* Effect.try({\n try: () => photon.PhotonImage.new_from_byteslice(Buffer.from(content.content, \"base64\")),\n catch: () => new DecodeError({ resource }),\n })\n try {\n const width = decoded.get_width()\n const height = decoded.get_height()\n const bytes = Buffer.byteLength(content.content, \"utf-8\")\n if (width <= limits.maxWidth && height <= limits.maxHeight && bytes <= limits.maxBase64Bytes) return content\n if (!limits.autoResize)\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n const scale = Math.min(1, limits.maxWidth / width, limits.maxHeight / height)\n const sizes = Array.from({ length: 32 }).reduce<Array<{ width: number; height: number }>>((acc) => {\n const previous = acc.at(-1) ?? {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n const next =\n acc.length === 0\n ? previous\n : {\n width: previous.width === 1 ? 1 : Math.max(1, Math.floor(previous.width * 0.75)),\n height: previous.height === 1 ? 1 : Math.max(1, Math.floor(previous.height * 0.75)),\n }\n return acc.some((item) => item.width === next.width && item.height === next.height) ? acc : [...acc, next]\n }, [])\n for (const size of sizes) {\n const resized = photon.resize(decoded, size.width, size.height, photon.SamplingFilter.Lanczos3)\n try {\n const encoders: Array<readonly [mime: string, encode: () => Uint8Array]> = [\n [\"image/png\", () => resized.get_bytes()],\n ...JPEG_QUALITIES.map((quality) => [\"image/jpeg\", () => resized.get_bytes_jpeg(quality)] as const),\n ]\n for (const [mime, encode] of encoders) {\n const candidate = Buffer.from(encode()).toString(\"base64\")\n if (Buffer.byteLength(candidate, \"utf-8\") <= limits.maxBase64Bytes)\n return { ...content, content: candidate, encoding: \"base64\" as const, mime }\n }\n } finally {\n resized.free()\n }\n }\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n } finally {\n decoded.free()\n }\n })\n})\n" | ||
| ], | ||
| "mappings": ";6zBAGA,SAAe,SCDf,yBACA,6BAAS,iBAIT,SAAM,OAAiB,MAAC,QAAI,QAAI,QAAI,QAAI,OAAE,OAE7B,OAAO,OAAO,SAAI,cAAU,OAAG,MACxC,gBAA4E,0CAC5E,EAAK,WAAW,CAAU,EAAI,EAAa,EAAc,IAAI,IAAI,EAAY,YAAY,GAAG,CAAC,EAC/F,IAAM,EAAa,MAAO,EAAO,OAC/B,EAAO,WAAW,CAChB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AK,OAAS,EAAK,SAAW,EAAK,MAAM,EAAI,EAAM,CAAC,GAAG,EAAK,CAAI,GACxG,CAAC,CAAC,EACL,QAAW,KAAQ,EAAO,CACxB,IAAM,EAAU,EAAO,OAAO,EAAS,EAAK,MAAO,EAAK,OAAQ,EAAO,eAAe,QAAQ,EAC9F,GAAI,CACF,IAAM,EAAqE,CACzE,CAAC,YAAa,IAAM,EAAQ,UAAU,CAAC,EACvC,GAAG,EAAe,IAAI,CAAC,IAAY,CAAC,aAAc,IAAM,EAAQ,eAAe,CAAO,CAAC,CAAU,CACnG,EACA,QAAY,EAAM,KAAW,EAAU,CACrC,IAAM,EAAY,OAAO,KAAK,EAAO,CAAC,EAAE,SAAS,QAAQ,EACzD,GAAI,OAAO,WAAW,EAAW,OAAO,GAAK,EAAO,eAClD,MAAO,IAAK,EAAS,QAAS,EAAW,SAAU,SAAmB,MAAK,UAE/E,CACA,EAAQ,KAAK,GAGjB,OAAO,MAAO,IAAI,EAAU,CAC1B,WACA,QACA,SACA,QACA,SAAU,EAAO,SACjB,UAAW,EAAO,UAClB,SAAU,EAAO,cACnB,CAAC,SACD,CACA,EAAQ,KAAK,GAEhB,EACF", | ||
| "debugId": "7AE69DD57C5E51F364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/add.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { readFile, stat, writeFile } from \"node:fs/promises\"\nimport { Effect, Option } from \"effect\"\nimport { applyEdits, modify } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.add,\n Effect.fn(\"cli.mcp.add\")(function* (input) {\n const url = Option.getOrUndefined(input.url)\n const headers = Option.getOrUndefined(input.header)\n const environment = Option.getOrUndefined(input.env)\n // The CLI framework strands `--` operands on the root command, so read the local server command\n // straight from argv after `--`. This also lets the command carry its own flags (e.g. `npx -y`).\n const dash = process.argv.indexOf(\"--\")\n const command = dash === -1 ? [...input.command] : process.argv.slice(dash + 1)\n\n const hasCommand = command.length > 0\n if (url && hasCommand)\n return yield* Effect.fail(new Error(\"Provide either --url <url> or a command after --, not both\"))\n if (!url && !hasCommand) return yield* Effect.fail(new Error(\"Provide either --url <url> or a command after --\"))\n if (url && !URL.canParse(url)) return yield* Effect.fail(new Error(`Invalid URL: ${url}`))\n if (url && environment) return yield* Effect.fail(new Error(\"--env is only valid for local MCP servers\"))\n if (hasCommand && headers) return yield* Effect.fail(new Error(\"--header is only valid for remote MCP servers\"))\n\n const server = url\n ? { type: \"remote\" as const, url, ...(headers ? { headers } : {}) }\n : { type: \"local\" as const, command, ...(environment ? { environment } : {}) }\n\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(input.global ? global.config : process.cwd()))\n yield* Effect.promise(() => write(configPath, input.name, server))\n process.stdout.write(`MCP server \"${input.name}\" added to ${configPath}` + EOL)\n }),\n)\n\nexport async function resolveConfigPath(directory: string) {\n const candidates = [\n path.join(directory, \"opencode.json\"),\n path.join(directory, \"opencode.jsonc\"),\n path.join(directory, \".opencode\", \"opencode.json\"),\n path.join(directory, \".opencode\", \"opencode.jsonc\"),\n ]\n for (const candidate of candidates) {\n if (\n await stat(candidate).then(\n (info) => info.isFile(),\n () => false,\n )\n )\n return candidate\n }\n return candidates[0]\n}\n\nasync function write(configPath: string, name: string, server: unknown) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return \"{}\"\n throw error\n })\n const edits = modify(text, [\"mcp\", \"servers\", name], server, {\n formattingOptions: { tabSize: 2, insertSpaces: true },\n })\n await writeFile(configPath, applyEdits(text, edits))\n}\n" | ||
| ], | ||
| "mappings": ";qrBAAA,mBAAS,gBACT,yBACA,wBAAS,eAAU,oBAA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K,EAAW,eAAe,EACpC,EAAK,KAAK,EAAW,gBAAgB,EACrC,EAAK,KAAK,EAAW,YAAa,eAAe,EACjD,EAAK,KAAK,EAAW,YAAa,gBAAgB,CACpD,EACA,QAAW,KAAa,EACtB,GACE,MAAM,EAAK,CAAS,EAAE,KACpB,CAAC,IAAS,EAAK,OAAO,EACtB,IAAM,EACR,EAEA,OAAO,EAEX,OAAO,EAAW,GAGpB,eAAe,CAAK,CAAC,EAAoB,EAAc,EAAiB,CACtE,IAAM,EAAO,MAAM,EAAS,EAAY,MAAM,EAAE,MAAM,CAAC,IAAU,CAC/D,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,SAAU,GAAS,EAAM,OAAS,SAAU,MAAO,KACtG,MAAM,EACP,EACK,EAAQ,EAAO,EAAM,CAAC,MAAO,UAAW,CAAI,EAAG,EAAQ,CAC3D,kBAAmB,CAAE,QAAS,EAAG,aAAc,EAAK,CACtD,CAAC,EACD,MAAM,EAAU,EAAY,EAAW,EAAM,CAAK,CAAC", | ||
| "debugId": "5935E728C5B31F9964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+groq@3.0.31+d6123d32214422cb/node_modules/@ai-sdk/groq/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/groq-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/groq-chat-language-model.ts\nimport {\n InvalidResponseDataError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n generateId,\n isParsableJson,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/convert-groq-usage.ts\nfunction convertGroqUsage(usage) {\n var _a, _b, _c, _d;\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;\n const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;\n const reasoningTokens = (_d = (_c = usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : void 0;\n const textTokens = reasoningTokens != null ? completionTokens - reasoningTokens : completionTokens;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: textTokens,\n reasoning: reasoningTokens\n },\n raw: usage\n };\n}\n\n// src/convert-to-groq-chat-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertToBase64 } from \"@ai-sdk/provider-utils\";\nfunction convertToGroqChatMessages(prompt) {\n var _a;\n const messages = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n if (content.length === 1 && content[0].type === \"text\") {\n messages.push({ role: \"user\", content: content[0].text });\n break;\n }\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n switch (part.type) {\n case \"text\": {\n return { type: \"text\", text: part.text };\n }\n case \"file\": {\n if (!part.mediaType.startsWith(\"image/\")) {\n throw new UnsupportedFunctionalityError({\n functionality: \"Non-image file content parts\"\n });\n }\n const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType;\n return {\n type: \"image_url\",\n image_url: {\n url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`\n }\n };\n }\n }\n })\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n let reasoning = \"\";\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n // groq supports reasoning for tool-calls in multi-turn conversations\n // https://github.com/vercel/ai/issues/7860\n case \"reasoning\": {\n reasoning += part.text;\n break;\n }\n case \"text\": {\n text += part.text;\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: text,\n ...reasoning.length > 0 ? { reasoning } : null,\n ...toolCalls.length > 0 ? { tool_calls: toolCalls } : null\n });\n break;\n }\n case \"tool\": {\n for (const toolResponse of content) {\n if (toolResponse.type === \"tool-approval-response\") {\n continue;\n }\n const output = toolResponse.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n messages.push({\n role: \"tool\",\n tool_call_id: toolResponse.toolCallId,\n content: contentValue\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/get-response-metadata.ts\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id: id != null ? id : void 0,\n modelId: model != null ? model : void 0,\n timestamp: created != null ? new Date(created * 1e3) : void 0\n };\n}\n\n// src/groq-chat-options.ts\nimport { z } from \"zod/v4\";\nvar groqLanguageModelOptions = z.object({\n reasoningFormat: z.enum([\"parsed\", \"raw\", \"hidden\"]).optional(),\n /**\n * Specifies the reasoning effort level for model inference.\n * @see https://console.groq.com/docs/reasoning#reasoning-effort\n */\n reasoningEffort: z.enum([\"none\", \"default\", \"low\", \"medium\", \"high\"]).optional(),\n /**\n * Whether to enable parallel function calling during tool use. Default to true.\n */\n parallelToolCalls: z.boolean().optional(),\n /**\n * A unique identifier representing your end-user, which can help OpenAI to\n * monitor and detect abuse. Learn more.\n */\n user: z.string().optional(),\n /**\n * Whether to use structured outputs.\n *\n * @default true\n */\n structuredOutputs: z.boolean().optional(),\n /**\n * Whether to use strict JSON schema validation.\n * When true, the model uses constrained decoding to guarantee schema compliance.\n * Only used when structured outputs are enabled and a schema is provided.\n *\n * @default true\n */\n strictJsonSchema: z.boolean().optional(),\n /**\n * Service tier for the request.\n * - 'on_demand': Default tier with consistent performance and fairness\n * - 'flex': Higher throughput tier optimized for workloads that can handle occasional request failures\n * - 'auto': Uses on_demand rate limits, then falls back to flex tier if exceeded\n *\n * @default 'on_demand'\n */\n serviceTier: z.enum([\"on_demand\", \"flex\", \"auto\"]).optional()\n});\n\n// src/groq-error.ts\nimport { z as z2 } from \"zod/v4\";\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nvar groqErrorDataSchema = z2.object({\n error: z2.object({\n message: z2.string(),\n type: z2.string()\n })\n});\nvar groqFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: groqErrorDataSchema,\n errorToMessage: (data) => data.error.message\n});\n\n// src/groq-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\n\n// src/groq-browser-search-models.ts\nvar BROWSER_SEARCH_SUPPORTED_MODELS = [\n \"openai/gpt-oss-20b\",\n \"openai/gpt-oss-120b\"\n];\nfunction isBrowserSearchSupportedModel(modelId) {\n return BROWSER_SEARCH_SUPPORTED_MODELS.includes(modelId);\n}\nfunction getSupportedModelsString() {\n return BROWSER_SEARCH_SUPPORTED_MODELS.join(\", \");\n}\n\n// src/groq-prepare-tools.ts\nfunction prepareTools({\n tools,\n toolChoice,\n modelId\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const groqTools2 = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n if (tool.id === \"groq.browser_search\") {\n if (!isBrowserSearchSupportedModel(modelId)) {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`,\n details: `Browser search is only supported on the following models: ${getSupportedModelsString()}. Current model: ${modelId}`\n });\n } else {\n groqTools2.push({\n type: \"browser_search\"\n });\n }\n } else {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n }\n } else {\n groqTools2.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n ...tool.strict != null ? { strict: tool.strict } : {}\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: groqTools2, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n case \"none\":\n case \"required\":\n return { tools: groqTools2, toolChoice: type, toolWarnings };\n case \"tool\":\n return {\n tools: groqTools2,\n toolChoice: {\n type: \"function\",\n function: {\n name: toolChoice.toolName\n }\n },\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError2({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/map-groq-finish-reason.ts\nfunction mapGroqFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n return \"length\";\n case \"content_filter\":\n return \"content-filter\";\n case \"function_call\":\n case \"tool_calls\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/groq-chat-language-model.ts\nvar GroqChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n \"image/*\": [/^https?:\\/\\/.*$/]\n };\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n stream,\n tools,\n toolChoice,\n providerOptions\n }) {\n var _a, _b, _c;\n const warnings = [];\n const groqOptions = await parseProviderOptions({\n provider: \"groq\",\n providerOptions,\n schema: groqLanguageModelOptions\n });\n const structuredOutputs = (_a = groqOptions == null ? void 0 : groqOptions.structuredOutputs) != null ? _a : true;\n const strictJsonSchema = (_b = groqOptions == null ? void 0 : groqOptions.strictJsonSchema) != null ? _b : true;\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n if ((responseFormat == null ? void 0 : responseFormat.type) === \"json\" && responseFormat.schema != null && !structuredOutputs) {\n warnings.push({\n type: \"unsupported\",\n feature: \"responseFormat\",\n details: \"JSON response format schema is only supported with structuredOutputs\"\n });\n }\n const {\n tools: groqTools2,\n toolChoice: groqToolChoice,\n toolWarnings\n } = prepareTools({ tools, toolChoice, modelId: this.modelId });\n return {\n args: {\n // model id:\n model: this.modelId,\n // model specific settings:\n user: groqOptions == null ? void 0 : groqOptions.user,\n parallel_tool_calls: groqOptions == null ? void 0 : groqOptions.parallelToolCalls,\n // standardized settings:\n max_tokens: maxOutputTokens,\n temperature,\n top_p: topP,\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n stop: stopSequences,\n seed,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? structuredOutputs && responseFormat.schema != null ? {\n type: \"json_schema\",\n json_schema: {\n schema: responseFormat.schema,\n strict: strictJsonSchema,\n name: (_c = responseFormat.name) != null ? _c : \"response\",\n description: responseFormat.description\n }\n } : { type: \"json_object\" } : void 0,\n // provider options:\n reasoning_format: groqOptions == null ? void 0 : groqOptions.reasoningFormat,\n reasoning_effort: groqOptions == null ? void 0 : groqOptions.reasoningEffort,\n service_tier: groqOptions == null ? void 0 : groqOptions.serviceTier,\n // messages:\n messages: convertToGroqChatMessages(prompt),\n // tools:\n tools: groqTools2,\n tool_choice: groqToolChoice\n },\n warnings: [...warnings, ...toolWarnings]\n };\n }\n async doGenerate(options) {\n var _a, _b;\n const { args, warnings } = await this.getArgs({\n ...options,\n stream: false\n });\n const body = JSON.stringify(args);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: this.config.url({\n path: \"/chat/completions\",\n modelId: this.modelId\n }),\n headers: combineHeaders(this.config.headers(), options.headers),\n body: args,\n failedResponseHandler: groqFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n groqChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n const text = choice.message.content;\n if (text != null && text.length > 0) {\n content.push({ type: \"text\", text });\n }\n const reasoning = choice.message.reasoning;\n if (reasoning != null && reasoning.length > 0) {\n content.push({\n type: \"reasoning\",\n text: reasoning\n });\n }\n if (choice.message.tool_calls != null) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: \"tool-call\",\n toolCallId: (_a = toolCall.id) != null ? _a : generateId(),\n toolName: toolCall.function.name,\n input: toolCall.function.arguments\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapGroqFinishReason(choice.finish_reason),\n raw: (_b = choice.finish_reason) != null ? _b : void 0\n },\n usage: convertGroqUsage(response.usage),\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n request: { body }\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs({ ...options, stream: true });\n const body = JSON.stringify({ ...args, stream: true });\n const { responseHeaders, value: response } = await postJsonToApi({\n url: this.config.url({\n path: \"/chat/completions\",\n modelId: this.modelId\n }),\n headers: combineHeaders(this.config.headers(), options.headers),\n body: {\n ...args,\n stream: true\n },\n failedResponseHandler: groqFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(groqChatChunkSchema),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const toolCalls = [];\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let isFirstChunk = true;\n let isActiveText = false;\n let isActiveReasoning = false;\n let providerMetadata;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n finishReason = {\n unified: \"error\",\n raw: void 0\n };\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (\"error\" in value) {\n finishReason = {\n unified: \"error\",\n raw: void 0\n };\n controller.enqueue({ type: \"error\", error: value.error });\n return;\n }\n if (isFirstChunk) {\n isFirstChunk = false;\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n }\n if (((_a = value.x_groq) == null ? void 0 : _a.usage) != null) {\n usage = value.x_groq.usage;\n }\n const choice = value.choices[0];\n if ((choice == null ? void 0 : choice.finish_reason) != null) {\n finishReason = {\n unified: mapGroqFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n if ((choice == null ? void 0 : choice.delta) == null) {\n return;\n }\n const delta = choice.delta;\n if (delta.reasoning != null && delta.reasoning.length > 0) {\n if (!isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-start\",\n id: \"reasoning-0\"\n });\n isActiveReasoning = true;\n }\n controller.enqueue({\n type: \"reasoning-delta\",\n id: \"reasoning-0\",\n delta: delta.reasoning\n });\n }\n if (delta.content != null && delta.content.length > 0) {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: \"reasoning-0\"\n });\n isActiveReasoning = false;\n }\n if (!isActiveText) {\n controller.enqueue({ type: \"text-start\", id: \"txt-0\" });\n isActiveText = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"txt-0\",\n delta: delta.content\n });\n }\n if (delta.tool_calls != null) {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: \"reasoning-0\"\n });\n isActiveReasoning = false;\n }\n for (const toolCallDelta of delta.tool_calls) {\n const index = toolCallDelta.index;\n if (toolCalls[index] == null) {\n if (toolCallDelta.type !== \"function\") {\n throw new InvalidResponseDataError({\n data: toolCallDelta,\n message: `Expected 'function' type.`\n });\n }\n if (toolCallDelta.id == null) {\n throw new InvalidResponseDataError({\n data: toolCallDelta,\n message: `Expected 'id' to be a string.`\n });\n }\n if (((_b = toolCallDelta.function) == null ? void 0 : _b.name) == null) {\n throw new InvalidResponseDataError({\n data: toolCallDelta,\n message: `Expected 'function.name' to be a string.`\n });\n }\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolCallDelta.id,\n toolName: toolCallDelta.function.name\n });\n toolCalls[index] = {\n id: toolCallDelta.id,\n type: \"function\",\n function: {\n name: toolCallDelta.function.name,\n arguments: (_c = toolCallDelta.function.arguments) != null ? _c : \"\"\n },\n hasFinished: false\n };\n const toolCall2 = toolCalls[index];\n if (((_d = toolCall2.function) == null ? void 0 : _d.name) != null && ((_e = toolCall2.function) == null ? void 0 : _e.arguments) != null) {\n if (toolCall2.function.arguments.length > 0) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCall2.id,\n delta: toolCall2.function.arguments\n });\n }\n if (isParsableJson(toolCall2.function.arguments)) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCall2.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: (_f = toolCall2.id) != null ? _f : generateId(),\n toolName: toolCall2.function.name,\n input: toolCall2.function.arguments\n });\n toolCall2.hasFinished = true;\n }\n }\n continue;\n }\n const toolCall = toolCalls[index];\n if (toolCall.hasFinished) {\n continue;\n }\n if (((_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null) {\n toolCall.function.arguments += (_i = (_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null ? _i : \"\";\n }\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCall.id,\n delta: (_j = toolCallDelta.function.arguments) != null ? _j : \"\"\n });\n if (((_k = toolCall.function) == null ? void 0 : _k.name) != null && ((_l = toolCall.function) == null ? void 0 : _l.arguments) != null && isParsableJson(toolCall.function.arguments)) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCall.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: (_m = toolCall.id) != null ? _m : generateId(),\n toolName: toolCall.function.name,\n input: toolCall.function.arguments\n });\n toolCall.hasFinished = true;\n }\n }\n }\n },\n flush(controller) {\n if (isActiveReasoning) {\n controller.enqueue({ type: \"reasoning-end\", id: \"reasoning-0\" });\n }\n if (isActiveText) {\n controller.enqueue({ type: \"text-end\", id: \"txt-0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertGroqUsage(usage),\n ...providerMetadata != null ? { providerMetadata } : {}\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nvar groqChatResponseSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n message: z3.object({\n content: z3.string().nullish(),\n reasoning: z3.string().nullish(),\n tool_calls: z3.array(\n z3.object({\n id: z3.string().nullish(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n ).nullish()\n }),\n index: z3.number(),\n finish_reason: z3.string().nullish()\n })\n ),\n usage: z3.object({\n prompt_tokens: z3.number().nullish(),\n completion_tokens: z3.number().nullish(),\n total_tokens: z3.number().nullish(),\n prompt_tokens_details: z3.object({\n cached_tokens: z3.number().nullish()\n }).nullish(),\n completion_tokens_details: z3.object({\n reasoning_tokens: z3.number().nullish()\n }).nullish()\n }).nullish()\n});\nvar groqChatChunkSchema = z3.union([\n z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n delta: z3.object({\n content: z3.string().nullish(),\n reasoning: z3.string().nullish(),\n tool_calls: z3.array(\n z3.object({\n index: z3.number(),\n id: z3.string().nullish(),\n type: z3.literal(\"function\").optional(),\n function: z3.object({\n name: z3.string().nullish(),\n arguments: z3.string().nullish()\n })\n })\n ).nullish()\n }).nullish(),\n finish_reason: z3.string().nullable().optional(),\n index: z3.number()\n })\n ),\n x_groq: z3.object({\n usage: z3.object({\n prompt_tokens: z3.number().nullish(),\n completion_tokens: z3.number().nullish(),\n total_tokens: z3.number().nullish(),\n prompt_tokens_details: z3.object({\n cached_tokens: z3.number().nullish()\n }).nullish(),\n completion_tokens_details: z3.object({\n reasoning_tokens: z3.number().nullish()\n }).nullish()\n }).nullish()\n }).nullish()\n }),\n groqErrorDataSchema\n]);\n\n// src/groq-transcription-model.ts\nimport {\n combineHeaders as combineHeaders2,\n convertBase64ToUint8Array,\n createJsonResponseHandler as createJsonResponseHandler2,\n mediaTypeToExtension,\n parseProviderOptions as parseProviderOptions2,\n postFormDataToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\n\n// src/groq-transcription-options.ts\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\nvar groqTranscriptionModelOptions = lazySchema(\n () => zodSchema(\n z4.object({\n language: z4.string().nullish(),\n prompt: z4.string().nullish(),\n responseFormat: z4.string().nullish(),\n temperature: z4.number().min(0).max(1).nullish(),\n timestampGranularities: z4.array(z4.string()).nullish()\n })\n )\n);\n\n// src/groq-transcription-model.ts\nvar GroqTranscriptionModel = class {\n constructor(modelId, config) {\n this.modelId = modelId;\n this.config = config;\n this.specificationVersion = \"v3\";\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n audio,\n mediaType,\n providerOptions\n }) {\n var _a, _b, _c, _d, _e;\n const warnings = [];\n const groqOptions = await parseProviderOptions2({\n provider: \"groq\",\n providerOptions,\n schema: groqTranscriptionModelOptions\n });\n const formData = new FormData();\n const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);\n formData.append(\"model\", this.modelId);\n const fileExtension = mediaTypeToExtension(mediaType);\n formData.append(\n \"file\",\n new File([blob], \"audio\", { type: mediaType }),\n `audio.${fileExtension}`\n );\n if (groqOptions) {\n const transcriptionModelOptions = {\n language: (_a = groqOptions.language) != null ? _a : void 0,\n prompt: (_b = groqOptions.prompt) != null ? _b : void 0,\n response_format: (_c = groqOptions.responseFormat) != null ? _c : void 0,\n temperature: (_d = groqOptions.temperature) != null ? _d : void 0,\n timestamp_granularities: (_e = groqOptions.timestampGranularities) != null ? _e : void 0\n };\n for (const key in transcriptionModelOptions) {\n const value = transcriptionModelOptions[key];\n if (value !== void 0) {\n if (Array.isArray(value)) {\n for (const item of value) {\n formData.append(`${key}[]`, String(item));\n }\n } else {\n formData.append(key, String(value));\n }\n }\n }\n }\n return {\n formData,\n warnings\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g;\n const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();\n const { formData, warnings } = await this.getArgs(options);\n const {\n value: response,\n responseHeaders,\n rawValue: rawResponse\n } = await postFormDataToApi({\n url: this.config.url({\n path: \"/audio/transcriptions\",\n modelId: this.modelId\n }),\n headers: combineHeaders2(this.config.headers(), options.headers),\n formData,\n failedResponseHandler: groqFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n groqTranscriptionResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n return {\n text: response.text,\n segments: (_e = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({\n text: segment.text,\n startSecond: segment.start,\n endSecond: segment.end\n }))) != null ? _e : [],\n language: (_f = response.language) != null ? _f : void 0,\n durationInSeconds: (_g = response.duration) != null ? _g : void 0,\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawResponse\n }\n };\n }\n};\nvar groqTranscriptionResponseSchema = z5.object({\n text: z5.string(),\n x_groq: z5.object({\n id: z5.string()\n }),\n // additional properties are returned when `response_format: 'verbose_json'` is\n task: z5.string().nullish(),\n language: z5.string().nullish(),\n duration: z5.number().nullish(),\n segments: z5.array(\n z5.object({\n id: z5.number(),\n seek: z5.number(),\n start: z5.number(),\n end: z5.number(),\n text: z5.string(),\n tokens: z5.array(z5.number()),\n temperature: z5.number(),\n avg_logprob: z5.number(),\n compression_ratio: z5.number(),\n no_speech_prob: z5.number()\n })\n ).nullish()\n});\n\n// src/tool/browser-search.ts\nimport { createProviderToolFactory } from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar browserSearch = createProviderToolFactory({\n id: \"groq.browser_search\",\n inputSchema: z6.object({})\n});\n\n// src/groq-tools.ts\nvar groqTools = {\n browserSearch\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.31\" : \"0.0.0-test\";\n\n// src/groq-provider.ts\nfunction createGroq(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.groq.com/openai/v1\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"GROQ_API_KEY\",\n description: \"Groq\"\n })}`,\n ...options.headers\n },\n `ai-sdk/groq/${VERSION}`\n );\n const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {\n provider: \"groq.chat\",\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createLanguageModel = (modelId) => {\n if (new.target) {\n throw new Error(\n \"The Groq model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n const createTranscriptionModel = (modelId) => {\n return new GroqTranscriptionModel(modelId, {\n provider: \"groq.transcription\",\n url: ({ path }) => `${baseURL}${path}`,\n headers: getHeaders,\n fetch: options.fetch\n });\n };\n const provider = function(modelId) {\n return createLanguageModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createLanguageModel;\n provider.chat = createChatModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n provider.transcription = createTranscriptionModel;\n provider.transcriptionModel = createTranscriptionModel;\n provider.tools = groqTools;\n return provider;\n}\nvar groq = createGroq();\nexport {\n VERSION,\n browserSearch,\n createGroq,\n groq\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";ybA0BA,cAAS,MAAgB,MAAC,OAAO,MAC/B,SAAI,EAAI,EAAI,EAAI,EAChB,GAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAY,OACZ,KAAW,OACX,UAAgB,MAClB,EACA,IAAU,MACZ,EAEF,IAAM,GAAgB,EAAK,EAAM,gBAAkB,KAAO,EAAK,EACzD,GAAoB,EAAK,EAAM,oBAAsB,KAAO,EAAK,EACjE,GAAmB,GAAM,EAAK,EAAM,4BAA8B,KAAY,OAAI,EAAG,mBAAqB,KAAO,EAAU,OAC3H,EAAa,GAAmB,KAAO,EAAmB,EAAkB,EAClF,MAAO,CACL,YAAa,CACX,MAAO,EACP,QAAS,EACT,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAO,EACP,KAAM,EACN,UAAW,CACb,EACA,IAAK,CACP,EAQF,SAAS,EAAyB,CAAC,EAAQ,CACzC,IAAI,EACJ,IAAM,EAAW,CAAC,EAClB,QAAa,OAAM,aAAa,EAC9B,OAAQ,OACD,SAAU,CACb,EAAS,KAAK,CAAE,KAAM,SAAU,SAAQ,CAAC,EACzC,KACF,KACK,OAAQ,CACX,GAAI,EAAQ,SAAW,GAAK,EAAQ,GAAG,OAAS,OAAQ,CACtD,EAAS,KAAK,CAAE,KAAM,OAAQ,QAAS,EAAQ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jB,CAAC,GAEG,EAAW,QAAQ,CAAC,EAAS,CACjC,OAAO,EAAoB,CAAO,GAepC,OAbA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,KAAO,EAChB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAEjE,EAAS,cAAgB,EACzB,EAAS,mBAAqB,EAC9B,EAAS,MAAQ,GACV,EAET,IAAI,GAAO,GAAW", | ||
| "debugId": "E779DA0EFA008FC964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.59/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js", "../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.59/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.59/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js"], | ||
| "sourcesContent": [ | ||
| "import { getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { resolveProcessCredentials } from \"./resolveProcessCredentials\";\nexport const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-process - fromProcess\");\n const profiles = await parseKnownFiles(init);\n return resolveProcessCredentials(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init.logger);\n};\n", | ||
| "import { CredentialsProviderError, externalDataInterceptor } from \"@smithy/core/config\";\nimport { exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { getValidatedProcessCredentials } from \"./getValidatedProcessCredentials\";\nexport const resolveProcessCredentials = async (profileName, profiles, logger) => {\n const profile = profiles[profileName];\n if (profiles[profileName]) {\n const credentialProcess = profile[\"credential_process\"];\n if (credentialProcess !== undefined) {\n const execPromise = promisify(externalDataInterceptor?.getTokenRecord?.().exec ?? exec);\n try {\n const { stdout } = await execPromise(credentialProcess);\n let data;\n try {\n data = JSON.parse(stdout.trim());\n }\n catch {\n throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);\n }\n return getValidatedProcessCredentials(profileName, data, profiles);\n }\n catch (error) {\n throw new CredentialsProviderError(error.message, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {\n logger,\n });\n }\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const getValidatedProcessCredentials = (profileName, data, profiles) => {\n if (data.Version !== 1) {\n throw Error(`Profile ${profileName} credential_process did not return Version 1.`);\n }\n if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {\n throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);\n }\n if (data.Expiration) {\n const currentTime = new Date();\n const expireTime = new Date(data.Expiration);\n if (expireTime < currentTime) {\n throw Error(`Profile ${profileName} credential_process returned expired credentials.`);\n }\n }\n let accountId = data.AccountId;\n if (!accountId && profiles?.[profileName]?.aws_account_id) {\n accountId = profiles[profileName].aws_account_id;\n }\n const credentials = {\n accessKeyId: data.AccessKeyId,\n secretAccessKey: data.SecretAccessKey,\n ...(data.SessionToken && { sessionToken: data.SessionToken }),\n ...(data.Expiration && { expiration: new Date(data.Expiration) }),\n ...(data.CredentialScope && { credentialScope: data.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_PROCESS\", \"w\");\n return credentials;\n};\n" | ||
| ], | ||
| "mappings": ";kJAAA,oBCAA,oBACA,eAAS,sBACT,oB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,2BAAyB,WAAW,mDAA8D,CACxG,QACJ,CAAC,GD9BF,IAAM,EAAc,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CAC7E,EAAK,QAAQ,MAAM,oDAAoD,EACvE,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAA0B,iBAAe,CAC5C,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAK,MAAM", | ||
| "debugId": "7C245390BD821FD664756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-login@3.972.66/node_modules/@aws-sdk/credential-provider-login/dist-es/fromLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-login@3.972.66/node_modules/@aws-sdk/credential-provider-login/dist-es/LoginCredentialsFetcher.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { LoginCredentialsFetcher } from \"./LoginCredentialsFetcher\";\nexport const fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => {\n init?.logger?.debug?.(\"@aws-sdk/credential-providers - fromLoginCredentials\");\n const profiles = await parseKnownFiles(init || {});\n const profileName = getProfileName({\n profile: init?.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile?.login_session) {\n throw new CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, {\n tryNextLink: true,\n logger: init?.logger,\n });\n }\n const fetcher = new LoginCredentialsFetcher(profile, init, callerClientConfig);\n const credentials = await fetcher.loadCredentials();\n return setCredentialFeature(credentials, \"CREDENTIALS_LOGIN\", \"AD\");\n};\n", | ||
| "import { CredentialsProviderError, readFile } from \"@smithy/core/config\";\nimport { HttpRequest } from \"@smithy/core/protocols\";\nimport { createHash, createPrivateKey, createPublicKey, sign } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nexport class LoginCredentialsFetcher {\n profileData;\n init;\n callerClientConfig;\n static REFRESH_THRESHOLD = 5 * 60 * 1000;\n constructor(profileData, init, callerClientConfig) {\n this.profileData = profileData;\n this.init = init;\n this.callerClientConfig = callerClientConfig;\n }\n async loadCredentials() {\n const token = await this.loadToken();\n if (!token) {\n throw new CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger });\n }\n const accessToken = token.accessToken;\n const now = Date.now();\n const expiryTime = new Date(accessToken.expiresAt).getTime();\n const timeUntilExpiry = expiryTime - now;\n if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) {\n return this.refresh(token);\n }\n return {\n accessKeyId: accessToken.accessKeyId,\n secretAccessKey: accessToken.secretAccessKey,\n sessionToken: accessToken.sessionToken,\n accountId: accessToken.accountId,\n expiration: new Date(accessToken.expiresAt),\n };\n }\n get logger() {\n return this.init?.logger;\n }\n get loginSession() {\n return this.profileData.login_session;\n }\n async refresh(token) {\n const { SigninClient, CreateOAuth2TokenCommand } = await import(\"@aws-sdk/nested-clients/signin\");\n const { logger, userAgentAppId } = this.callerClientConfig ?? {};\n const isH2 = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\";\n };\n const requestHandler = isH2(this.callerClientConfig?.requestHandler)\n ? undefined\n : this.callerClientConfig?.requestHandler;\n const region = this.profileData.region ?? (await this.callerClientConfig?.region?.()) ?? process.env.AWS_REGION;\n const client = new SigninClient({\n credentials: {\n accessKeyId: \"\",\n secretAccessKey: \"\",\n },\n region,\n requestHandler,\n logger,\n userAgentAppId,\n ...this.init?.clientConfig,\n });\n this.createDPoPInterceptor(client.middlewareStack);\n const commandInput = {\n tokenInput: {\n clientId: token.clientId,\n refreshToken: token.refreshToken,\n grantType: \"refresh_token\",\n },\n };\n try {\n const response = await client.send(new CreateOAuth2TokenCommand(commandInput));\n const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {};\n const { refreshToken, expiresIn } = response.tokenOutput ?? {};\n if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) {\n throw new CredentialsProviderError(\"Token refresh response missing required fields\", {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n const expiresInMs = (expiresIn ?? 900) * 1000;\n const expiration = new Date(Date.now() + expiresInMs);\n const updatedToken = {\n ...token,\n accessToken: {\n ...token.accessToken,\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiresAt: expiration.toISOString(),\n },\n refreshToken,\n };\n await this.saveToken(updatedToken);\n const newAccessToken = updatedToken.accessToken;\n return {\n accessKeyId: newAccessToken.accessKeyId,\n secretAccessKey: newAccessToken.secretAccessKey,\n sessionToken: newAccessToken.sessionToken,\n accountId: newAccessToken.accountId,\n expiration,\n };\n }\n catch (error) {\n if (error.name === \"AccessDeniedException\") {\n const errorType = error.error;\n let message;\n switch (errorType) {\n case \"TOKEN_EXPIRED\":\n message = \"Your session has expired. Please reauthenticate.\";\n break;\n case \"USER_CREDENTIALS_CHANGED\":\n message =\n \"Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.\";\n break;\n case \"INSUFFICIENT_PERMISSIONS\":\n message =\n \"Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.\";\n break;\n default:\n message = `Failed to refresh token: ${String(error)}. Please re-authenticate using \\`aws login\\``;\n }\n throw new CredentialsProviderError(message, { logger: this.logger, tryNextLink: false });\n }\n throw new CredentialsProviderError(`Failed to refresh token: ${String(error)}. Please re-authenticate using aws login`, { logger: this.logger });\n }\n }\n async loadToken() {\n const tokenFilePath = this.getTokenFilePath();\n try {\n let tokenData;\n try {\n tokenData = await readFile(tokenFilePath, { ignoreCache: this.init?.ignoreCache });\n }\n catch {\n tokenData = await fs.readFile(tokenFilePath, \"utf8\");\n }\n const token = JSON.parse(tokenData);\n const missingFields = [\"accessToken\", \"clientId\", \"refreshToken\", \"dpopKey\"].filter((k) => !token[k]);\n if (!token.accessToken?.accountId) {\n missingFields.push(\"accountId\");\n }\n if (missingFields.length > 0) {\n throw new CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(\", \")}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n return token;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error)}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n }\n async saveToken(token) {\n const tokenFilePath = this.getTokenFilePath();\n const directory = dirname(tokenFilePath);\n try {\n await fs.mkdir(directory, { recursive: true });\n }\n catch (error) {\n }\n await fs.writeFile(tokenFilePath, JSON.stringify(token, null, 2), \"utf8\");\n }\n getTokenFilePath() {\n const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join(homedir(), \".aws\", \"login\", \"cache\");\n const loginSessionBytes = Buffer.from(this.loginSession, \"utf8\");\n const loginSessionSha256 = createHash(\"sha256\").update(loginSessionBytes).digest(\"hex\");\n return join(directory, `${loginSessionSha256}.json`);\n }\n derToRawSignature(derSignature) {\n let offset = 2;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const rLength = derSignature[offset++];\n let r = derSignature.subarray(offset, offset + rLength);\n offset += rLength;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const sLength = derSignature[offset++];\n let s = derSignature.subarray(offset, offset + sLength);\n r = r[0] === 0x00 ? r.subarray(1) : r;\n s = s[0] === 0x00 ? s.subarray(1) : s;\n const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]);\n const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]);\n return Buffer.concat([rPadded, sPadded]);\n }\n createDPoPInterceptor(middlewareStack) {\n middlewareStack.add((next) => async (args) => {\n if (HttpRequest.isInstance(args.request)) {\n const request = args.request;\n const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : \"\"}${request.path}`;\n const dpop = await this.generateDpop(request.method, actualEndpoint);\n request.headers = {\n ...request.headers,\n DPoP: dpop,\n };\n }\n return next(args);\n }, {\n step: \"finalizeRequest\",\n name: \"dpopInterceptor\",\n override: true,\n });\n }\n async generateDpop(method = \"POST\", endpoint) {\n const token = await this.loadToken();\n try {\n const privateKey = createPrivateKey({\n key: token.dpopKey,\n format: \"pem\",\n type: \"sec1\",\n });\n const publicKey = createPublicKey(privateKey);\n const publicDer = publicKey.export({ format: \"der\", type: \"spki\" });\n let pointStart = -1;\n for (let i = 0; i < publicDer.length; i++) {\n if (publicDer[i] === 0x04) {\n pointStart = i;\n break;\n }\n }\n const x = publicDer.slice(pointStart + 1, pointStart + 33);\n const y = publicDer.slice(pointStart + 33, pointStart + 65);\n const header = {\n alg: \"ES256\",\n typ: \"dpop+jwt\",\n jwk: {\n kty: \"EC\",\n crv: \"P-256\",\n x: x.toString(\"base64url\"),\n y: y.toString(\"base64url\"),\n },\n };\n const payload = {\n jti: crypto.randomUUID(),\n htm: method,\n htu: endpoint,\n iat: Math.floor(Date.now() / 1000),\n };\n const headerB64 = Buffer.from(JSON.stringify(header)).toString(\"base64url\");\n const payloadB64 = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const message = `${headerB64}.${payloadB64}`;\n const asn1Signature = sign(\"sha256\", Buffer.from(message), privateKey);\n const rawSignature = this.derToRawSignature(asn1Signature);\n const signatureB64 = rawSignature.toString(\"base64url\");\n return `${message}.${signatureB64}`;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to generate Dpop proof: ${error instanceof Error ? error.message : String(error)}`, { logger: this.logger, tryNextLink: false });\n }\n }\n}\n" | ||
| ], | ||
| "mappings": ";iMAAA,oBACA,gBCDA,oBACA,WACA,qBAAS,sBAAY,qBAAkB,UAAiB,eACxD,mBAAS,WACT,kBAAS,WACT,kBAAS,UAAS,aACX,MAAM,CAAwB,CAC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ACZ,IAAK,OAAO,WAAW,EACvB,IAAK,EACL,IAAK,EACL,IAAK,KAAK,MAAM,KAAK,IAAI,EAAI,IAAI,CACrC,EACM,EAAY,OAAO,KAAK,KAAK,UAAU,CAAM,CAAC,EAAE,SAAS,WAAW,EACpE,EAAa,OAAO,KAAK,KAAK,UAAU,CAAO,CAAC,EAAE,SAAS,WAAW,EACtE,EAAU,GAAG,KAAa,IAC1B,EAAgB,EAAK,SAAU,OAAO,KAAK,CAAO,EAAG,CAAU,EAE/D,EADe,KAAK,kBAAkB,CAAa,EACvB,SAAS,WAAW,EACtD,MAAO,GAAG,KAAW,IAEzB,MAAO,EAAO,CACV,MAAM,IAAI,2BAAyB,kCAAkC,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,IAAK,CAAE,OAAQ,KAAK,OAAQ,YAAa,EAAM,CAAC,GAGtL,CDjQO,IAAM,EAAuB,CAAC,IAAS,OAAS,sBAAuB,CAAC,IAAM,CACjF,GAAM,QAAQ,QAAQ,sDAAsD,EAC5E,IAAM,EAAW,MAAM,kBAAgB,GAAQ,CAAC,CAAC,EAC3C,EAAc,iBAAe,CAC/B,QAAS,GAAM,SAAW,GAAoB,OAClD,CAAC,EACK,EAAU,EAAS,GACzB,GAAI,CAAC,GAAS,cACV,MAAM,IAAI,2BAAyB,WAAW,oCAA+C,CACzF,YAAa,GACb,OAAQ,GAAM,MAClB,CAAC,EAGL,IAAM,EAAc,MADJ,IAAI,EAAwB,EAAS,EAAM,CAAkB,EAC3C,gBAAgB,EAClD,OAAO,uBAAqB,EAAa,oBAAqB,IAAI", | ||
| "debugId": "6D12B1E96DDF224864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/stop.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.stop,\n Effect.fn(\"cli.service.stop\")(function* () {\n yield* Service.stop(yield* ServiceConfig.options())\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+0BAMA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,UACnC,OAAO,QAAG,uBAAkB,OAAE,cAAU,OAAG,MACzC,WAAO,OAAQ,UAAK,WAAO,OAAc,aAAQ,MAAC,EACnD,CACH", | ||
| "debugId": "C8258D95CE88312564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "E10659931ED7C8B764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@vercel+oidc@3.2.0/node_modules/@vercel/oidc/dist/token.js"], | ||
| "sourcesContent": [ | ||
| "\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar token_exports = {};\n__export(token_exports, {\n refreshToken: () => refreshToken\n});\nmodule.exports = __toCommonJS(token_exports);\nvar import_token_error = require(\"./token-error\");\nvar import_token_util = require(\"./token-util\");\nasync function refreshToken(options) {\n let projectId = options?.project;\n let teamId = options?.team;\n if (!projectId && !teamId) {\n const projectInfo = (0, import_token_util.findProjectInfo)();\n projectId = projectInfo.projectId;\n teamId = projectInfo.teamId;\n } else if (!projectId || !teamId) {\n const projectInfo = (0, import_token_util.findProjectInfo)();\n projectId = projectId ?? projectInfo.projectId;\n teamId = teamId ?? projectInfo.teamId;\n }\n if (!projectId) {\n throw new import_token_error.VercelOidcTokenError(\n \"Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`\"\n );\n }\n let maybeToken = (0, import_token_util.loadToken)(projectId);\n if (!maybeToken || (0, import_token_util.isExpired)((0, import_token_util.getTokenPayload)(maybeToken.token), options?.expirationBufferMs)) {\n const authToken = await (0, import_token_util.getVercelToken)({\n expirationBufferMs: options?.expirationBufferMs\n });\n maybeToken = await (0, import_token_util.getVercelOidcToken)(authToken, projectId, teamId);\n if (!maybeToken) {\n throw new import_token_error.VercelOidcTokenError(\"Failed to refresh OIDC token\");\n }\n (0, import_token_util.saveToken)(maybeToken, projectId);\n }\n process.env.VERCEL_OIDC_TOKEN = maybeToken.token;\n return;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n refreshToken\n});\n" | ||
| ], | ||
| "mappings": ";2HACA,SAAuB,eAAnB,EAC0B,yBAA1B,EAC2B,oBAA3B,GADmB,OAEnB,EAAe,OAAO,UAAU,eAChC,EAAW,CAAC,EAAQ,IAAQ,CAC9B,QAAS,KAAQ,EACf,EAAU,EAAQ,EAAM,CAAE,IAAK,EAAI,GAAO,WAAY,EAAK,CAAC,GAE5D,EAAc,CAAC,EAAI,EAAM,EAAQ,IAAS,CAC5C,GAAI,GAAQ,OAAO,IAAS,UAAY,OAAO,IAAS,YACtD,QAAS,KAAO,EAAkB,CAAI,EACpC,GAAI,CAAC,EAAa,KAAK,EAAI,CAAG,GAAK,IAAQ,EACzC,EAAU,EAAI,EAAK,CAAE,IAAK,IAAM,EAAK,GAAM,WAAY,EAAE,EAAO,EAAiB,EAAM,CAAG,IAAM,EAAK,UAAW,CAAC,EAEvH,OAAO,GAEL,EAAe,CAAC,IAAQ,EAAY,EAAU,CAAC,EAAG,aAAc,CAAE,MAAO,EAAK,CAAC,EAAG,CAAG,EACrF,EAAgB,CAAC,EACrB,EAAS,EAAe,CACtB,aAAc,IAAM,CACtB,CAAC,EACD,EAAO,QAAU,EAAa,CAAa,EAC3C,IAAI,MACA,MACJ,eAAe,CAAY,CAAC,EAAS,CACnC,IAAI,EAAY,GAAS,QACrB,EAAS,GAAS,KACtB,GAAI,CAAC,GAAa,CAAC,EAAQ,CACzB,IAAM,GAAe,EAAG,EAAkB,iBAAiB,EAC3D,EAAY,EAAY,UACxB,EAAS,EAAY,OAChB,QAAI,CAAC,GAAa,CAAC,EAAQ,CAChC,IAAM,GAAe,EAAG,EAAkB,iBAAiB,EAC3D,EAAY,GAAa,EAAY,UACrC,EAAS,GAAU,EAAY,OAEjC,GAAI,CAAC,EACH,MAAM,IAAI,EAAmB,qBAC3B,gGACF,EAEF,IAAI,GAAc,EAAG,EAAkB,WAAW,CAAS,EAC3D,GAAI,CAAC,IAAe,EAAG,EAAkB,YAAY,EAAG,EAAkB,iBAAiB,EAAW,KAAK,EAAG,GAAS,kBAAkB,EAAG,CAC1I,IAAM,EAAY,MAAO,EAAG,EAAkB,gBAAgB,CAC5D,mBAAoB,GAAS,kBAC/B,CAAC,EAED,GADA,EAAa,MAAO,EAAG,EAAkB,oBAAoB,EAAW,EAAW,CAAM,EACrF,CAAC,EACH,MAAM,IAAI,EAAmB,qBAAqB,8BAA8B,GAEjF,EAAG,EAAkB,WAAW,EAAY,CAAS,EAExD,QAAQ,IAAI,kBAAoB,EAAW,MAC3C", | ||
| "debugId": "E9263495C84EE01664756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "9AAADDC3C35BECB364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/migrate.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\n\nexport default Runtime.handler(Commands.commands.migrate, (_input) => Effect.log(\"No migrations to run.\"))\n" | ||
| ], | ||
| "mappings": ";2oBAIA,SAAe,SAAQ,aAAQ,OAAS,cAAS,aAAS,MAAC,SAAW,OAAO,SAAI,4BAAuB,MAAC", | ||
| "debugId": "BC8C3A98F28D6D2264756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.61/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.61/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.61/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.61/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nimport { NodeHttpHandler } from \"@smithy/node-http-handler\";\nimport fs from \"node:fs/promises\";\nimport { checkUrl } from \"./checkUrl\";\nimport { createGetRequest, getCredentials } from \"./requestHelpers\";\nimport { retryWrapper } from \"./retry-wrapper\";\nconst AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nconst DEFAULT_LINK_LOCAL_HOST = \"http://169.254.170.2\";\nconst AWS_CONTAINER_CREDENTIALS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = \"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromHttp = (options = {}) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-http - fromHttp\");\n let host;\n const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];\n const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];\n const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];\n const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];\n const warn = options.logger?.constructor?.name === \"NoOpLogger\" || !options.logger?.warn\n ? console.warn\n : options.logger.warn.bind(options.logger);\n if (relative && full) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.\");\n warn(\"awsContainerCredentialsRelativeUri will take precedence.\");\n }\n if (token && tokenFile) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.\");\n warn(\"awsContainerAuthorizationTokenFile will take precedence.\");\n }\n if (relative) {\n host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;\n }\n else if (full) {\n host = full;\n }\n else {\n throw new CredentialsProviderError(`No HTTP credential provider host provided.\nSet AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });\n }\n const url = new URL(host);\n checkUrl(url, options.logger);\n const requestHandler = NodeHttpHandler.create({ connectionTimeout: options.timeout ?? 1000 });\n const requestTimeout = options.timeout ?? 1000;\n const provider = retryWrapper(async () => {\n const request = createGetRequest(url);\n if (tokenFile) {\n request.headers.Authorization = validateToken((await fs.readFile(tokenFile)).toString());\n }\n else if (token) {\n request.headers.Authorization = validateToken(token);\n }\n try {\n const result = await requestHandler.handle(request, { requestTimeout });\n return getCredentials(result.response).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_HTTP\", \"z\"));\n }\n catch (e) {\n throw new CredentialsProviderError(String(e), { logger: options.logger });\n }\n }, options.maxRetries ?? 3, options.timeout ?? 1000);\n return async () => {\n try {\n return await provider();\n }\n finally {\n requestHandler.destroy?.();\n }\n };\n};\nconst validateToken = (token) => {\n if (token.includes(\"\\r\\n\")) {\n throw new CredentialsProviderError(\"Authorization token contains invalid \\\\r\\\\n sequence.\");\n }\n return token;\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nconst LOOPBACK_CIDR_IPv4 = \"127.0.0.0/8\";\nconst LOOPBACK_CIDR_IPv6 = \"::1/128\";\nconst ECS_CONTAINER_HOST = \"169.254.170.2\";\nconst EKS_CONTAINER_HOST_IPv4 = \"169.254.170.23\";\nconst EKS_CONTAINER_HOST_IPv6 = \"[fd00:ec2::23]\";\nexport const checkUrl = (url, logger) => {\n if (url.protocol === \"https:\") {\n return;\n }\n if (url.hostname === ECS_CONTAINER_HOST ||\n url.hostname === EKS_CONTAINER_HOST_IPv4 ||\n url.hostname === EKS_CONTAINER_HOST_IPv6) {\n return;\n }\n if (url.hostname.includes(\"[\")) {\n if (url.hostname === \"[::1]\" || url.hostname === \"[0000:0000:0000:0000:0000:0000:0000:0001]\") {\n return;\n }\n }\n else {\n if (url.hostname === \"localhost\") {\n return;\n }\n const ipComponents = url.hostname.split(\".\");\n const inRange = (component) => {\n const num = parseInt(component, 10);\n return 0 <= num && num <= 255;\n };\n if (ipComponents[0] === \"127\" &&\n inRange(ipComponents[1]) &&\n inRange(ipComponents[2]) &&\n inRange(ipComponents[3]) &&\n ipComponents.length === 4) {\n return;\n }\n }\n throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:\n - loopback CIDR 127.0.0.0/8 or [::1/128]\n - ECS container host 169.254.170.2\n - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger });\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { HttpRequest } from \"@smithy/core/protocols\";\nimport { parseRfc3339DateTime } from \"@smithy/core/serde\";\nimport { sdkStreamMixin } from \"@smithy/core/serde\";\nexport function createGetRequest(url) {\n return new HttpRequest({\n protocol: url.protocol,\n hostname: url.hostname,\n port: Number(url.port),\n path: url.pathname,\n query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => {\n acc[k] = v;\n return acc;\n }, {}),\n fragment: url.hash,\n });\n}\nexport async function getCredentials(response, logger) {\n const stream = sdkStreamMixin(response.body);\n const str = await stream.transformToString();\n if (response.statusCode === 200) {\n const parsed = JSON.parse(str);\n if (typeof parsed.AccessKeyId !== \"string\" ||\n typeof parsed.SecretAccessKey !== \"string\" ||\n typeof parsed.Token !== \"string\" ||\n typeof parsed.Expiration !== \"string\") {\n throw new CredentialsProviderError(\"HTTP credential provider response not of the required format, an object matching: \" +\n \"{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }\", { logger });\n }\n return {\n accessKeyId: parsed.AccessKeyId,\n secretAccessKey: parsed.SecretAccessKey,\n sessionToken: parsed.Token,\n expiration: parseRfc3339DateTime(parsed.Expiration),\n };\n }\n if (response.statusCode >= 400 && response.statusCode < 500) {\n let parsedBody = {};\n try {\n parsedBody = JSON.parse(str);\n }\n catch (e) { }\n throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), {\n Code: parsedBody.Code,\n Message: parsedBody.Message,\n });\n }\n throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger });\n}\n", | ||
| "export const retryWrapper = (toRetry, maxRetries, delayMs) => {\n return async () => {\n for (let i = 0; i < maxRetries; ++i) {\n try {\n return await toRetry();\n }\n catch (e) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n return await toRetry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+nested-clients@3.997.33/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"sso-oauth\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateToken\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"sso-oauth\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.32\";\nvar packageInfo = {\n\tversion: version};\n\nconst k = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = { [k]: \"Endpoint\" }, h = { [k]: d }, i = {}, j = [{ [k]: \"Region\" }];\nconst _data = {\n conditions: [\n [c, [g]],\n [c, j],\n [\"aws.partition\", j, d],\n [e, [{ [k]: \"UseFIPS\" }, b]],\n [e, [{ [k]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [h, \"supportsDualStack\"] }, b]],\n [e, [{ fn: f, argv: [h, \"supportsFIPS\"] }, b]],\n [\"stringEquals\", [{ fn: f, argv: [h, \"name\"] }, \"aws-us-gov\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [g, i],\n [\"https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://oidc.{Region}.amazonaws.com\", i],\n [\"https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://oidc.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 13, 3,\n 1, 4, r + 12,\n 2, 5, r + 12,\n 3, 8, 6,\n 4, 7, r + 11,\n 5, r + 9, r + 10,\n 4, 11, 9,\n 6, 10, r + 8,\n 7, r + 6, r + 7,\n 5, 12, r + 5,\n 6, r + 4, r + 5,\n 3, r + 1, 14,\n 4, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SSOOIDCServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOOIDCServiceException.prototype);\n }\n}\n\nclass AccessDeniedException extends SSOOIDCServiceException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nclass AuthorizationPendingException extends SSOOIDCServiceException {\n name = \"AuthorizationPendingException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"AuthorizationPendingException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AuthorizationPendingException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass ExpiredTokenException extends SSOOIDCServiceException {\n name = \"ExpiredTokenException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"ExpiredTokenException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExpiredTokenException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InternalServerException extends SSOOIDCServiceException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidClientException extends SSOOIDCServiceException {\n name = \"InvalidClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidGrantException extends SSOOIDCServiceException {\n name = \"InvalidGrantException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidGrantException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidGrantException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidRequestException extends SSOOIDCServiceException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidScopeException extends SSOOIDCServiceException {\n name = \"InvalidScopeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidScopeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidScopeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass SlowDownException extends SSOOIDCServiceException {\n name = \"SlowDownException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"SlowDownException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, SlowDownException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass UnauthorizedClientException extends SSOOIDCServiceException {\n name = \"UnauthorizedClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnauthorizedClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass UnsupportedGrantTypeException extends SSOOIDCServiceException {\n name = \"UnsupportedGrantTypeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnsupportedGrantTypeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\n\nconst _ADE = \"AccessDeniedException\";\nconst _APE = \"AuthorizationPendingException\";\nconst _AT = \"AccessToken\";\nconst _CS = \"ClientSecret\";\nconst _CT = \"CreateToken\";\nconst _CTR = \"CreateTokenRequest\";\nconst _CTRr = \"CreateTokenResponse\";\nconst _CV = \"CodeVerifier\";\nconst _ETE = \"ExpiredTokenException\";\nconst _ICE = \"InvalidClientException\";\nconst _IGE = \"InvalidGrantException\";\nconst _IRE = \"InvalidRequestException\";\nconst _ISE = \"InternalServerException\";\nconst _ISEn = \"InvalidScopeException\";\nconst _IT = \"IdToken\";\nconst _RT = \"RefreshToken\";\nconst _SDE = \"SlowDownException\";\nconst _UCE = \"UnauthorizedClientException\";\nconst _UGTE = \"UnsupportedGrantTypeException\";\nconst _aT = \"accessToken\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cS = \"clientSecret\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _dC = \"deviceCode\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ed = \"error_description\";\nconst _gT = \"grantType\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _r = \"reason\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.ssooidc\";\nconst _sc = \"scope\";\nconst _se = \"server\";\nconst _tT = \"tokenType\";\nconst n0 = \"com.amazonaws.ssooidc\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SSOOIDCServiceException$ = [-3, _s, \"SSOOIDCServiceException\", 0, [], []];\n_s_registry.registerError(SSOOIDCServiceException$, SSOOIDCServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar AccessDeniedException$ = [-3, n0, _ADE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0]\n];\nn0_registry.registerError(AccessDeniedException$, AccessDeniedException);\nvar AuthorizationPendingException$ = [-3, n0, _APE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(AuthorizationPendingException$, AuthorizationPendingException);\nvar ExpiredTokenException$ = [-3, n0, _ETE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(ExpiredTokenException$, ExpiredTokenException);\nvar InternalServerException$ = [-3, n0, _ISE,\n { [_e]: _se, [_hE]: 500 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InternalServerException$, InternalServerException);\nvar InvalidClientException$ = [-3, n0, _ICE,\n { [_e]: _c, [_hE]: 401 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidClientException$, InvalidClientException);\nvar InvalidGrantException$ = [-3, n0, _IGE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidGrantException$, InvalidGrantException);\nvar InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0]\n];\nn0_registry.registerError(InvalidRequestException$, InvalidRequestException);\nvar InvalidScopeException$ = [-3, n0, _ISEn,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidScopeException$, InvalidScopeException);\nvar SlowDownException$ = [-3, n0, _SDE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(SlowDownException$, SlowDownException);\nvar UnauthorizedClientException$ = [-3, n0, _UCE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(UnauthorizedClientException$, UnauthorizedClientException);\nvar UnsupportedGrantTypeException$ = [-3, n0, _UGTE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar AccessToken = [0, n0, _AT, 8, 0];\nvar ClientSecret = [0, n0, _CS, 8, 0];\nvar CodeVerifier = [0, n0, _CV, 8, 0];\nvar IdToken = [0, n0, _IT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nvar CreateTokenRequest$ = [3, n0, _CTR,\n 0,\n [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV],\n [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], 3\n];\nvar CreateTokenResponse$ = [3, n0, _CTRr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]]\n];\nvar CreateToken$ = [9, n0, _CT,\n { [_h]: [\"POST\", \"/token\", 200] }, () => CreateTokenRequest$, () => CreateTokenResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.ssooidc\",\n errorTypeRegistries,\n version: \"2019-06-10\",\n serviceTarget: \"AWSSSOOIDCService\",\n },\n serviceId: config?.serviceId ?? \"SSO OIDC\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SSOOIDCClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"AWSSSOOIDCService\", \"SSOOIDCClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass CreateTokenCommand extends command(_ep0, _mw0, \"CreateToken\", CreateToken$) {\n}\n\nconst commands = {\n CreateTokenCommand,\n};\nclass SSOOIDC extends SSOOIDCClient {\n}\ncreateAggregatedClient(commands, SSOOIDC);\n\nconst AccessDeniedExceptionReason = {\n KMS_ACCESS_DENIED: \"KMS_AccessDeniedException\",\n};\nconst InvalidRequestExceptionReason = {\n KMS_DISABLED_KEY: \"KMS_DisabledException\",\n KMS_INVALID_KEY_USAGE: \"KMS_InvalidKeyUsageException\",\n KMS_INVALID_STATE: \"KMS_InvalidStateException\",\n KMS_KEY_NOT_FOUND: \"KMS_NotFoundException\",\n};\n\nexports.AccessDeniedException = AccessDeniedException;\nexports.AccessDeniedException$ = AccessDeniedException$;\nexports.AccessDeniedExceptionReason = AccessDeniedExceptionReason;\nexports.AuthorizationPendingException = AuthorizationPendingException;\nexports.AuthorizationPendingException$ = AuthorizationPendingException$;\nexports.CreateToken$ = CreateToken$;\nexports.CreateTokenCommand = CreateTokenCommand;\nexports.CreateTokenRequest$ = CreateTokenRequest$;\nexports.CreateTokenResponse$ = CreateTokenResponse$;\nexports.ExpiredTokenException = ExpiredTokenException;\nexports.ExpiredTokenException$ = ExpiredTokenException$;\nexports.InternalServerException = InternalServerException;\nexports.InternalServerException$ = InternalServerException$;\nexports.InvalidClientException = InvalidClientException;\nexports.InvalidClientException$ = InvalidClientException$;\nexports.InvalidGrantException = InvalidGrantException;\nexports.InvalidGrantException$ = InvalidGrantException$;\nexports.InvalidRequestException = InvalidRequestException;\nexports.InvalidRequestException$ = InvalidRequestException$;\nexports.InvalidRequestExceptionReason = InvalidRequestExceptionReason;\nexports.InvalidScopeException = InvalidScopeException;\nexports.InvalidScopeException$ = InvalidScopeException$;\nexports.SSOOIDC = SSOOIDC;\nexports.SSOOIDCClient = SSOOIDCClient;\nexports.SSOOIDCServiceException = SSOOIDCServiceException;\nexports.SSOOIDCServiceException$ = SSOOIDCServiceException$;\nexports.SlowDownException = SlowDownException;\nexports.SlowDownException$ = SlowDownException$;\nexports.UnauthorizedClientException = UnauthorizedClientException;\nexports.UnauthorizedClientException$ = UnauthorizedClientException$;\nexports.UnsupportedGrantTypeException = UnsupportedGrantTypeException;\nexports.UnsupportedGrantTypeException$ = UnsupportedGrantTypeException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";8VAAA,SAAQ,6BAAsB,qCAAiC,QAAmC,uCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,SAAQ,eAAa,gCACnN,QAAS,QACjB,IAAQ,GAAW,GACX,GAAW,EACnB,IAAQ,6BAA2B,aAAY,yCAAuC,8CAA4C,8BAA4B,mCAAiC,8BACvL,yBAAuB,iBAAe,kBAAgB,2BAAyB,yBAAuB,4BACtG,YAAU,wCAAsC,mCAAiC,iCACjF,sBAAoB,kCAAgC,mCAAiC,sBAAoB,yBACzG,eAAc,+BACd,4BAA0B,qBAAmB,8CAC7C,UAAQ,YAAU,YAAU,cAAY,8BACxC,mBAAiB,0BACjB,8BACA,gBAEF,GAAiD,MAAO,EAAQ,EAAS,IAAU,CACrF,MAAO,CACH,UAAW,GAAiB,CAAO,EAAE,UACrC,OAAQ,MAAM,EAAkB,EAAO,MAAM,EAAE,IAAM,IAAM,CACvD,MAAU,MAAM,yDAAyD,IAC1E,CACP,GAEJ,SAAS,EAAgC,CAAC,EAAgB,CACtD,MAAO,CACH,SAAU,iBACV,kBAAmB,CACf,KAAM,YACN,OAAQ,EAAe,MAC3B,EACA,oBAAqB,CAAC,EAAQ,KAAa,CACvC,kBAAmB,CACf,SACA,SACJ,CACJ,EACJ,EAEJ,SAAS,EAAmC,CAAC,EAAgB,CACzD,MAAO,CACH,SAAU,mBACd,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sBAAuB,+BACvB,kBAAmB,4BACnB,kBAAmB,uBACvB,EAEA,IAAQ,GAAwB,EACxB,GAAyB,EACzB,GAA8B,GAC9B,GAAgC,EAChC,GAAiC,EACjC,GAAe,GACf,GAAqB,EACrB,GAAsB,GACtB,GAAuB,GACvB,GAAwB,EACxB,GAAyB,EACzB,GAA0B,EAC1B,GAA2B,GAC3B,GAAyB,EACzB,GAA0B,GAC1B,GAAwB,EACxB,GAAyB,GACzB,GAA0B,EAC1B,GAA2B,GAC3B,GAAgC,GAChC,GAAwB,EACxB,GAAyB,GACzB,GAAU,EACV,GAAgB,EAChB,GAA0B,EAC1B,GAA2B,EAC3B,GAAoB,EACpB,GAAqB,GACrB,GAA8B,EAC9B,GAA+B,GAC/B,GAAgC,EAChC,GAAiC,GACjC,GAAsB", | ||
| "debugId": "831681E41E03430264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.4/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js"], | ||
| "sourcesContent": [ | ||
| "import { getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { resolveProfileData } from \"./resolveProfileData\";\nexport const fromIni = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-ini - fromIni\");\n const profiles = await parseKnownFiles(init);\n return resolveProfileData(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init, callerClientConfig);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { isAssumeRoleProfile, resolveAssumeRoleCredentials } from \"./resolveAssumeRoleCredentials\";\nimport { isLoginProfile, resolveLoginCredentials } from \"./resolveLoginCredentials\";\nimport { isProcessProfile, resolveProcessCredentials } from \"./resolveProcessCredentials\";\nimport { isSsoProfile, resolveSsoCredentials } from \"./resolveSsoCredentials\";\nimport { isStaticCredsProfile, resolveStaticCredentials } from \"./resolveStaticCredentials\";\nimport { isWebIdentityProfile, resolveWebIdentityCredentials } from \"./resolveWebIdentityCredentials\";\nexport const resolveProfileData = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {\n const data = profiles[profileName];\n if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {\n return resolveAssumeRoleCredentials(profileName, profiles, options, callerClientConfig, visitedProfiles, resolveProfileData);\n }\n if (isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isWebIdentityProfile(data)) {\n return resolveWebIdentityCredentials(data, options, callerClientConfig);\n }\n if (isProcessProfile(data)) {\n return resolveProcessCredentials(options, profileName);\n }\n if (isSsoProfile(data)) {\n return await resolveSsoCredentials(profileName, data, options, callerClientConfig);\n }\n if (isLoginProfile(data)) {\n return resolveLoginCredentials(profileName, options, callerClientConfig);\n }\n throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger });\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, getProfileName } from \"@smithy/core/config\";\nimport { resolveCredentialSource } from \"./resolveCredentialSource\";\nexport const isAssumeRoleProfile = (arg, { profile = \"default\", logger } = {}) => {\n return (Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.external_id) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.mfa_serial) > -1 &&\n (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })));\n};\nconst isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => {\n const withSourceProfile = typeof arg.source_profile === \"string\" && typeof arg.credential_source === \"undefined\";\n if (withSourceProfile) {\n logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);\n }\n return withSourceProfile;\n};\nconst isCredentialSourceProfile = (arg, { profile, logger }) => {\n const withProviderProfile = typeof arg.credential_source === \"string\" && typeof arg.source_profile === \"undefined\";\n if (withProviderProfile) {\n logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);\n }\n return withProviderProfile;\n};\nexport const resolveAssumeRoleCredentials = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, resolveProfileData) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)\");\n const profileData = profiles[profileName];\n const { source_profile, region } = profileData;\n if (!options.roleAssumer) {\n const { getDefaultRoleAssumer } = await import(\"@aws-sdk/nested-clients/sts\");\n options.roleAssumer = getDefaultRoleAssumer({\n ...options.clientConfig,\n credentialProviderLogger: options.logger,\n parentClientConfig: {\n ...callerClientConfig,\n ...options?.parentClientConfig,\n region: region ?? options?.parentClientConfig?.region ?? callerClientConfig?.region,\n },\n }, options.clientPlugins);\n }\n if (source_profile && source_profile in visitedProfiles) {\n throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` +\n ` ${getProfileName(options)}. Profiles visited: ` +\n Object.keys(visitedProfiles).join(\", \"), { logger: options.logger });\n }\n options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);\n const sourceCredsProvider = source_profile\n ? resolveProfileData(source_profile, profiles, options, callerClientConfig, {\n ...visitedProfiles,\n [source_profile]: true,\n }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}))\n : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();\n if (isCredentialSourceWithoutRoleArn(profileData)) {\n return sourceCredsProvider.then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n else {\n const params = {\n RoleArn: profileData.role_arn,\n RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,\n ExternalId: profileData.external_id,\n DurationSeconds: parseInt(profileData.duration_seconds || \"3600\", 10),\n };\n const { mfa_serial } = profileData;\n if (mfa_serial) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false });\n }\n params.SerialNumber = mfa_serial;\n params.TokenCode = await options.mfaCodeProvider(mfa_serial);\n }\n const sourceCreds = await sourceCredsProvider;\n return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n};\nconst isCredentialSourceWithoutRoleArn = (section) => {\n return !section.role_arn && !!section.credential_source;\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { chain, CredentialsProviderError } from \"@smithy/core/config\";\nexport const resolveCredentialSource = (credentialSource, profileName, logger) => {\n const sourceProvidersMap = {\n EcsContainer: async (options) => {\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n const { fromContainerMetadata } = await import(\"@smithy/credential-provider-imds\");\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is EcsContainer\");\n return async () => chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider);\n },\n Ec2InstanceMetadata: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata\");\n const { fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n return async () => fromInstanceMetadata(options)().then(setNamedProvider);\n },\n Environment: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Environment\");\n const { fromEnv } = await import(\"@aws-sdk/credential-provider-env\");\n return async () => fromEnv(options)().then(setNamedProvider);\n },\n };\n if (credentialSource in sourceProvidersMap) {\n return sourceProvidersMap[credentialSource];\n }\n else {\n throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` +\n `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger });\n }\n};\nconst setNamedProvider = (creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_NAMED_PROVIDER\", \"p\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isLoginProfile = (data) => {\n return Boolean(data && data.login_session);\n};\nexport const resolveLoginCredentials = async (profileName, options, callerClientConfig) => {\n const { fromLoginCredentials } = await import(\"@aws-sdk/credential-provider-login\");\n const credentials = await fromLoginCredentials({\n ...options,\n profile: profileName,\n })({ callerClientConfig });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_LOGIN\", \"AC\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isProcessProfile = (arg) => Boolean(arg) && typeof arg === \"object\" && typeof arg.credential_process === \"string\";\nexport const resolveProcessCredentials = async (options, profile) => {\n const { fromProcess } = await import(\"@aws-sdk/credential-provider-process\");\n const credentials = await fromProcess({\n ...options,\n profile,\n })();\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_PROCESS\", \"v\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => {\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO({\n profile,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n clientConfig: options.clientConfig,\n })({\n callerClientConfig,\n }).then((creds) => {\n if (profileData.sso_session) {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO\", \"r\");\n }\n else {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO_LEGACY\", \"t\");\n }\n });\n};\nexport const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isStaticCredsProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.aws_access_key_id === \"string\" &&\n typeof arg.aws_secret_access_key === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_session_token) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_account_id) > -1;\nexport const resolveStaticCredentials = async (profile, options) => {\n options?.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveStaticCredentials\");\n const credentials = {\n accessKeyId: profile.aws_access_key_id,\n secretAccessKey: profile.aws_secret_access_key,\n sessionToken: profile.aws_session_token,\n ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }),\n ...(profile.aws_account_id && { accountId: profile.aws_account_id }),\n };\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE\", \"n\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => {\n const { fromTokenFile } = await import(\"@aws-sdk/credential-provider-web-identity\");\n const credentials = await fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n })({\n callerClientConfig,\n });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN\", \"q\");\n};\n" | ||
| ], | ||
| "mappings": ";0JAAA,oBCAA,oBCAA,eACA,WCDA,eACA,WACa,EAA0B,CAAC,EAAkB,EAAa,IAAW,CAC9E,IAAM,EAAqB,CACvB,aAAc,MAAO,IAAY,CAC7B,IAAQ,YAAa,KAAa,2CAC1B,yBAA0B,KAAa,0CAE/C,OADA,GAAQ,MAAM,sEAAsE,EAC7E,SAAY,QAAM,EAAS,GAAW,CAAC,CAAC,EAAG,EAAsB,CAAO,CAAC,EAAE,EAAE,KAAK,CAAgB,GAE7G,oBAAqB,MAAO,IAAY,CACpC,GAAQ,MAAM,6EAA6E,EAC3F,IAAQ,wBAAyB,KAAa,0CAC9C,MAAO,UAAY,EAAqB,CAAO,EAAE,EAAE,KAAK,CAAgB,GAE5E,YAAa,MAAO,IAAY,CAC5B,GAAQ,MAAM,qEAAqE,EACnF,IAAQ,WAAY,KAAa,0CACjC,MAAO,UAAY,EAAQ,CAAO,EAAE,EAAE,KAAK,CAAgB,EA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ACrB,OAAO,EAA0B,EAAS,CAAW,EAEzD,GAAI,EAAa,CAAI,EACjB,OAAO,MAAM,EAAsB,EAAa,EAAM,EAAS,CAAkB,EAErF,GAAI,EAAe,CAAI,EACnB,OAAO,EAAwB,EAAa,EAAS,CAAkB,EAE3E,MAAM,IAAI,2BAAyB,iDAAiD,2CAAsD,CAAE,OAAQ,EAAQ,MAAO,CAAC,GD5BjK,IAAM,EAAU,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CACzE,EAAK,QAAQ,MAAM,4CAA4C,EAC/D,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAAmB,iBAAe,CACrC,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAM,CAAkB", | ||
| "debugId": "2D866EE34881E6C864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "7B3F380E69D1F42164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+cohere@3.0.27+d6123d32214422cb/node_modules/@ai-sdk/cohere/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/cohere-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/cohere-chat-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/cohere-chat-options.ts\nimport { z } from \"zod/v4\";\nvar cohereLanguageModelOptions = z.object({\n /**\n * Configuration for reasoning features (optional)\n *\n * Can be set to an object with the two properties `type` and `tokenBudget`. `type` can be set to `'enabled'` or `'disabled'` (defaults to `'enabled'`).\n * `tokenBudget` is the maximum number of tokens the model can use for thinking, which must be set to a positive integer. The model will stop thinking if it reaches the thinking token budget and will proceed with the response\n *\n * @see https://docs.cohere.com/reference/chat#request.body.thinking\n */\n thinking: z.object({\n type: z.enum([\"enabled\", \"disabled\"]).optional(),\n tokenBudget: z.number().optional()\n }).optional()\n});\n\n// src/cohere-error.ts\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar cohereErrorDataSchema = z2.object({\n message: z2.string()\n});\nvar cohereFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: cohereErrorDataSchema,\n errorToMessage: (data) => data.message\n});\n\n// src/cohere-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nfunction prepareTools({\n tools,\n toolChoice\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const cohereTools = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n } else {\n cohereTools.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: cohereTools, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n return { tools: cohereTools, toolChoice: void 0, toolWarnings };\n case \"none\":\n return { tools: cohereTools, toolChoice: \"NONE\", toolWarnings };\n case \"required\":\n return { tools: cohereTools, toolChoice: \"REQUIRED\", toolWarnings };\n case \"tool\":\n return {\n tools: cohereTools.filter(\n (tool) => tool.function.name === toolChoice.toolName\n ),\n toolChoice: \"REQUIRED\",\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/convert-cohere-usage.ts\nfunction convertCohereUsage(tokens) {\n if (tokens == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const inputTokens = tokens.input_tokens;\n const outputTokens = tokens.output_tokens;\n return {\n inputTokens: {\n total: inputTokens,\n noCache: inputTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: outputTokens,\n text: outputTokens,\n reasoning: void 0\n },\n raw: tokens\n };\n}\n\n// src/convert-to-cohere-chat-prompt.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nfunction convertToCohereChatPrompt(prompt) {\n const messages = [];\n const documents = [];\n const warnings = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n var _a;\n switch (part.type) {\n case \"text\": {\n return part.text;\n }\n case \"file\": {\n let textContent;\n if (typeof part.data === \"string\") {\n textContent = part.data;\n } else if (part.data instanceof Uint8Array) {\n if (!(((_a = part.mediaType) == null ? void 0 : _a.startsWith(\"text/\")) || part.mediaType === \"application/json\")) {\n throw new UnsupportedFunctionalityError2({\n functionality: `document media type: ${part.mediaType}`,\n message: `Media type '${part.mediaType}' is not supported. Supported media types are: text/* and application/json.`\n });\n }\n textContent = new TextDecoder().decode(part.data);\n } else {\n throw new UnsupportedFunctionalityError2({\n functionality: \"File URL data\",\n message: \"URLs should be downloaded by the AI SDK and not reach this point. This indicates a configuration issue.\"\n });\n }\n documents.push({\n data: {\n text: textContent,\n title: part.filename\n }\n });\n return \"\";\n }\n }\n }).join(\"\")\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: toolCalls.length > 0 ? void 0 : text,\n tool_calls: toolCalls.length > 0 ? toolCalls : void 0,\n tool_plan: void 0\n });\n break;\n }\n case \"tool\": {\n messages.push(\n ...content.filter((toolResult) => toolResult.type !== \"tool-approval-response\").map((toolResult) => {\n var _a;\n const output = toolResult.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n return {\n role: \"tool\",\n content: contentValue,\n tool_call_id: toolResult.toolCallId\n };\n })\n );\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return { messages, documents, warnings };\n}\n\n// src/map-cohere-finish-reason.ts\nfunction mapCohereFinishReason(finishReason) {\n switch (finishReason) {\n case \"COMPLETE\":\n case \"STOP_SEQUENCE\":\n return \"stop\";\n case \"MAX_TOKENS\":\n return \"length\";\n case \"ERROR\":\n return \"error\";\n case \"TOOL_CALL\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/cohere-chat-language-model.ts\nvar CohereChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n // No URLs are supported.\n };\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n tools,\n toolChoice,\n providerOptions\n }) {\n var _a, _b;\n const cohereOptions = (_a = await parseProviderOptions({\n provider: \"cohere\",\n providerOptions,\n schema: cohereLanguageModelOptions\n })) != null ? _a : {};\n const {\n messages: chatPrompt,\n documents: cohereDocuments,\n warnings: promptWarnings\n } = convertToCohereChatPrompt(prompt);\n const {\n tools: cohereTools,\n toolChoice: cohereToolChoice,\n toolWarnings\n } = prepareTools({ tools, toolChoice });\n return {\n args: {\n // model id:\n model: this.modelId,\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n max_tokens: maxOutputTokens,\n temperature,\n p: topP,\n k: topK,\n seed,\n stop_sequences: stopSequences,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? { type: \"json_object\", json_schema: responseFormat.schema } : void 0,\n // messages:\n messages: chatPrompt,\n // tools:\n tools: cohereTools,\n tool_choice: cohereToolChoice,\n // documents for RAG:\n ...cohereDocuments.length > 0 && { documents: cohereDocuments },\n // reasoning\n ...cohereOptions.thinking && {\n thinking: {\n type: (_b = cohereOptions.thinking.type) != null ? _b : \"enabled\",\n token_budget: cohereOptions.thinking.tokenBudget\n }\n }\n },\n warnings: [...toolWarnings, ...promptWarnings]\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g;\n const { args, warnings } = await this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: args,\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const content = [];\n for (const item of (_a = response.message.content) != null ? _a : []) {\n if (item.type === \"text\" && item.text.length > 0) {\n content.push({ type: \"text\", text: item.text });\n continue;\n }\n if (item.type === \"thinking\" && item.thinking.length > 0) {\n content.push({ type: \"reasoning\", text: item.thinking });\n continue;\n }\n }\n for (const citation of (_b = response.message.citations) != null ? _b : []) {\n content.push({\n type: \"source\",\n sourceType: \"document\",\n id: this.config.generateId(),\n mediaType: \"text/plain\",\n title: ((_d = (_c = citation.sources[0]) == null ? void 0 : _c.document) == null ? void 0 : _d.title) || \"Document\",\n providerMetadata: {\n cohere: {\n start: citation.start,\n end: citation.end,\n text: citation.text,\n sources: citation.sources,\n ...citation.type && { citationType: citation.type }\n }\n }\n });\n }\n for (const toolCall of (_e = response.message.tool_calls) != null ? _e : []) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n // Cohere sometimes returns `null` for tool call arguments for tools\n // defined as having no arguments.\n input: toolCall.function.arguments.replace(/^null$/, \"{}\")\n });\n }\n return {\n content,\n finishReason: {\n unified: mapCohereFinishReason(response.finish_reason),\n raw: (_f = response.finish_reason) != null ? _f : void 0\n },\n usage: convertCohereUsage(response.usage.tokens),\n request: { body: args },\n response: {\n // TODO timestamp, model id\n id: (_g = response.generation_id) != null ? _g : void 0,\n headers: responseHeaders,\n body: rawResponse\n },\n warnings\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs(options);\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: { ...args, stream: true },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n cohereChatChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let pendingToolCall = null;\n let isActiveReasoning = false;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n finishReason = { unified: \"error\", raw: void 0 };\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n const type = value.type;\n switch (type) {\n case \"content-start\": {\n if (value.delta.message.content.type === \"thinking\") {\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(value.index)\n });\n isActiveReasoning = true;\n return;\n }\n controller.enqueue({\n type: \"text-start\",\n id: String(value.index)\n });\n return;\n }\n case \"content-delta\": {\n if (\"thinking\" in value.delta.message.content) {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(value.index),\n delta: value.delta.message.content.thinking\n });\n return;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: String(value.index),\n delta: value.delta.message.content.text\n });\n return;\n }\n case \"content-end\": {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: String(value.index)\n });\n isActiveReasoning = false;\n return;\n }\n controller.enqueue({\n type: \"text-end\",\n id: String(value.index)\n });\n return;\n }\n case \"tool-call-start\": {\n const toolId = value.delta.message.tool_calls.id;\n const toolName = value.delta.message.tool_calls.function.name;\n const initialArgs = value.delta.message.tool_calls.function.arguments;\n pendingToolCall = {\n id: toolId,\n name: toolName,\n arguments: initialArgs,\n hasFinished: false\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolId,\n toolName\n });\n if (initialArgs.length > 0) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolId,\n delta: initialArgs\n });\n }\n return;\n }\n case \"tool-call-delta\": {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n const argsDelta = value.delta.message.tool_calls.function.arguments;\n pendingToolCall.arguments += argsDelta;\n controller.enqueue({\n type: \"tool-input-delta\",\n id: pendingToolCall.id,\n delta: argsDelta\n });\n }\n return;\n }\n case \"tool-call-end\": {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: pendingToolCall.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: pendingToolCall.id,\n toolName: pendingToolCall.name,\n input: JSON.stringify(\n JSON.parse(((_a = pendingToolCall.arguments) == null ? void 0 : _a.trim()) || \"{}\")\n )\n });\n pendingToolCall.hasFinished = true;\n pendingToolCall = null;\n }\n return;\n }\n case \"message-start\": {\n controller.enqueue({\n type: \"response-metadata\",\n id: (_b = value.id) != null ? _b : void 0\n });\n return;\n }\n case \"message-end\": {\n finishReason = {\n unified: mapCohereFinishReason(value.delta.finish_reason),\n raw: value.delta.finish_reason\n };\n usage = value.delta.usage.tokens;\n return;\n }\n default: {\n return;\n }\n }\n },\n flush(controller) {\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertCohereUsage(usage)\n });\n }\n })\n ),\n request: { body: { ...args, stream: true } },\n response: { headers: responseHeaders }\n };\n }\n};\nvar cohereChatResponseSchema = z3.object({\n generation_id: z3.string().nullish(),\n message: z3.object({\n role: z3.string(),\n content: z3.array(\n z3.union([\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.string()\n })\n ])\n ).nullish(),\n tool_plan: z3.string().nullish(),\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n ).nullish(),\n citations: z3.array(\n z3.object({\n start: z3.number(),\n end: z3.number(),\n text: z3.string(),\n sources: z3.array(\n z3.object({\n type: z3.string().optional(),\n id: z3.string().optional(),\n document: z3.object({\n id: z3.string().optional(),\n text: z3.string(),\n title: z3.string()\n })\n })\n ),\n type: z3.string().optional()\n })\n ).nullish()\n }),\n finish_reason: z3.string(),\n usage: z3.object({\n billed_units: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n }),\n tokens: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n })\n })\n});\nvar cohereChatChunkSchema = z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"citation-start\")\n }),\n z3.object({\n type: z3.literal(\"citation-end\")\n }),\n z3.object({\n type: z3.literal(\"content-start\"),\n index: z3.number(),\n delta: z3.object({\n message: z3.object({\n content: z3.union([\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.string()\n })\n ])\n })\n })\n }),\n z3.object({\n type: z3.literal(\"content-delta\"),\n index: z3.number(),\n delta: z3.object({\n message: z3.object({\n content: z3.union([\n z3.object({\n text: z3.string()\n }),\n z3.object({\n thinking: z3.string()\n })\n ])\n })\n })\n }),\n z3.object({\n type: z3.literal(\"content-end\"),\n index: z3.number()\n }),\n z3.object({\n type: z3.literal(\"message-start\"),\n id: z3.string().nullish()\n }),\n z3.object({\n type: z3.literal(\"message-end\"),\n delta: z3.object({\n finish_reason: z3.string(),\n usage: z3.object({\n tokens: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n })\n })\n })\n }),\n // https://docs.cohere.com/v2/docs/streaming#tool-use-stream-events-for-tool-calling\n z3.object({\n type: z3.literal(\"tool-plan-delta\"),\n delta: z3.object({\n message: z3.object({\n tool_plan: z3.string()\n })\n })\n }),\n z3.object({\n type: z3.literal(\"tool-call-start\"),\n delta: z3.object({\n message: z3.object({\n tool_calls: z3.object({\n id: z3.string(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n })\n })\n }),\n // A single tool call's `arguments` stream in chunks and must be accumulated\n // in a string and so the full tool object info can only be parsed once we see\n // `tool-call-end`.\n z3.object({\n type: z3.literal(\"tool-call-delta\"),\n delta: z3.object({\n message: z3.object({\n tool_calls: z3.object({\n function: z3.object({\n arguments: z3.string()\n })\n })\n })\n })\n }),\n z3.object({\n type: z3.literal(\"tool-call-end\")\n })\n]);\n\n// src/cohere-embedding-model.ts\nimport {\n TooManyEmbeddingValuesForCallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders as combineHeaders2,\n createJsonResponseHandler as createJsonResponseHandler2,\n parseProviderOptions as parseProviderOptions2,\n postJsonToApi as postJsonToApi2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\n\n// src/cohere-embedding-options.ts\nimport { z as z4 } from \"zod/v4\";\nvar cohereEmbeddingModelOptions = z4.object({\n /**\n * Specifies the type of input passed to the model. Default is `search_query`.\n *\n * - \"search_document\": Used for embeddings stored in a vector database for search use-cases.\n * - \"search_query\": Used for embeddings of search queries run against a vector DB to find relevant documents.\n * - \"classification\": Used for embeddings passed through a text classifier.\n * - \"clustering\": Used for embeddings run through a clustering algorithm.\n */\n inputType: z4.enum([\"search_document\", \"search_query\", \"classification\", \"clustering\"]).optional(),\n /**\n * Specifies how the API will handle inputs longer than the maximum token length.\n * Default is `END`.\n *\n * - \"NONE\": If selected, when the input exceeds the maximum input token length will return an error.\n * - \"START\": Will discard the start of the input until the remaining input is exactly the maximum input token length for the model.\n * - \"END\": Will discard the end of the input until the remaining input is exactly the maximum input token length for the model.\n */\n truncate: z4.enum([\"NONE\", \"START\", \"END\"]).optional(),\n /**\n * The number of dimensions of the output embedding.\n * Only available for `embed-v4.0` and newer models.\n *\n * Possible values are `256`, `512`, `1024`, and `1536`.\n * The default is `1536`.\n */\n outputDimension: z4.union([z4.literal(256), z4.literal(512), z4.literal(1024), z4.literal(1536)]).optional()\n});\n\n// src/cohere-embedding-model.ts\nvar CohereEmbeddingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.maxEmbeddingsPerCall = 96;\n this.supportsParallelCalls = true;\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async doEmbed({\n values,\n headers,\n abortSignal,\n providerOptions\n }) {\n var _a;\n const embeddingOptions = await parseProviderOptions2({\n provider: \"cohere\",\n providerOptions,\n schema: cohereEmbeddingModelOptions\n });\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi2({\n url: `${this.config.baseURL}/embed`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n // The AI SDK only supports 'float' embeddings. Note that the Cohere API\n // supports other embedding types, but they are not currently supported by the AI SDK.\n // https://docs.cohere.com/v2/reference/embed#request.body.embedding_types\n embedding_types: [\"float\"],\n texts: values,\n input_type: (_a = embeddingOptions == null ? void 0 : embeddingOptions.inputType) != null ? _a : \"search_query\",\n truncate: embeddingOptions == null ? void 0 : embeddingOptions.truncate,\n output_dimension: embeddingOptions == null ? void 0 : embeddingOptions.outputDimension\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n cohereTextEmbeddingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n warnings: [],\n embeddings: response.embeddings.float,\n usage: { tokens: response.meta.billed_units.input_tokens },\n response: { headers: responseHeaders, body: rawValue }\n };\n }\n};\nvar cohereTextEmbeddingResponseSchema = z5.object({\n embeddings: z5.object({\n float: z5.array(z5.array(z5.number()))\n }),\n meta: z5.object({\n billed_units: z5.object({\n input_tokens: z5.number()\n })\n })\n});\n\n// src/reranking/cohere-reranking-model.ts\nimport {\n combineHeaders as combineHeaders3,\n createJsonResponseHandler as createJsonResponseHandler3,\n parseProviderOptions as parseProviderOptions3,\n postJsonToApi as postJsonToApi3\n} from \"@ai-sdk/provider-utils\";\n\n// src/reranking/cohere-reranking-api.ts\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar cohereRerankingResponseSchema = lazySchema(\n () => zodSchema(\n z6.object({\n id: z6.string().nullish(),\n results: z6.array(\n z6.object({\n index: z6.number(),\n relevance_score: z6.number()\n })\n ),\n meta: z6.any()\n })\n )\n);\n\n// src/reranking/cohere-reranking-options.ts\nimport { lazySchema as lazySchema2, zodSchema as zodSchema2 } from \"@ai-sdk/provider-utils\";\nimport { z as z7 } from \"zod/v4\";\nvar cohereRerankingModelOptionsSchema = lazySchema2(\n () => zodSchema2(\n z7.object({\n maxTokensPerDoc: z7.number().optional(),\n priority: z7.number().optional()\n })\n )\n);\n\n// src/reranking/cohere-reranking-model.ts\nvar CohereRerankingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n // current implementation is based on v2 of the API: https://docs.cohere.com/v2/reference/rerank\n async doRerank({\n documents,\n headers,\n query,\n topN,\n abortSignal,\n providerOptions\n }) {\n var _a;\n const rerankingOptions = await parseProviderOptions3({\n provider: \"cohere\",\n providerOptions,\n schema: cohereRerankingModelOptionsSchema\n });\n const warnings = [];\n if (documents.type === \"object\") {\n warnings.push({\n type: \"compatibility\",\n feature: \"object documents\",\n details: \"Object documents are converted to strings.\"\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi3({\n url: `${this.config.baseURL}/rerank`,\n headers: combineHeaders3(this.config.headers(), headers),\n body: {\n model: this.modelId,\n query,\n documents: documents.type === \"text\" ? documents.values : documents.values.map((value) => JSON.stringify(value)),\n top_n: topN,\n max_tokens_per_doc: rerankingOptions == null ? void 0 : rerankingOptions.maxTokensPerDoc,\n priority: rerankingOptions == null ? void 0 : rerankingOptions.priority\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler3(\n cohereRerankingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n ranking: response.results.map((result) => ({\n index: result.index,\n relevanceScore: result.relevance_score\n })),\n warnings,\n response: {\n id: (_a = response.id) != null ? _a : void 0,\n headers: responseHeaders,\n body: rawValue\n }\n };\n }\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.27\" : \"0.0.0-test\";\n\n// src/cohere-provider.ts\nfunction createCohere(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.cohere.com/v2\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"COHERE_API_KEY\",\n description: \"Cohere\"\n })}`,\n ...options.headers\n },\n `ai-sdk/cohere/${VERSION}`\n );\n const createChatModel = (modelId) => {\n var _a2;\n return new CohereChatLanguageModel(modelId, {\n provider: \"cohere.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: (_a2 = options.generateId) != null ? _a2 : generateId\n });\n };\n const createEmbeddingModel = (modelId) => new CohereEmbeddingModel(modelId, {\n provider: \"cohere.textEmbedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createRerankingModel = (modelId) => new CohereRerankingModel(modelId, {\n provider: \"cohere.reranking\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Cohere model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.reranking = createRerankingModel;\n provider.rerankingModel = createRerankingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar cohere = createCohere();\nexport {\n VERSION,\n cohere,\n createCohere\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";kYAuBA,SAAI,OAA6B,OAAE,YAAO,MASxC,cAAU,EAAE,OAAO,CACjB,KAAM,EAAE,KAAK,CAAC,UAAW,UAAU,CAAC,EAAE,SAAS,EAC/C,YAAa,EAAE,OAAO,EAAE,SAAS,CACnC,CAAC,EAAE,SAAS,CACd,CAAC,EAKG,EAAwB,EAAG,OAAO,CACpC,QAAS,EAAG,OAAO,CACrB,CAAC,EACG,EAA8B,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3C,QAAS,EACT,KAAM,CACR,CACF,EAEJ,EAGI,GAAiB,SAGrB,SAAS,EAAY,CAAC,EAAU,CAAC,EAAG,CAClC,IAAI,EACJ,IAAM,GAAW,EAAK,EAAqB,EAAQ,OAAO,IAAM,KAAO,EAAK,4BACtE,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,iBACzB,YAAa,QACf,CAAC,OACE,EAAQ,OACb,EACA,iBAAiB,IACnB,EACM,EAAkB,CAAC,IAAY,CACnC,IAAI,EACJ,OAAO,IAAI,EAAwB,EAAS,CAC1C,SAAU,cACV,UACA,QAAS,EACT,MAAO,EAAQ,MACf,YAAa,EAAM,EAAQ,aAAe,KAAO,EAAM,CACzD,CAAC,GAEG,EAAuB,CAAC,IAAY,IAAI,EAAqB,EAAS,CAC1E,SAAU,uBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAuB,CAAC,IAAY,IAAI,EAAqB,EAAS,CAC1E,SAAU,mBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAW,QAAQ,CAAC,EAAS,CACjC,GAAI,WACF,MAAU,MACR,kEACF,EAEF,OAAO,EAAgB,CAAO,GAahC,OAXA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,cAAgB,EACzB,EAAS,mBAAqB,EAC9B,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAS,GAAa", | ||
| "debugId": "BBBE21CBDCF26BDC64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-env@3.972.59/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nexport const ENV_KEY = \"AWS_ACCESS_KEY_ID\";\nexport const ENV_SECRET = \"AWS_SECRET_ACCESS_KEY\";\nexport const ENV_SESSION = \"AWS_SESSION_TOKEN\";\nexport const ENV_EXPIRATION = \"AWS_CREDENTIAL_EXPIRATION\";\nexport const ENV_CREDENTIAL_SCOPE = \"AWS_CREDENTIAL_SCOPE\";\nexport const ENV_ACCOUNT_ID = \"AWS_ACCOUNT_ID\";\nexport const fromEnv = (init) => async () => {\n init?.logger?.debug(\"@aws-sdk/credential-provider-env - fromEnv\");\n const accessKeyId = process.env[ENV_KEY];\n const secretAccessKey = process.env[ENV_SECRET];\n const sessionToken = process.env[ENV_SESSION];\n const expiry = process.env[ENV_EXPIRATION];\n const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];\n const accountId = process.env[ENV_ACCOUNT_ID];\n if (accessKeyId && secretAccessKey) {\n const credentials = {\n accessKeyId,\n secretAccessKey,\n ...(sessionToken && { sessionToken }),\n ...(expiry && { expiration: new Date(expiry) }),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS\", \"g\");\n return credentials;\n }\n throw new CredentialsProviderError(\"Unable to find environment variable credentials.\", { logger: init?.logger });\n};\n" | ||
| ], | ||
| "mappings": ";kJAAA,oBACA,gBACa,EAAU,oBACV,EAAa,wBACb,EAAc,oBACd,EAAiB,4BACjB,EAAuB,uBACvB,EAAiB,iBACjB,EAAU,CAAC,IAAS,SAAY,CACzC,GAAM,QAAQ,MAAM,4CAA4C,EAChE,IAAM,EAAc,QAAQ,IAAI,GAC1B,EAAkB,QAAQ,IAAI,GAC9B,EAAe,QAAQ,IAAI,GAC3B,EAAS,QAAQ,IAAI,GACrB,EAAkB,QAAQ,IAAI,GAC9B,EAAY,QAAQ,IAAI,GAC9B,GAAI,GAAe,EAAiB,CAChC,IAAM,EAAc,CAChB,cACA,qBACI,GAAgB,CAAE,cAAa,KAC/B,GAAU,CAAE,WAAY,IAAI,KAAK,CAAM,CAAE,KACzC,GAAmB,CAAE,iBAAgB,KACrC,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,uBAAwB,GAAG,EACtD,EAEX,MAAM,IAAI,2BAAyB,mDAAoD,CAAE,OAAQ,GAAM,MAAO,CAAC", | ||
| "debugId": "652EF1C2D8C1F30A64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../tui/src/mini/demo.ts"], | ||
| "sourcesContent": [ | ||
| "// Demo mode for testing direct interactive mode without a real SDK.\n//\n// Enabled with `--demo`. Intercepts prompt submissions and drives the same\n// presentation commits and footer actions as the live transport. This\n// lets you test scrollback formatting, permission UI, canonical Form UI, and tool\n// snapshots without making actual model calls. Pass a demo slash command as\n// the initial interactive message to trigger a preview immediately.\n//\n// Slash commands:\n// /permission [kind] → triggers a permission request variant\n// /form [kind] → triggers a canonical Form request variant\n// /fmt <kind> → emits a specific tool/text type (text, reasoning, shell,\n// write, edit, patch, subagent, question, error, mix)\n//\n// Demo mode handles permission and Form replies locally, completing or failing\n// the synthetic tool parts through the same callbacks used by the live footer.\nimport path from \"path\"\nimport type { JsonValue, SessionMessageAssistantTool } from \"@opencode-ai/client/promise\"\nimport { parseSlashHead } from \"../prompt/parse\"\nimport { writeSessionOutput } from \"./stream\"\nimport { toolCommit, toolFinalPhase } from \"./stream-v2.subagent\"\nimport type {\n FooterApi,\n FooterView,\n FormCancel,\n FormReply,\n MiniFormRequest,\n MiniPermissionRequest,\n PermissionReply,\n RunPrompt,\n StreamCommit,\n} from \"./types\"\n\nconst KINDS = [\n \"markdown\",\n \"table\",\n \"text\",\n \"reasoning\",\n \"shell\",\n \"write\",\n \"edit\",\n \"patch\",\n \"subagent\",\n \"question\",\n \"error\",\n \"mix\",\n]\nconst PERMISSIONS = [\"edit\", \"shell\", \"read\", \"subagent\", \"external\", \"doom\"] as const\nconst FORMS = [\"question\", \"external\"] as const\n\ntype PermissionKind = (typeof PERMISSIONS)[number]\ntype FormKind = (typeof FORMS)[number]\n\nfunction permissionKind(value: string | undefined): PermissionKind | undefined {\n const next = (value || \"edit\").toLowerCase()\n return PERMISSIONS.find((item) => item === next)\n}\n\nfunction formKind(value: string | undefined): FormKind | undefined {\n const next = (value || \"question\").toLowerCase()\n return FORMS.find((item) => item === next)\n}\n\nconst SAMPLE_MARKDOWN = [\n \"# Direct Mode Demo\",\n \"\",\n \"This is a realistic assistant response for direct-mode formatting checks.\",\n \"It mixes **bold**, _italic_, `inline code`, links, code fences, and tables in one streamed reply.\",\n \"\",\n \"## Summary\",\n \"\",\n \"- Restored the final markdown flush so the last block is committed on idle.\",\n \"- Switched markdown scrollback commits back to top-level block boundaries.\",\n \"- Added footer-level regression coverage for split-footer rendering.\",\n \"\",\n \"## Status\",\n \"\",\n \"| Area | Before | After | Notes |\",\n \"| --- | --- | --- | --- |\",\n \"| Direct mode | Missing final rows | Stable | Final markdown block now flushes on idle |\",\n \"| Tables | Dropped in streaming mode | Visible | Block-based commits match the working OpenTUI demo |\",\n \"| Tests | Partial coverage | Broader coverage | Includes a footer-level split render capture |\",\n \"\",\n \"> This sample intentionally includes a wide table so you can spot wrapping and commit bugs quickly.\",\n \"\",\n \"```ts\",\n \"const result = { markdown: true, tables: 2, stable: true }\",\n \"```\",\n \"\",\n \"## Files\",\n \"\",\n \"| File | Change |\",\n \"| --- | --- |\",\n \"| `scrollback.surface.ts` | Align markdown commit logic with the split-footer demo |\",\n \"| `footer.ts` | Keep active surfaces across footer-height-only resizes |\",\n \"| `footer.test.ts` | Capture real split-footer markdown payloads during idle completion |\",\n \"\",\n \"Next step: run `/fmt table` if you want a tighter table-only sample.\",\n].join(\"\\n\")\n\nconst SAMPLE_TABLE = [\n \"# Table Sample\",\n \"\",\n \"| Kind | Example | Notes |\",\n \"| --- | --- | --- |\",\n \"| Pipe | `A\\\\|B` | Escaped pipes should stay in one cell |\",\n \"| Unicode | `漢字` | Wide characters should remain aligned |\",\n \"| Wrap | `LongTokenWithoutNaturalBreaks_1234567890` | Useful for width stress |\",\n \"| Status | done | Final row should still appear after idle |\",\n].join(\"\\n\")\n\ntype Ref = {\n msg: string\n call: string\n tool: string\n input: Record<string, JsonValue>\n start: number\n}\n\ntype FormRequest = {\n ref: Ref\n kind: FormKind\n request: MiniFormRequest\n}\n\ntype Perm = {\n ref: Ref\n done: {\n output: string\n metadata?: Record<string, JsonValue>\n }\n}\n\ntype Permit = {\n ref: Ref\n permission: string\n patterns: string[]\n metadata?: MiniPermissionRequest[\"metadata\"]\n always: string[]\n done: Perm[\"done\"]\n}\n\ntype State = {\n id: string\n thinking: boolean\n footer: FooterApi\n msg: number\n part: number\n call: number\n perm: number\n form: number\n perms: Map<string, Perm>\n forms: Map<string, FormRequest>\n started: Set<string>\n}\n\ntype Input = {\n sessionID: string\n thinking: boolean\n footer: FooterApi\n}\n\nfunction note(footer: FooterApi, text: string): void {\n footer.append({\n kind: \"system\",\n text,\n phase: \"start\",\n source: \"system\",\n })\n}\n\nfunction clearSubagent(footer: FooterApi): void {\n footer.event({\n type: \"stream.subagent\",\n state: {\n tabs: [],\n details: {},\n permissions: [],\n forms: [],\n },\n })\n}\n\nfunction showSubagent(\n state: State,\n input: {\n sessionID: string\n label: string\n description: string\n status: \"running\" | \"completed\" | \"cancelled\" | \"error\"\n title?: string\n commits: StreamCommit[]\n },\n) {\n state.footer.event({\n type: \"stream.subagent\",\n state: {\n tabs: [\n {\n sessionID: input.sessionID,\n label: input.label,\n description: input.description,\n status: input.status,\n title: input.title,\n },\n ],\n details: {\n [input.sessionID]: {\n commits: input.commits,\n },\n },\n permissions: [],\n forms: [],\n },\n })\n}\n\nfunction wait(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (!signal) {\n setTimeout(resolve, ms)\n return\n }\n\n if (signal.aborted) {\n resolve()\n return\n }\n\n const done = () => {\n clearTimeout(timer)\n signal.removeEventListener(\"abort\", done)\n resolve()\n }\n\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", done)\n resolve()\n }, ms)\n\n signal.addEventListener(\"abort\", done, { once: true })\n })\n}\n\nfunction split(text: string): string[] {\n if (text.length <= 48) {\n return [text]\n }\n\n const size = Math.ceil(text.length / 3)\n return [text.slice(0, size), text.slice(size, size * 2), text.slice(size * 2)]\n}\n\nfunction take(state: State, key: \"msg\" | \"part\" | \"call\" | \"perm\", prefix: string): string {\n state[key] += 1\n return `demo_${prefix}_${state[key]}`\n}\n\nfunction present(state: State, commits: StreamCommit[], view?: FooterView): void {\n writeSessionOutput(\n { footer: state.footer },\n {\n commits,\n updates: view\n ? [\n {\n type: \"stream.patch\" as const,\n patch: { status: view.type === \"permission\" ? \"awaiting permission\" : \"awaiting form\" },\n },\n { type: \"stream.view\" as const, view },\n ]\n : undefined,\n },\n )\n}\n\nfunction clearBlocker(state: State): void {\n writeSessionOutput(\n { footer: state.footer },\n {\n commits: [],\n updates: [\n { type: \"stream.patch\", patch: { status: \"\" } },\n { type: \"stream.view\", view: { type: \"prompt\" } },\n ],\n },\n )\n}\n\nfunction open(state: State): string {\n return take(state, \"msg\", \"msg\")\n}\n\nasync function emitText(state: State, body: string, signal?: AbortSignal): Promise<void> {\n const msg = open(state)\n const part = take(state, \"part\", \"part\")\n for (const item of split(body)) {\n if (signal?.aborted) {\n return\n }\n\n present(state, [\n { kind: \"assistant\", source: \"assistant\", text: item, phase: \"progress\", messageID: msg, partID: part },\n ])\n await wait(45, signal)\n }\n}\n\nasync function emitReasoning(state: State, body: string, signal?: AbortSignal): Promise<void> {\n const msg = open(state)\n const part = take(state, \"part\", \"part\")\n let first = true\n for (const item of split(body)) {\n if (signal?.aborted) {\n return\n }\n\n if (state.thinking) {\n present(state, [\n {\n kind: \"reasoning\",\n source: \"reasoning\",\n text: first ? `Thinking: ${item.replace(/\\[REDACTED\\]/g, \"\")}` : item.replace(/\\[REDACTED\\]/g, \"\"),\n phase: \"progress\",\n messageID: msg,\n partID: part,\n },\n ])\n first = false\n }\n await wait(45, signal)\n }\n}\n\nfunction make(state: State, tool: string, input: Record<string, JsonValue>): Ref {\n return {\n msg: open(state),\n call: take(state, \"call\", \"call\"),\n tool,\n input,\n start: Date.now(),\n }\n}\n\nfunction startTool(state: State, ref: Ref, structured: Record<string, JsonValue> = {}): SessionMessageAssistantTool {\n state.started.add(ref.call)\n const part = {\n type: \"tool\" as const,\n id: ref.call,\n name: ref.tool,\n state: { status: \"running\" as const, input: ref.input, structured, content: [] },\n time: { created: ref.start, ran: ref.start },\n }\n present(state, [toolCommit(part, ref.msg, \"start\")])\n return part\n}\n\nfunction askPermission(state: State, item: Permit): void {\n const tool = startTool(state, item.ref)\n\n const id = take(state, \"perm\", \"perm\")\n state.perms.set(id, {\n ref: item.ref,\n done: item.done,\n })\n\n present(state, [], {\n type: \"permission\",\n request: {\n id,\n sessionID: state.id,\n action: item.permission,\n resources: item.patterns,\n metadata: item.metadata ?? {},\n save: item.always,\n source: { type: \"tool\", messageID: item.ref.msg, callID: item.ref.call },\n tool,\n },\n })\n}\n\nfunction doneTool(\n state: State,\n ref: Ref,\n output: {\n output: string\n metadata?: Record<string, JsonValue>\n },\n): void {\n if (!state.started.has(ref.call)) startTool(state, ref)\n const part: SessionMessageAssistantTool = {\n type: \"tool\",\n id: ref.call,\n name: ref.tool,\n state: {\n status: \"completed\",\n input: ref.input,\n content: output.output ? [{ type: \"text\", text: output.output }] : [],\n structured: output.metadata ?? {},\n },\n time: { created: ref.start, ran: ref.start, completed: Date.now() },\n }\n present(state, [toolCommit(part, ref.msg, toolFinalPhase(part))])\n}\n\nfunction failTool(state: State, ref: Ref, error: string): void {\n if (!state.started.has(ref.call)) startTool(state, ref)\n present(state, [\n toolCommit(\n {\n type: \"tool\",\n id: ref.call,\n name: ref.tool,\n state: {\n status: \"error\",\n input: ref.input,\n error: { type: \"unknown\", message: error },\n structured: {},\n content: [],\n },\n time: { created: ref.start, ran: ref.start, completed: Date.now() },\n },\n ref.msg,\n \"final\",\n ),\n ])\n}\n\nfunction emitError(state: State, text: string): void {\n present(state, [{ kind: \"error\", source: \"system\", text, phase: \"start\" }])\n}\n\nasync function emitBash(state: State, signal?: AbortSignal): Promise<void> {\n const ref = make(state, \"shell\", {\n command: \"git status\",\n workdir: process.cwd(),\n description: \"Show git status\",\n })\n startTool(state, ref)\n await wait(70, signal)\n doneTool(state, ref, {\n output: `${process.cwd()}\\ngit status\\nOn branch demo\\nnothing to commit, working tree clean\\n`,\n metadata: {\n exit: 0,\n },\n })\n}\n\nfunction emitWrite(state: State): void {\n const file = path.join(process.cwd(), \"src\", \"demo-format.ts\")\n const ref = make(state, \"write\", {\n path: file,\n content: \"export const demo = 42\\n\",\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {},\n })\n}\n\nfunction emitEdit(state: State): void {\n const file = path.join(process.cwd(), \"src\", \"demo-format.ts\")\n const ref = make(state, \"edit\", {\n path: file,\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {\n files: [\n {\n file,\n status: \"modified\",\n patch: \"@@ -1 +1 @@\\n-export const demo = 1\\n+export const demo = 42\\n\",\n },\n ],\n },\n })\n}\n\nfunction emitPatch(state: State): void {\n const file = path.join(process.cwd(), \"src\", \"demo-format.ts\")\n const ref = make(state, \"patch\", {\n patchText: \"*** Begin Patch\\n*** End Patch\",\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {\n files: [\n {\n status: \"modified\",\n file,\n patch: \"@@ -1 +1 @@\\n-export const demo = 1\\n+export const demo = 42\\n\",\n deletions: 1,\n },\n {\n status: \"added\",\n file: path.join(process.cwd(), \"README-demo.md\"),\n patch: \"@@ -0,0 +1,4 @@\\n+# Demo\\n+This is a generated preview file.\\n\",\n deletions: 0,\n },\n ],\n },\n })\n}\n\nfunction emitTask(state: State): void {\n const ref = make(state, \"subagent\", {\n description: \"Scan run/* for reducer touchpoints\",\n agent: \"explore\",\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {\n sessionID: \"ses_demo_child\",\n status: \"completed\",\n output: \"\",\n },\n })\n const part = {\n type: \"tool\",\n id: \"sub_demo_call_1\",\n name: \"read\",\n state: {\n status: \"running\",\n input: {\n path: \"packages/tui/src/mini/stream.ts\",\n offset: 1,\n limit: 200,\n },\n structured: {},\n content: [],\n },\n time: { created: Date.now(), ran: Date.now() },\n } satisfies SessionMessageAssistantTool\n showSubagent(state, {\n sessionID: \"ses_demo_child\",\n label: \"Explore\",\n description: \"Scan run/* for reducer touchpoints\",\n status: \"completed\",\n title: \"Reducer touchpoints found\",\n commits: [\n {\n kind: \"user\",\n text: \"Scan run/* for reducer touchpoints\",\n phase: \"start\",\n source: \"system\",\n },\n {\n kind: \"reasoning\",\n text: \"Thinking: tracing reducer and footer boundaries\",\n phase: \"progress\",\n source: \"reasoning\",\n messageID: \"sub_demo_msg_reasoning\",\n partID: \"sub_demo_reasoning_1\",\n },\n toolCommit(part, \"sub_demo_msg_tool\", \"start\"),\n {\n kind: \"assistant\",\n text: \"Footer updates flow through stream.ts into RunFooter\",\n phase: \"progress\",\n source: \"assistant\",\n messageID: \"sub_demo_msg_text\",\n partID: \"sub_demo_text_1\",\n },\n ],\n })\n}\n\nfunction emitQuestionTool(state: State): void {\n const ref = make(state, \"question\", {\n questions: [\n {\n header: \"Style\",\n question: \"Which output style do you want to inspect?\",\n options: [\n { label: \"Diff\", description: \"Show diff block\" },\n { label: \"Code\", description: \"Show code block\" },\n ],\n multiple: false,\n custom: false,\n },\n {\n header: \"Extras\",\n question: \"Pick extra rows\",\n options: [\n { label: \"Usage\", description: \"Add usage row\" },\n { label: \"Duration\", description: \"Add duration row\" },\n ],\n multiple: true,\n custom: true,\n },\n ],\n })\n doneTool(state, ref, {\n output: \"\",\n metadata: {\n answers: [[\"Diff\"], [\"Usage\", \"custom-note\"]],\n },\n })\n}\n\nfunction emitPermission(state: State, kind: PermissionKind = \"edit\"): void {\n const root = process.cwd()\n const file = path.join(root, \"src\", \"demo-format.ts\")\n\n if (kind === \"shell\") {\n const command = \"git status --short\"\n const ref = make(state, \"shell\", {\n command,\n workdir: root,\n description: \"Inspect worktree changes\",\n })\n askPermission(state, {\n ref,\n permission: \"shell\",\n patterns: [command],\n always: [\"*\"],\n done: {\n output: `${root}\\ngit status --short\\n M src/demo-format.ts\\n?? src/demo-permission.ts\\n`,\n metadata: {\n exit: 0,\n },\n },\n })\n return\n }\n\n if (kind === \"read\") {\n const target = path.join(root, \"package.json\")\n const ref = make(state, \"read\", {\n path: target,\n offset: 1,\n limit: 80,\n })\n askPermission(state, {\n ref,\n permission: \"read\",\n patterns: [target],\n always: [target],\n done: {\n output: [\"1: {\", '2: \"name\": \"opencode\",', '3: \"private\": true', \"4: }\"].join(\"\\n\"),\n metadata: {},\n },\n })\n return\n }\n\n if (kind === \"subagent\") {\n const ref = make(state, \"subagent\", {\n description: \"Inspect footer spacing across direct-mode prompts\",\n agent: \"explore\",\n })\n askPermission(state, {\n ref,\n permission: \"subagent\",\n patterns: [\"explore\"],\n always: [\"*\"],\n done: {\n output: \"\",\n metadata: {\n sessionID: \"sub_demo_perm_1\",\n status: \"completed\",\n output: \"\",\n },\n },\n })\n return\n }\n\n if (kind === \"external\") {\n const dir = path.join(path.dirname(root), \"demo-shared\")\n const target = path.join(dir, \"README.md\")\n const ref = make(state, \"read\", {\n path: target,\n offset: 1,\n limit: 40,\n })\n askPermission(state, {\n ref,\n permission: \"external_directory\",\n patterns: [`${dir}/**`],\n metadata: {\n parentDir: dir,\n filepath: target,\n },\n always: [`${dir}/**`],\n done: {\n output: `1: # External demo\\n2: Shared preview file\\nPath: ${target}`,\n metadata: {},\n },\n })\n return\n }\n\n if (kind === \"doom\") {\n const ref = make(state, \"subagent\", {\n description: \"Retry the formatter after repeated failures\",\n agent: \"general\",\n })\n askPermission(state, {\n ref,\n permission: \"doom_loop\",\n patterns: [\"*\"],\n always: [\"*\"],\n done: {\n output: \"Continuing after repeated failures.\\n\",\n metadata: {},\n },\n })\n return\n }\n\n const diff = \"@@ -1 +1 @@\\n-export const demo = 1\\n+export const demo = 42\\n\"\n const ref = make(state, \"edit\", {\n path: file,\n })\n askPermission(state, {\n ref,\n permission: \"edit\",\n patterns: [file],\n always: [file],\n done: {\n output: \"\",\n metadata: {\n files: [{ file, status: \"modified\", patch: diff }],\n },\n },\n })\n}\n\nfunction demoForm(kind: FormKind): { title: string; fields: MiniFormRequest[\"fields\"]; questions?: JsonValue[] } {\n if (kind === \"question\") {\n const questions: JsonValue[] = [\n {\n header: \"Layout\",\n question: \"Which footer view should be the reference for spacing checks?\",\n options: [\n { label: \"Form\", description: \"Inspect the canonical Form footer\" },\n { label: \"Prompt\", description: \"Return to the normal composer\" },\n ],\n multiple: false,\n custom: true,\n },\n {\n header: \"Checks\",\n question: \"Pick formatting previews\",\n options: [\n { label: \"Diff\", description: \"Emit an edit diff\" },\n { label: \"Subagent\", description: \"Emit a subagent card\" },\n ],\n multiple: true,\n custom: true,\n },\n ]\n return {\n title: \"Questions\",\n questions,\n fields: [\n {\n key: \"q0\",\n title: \"Layout\",\n description: \"Which footer view should be the reference for spacing checks?\",\n type: \"string\",\n options: [\n { value: \"Form\", label: \"Form\", description: \"Inspect the canonical Form footer\" },\n { value: \"Prompt\", label: \"Prompt\", description: \"Return to the normal composer\" },\n ],\n custom: true,\n },\n {\n key: \"q1\",\n title: \"Checks\",\n description: \"Pick formatting previews\",\n type: \"multiselect\",\n options: [\n { value: \"Diff\", label: \"Diff\", description: \"Emit an edit diff\" },\n { value: \"Subagent\", label: \"Subagent\", description: \"Emit a subagent card\" },\n ],\n custom: true,\n },\n ],\n }\n }\n return {\n title: \"MCP authorization\",\n fields: [\n {\n key: \"authorization\",\n type: \"external\",\n url: \"https://example.com/opencode-demo\",\n title: \"Authorize demo MCP server\",\n description: \"Complete authorization in your browser\",\n },\n ],\n }\n}\n\nfunction emitForm(state: State, kind: FormKind = \"question\"): void {\n const form = demoForm(kind)\n const ref = make(state, kind === \"question\" ? \"question\" : \"mcp_demo\", {\n ...(form.questions ? { questions: form.questions } : { form: kind }),\n })\n startTool(state, ref)\n state.form++\n const request: MiniFormRequest = {\n id: `frm_demo_${state.form}`,\n sessionID: state.id,\n title: form.title,\n metadata:\n kind === \"question\"\n ? { kind: \"question\", tool: { messageID: ref.msg, callID: ref.call } }\n : { kind: \"mcp\", message: `Synthetic ${kind} MCP elicitation` },\n fields: form.fields,\n }\n state.forms.set(request.id, { ref, kind, request })\n present(state, [], { type: \"form\", request })\n}\n\nasync function emitFmt(state: State, kind: string, body: string, signal?: AbortSignal): Promise<boolean> {\n if (kind === \"text\") {\n await emitText(state, body || SAMPLE_MARKDOWN, signal)\n return true\n }\n\n if (kind === \"markdown\" || kind === \"md\") {\n await emitText(state, body || SAMPLE_MARKDOWN, signal)\n return true\n }\n\n if (kind === \"table\") {\n await emitText(state, body || SAMPLE_TABLE, signal)\n return true\n }\n\n if (kind === \"reasoning\") {\n await emitReasoning(state, body || \"Planning next steps [REDACTED] while preserving reducer ordering.\", signal)\n return true\n }\n\n if (kind === \"shell\") {\n await emitBash(state, signal)\n return true\n }\n\n if (kind === \"write\") {\n emitWrite(state)\n return true\n }\n\n if (kind === \"edit\") {\n emitEdit(state)\n return true\n }\n\n if (kind === \"patch\") {\n emitPatch(state)\n return true\n }\n\n if (kind === \"subagent\") {\n emitTask(state)\n return true\n }\n\n if (kind === \"question\") {\n emitQuestionTool(state)\n return true\n }\n\n if (kind === \"error\") {\n emitError(state, body || \"demo error event\")\n return true\n }\n\n if (kind === \"mix\") {\n await emitText(state, SAMPLE_MARKDOWN, signal)\n await wait(50, signal)\n await emitReasoning(state, \"Thinking through formatter edge cases [REDACTED].\", signal)\n await wait(50, signal)\n await emitBash(state, signal)\n emitWrite(state)\n emitEdit(state)\n emitPatch(state)\n emitTask(state)\n emitQuestionTool(state)\n emitError(state, \"demo mixed scenario error\")\n return true\n }\n\n return false\n}\n\nfunction intro(state: State): void {\n note(\n state.footer,\n [\n \"Demo slash commands enabled for interactive mode.\",\n `- /permission [kind] (${PERMISSIONS.join(\", \")})`,\n `- /form [kind] (${FORMS.join(\", \")})`,\n `- /fmt <kind> (${KINDS.join(\", \")})`,\n \"Examples:\",\n \"- /permission shell\",\n \"- /form question\",\n \"- /form external\",\n \"- /fmt markdown\",\n \"- /fmt table\",\n \"- /fmt text your custom text\",\n ].join(\"\\n\"),\n )\n}\n\nexport function createRunDemo(input: Input) {\n const state: State = {\n id: input.sessionID,\n thinking: input.thinking,\n footer: input.footer,\n msg: 0,\n part: 0,\n call: 0,\n perm: 0,\n form: 0,\n perms: new Map(),\n forms: new Map(),\n started: new Set(),\n }\n\n const start = async (): Promise<void> => {\n intro(state)\n }\n\n const prompt = async (line: RunPrompt, signal?: AbortSignal): Promise<boolean> => {\n const text = line.text.trim()\n const head = parseSlashHead(text)\n const list = head?.arguments.split(/\\s+/).filter(Boolean) ?? []\n const cmd = head ? `/${head.name}` : \"\"\n\n clearSubagent(state.footer)\n\n if (cmd === \"/help\") {\n intro(state)\n return true\n }\n\n if (cmd === \"/permission\") {\n const kind = permissionKind(list[0])\n if (!kind) {\n note(state.footer, `Pick a permission kind: ${PERMISSIONS.join(\", \")}`)\n return true\n }\n\n emitPermission(state, kind)\n return true\n }\n\n if (cmd === \"/form\") {\n const kind = formKind(list[0])\n if (!kind) {\n note(state.footer, `Pick a form kind: ${FORMS.join(\", \")}`)\n return true\n }\n\n emitForm(state, kind)\n return true\n }\n\n if (cmd === \"/fmt\") {\n const kind = (list[0] || \"\").toLowerCase()\n const body = list.slice(1).join(\" \")\n if (!kind) {\n note(state.footer, `Pick a kind: ${KINDS.join(\", \")}`)\n return true\n }\n\n const ok = await emitFmt(state, kind, body, signal)\n if (ok) {\n return true\n }\n\n note(state.footer, `Unknown kind \"${kind}\". Use: ${KINDS.join(\", \")}`)\n return true\n }\n\n return false\n }\n\n const permission = (input: PermissionReply): boolean => {\n const item = state.perms.get(input.requestID)\n if (!item || !input.reply) {\n return false\n }\n\n state.perms.delete(input.requestID)\n clearBlocker(state)\n\n if (input.reply === \"reject\") {\n failTool(state, item.ref, input.message || \"permission rejected\")\n return true\n }\n\n doneTool(state, item.ref, item.done)\n return true\n }\n\n const formReply = (input: FormReply): boolean => {\n const form = state.forms.get(input.formID)\n if (!form || input.sessionID !== form.request.sessionID) return false\n state.forms.delete(input.formID)\n clearBlocker(state)\n if (form.kind === \"question\") {\n doneTool(state, form.ref, {\n output: \"\",\n metadata: {\n answers: form.request.fields.map((field) => {\n const value = input.answer[field.key]\n if (value === undefined) return []\n return Array.isArray(value) ? [...value] : [String(value)]\n }),\n },\n })\n return true\n }\n doneTool(state, form.ref, {\n output: `Form submitted: ${Object.entries(input.answer)\n .map(([key, value]) => `${key}=${Array.isArray(value) ? value.join(\", \") : String(value)}`)\n .join(\"; \")}\\n`,\n metadata: { answer: input.answer },\n })\n return true\n }\n\n const formCancel = (input: FormCancel): boolean => {\n const form = state.forms.get(input.formID)\n if (!form || input.sessionID !== form.request.sessionID) return false\n state.forms.delete(input.formID)\n clearBlocker(state)\n failTool(state, form.ref, \"form cancelled\")\n return true\n }\n\n return {\n start,\n prompt,\n permission,\n formReply,\n formCancel,\n }\n}\n" | ||
| ], | ||
| "mappings": ";2PAgBA,yBAiBA,SAAM,OAAQ,MACZ,gBACA,QACA,OACA,YACA,QACA,QACA,OACA,QACA,WACA,WACA,QACA,KACF,EACM,EAAc,CAAC,OAAQ,QAAS,OAAQ,WAAY,WAAY,MAAM,EACtE,EAAQ,CAAC,WAAY,UAAU,EAKrC,SAAS,CAAc,CAAC,EAAuD,CAC7E,IAAM,GAAQ,GAAS,QAAQ,YAAY,EAC3C,OAAO,EAAY,KAAK,CAAC,IAAS,IAAS,CAAI,EAGjD,SAAS,CAAQ,CAAC,EAAiD,CACjE,IAAM,GAAQ,GAAS,YAAY,YAAY,EAC/C,OAAO,EAAM,KAAK,CAAC,IAAS,IAAS,CAAI,EAG3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Q,UAAW,MAAO,GAIhE,OAHA,EAAM,MAAM,OAAO,EAAM,MAAM,EAC/B,EAAa,CAAK,EAClB,EAAS,EAAO,EAAK,IAAK,gBAAgB,EACnC,GAST", | ||
| "debugId": "384B84E53C764AFC64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/providers/openai-compatible.ts"], | ||
| "sourcesContent": [ | ||
| "import { ProviderID, type ModelID } from \"../schema\"\nimport * as OpenAICompatibleChat from \"../protocols/openai-compatible-chat\"\nimport type { RouteDefaultsInput } from \"../route/client\"\nimport { AuthOptions, type ProviderAuthOption } from \"../route/auth-options\"\nimport type { ProviderPackage } from \"../provider-package\"\nimport { profiles, type OpenAICompatibleProfile } from \"./openai-compatible-profile\"\n\nexport const id = ProviderID.make(\"openai-compatible\")\n\ntype GenericModelOptions = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly provider?: string\n readonly baseURL: string\n }\n\nexport interface Settings extends ProviderPackage.Settings {\n readonly apiKey?: string\n readonly baseURL: string\n readonly provider?: string\n}\n\nexport type FamilyModelOptions = RouteDefaultsInput &\n ProviderAuthOption<\"optional\"> & {\n readonly baseURL?: string\n }\n\nexport const routes = [OpenAICompatibleChat.route]\n\nexport const configure = (input: GenericModelOptions) => {\n const provider = input.provider ?? \"openai-compatible\"\n const { provider: _, baseURL, apiKey: _apiKey, auth: _auth, ...rest } = input\n const route = OpenAICompatibleChat.route.with({\n ...rest,\n provider,\n endpoint: { baseURL },\n auth: AuthOptions.bearer(input, []),\n })\n return {\n id: ProviderID.make(provider),\n model: (modelID: string | ModelID) => route.model({ id: modelID, provider: ProviderID.make(provider) }),\n configure,\n }\n}\n\nconst define = (profile: OpenAICompatibleProfile) => {\n const configureProfile = (input: FamilyModelOptions = {}) => {\n const facade = configure({\n ...input,\n baseURL: input.baseURL ?? profile.baseURL,\n provider: profile.provider,\n })\n return {\n id: ProviderID.make(profile.provider),\n model: facade.model,\n configure: configureProfile,\n }\n }\n return configureProfile()\n}\n\nexport const provider = {\n id,\n configure,\n}\n\nexport const model: ProviderPackage.Definition<Settings>[\"model\"] = (modelID, settings) =>\n configure({\n apiKey: settings.apiKey,\n baseURL: settings.baseURL,\n headers: settings.headers === undefined ? undefined : { ...settings.headers },\n http: settings.body === undefined ? undefined : { body: { ...settings.body } },\n limits: settings.limits,\n provider: settings.provider,\n }).model(modelID)\n\nexport const baseten = define(profiles.baseten)\nexport const cerebras = define(profiles.cerebras)\nexport const deepinfra = define(profiles.deepinfra)\nexport const deepseek = define(profiles.deepseek)\nexport const fireworks = define(profiles.fireworks)\nexport const groq = define(profiles.groq)\nexport const togetherai = define(profiles.togetherai)\n" | ||
| ], | ||
| "mappings": ";qhBAOO,SAAM,OAAK,OAAW,UAAK,wBAAmB,OAmBxC,OAAS,MAAsB,MAAK,OAEpC,OAAY,MAAC,SAA+B,CACvD,IAAM,EAAW,EAAM,UAAY,qBAC3B,SAAU,EAAG,UAAS,OAAQ,EAAS,KAAM,KAAU,GAAS,EAClE,EAA6B,EAAM,KAAK,IACzC,EACH,WACA,SAAU,CAAE,SAAQ,EACpB,KAAM,EAAY,OAAO,EAAO,CAAC,CAAC,CACpC,CAAC,EACD,MAAO,CACL,GAAI,EAAW,KAAK,CAAQ,EAC5B,MAAO,CAAC,IAA8B,EAAM,MAAM,CAAE,GAAI,EAAS,SAAU,EAAW,KAAK,CAAQ,CAAE,CAAC,EACtG,WACF,GAGI,EAAS,CAAC,IAAqC,CACnD,IAAM,EAAmB,CAAC,EAA4B,CAAC,IAAM,CAC3D,IAAM,EAAS,EAAU,IACpB,EACH,QAAS,EAAM,SAAW,EAAQ,QAClC,SAAU,EAAQ,QACpB,CAAC,EACD,MAAO,CACL,GAAI,EAAW,KAAK,EAAQ,QAAQ,EACpC,MAAO,EAAO,MACd,UAAW,CACb,GAEF,OAAO,EAAiB,GAGb,EAAW,CACtB,KACA,WACF,EAEa,EAAuD,CAAC,EAAS,IAC5E,EAAU,CACR,OAAQ,EAAS,OACjB,QAAS,EAAS,QAClB,QAAS,EAAS,UAAY,OAAY,OAAY,IAAK,EAAS,OAAQ,EAC5E,KAAM,EAAS,OAAS,OAAY,OAAY,CAAE,KAAM,IAAK,EAAS,IAAK,CAAE,EAC7E,OAAQ,EAAS,OACjB,SAAU,EAAS,QACrB,CAAC,EAAE,MAAM,CAAO,EAEL,EAAU,EAAO,EAAS,OAAO,EACjC,EAAW,EAAO,EAAS,QAAQ,EACnC,EAAY,EAAO,EAAS,SAAS,EACrC,EAAW,EAAO,EAAS,QAAQ,EACnC,EAAY,EAAO,EAAS,SAAS,EACrC,EAAO,EAAO,EAAS,IAAI,EAC3B,EAAa,EAAO,EAAS,UAAU", | ||
| "debugId": "CB1B39BE4F85243964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "02C44D41A470E8AA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/run.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(Commands.commands.run, (input) =>\n Effect.gen(function* () {\n const { runNonInteractive } = yield* Effect.promise(() => import(\"../../run/run\"))\n const separator = process.argv.indexOf(\"--\", 2)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n yield* Effect.promise(() =>\n runNonInteractive({\n server,\n message: [...input.message, ...(separator === -1 ? [] : process.argv.slice(separator + 1))],\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n format: input.format,\n file: [...input.file],\n title: Option.getOrUndefined(input.title),\n thinking: input.thinking,\n auto: input.auto || input.yolo,\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+9BAKA,SAAe,SAAQ,aAAQ,OAAS,cAAS,SAAK,MAAC,SACrD,OAAO,SAAI,cAAU,OAAG,MACtB,SAAQ,0BAAsB,WAAO,OAAO,aAAQ,SAAa,wCAAgB,OAC3E,OAAY,aAAQ,UAAK,aAAQ,UAAM,MAAC,EACxC,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACD,MAAO,EAAO,QAAQ,IACpB,EAAkB,CAChB,SACA,QAAS,CAAC,GAAG,EAAM,QAAS,GAAI,IAAc,GAAK,CAAC,EAAI,QAAQ,KAAK,MAAM,EAAY,CAAC,CAAE,EAC1F,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAM,OACd,KAAM,CAAC,GAAG,EAAM,IAAI,EACpB,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,SAAU,EAAM,SAChB,KAAM,EAAM,MAAQ,EAAM,IAC5B,CAAC,CACH,EACD,CACH", | ||
| "debugId": "B07C05B3FE06C7B764756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "41B6B139F6D8B33664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/connect.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type IntegrationCommandStatusOutput, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.connect,\n Effect.fn(\"cli.auth.connect\")(function* (input) {\n process.stdout.write(\"Connecting...\" + EOL + EOL)\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n yield* request(() => client.integration.wellknown.add({ url: input.url, location }))\n const integrationID = input.url.replace(/\\/+$/, \"\")\n const started = yield* request(() =>\n client.integration.command.connect({ integrationID, methodID: \"login\", location }),\n )\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.command.cancel({ integrationID, attemptID: started.data.attemptID, location }),\n ).pipe(Effect.ignore),\n )\n\n const status = yield* wait(client, integrationID, started.data.attemptID)\n if (status.status === \"failed\") return yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") return yield* Effect.fail(new Error(\"Authentication expired\"))\n process.stdout.write(\"Connected\" + EOL)\n }),\n)\n\nconst wait = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n shown = false,\n): Effect.Effect<Exclude<IntegrationCommandStatusOutput[\"data\"], { status: \"pending\" }>, unknown> =>\n Effect.gen(function* () {\n const response = yield* request(() => client.integration.command.status({ integrationID, attemptID, location }))\n if (response.data.status !== \"pending\") return response.data\n const output = response.data.message?.trim()\n if (!shown && output) process.stdout.write(output + EOL + EOL)\n yield* Effect.sleep(500)\n return yield* wait(client, integrationID, attemptID, shown || !!output)\n })\n\nfunction request<A>(task: () => Promise<A>) {\n return Effect.tryPromise({ try: task, catch: (cause) => cause })\n}\n" | ||
| ], | ||
| "mappings": ";83BAAA,mBAAS,gBAQT,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,UAAK,cAAS,aAChC,OAAO,QAAG,uBAAkB,OAAE,cAAU,MAAC,E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,EAChB,MAAO,EAAK,EAAQ,EAAe,EAAW,GAAS,CAAC,CAAC,CAAM,EACvE,EAEH,SAAS,CAAU,CAAC,EAAwB,CAC1C,OAAO,EAAO,WAAW,CAAE,IAAK,EAAM,MAAO,CAAC,IAAU,CAAM,CAAC", | ||
| "debugId": "CF85AFB46ACAAA8664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/status.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.status,\n Effect.fn(\"cli.service.status\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover({ ...options, version: undefined })\n process.stdout.write((found?.url ?? \"stopped\") + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+0BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,YACnC,OAAO,QAAG,yBAAoB,OAAE,cAAU,OAAG,MAC3C,SAAM,OAAU,WAAO,OAAc,aAAQ,EACvC,EAAQ,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,EACxE,QAAQ,OAAO,OAAO,GAAO,KAAO,WAAa,CAAG,EACrD,CACH", | ||
| "debugId": "63FF9ECAF29B058864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/unset.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.unset,\n Effect.fn(\"cli.service.unset\")(function* (input) {\n yield* ServiceConfig.unset(input.key)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";k0BAKA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,WACnC,OAAO,QAAG,wBAAmB,OAAE,cAAU,MAAC,OAAO,MAC/C,WAAO,OAAc,WAAM,OAAM,QAAG,OACrC,CACH", | ||
| "debugId": "3195B6BC099E09E464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../ai/src/image-client.ts", "../ai/src/image.ts"], | ||
| "sourcesContent": [ | ||
| "import { Context, Effect, Layer } from \"effect\"\nimport { RequestExecutor } from \"./route/executor\"\nimport type { ImageOptions, ImageRequest, ImageRequestFor, ImageResponse } from \"./image\"\nimport type { LLMError } from \"./schema\"\n\nexport type Execute = RequestExecutor.Interface[\"execute\"]\n\nexport interface Interface {\n readonly generate: <Options extends ImageOptions>(\n request: ImageRequestFor<Options>,\n ) => Effect.Effect<ImageResponse, LLMError>\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/ImageClient\") {}\n\nexport const generate = <Options extends ImageOptions>(\n request: ImageRequestFor<Options>,\n): Effect.Effect<ImageResponse, LLMError> =>\n Effect.gen(function* () {\n const client = yield* Service\n return yield* client.generate(request)\n }) as Effect.Effect<ImageResponse, LLMError>\n\nexport const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer.effect(\n Service,\n Effect.gen(function* () {\n const executor = yield* RequestExecutor.Service\n return Service.of({\n generate: (request) => request.model.route.generate(request, executor.execute),\n })\n }),\n)\n\nexport const ImageClient = {\n Service,\n layer,\n generate,\n} as const\n", | ||
| "import { Effect, Schema } from \"effect\"\nimport { HttpOptions, InvalidRequestReason, LLMError, ModelID, ProviderID, ProviderMetadata, Usage } from \"./schema\"\nimport { ImageClient, Service, type Execute as ImageExecute } from \"./image-client\"\n\nexport interface ImageRoute<Options extends ImageOptions = ImageOptions> {\n readonly id: string\n readonly generate: (\n request: ImageRequestFor<Options>,\n execute: ImageExecute,\n ) => Effect.Effect<ImageResponse, LLMError>\n}\n\nexport type ImageOptions = Record<string, unknown>\n\nexport class ImageModel<Options extends ImageOptions = ImageOptions> {\n declare protected readonly _Options: (options: Options) => Options\n readonly id: ModelID\n readonly provider: ProviderID\n readonly route: ImageRoute<Options>\n readonly http?: HttpOptions\n\n constructor(input: ImageModel.Input<Options>) {\n this.id = input.id\n this.provider = input.provider\n this.route = input.route\n this.http = input.http\n }\n\n static make<Options extends ImageOptions = ImageOptions>(input: ImageModel.MakeInput<Options>) {\n return new ImageModel<Options>({\n id: ModelID.make(input.id),\n provider: ProviderID.make(input.provider),\n route: input.route,\n http: input.http,\n })\n }\n}\n\nexport namespace ImageModel {\n export interface Input<Options extends ImageOptions = ImageOptions> {\n readonly id: ModelID\n readonly provider: ProviderID\n readonly route: ImageRoute<Options>\n readonly http?: HttpOptions\n }\n\n export interface MakeInput<Options extends ImageOptions = ImageOptions>\n extends Omit<Input<Options>, \"id\" | \"provider\"> {\n readonly id: string | ModelID\n readonly provider: string | ProviderID\n }\n}\n\nexport const ImageModelSchema = Schema.declare((value): value is ImageModel => value instanceof ImageModel, {\n expected: \"Image.Model\",\n})\n\nconst ImageBytesInput = Schema.Struct({\n type: Schema.Literal(\"bytes\"),\n data: Schema.Uint8Array,\n mediaType: Schema.String,\n})\nconst ImageUrlInput = Schema.Struct({\n type: Schema.Literal(\"url\"),\n url: Schema.String,\n})\nconst ImageFileIDInput = Schema.Struct({\n type: Schema.Literal(\"file-id\"),\n id: Schema.String,\n})\nconst ImageFileURIInput = Schema.Struct({\n type: Schema.Literal(\"file-uri\"),\n uri: Schema.String,\n mediaType: Schema.String,\n})\n\nexport const ImageInputSchema = Schema.Union([\n ImageBytesInput,\n ImageUrlInput,\n ImageFileIDInput,\n ImageFileURIInput,\n]).pipe(Schema.toTaggedUnion(\"type\"))\nexport type ImageInput = Schema.Schema.Type<typeof ImageInputSchema>\n\nexport const ImageInput = {\n bytes: (data: Uint8Array, mediaType: string): ImageInput => ({ type: \"bytes\", data, mediaType }),\n url: (url: string): ImageInput => ({ type: \"url\", url }),\n file: (id: string): ImageInput => ({ type: \"file-id\", id }),\n fileUri: (uri: string, mediaType: string): ImageInput => ({ type: \"file-uri\", uri, mediaType }),\n} as const\n\nexport class ImageRequest extends Schema.Class<ImageRequest>(\"Image.Request\")({\n model: ImageModelSchema,\n prompt: Schema.String,\n images: Schema.optional(Schema.Array(ImageInputSchema)),\n options: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n http: Schema.optional(HttpOptions),\n}) {\n declare protected readonly _ImageRequest: void\n}\n\nexport type ImageRequestFor<Options extends ImageOptions = ImageOptions> = Omit<ImageRequest, \"model\" | \"options\"> & {\n readonly model: ImageModel<Options>\n readonly options?: Options\n}\n\nexport type ImageModelOptions<Model> = Model extends ImageModel<infer Options> ? Options : never\n\nexport type ImageRequestInput<Model extends object = ImageModel> = Omit<\n ConstructorParameters<typeof ImageRequest>[0],\n \"model\" | \"options\" | \"http\"\n> & {\n readonly model: Model\n readonly options?: NoInfer<ImageModelOptions<Model>>\n readonly http?: HttpOptions.Input\n} & (Model extends ImageModel<ImageModelOptions<Model>> ? unknown : never)\n\nexport class GeneratedImage extends Schema.Class<GeneratedImage>(\"Image.Generated\")({\n mediaType: Schema.String,\n data: Schema.Union([Schema.String, Schema.Uint8Array]),\n providerMetadata: Schema.optional(ProviderMetadata),\n}) {}\n\nexport class ImageResponse extends Schema.Class<ImageResponse>(\"Image.Response\")({\n images: Schema.Array(GeneratedImage),\n usage: Schema.optional(Usage),\n providerMetadata: Schema.optional(ProviderMetadata),\n}) {\n get image() {\n return this.images[0]\n }\n}\n\nexport function request<const Model extends object>(\n input: ImageRequestInput<Model>,\n): ImageRequestFor<ImageModelOptions<Model>>\nexport function request(input: ImageRequest): ImageRequest\nexport function request(input: ImageRequest | ImageRequestInput) {\n if (input instanceof ImageRequest) return input\n return new ImageRequest({\n ...input,\n model: input.model as unknown as ImageModel,\n http: input.http === undefined ? undefined : HttpOptions.make(input.http),\n })\n}\n\nexport function generate<const Model extends object>(\n input: ImageRequestInput<Model>,\n): Effect.Effect<ImageResponse, LLMError, Service>\nexport function generate(input: ImageRequest): Effect.Effect<ImageResponse, LLMError, Service>\nexport function generate(input: ImageRequest | ImageRequestInput) {\n return Effect.try({\n try: () => (input instanceof ImageRequest ? input : request(input)),\n catch: (error) =>\n new LLMError({\n module: \"Image\",\n method: \"generate\",\n reason: new InvalidRequestReason({ message: error instanceof Error ? error.message : String(error) }),\n }),\n }).pipe(Effect.flatMap((request) => ImageClient.generate(request as unknown as ImageRequestFor<ImageOptions>)))\n}\n\nexport const Image = {\n request,\n generate,\n} as const\n" | ||
| ], | ||
| "mappings": ";0MAaO,WAAM,eAAgB,EAAQ,QAA4B,EAAE,uBAAuB,CAAE,CAAC,CAUtF,IAAM,EAA8D,EAAM,OAC/E,EACA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAW,MAAO,EAAgB,QACxC,OAAO,EAAQ,GAAG,CAChB,SAAU,CAAC,IAAY,EAAQ,MAAM,MAAM,SAAS,EAAS,EAAS,OAAO,CAC/E,CAAC,EACF,CACH,ECjBO,MAAM,CAAwD,CAE1D,GACA,SACA,MACA,KAET,WAAW,CAAC,EAAkC,CAC5C,KAAK,GAAK,EAAM,GAChB,KAAK,SAAW,EAAM,SACtB,KAAK,MAAQ,EAAM,MACnB,KAAK,KAAO,EAAM,WAGb,KAAiD,CAAC,EAAsC,CAC7F,OAAO,IAAI,EAAoB,CAC7B,GAAI,EAAQ,KAAK,EAAM,EAAE,EACzB,SAAU,EAAW,KAAK,EAAM,QAAQ,EACxC,MAAO,EAAM,MACb,KAAM,EAAM,IACd,CAAC,EAEL,CAiBO,IAAM,EAAmB,EAAO,QAAQ,CAAC,IAA+B,aAAiB,EAAY,CAC1G,SAAU,aACZ,CAAC,EAEK,EAAkB,EAAO,OAAO,CACpC,KAAM,EAAO,QAAQ,OAAO,EAC5B,KAAM,EAAO,WACb,UAAW,EAAO,MACpB,CAAC,EACK,EAAgB,EAAO,OAAO,CAClC,KAAM,EAAO,QAAQ,KAAK,EAC1B,IAAK,EAAO,MACd,CAAC,EACK,EAAmB,EAAO,OAAO,CACrC,KAAM,EAAO,QAAQ,SAAS,EAC9B,GAAI,EAAO,MACb,CAAC,EACK,EAAoB,EAAO,OAAO,CACtC,KAAM,EAAO,QAAQ,UAAU,EAC/B,IAAK,EAAO,OACZ,UAAW,EAAO,MACpB,CAAC,EAEY,EAAmB,EAAO,MAAM,CAC3C,EACA,EACA,EACA,CACF,CAAC,EAAE,KAAK,EAAO,cAAc,MAAM,CAAC,EAU7B,MAAM,UAAqB,EAAO,MAAoB,eAAe,EAAE,CAC5E,MAAO,EACP,OAAQ,EAAO,OACf,OAAQ,EAAO,SAAS,EAAO,MAAM,CAAgB,CAAC,EACtD,QAAS,EAAO,SAAS,EAAO,OAAO,EAAO,OAAQ,EAAO,OAAO,CAAC,EACrE,KAAM,EAAO,SAAS,CAAW,CACnC,CAAC,CAAE,CAEH,CAkBO,MAAM,UAAuB,EAAO,MAAsB,iBAAiB,EAAE,CAClF,UAAW,EAAO,OAClB,KAAM,EAAO,MAAM,CAAC,EAAO,OAAQ,EAAO,UAAU,CAAC,EACrD,iBAAkB,EAAO,SAAS,CAAgB,CACpD,CAAC,CAAE,CAAC,CAEG,MAAM,UAAsB,EAAO,MAAqB,gBAAgB,EAAE,CAC/E,OAAQ,EAAO,MAAM,CAAc,EACnC,MAAO,EAAO,SAAS,CAAK,EAC5B,iBAAkB,EAAO,SAAS,CAAgB,CACpD,CAAC,CAAE,IACG,MAAK,EAAG,CACV,OAAO,KAAK,OAAO,GAEvB", | ||
| "debugId": "A9EF4FFA1D7C87D464756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/mini.ts", "src/mini-host.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { setTimeout } from \"node:timers/promises\"\nimport { readStdin } from \"./util/io\"\nimport { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from \"./mini-host\"\nimport { parseSessionTargetModel, resolveSessionTarget, type SessionTargetPreparation } from \"./session-target\"\n\nexport type MiniCommandInput = {\n server: {\n endpoint: Endpoint\n reconnect?: (signal: AbortSignal) => Promise<Endpoint>\n }\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n prompt?: string\n replay?: boolean\n replayLimit?: number\n demo?: boolean\n tuiConfig?: MiniFrontendInput[\"tuiConfig\"]\n config?: MiniFrontendInput[\"config\"]\n}\n\ntype Model = MiniFrontendInput[\"model\"]\n\nclass MiniInputError extends Error {}\n\nexport async function runMini(input: MiniCommandInput) {\n try {\n validate(input)\n const result = await usingInteractiveStdin(async (terminal) => {\n const initialInput = mergeInput(process.stdin.isTTY ? undefined : await readStdin(), input.prompt)\n const frontendTask = import(\"@opencode-ai/tui/mini\")\n const directory = localDirectory()\n const connection = createMiniConnection(input.server)\n const sdk = connection.sdk\n const requested = parseModel(input.model)\n const model = requested ? { providerID: requested.providerID, modelID: requested.id } : undefined\n const prepare = prepareTarget(input.agent)\n const resolveTarget = async (initial: OpenCodeClient, signal: AbortSignal) => {\n const resolved = await resolveMiniTarget({\n sdk: initial,\n reconnect: connection.reconnect,\n signal,\n resolve: (client) =>\n resolveSessionTarget({\n client,\n location: { directory },\n continue: input.continue,\n session: input.session,\n fork: input.fork,\n model: requested,\n agent: input.agent,\n prepare,\n signal,\n }).catch((error) => {\n if (error instanceof Error && error.message === \"Session not found\")\n throw new MiniInputError(error.message)\n throw error\n }),\n })\n const target = resolved.value\n return {\n sdk: resolved.sdk,\n sessionID: target.session.id,\n sessionTitle: target.session.title,\n location: target.location,\n model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,\n variant: target.model?.variant,\n agent: target.agent,\n resume: target.resume,\n }\n }\n const create = (\n client: OpenCodeClient,\n next: {\n location: { directory: string; workspaceID?: string }\n agent: string | undefined\n model: Model\n variant: string | undefined\n },\n signal?: AbortSignal,\n ) =>\n resolveSessionTarget({\n client,\n location: { directory: next.location.directory, workspace: next.location.workspaceID },\n agent: next.agent,\n model: next.model\n ? { providerID: next.model.providerID, id: next.model.modelID, variant: next.variant }\n : undefined,\n prepare,\n signal,\n }).then((target) => ({\n sessionID: target.session.id,\n sessionTitle: target.session.title,\n location: target.location,\n model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,\n variant: target.model?.variant,\n agent: target.agent,\n resume: false,\n }))\n const frontend = await frontendTask\n return frontend.runMiniFrontend({\n host: createMiniHost({ terminal, directory }),\n sdk,\n directory,\n target: resolveTarget,\n reconnect: connection.reconnect,\n createSession: create,\n agent: input.agent,\n model,\n variant: requested?.variant,\n files: [],\n initialInput,\n replay: input.replay ?? true,\n replayLimit: input.replayLimit,\n demo: input.demo,\n tuiConfig: input.tuiConfig,\n config: input.config,\n })\n })\n if (result.exitCode !== 0) process.exit(result.exitCode)\n } catch (error) {\n if (error instanceof MiniInputError || (error instanceof Error && error.message === INTERACTIVE_INPUT_ERROR))\n fail(error.message)\n throw error\n }\n}\n\n/** @internal Exported for CLI boundary tests. */\nexport function createMiniConnection(input: MiniCommandInput[\"server\"]) {\n const make = (endpoint: Endpoint) =>\n OpenCode.make({\n baseUrl: endpoint.url,\n headers: Service.headers(endpoint),\n })\n const reconnect = input.reconnect\n return {\n sdk: make(input.endpoint),\n reconnect: reconnect\n ? async (signal: AbortSignal) => {\n const endpoint = await reconnect(signal)\n return make(endpoint)\n }\n : undefined,\n }\n}\n\n/** @internal Exported for reconnect lifecycle tests. */\nexport async function resolveMiniTarget<A>(input: {\n sdk: OpenCodeClient\n reconnect?: (signal: AbortSignal) => Promise<OpenCodeClient>\n signal: AbortSignal\n resolve: (sdk: OpenCodeClient) => Promise<A>\n}) {\n let sdk = input.sdk\n while (true) {\n try {\n return { sdk, value: await input.resolve(sdk) }\n } catch (error) {\n if (!input.reconnect || !(error instanceof ClientError) || error.reason !== \"Transport\") throw error\n while (true) {\n try {\n sdk = await input.reconnect(input.signal)\n break\n } catch (resolveError) {\n if (input.signal.aborted) throw resolveError\n await setTimeout(250, undefined, { signal: input.signal })\n }\n }\n }\n }\n}\n\nexport function validateMiniTerminal() {\n if (!process.stdout.isTTY) fail(\"opencode mini requires a TTY stdout\")\n}\n\n/** @internal Exported for testing. */\nexport function mergeInput(piped: string | undefined, prompt: string | undefined) {\n if (!prompt) return piped || undefined\n if (!piped) return prompt\n return piped + \"\\n\" + prompt\n}\n\nfunction validate(input: MiniCommandInput) {\n validateMiniTerminal()\n if (input.replayLimit !== undefined && (!Number.isInteger(input.replayLimit) || input.replayLimit <= 0)) {\n fail(\"--replay-limit must be a positive integer\")\n }\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n}\n\nfunction localDirectory(): string {\n const root = process.env.PWD ?? process.cwd()\n try {\n process.chdir(root)\n return process.cwd()\n } catch {\n throw new MiniInputError(`Failed to change directory to ${root}`)\n }\n}\n\nfunction parseModel(value?: string) {\n try {\n return parseSessionTargetModel(value)\n } catch {\n throw new MiniInputError(\"--model must use the format provider/model[#variant]\")\n }\n}\n\nfunction prepareTarget(requestedAgent?: string): SessionTargetPreparation {\n return async (input) => ({ model: input.model, agent: requestedAgent ?? input.agent })\n}\n\nfunction fail(message: string): never {\n process.stderr.write(`\\x1b[91m\\x1b[1mError: \\x1b[0m${message}\\n`)\n process.exit(1)\n}\n", | ||
| "import type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { createModelPreferenceRepository } from \"@opencode-ai/tui/model-preference\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport fs from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { ReadStream } from \"node:tty\"\n\nexport const INTERACTIVE_INPUT_ERROR = \"opencode mini requires a controlling terminal for input\"\n\nexport type InteractiveStdin = {\n stdin: NodeJS.ReadStream\n cleanup(): void\n}\n\ntype MiniHost = MiniFrontendInput[\"host\"]\n\nfunction preferences(statePath: string): MiniHost[\"preferences\"] {\n const repository = createModelPreferenceRepository(path.join(statePath, \"model.json\"))\n return {\n async resolveVariant(model) {\n if (!model) return\n return repository.resolveVariant(model)\n },\n async saveVariant(model, variant) {\n if (!model) return\n await repository.saveVariant(model, variant).catch(() => undefined)\n },\n }\n}\n\nfunction signal(name: \"SIGINT\" | \"SIGUSR2\"): MiniHost[\"signals\"][\"sigint\"] {\n return {\n subscribe(listener) {\n let subscribed = true\n process.on(name, listener)\n return () => {\n if (!subscribed) return\n subscribed = false\n process.off(name, listener)\n }\n },\n }\n}\n\nfunction createTrace(\n logPath: string,\n diagnostics: { pid: number; cwd: string; argv: string[] },\n): MiniHost[\"diagnostics\"][\"trace\"] {\n if (!process.env.OPENCODE_DIRECT_TRACE) return\n const stamp = new Date()\n .toISOString()\n .replace(/[-:]/g, \"\")\n .replace(/\\.\\d+Z$/, \"Z\")\n const target = path.join(logPath, \"direct\", `${stamp}-${diagnostics.pid}.jsonl`)\n const text = (data: unknown) =>\n JSON.stringify(data, (_key, value) => (typeof value === \"bigint\" ? String(value) : value), 0)\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(\n path.join(logPath, \"direct\", \"latest.json\"),\n text({\n time: new Date().toISOString(),\n ...diagnostics,\n path: target,\n }) + \"\\n\",\n )\n const trace = {\n write(type: string, data?: unknown) {\n fs.appendFileSync(\n target,\n text({\n time: new Date().toISOString(),\n pid: diagnostics.pid,\n type,\n data,\n }) + \"\\n\",\n )\n },\n }\n trace.write(\"trace.start\", {\n argv: diagnostics.argv,\n cwd: diagnostics.cwd,\n path: target,\n })\n return trace\n}\n\nfunction openTerminalStdin(target: string): NodeJS.ReadStream {\n return new ReadStream(fs.openSync(target, \"r\"))\n}\n\nexport function resolveInteractiveStdin(\n stdin: NodeJS.ReadStream = process.stdin,\n open: (target: string) => NodeJS.ReadStream = openTerminalStdin,\n platform: NodeJS.Platform = process.platform,\n): InteractiveStdin {\n if (stdin.isTTY) return { stdin, cleanup() {} }\n const target = platform === \"win32\" ? \"CONIN$\" : \"/dev/tty\"\n try {\n const source = open(target)\n let cleaned = false\n return {\n stdin: source,\n cleanup() {\n if (cleaned) return\n cleaned = true\n source.destroy()\n },\n }\n } catch (error) {\n throw new Error(INTERACTIVE_INPUT_ERROR, { cause: error })\n }\n}\n\n/** @internal Exported for owner-local resource cleanup tests. */\nexport async function usingInteractiveStdin<T>(\n run: (terminal: InteractiveStdin) => Promise<T>,\n resolve: () => InteractiveStdin = resolveInteractiveStdin,\n) {\n const terminal = resolve()\n try {\n return await run(terminal)\n } finally {\n terminal.cleanup()\n }\n}\n\n/** @internal Exported for owner-local host capability tests. */\nexport function createMiniHost(input: {\n terminal: InteractiveStdin\n directory: string\n paths?: { home: string; state: string; log: string }\n}): MiniHost {\n const paths = input.paths ?? {\n home: Global.Path.home,\n state: Global.Path.state,\n log: Global.Path.log,\n }\n const diagnostics = {\n pid: process.pid,\n cwd: input.directory,\n argv: process.argv.slice(2),\n }\n return {\n terminal: { stdin: input.terminal.stdin },\n platform: process.platform,\n stdout: {\n write(value) {\n process.stdout.write(value)\n },\n },\n files: {\n readText: (url) => readFile(new URL(url), \"utf8\"),\n },\n editor: {\n async open(options) {\n const { openEditor } = await import(\"@opencode-ai/tui/editor\")\n return openEditor(options)\n },\n },\n paths: { home: paths.home },\n signals: {\n sigint: signal(\"SIGINT\"),\n sigusr2: signal(\"SIGUSR2\"),\n },\n startup: {\n showTiming: [\"1\", \"true\"].includes(process.env.OPENCODE_SHOW_TTFD?.toLowerCase() ?? \"\"),\n now: () => performance.now(),\n },\n diagnostics: {\n trace: createTrace(paths.log, diagnostics),\n },\n preferences: preferences(paths.state),\n }\n}\n" | ||
| ], | ||
| "mappings": ";qiBAGA,0BAAS,6BCAT,uBAC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AAQ,MAAM,CAAI,EACX,QAAQ,IAAI,EACnB,KAAM,CACN,MAAM,IAAI,EAAe,iCAAiC,GAAM,GAIpE,SAAS,CAAU,CAAC,EAAgB,CAClC,GAAI,CACF,OAAO,EAAwB,CAAK,EACpC,KAAM,CACN,MAAM,IAAI,EAAe,sDAAsD,GAInF,SAAS,CAAa,CAAC,EAAmD,CACxE,MAAO,OAAO,KAAW,CAAE,MAAO,EAAM,MAAO,MAAO,GAAkB,EAAM,KAAM,GAGtF,SAAS,CAAI,CAAC,EAAwB,CACpC,QAAQ,OAAO,MAAM,gCAAgC;AAAA,CAAW,EAChE,QAAQ,KAAK,CAAC", | ||
| "debugId": "FFEB8B23C302D97A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/start.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.start,\n Effect.fn(\"cli.service.start\")(function* () {\n const transport = yield* Service.ensure(yield* ServiceConfig.options())\n process.stdout.write(transport.url + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+0BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,WACnC,OAAO,QAAG,wBAAmB,OAAE,cAAU,OAAG,MAC1C,SAAM,OAAY,WAAO,OAAQ,YAAO,MAAO,EAAc,QAAQ,CAAC,EACtE,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "882EDB8FFBBB07A964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "664B4A7BBE4AB47B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "591B346E1B4D713F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+mistral@3.0.27+d6123d32214422cb/node_modules/@ai-sdk/mistral/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/mistral-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/mistral-chat-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n generateId,\n injectJsonInstructionIntoMessages,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/convert-mistral-usage.ts\nfunction convertMistralUsage(usage) {\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = usage.prompt_tokens;\n const completionTokens = usage.completion_tokens;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens,\n reasoning: void 0\n },\n raw: usage\n };\n}\n\n// src/convert-to-mistral-chat-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertToBase64 } from \"@ai-sdk/provider-utils\";\nfunction formatFileUrl({\n data,\n mediaType\n}) {\n return data instanceof URL ? data.toString() : `data:${mediaType};base64,${convertToBase64(data)}`;\n}\nfunction convertToMistralChatMessages(prompt) {\n var _a;\n const messages = [];\n for (let i = 0; i < prompt.length; i++) {\n const { role, content } = prompt[i];\n const isLastMessage = i === prompt.length - 1;\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n switch (part.type) {\n case \"text\": {\n return { type: \"text\", text: part.text };\n }\n case \"file\": {\n if (part.mediaType.startsWith(\"image/\")) {\n const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType;\n return {\n type: \"image_url\",\n image_url: formatFileUrl({ data: part.data, mediaType })\n };\n } else if (part.mediaType === \"application/pdf\") {\n return {\n type: \"document_url\",\n document_url: formatFileUrl({\n data: part.data,\n mediaType: \"application/pdf\"\n })\n };\n } else {\n throw new UnsupportedFunctionalityError({\n functionality: \"Only images and PDF file parts are supported\"\n });\n }\n }\n }\n })\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n case \"reasoning\": {\n text += part.text;\n break;\n }\n default: {\n throw new Error(\n `Unsupported content type in assistant message: ${part.type}`\n );\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: text,\n prefix: isLastMessage ? true : void 0,\n tool_calls: toolCalls.length > 0 ? toolCalls : void 0\n });\n break;\n }\n case \"tool\": {\n for (const toolResponse of content) {\n if (toolResponse.type === \"tool-approval-response\") {\n continue;\n }\n const output = toolResponse.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n messages.push({\n role: \"tool\",\n name: toolResponse.toolName,\n tool_call_id: toolResponse.toolCallId,\n content: contentValue\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/get-response-metadata.ts\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id: id != null ? id : void 0,\n modelId: model != null ? model : void 0,\n timestamp: created != null ? new Date(created * 1e3) : void 0\n };\n}\n\n// src/map-mistral-finish-reason.ts\nfunction mapMistralFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n case \"model_length\":\n return \"length\";\n case \"tool_calls\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/mistral-chat-options.ts\nimport { z } from \"zod/v4\";\nvar mistralLanguageModelOptions = z.object({\n /**\n * Whether to inject a safety prompt before all conversations.\n *\n * Defaults to `false`.\n */\n safePrompt: z.boolean().optional(),\n documentImageLimit: z.number().optional(),\n documentPageLimit: z.number().optional(),\n /**\n * Whether to use structured outputs.\n *\n * @default true\n */\n structuredOutputs: z.boolean().optional(),\n /**\n * Whether to use strict JSON schema validation.\n *\n * @default false\n */\n strictJsonSchema: z.boolean().optional(),\n /**\n * Whether to enable parallel function calling during tool use.\n * When set to false, the model will use at most one tool per response.\n *\n * @default true\n */\n parallelToolCalls: z.boolean().optional(),\n /**\n * Controls the reasoning effort for models that support adjustable reasoning.\n *\n * - `'high'`: Enable reasoning\n * - `'none'`: Disable reasoning\n */\n reasoningEffort: z.enum([\"high\", \"none\"]).optional()\n});\n\n// src/mistral-error.ts\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar mistralErrorDataSchema = z2.object({\n object: z2.literal(\"error\"),\n message: z2.string(),\n type: z2.string(),\n param: z2.string().nullable(),\n code: z2.string().nullable()\n});\nvar mistralFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: mistralErrorDataSchema,\n errorToMessage: (data) => data.message\n});\n\n// src/mistral-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nfunction prepareTools({\n tools,\n toolChoice\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const mistralTools = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n } else {\n mistralTools.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n ...tool.strict != null ? { strict: tool.strict } : {}\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: mistralTools, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n case \"none\":\n return { tools: mistralTools, toolChoice: type, toolWarnings };\n case \"required\":\n return { tools: mistralTools, toolChoice: \"any\", toolWarnings };\n // mistral does not support tool mode directly,\n // so we filter the tools and force the tool choice through 'any'\n case \"tool\":\n return {\n tools: mistralTools.filter(\n (tool) => tool.function.name === toolChoice.toolName\n ),\n toolChoice: \"any\",\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError2({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/mistral-chat-language-model.ts\nvar MistralChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n \"application/pdf\": [/^https:\\/\\/.*$/]\n };\n var _a;\n this.modelId = modelId;\n this.config = config;\n this.generateId = (_a = config.generateId) != null ? _a : generateId;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n providerOptions,\n tools,\n toolChoice\n }) {\n var _a, _b, _c, _d;\n const warnings = [];\n const options = (_a = await parseProviderOptions({\n provider: \"mistral\",\n providerOptions,\n schema: mistralLanguageModelOptions\n })) != null ? _a : {};\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n if (frequencyPenalty != null) {\n warnings.push({ type: \"unsupported\", feature: \"frequencyPenalty\" });\n }\n if (presencePenalty != null) {\n warnings.push({ type: \"unsupported\", feature: \"presencePenalty\" });\n }\n if (stopSequences != null) {\n warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n }\n const structuredOutputs = (_b = options.structuredOutputs) != null ? _b : true;\n const strictJsonSchema = (_c = options.strictJsonSchema) != null ? _c : false;\n if ((responseFormat == null ? void 0 : responseFormat.type) === \"json\" && !(responseFormat == null ? void 0 : responseFormat.schema)) {\n prompt = injectJsonInstructionIntoMessages({\n messages: prompt,\n schema: responseFormat.schema\n });\n }\n const baseArgs = {\n // model id:\n model: this.modelId,\n // model specific settings:\n safe_prompt: options.safePrompt,\n // standardized settings:\n max_tokens: maxOutputTokens,\n temperature,\n top_p: topP,\n random_seed: seed,\n reasoning_effort: options.reasoningEffort,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? structuredOutputs && (responseFormat == null ? void 0 : responseFormat.schema) != null ? {\n type: \"json_schema\",\n json_schema: {\n schema: responseFormat.schema,\n strict: strictJsonSchema,\n name: (_d = responseFormat.name) != null ? _d : \"response\",\n description: responseFormat.description\n }\n } : { type: \"json_object\" } : void 0,\n // mistral-specific provider options:\n document_image_limit: options.documentImageLimit,\n document_page_limit: options.documentPageLimit,\n // messages:\n messages: convertToMistralChatMessages(prompt)\n };\n const {\n tools: mistralTools,\n toolChoice: mistralToolChoice,\n toolWarnings\n } = prepareTools({\n tools,\n toolChoice\n });\n return {\n args: {\n ...baseArgs,\n tools: mistralTools,\n tool_choice: mistralToolChoice,\n ...mistralTools != null && options.parallelToolCalls !== void 0 ? { parallel_tool_calls: options.parallelToolCalls } : {}\n },\n warnings: [...warnings, ...toolWarnings]\n };\n }\n async doGenerate(options) {\n var _a;\n const { args: body, warnings } = await this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n mistralChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n if (choice.message.content != null && Array.isArray(choice.message.content)) {\n for (const part of choice.message.content) {\n if (part.type === \"thinking\") {\n const reasoningText = extractReasoningContent(part.thinking);\n if (reasoningText.length > 0) {\n content.push({ type: \"reasoning\", text: reasoningText });\n }\n } else if (part.type === \"text\") {\n if (part.text.length > 0) {\n content.push({ type: \"text\", text: part.text });\n }\n }\n }\n } else {\n const text = extractTextContent(choice.message.content);\n if (text != null && text.length > 0) {\n content.push({ type: \"text\", text });\n }\n }\n if (choice.message.tool_calls != null) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: toolCall.function.arguments\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapMistralFinishReason(choice.finish_reason),\n raw: (_a = choice.finish_reason) != null ? _a : void 0\n },\n usage: convertMistralUsage(response.usage),\n request: { body },\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs(options);\n const body = { ...args, stream: true };\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n mistralChatChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let isFirstChunk = true;\n let activeText = false;\n let activeReasoningId = null;\n const generateId2 = this.generateId;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (isFirstChunk) {\n isFirstChunk = false;\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n }\n if (value.usage != null) {\n usage = value.usage;\n }\n const choice = value.choices[0];\n const delta = choice.delta;\n const textContent = extractTextContent(delta.content);\n if (delta.content != null && Array.isArray(delta.content)) {\n for (const part of delta.content) {\n if (part.type === \"thinking\") {\n const reasoningDelta = extractReasoningContent(part.thinking);\n if (reasoningDelta.length > 0) {\n if (activeReasoningId == null) {\n if (activeText) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n activeText = false;\n }\n activeReasoningId = generateId2();\n controller.enqueue({\n type: \"reasoning-start\",\n id: activeReasoningId\n });\n }\n controller.enqueue({\n type: \"reasoning-delta\",\n id: activeReasoningId,\n delta: reasoningDelta\n });\n }\n }\n }\n }\n if (textContent != null && textContent.length > 0) {\n if (!activeText) {\n if (activeReasoningId != null) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: activeReasoningId\n });\n activeReasoningId = null;\n }\n controller.enqueue({ type: \"text-start\", id: \"0\" });\n activeText = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"0\",\n delta: textContent\n });\n }\n if ((delta == null ? void 0 : delta.tool_calls) != null) {\n for (const toolCall of delta.tool_calls) {\n const toolCallId = toolCall.id;\n const toolName = toolCall.function.name;\n const input = toolCall.function.arguments;\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolCallId,\n toolName\n });\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCallId,\n delta: input\n });\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCallId\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId,\n toolName,\n input\n });\n }\n }\n if (choice.finish_reason != null) {\n finishReason = {\n unified: mapMistralFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n },\n flush(controller) {\n if (activeReasoningId != null) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: activeReasoningId\n });\n }\n if (activeText) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertMistralUsage(usage)\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction extractReasoningContent(thinking) {\n return thinking.filter((chunk) => chunk.type === \"text\").map((chunk) => chunk.text).join(\"\");\n}\nfunction extractTextContent(content) {\n if (typeof content === \"string\") {\n return content;\n }\n if (content == null) {\n return void 0;\n }\n const textContent = [];\n for (const chunk of content) {\n const { type } = chunk;\n switch (type) {\n case \"text\":\n textContent.push(chunk.text);\n break;\n case \"thinking\":\n case \"image_url\":\n case \"reference\":\n break;\n default: {\n const _exhaustiveCheck = type;\n throw new Error(`Unsupported type: ${_exhaustiveCheck}`);\n }\n }\n }\n return textContent.length ? textContent.join(\"\") : void 0;\n}\nvar mistralContentSchema = z3.union([\n z3.string(),\n z3.array(\n z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"image_url\"),\n image_url: z3.union([\n z3.string(),\n z3.object({\n url: z3.string(),\n detail: z3.string().nullable()\n })\n ])\n }),\n z3.object({\n type: z3.literal(\"reference\"),\n reference_ids: z3.array(z3.union([z3.string(), z3.number()]))\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.array(\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n })\n )\n })\n ])\n )\n]).nullish();\nvar mistralUsageSchema = z3.object({\n prompt_tokens: z3.number(),\n completion_tokens: z3.number(),\n total_tokens: z3.number()\n});\nvar mistralChatResponseSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n message: z3.object({\n role: z3.literal(\"assistant\"),\n content: mistralContentSchema,\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n function: z3.object({ name: z3.string(), arguments: z3.string() })\n })\n ).nullish()\n }),\n index: z3.number(),\n finish_reason: z3.string().nullish()\n })\n ),\n object: z3.literal(\"chat.completion\"),\n usage: mistralUsageSchema\n});\nvar mistralChatChunkSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n delta: z3.object({\n role: z3.enum([\"assistant\"]).optional(),\n content: mistralContentSchema,\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n function: z3.object({ name: z3.string(), arguments: z3.string() })\n })\n ).nullish()\n }),\n finish_reason: z3.string().nullish(),\n index: z3.number()\n })\n ),\n usage: mistralUsageSchema.nullish()\n});\n\n// src/mistral-embedding-model.ts\nimport {\n TooManyEmbeddingValuesForCallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders as combineHeaders2,\n createJsonResponseHandler as createJsonResponseHandler2,\n postJsonToApi as postJsonToApi2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\nvar MistralEmbeddingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.maxEmbeddingsPerCall = 32;\n this.supportsParallelCalls = false;\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async doEmbed({\n values,\n abortSignal,\n headers\n }) {\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi2({\n url: `${this.config.baseURL}/embeddings`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n input: values,\n encoding_format: \"float\"\n },\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n MistralTextEmbeddingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n warnings: [],\n embeddings: response.data.map((item) => item.embedding),\n usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,\n response: { headers: responseHeaders, body: rawValue }\n };\n }\n};\nvar MistralTextEmbeddingResponseSchema = z4.object({\n data: z4.array(z4.object({ embedding: z4.array(z4.number()) })),\n usage: z4.object({ prompt_tokens: z4.number() }).nullish()\n});\n\n// src/version.ts\nvar VERSION = true ? \"3.0.27\" : \"0.0.0-test\";\n\n// src/mistral-provider.ts\nfunction createMistral(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.mistral.ai/v1\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"MISTRAL_API_KEY\",\n description: \"Mistral\"\n })}`,\n ...options.headers\n },\n `ai-sdk/mistral/${VERSION}`\n );\n const createChatModel = (modelId) => new MistralChatLanguageModel(modelId, {\n provider: \"mistral.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: options.generateId\n });\n const createEmbeddingModel = (modelId) => new MistralEmbeddingModel(modelId, {\n provider: \"mistral.embedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Mistral model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar mistral = createMistral();\nexport {\n VERSION,\n createMistral,\n mistral\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";kYAuBA,cAAS,MAAmB,MAAC,OAAO,MAClC,QAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAY,OACZ,KAAW,OACX,UAAgB,MAClB,EACA,IAAU,MACZ,EAEF,IAA2B,cAArB,EACyB,kBAAzB,GAAmB,EACzB,MAAO,CACL,YAAa,CACX,MAAO,EACP,QAAS,EACT,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAO,EACP,KAAM,EACN,UAAgB,MAClB,EACA,IAAK,CACP,EAQF,SAAS,CAAa,EACpB,OACA,aACC,CACD,OAAO,aAAgB,IAAM,EAAK,SAAS,EAAI,QAAQ,YAAoB,EAAgB,CAAI,IAEjG,SAAS,CAA4B,CAAC,EAAQ,CAC5C,IAAI,EACJ,IAAM,EAAW,CAAC,EAClB,QAAS,EAAI,EAAG,EAAI,EAAO,OAAQ,IAAK,CACtC,IAAQ,OAAM,WAAY,EAAO,GAC3B,EAAgB,IAAM,EAAO,OAAS,EAC5C,OAAQ,OACD,SAAU,CACb,EAAS,KAAK,CAAE,KAAM,SAAU,SAAQ,CAAC,EACzC,KACF,KACK,OAAQ,CACX,EAAS,KAAK,CACZ,KAAM,OACN,QAAS,EAAQ,IAAI,CAAC,IAAS,CAC7B,OAAQ,EAAK,UACN,OACH,MAAO,CAAE,KAAM,OAAQ,KAAM,EAAK,IAAK,MAEpC,OACH,GAAI,EAAK,UAAU,WAAW,QAAQ,EAAG,CACvC,IAAM,EAAY,EAAK,YAAc,UAAY,aAAe,EAAK,UACrE,MAAO,CACL,KA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B,EAAS,CAC3E,SAAU,oBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAW,QAAQ,CAAC,EAAS,CACjC,GAAI,WACF,MAAU,MACR,mEACF,EAEF,OAAO,EAAgB,CAAO,GAYhC,OAVA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,KAAO,EAChB,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,cAAgB,EACzB,EAAS,mBAAqB,EAC9B,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAU,GAAc", | ||
| "debugId": "197B6FA08810F32C64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-web-identity@3.972.65/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-web-identity@3.972.65/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, externalDataInterceptor } from \"@smithy/core/config\";\nimport { readFileSync } from \"node:fs\";\nimport { fromWebToken } from \"./fromWebToken\";\nconst ENV_TOKEN_FILE = \"AWS_WEB_IDENTITY_TOKEN_FILE\";\nconst ENV_ROLE_ARN = \"AWS_ROLE_ARN\";\nconst ENV_ROLE_SESSION_NAME = \"AWS_ROLE_SESSION_NAME\";\nexport const fromTokenFile = (init = {}) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromTokenFile\");\n const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];\n const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN];\n const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];\n if (!webIdentityTokenFile || !roleArn) {\n throw new CredentialsProviderError(\"Web identity configuration not specified\", {\n logger: init.logger,\n });\n }\n const credentials = await fromWebToken({\n ...init,\n webIdentityToken: externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ??\n readFileSync(webIdentityTokenFile, { encoding: \"ascii\" }),\n roleArn,\n roleSessionName,\n })(awsIdentityProperties);\n if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN\", \"h\");\n }\n return credentials;\n};\n", | ||
| "export const fromWebToken = (init) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromWebToken\");\n const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init;\n let { roleAssumerWithWebIdentity } = init;\n if (!roleAssumerWithWebIdentity) {\n const { getDefaultRoleAssumerWithWebIdentity } = await import(\"@aws-sdk/nested-clients/sts\");\n roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({\n ...init.clientConfig,\n credentialProviderLogger: init.logger,\n parentClientConfig: {\n ...awsIdentityProperties?.callerClientConfig,\n ...init.parentClientConfig,\n },\n }, init.clientPlugins);\n }\n return roleAssumerWithWebIdentity({\n RoleArn: roleArn,\n RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,\n WebIdentityToken: webIdentityToken,\n ProviderId: providerId,\n PolicyArns: policyArns,\n Policy: policy,\n DurationSeconds: durationSeconds,\n });\n};\n" | ||
| ], | ||
| "mappings": ";kJAAA,oBACA,gBACA,uBAAS,WCFF,IAAM,EAAe,CAAC,IAAS,MAAO,IAA0B,CACnE,EAAK,QAAQ,MAAM,0DAA0D,EAC7E,IAAQ,UAAS,kBAAiB,mBAAkB,aAAY,aAAY,SAAQ,mBAAoB,GAClG,8BAA+B,EACrC,GAAI,CAAC,EAA4B,CAC7B,IAAQ,wCAAyC,KAAa,0CAC9D,EAA6B,EAAqC,IAC3D,EAAK,aACR,yBAA0B,EAAK,OAC/B,mBAAoB,IACb,GAAuB,sBACvB,EAAK,kBACZ,CACJ,EAAG,EAAK,aAAa,EAEzB,OAAO,EAA2B,CAC9B,QAAS,EACT,gBAAiB,GAAmB,sBAAsB,KAAK,IAAI,IACnE,iBAAkB,EAClB,WAAY,EACZ,WAAY,EACZ,OAAQ,EACR,gBAAiB,CACrB,CAAC,GDnBL,IAAM,EAAiB,8BACjB,EAAe,eACf,EAAwB,wBACjB,EAAgB,CAAC,EAAO,CAAC,IAAM,MAAO,IAA0B,CACzE,EAAK,QAAQ,MAAM,2DAA2D,EAC9E,IAAM,EAAuB,GAAM,sBAAwB,QAAQ,IAAI,GACjE,EAAU,GAAM,SAAW,QAAQ,IAAI,GACvC,EAAkB,GAAM,iBAAmB,QAAQ,IAAI,GAC7D,GAAI,CAAC,GAAwB,CAAC,EAC1B,MAAM,IAAI,2BAAyB,2CAA4C,CAC3E,OAAQ,EAAK,MACjB,CAAC,EAEL,IAAM,EAAc,MAAM,EAAa,IAChC,EACH,iBAAkB,2BAAyB,iBAAiB,EAAE,IAC1D,EAAa,EAAsB,CAAE,SAAU,OAAQ,CAAC,EAC5D,UACA,iBACJ,CAAC,EAAE,CAAqB,EACxB,GAAI,IAAyB,QAAQ,IAAI,GACrC,uBAAqB,EAAa,wCAAyC,GAAG,EAElF,OAAO", | ||
| "debugId": "241B6B49FABCACF964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/auth.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport {\n OpenCode,\n type IntegrationAttemptStatus,\n type IntegrationOAuthMethod,\n type OpenCodeClient,\n} from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.auth,\n Effect.fn(\"cli.mcp.auth\")(function* (input) {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n const method = integration.methods.find(\n (candidate): candidate is IntegrationOAuthMethod => candidate.type === \"oauth\",\n )\n if (!method)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n\n const started = yield* Effect.promise(() =>\n client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),\n )\n const attempt = started.data\n if (attempt.mode === \"code\")\n return yield* Effect.fail(new Error(\"This server requires manual code entry, which the CLI does not support\"))\n\n process.stdout.write(attempt.instructions + EOL + attempt.url + EOL)\n\n const result = yield* poll(client, integration.id, attempt.attemptID)\n if (result.status === \"complete\") {\n process.stdout.write(`Authenticated with ${input.name}` + EOL)\n return\n }\n const reason = result.status === \"failed\" ? `: ${result.message}` : \"\"\n return yield* Effect.fail(new Error(`Authentication ${result.status}${reason}`))\n }),\n)\n\nconst poll = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n): Effect.Effect<Exclude<IntegrationAttemptStatus, { status: \"pending\" }>> =>\n Effect.gen(function* () {\n const status = yield* Effect.promise(() =>\n client.integration.oauth.status({ integrationID, attemptID, location }),\n ).pipe(Effect.map((result) => result.data))\n if (status.status === \"pending\") {\n yield* Effect.sleep(\"1 second\")\n return yield* poll(client, integrationID, attemptID)\n }\n return status\n })\n" | ||
| ], | ||
| "mappings": ";66BAAA,mBAAS,gBAcT,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OA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O,EAAO,QAAQ,IACnC,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,CAAC,CACxE,EAAE,KAAK,EAAO,IAAI,CAAC,IAAW,EAAO,IAAI,CAAC,EAC1C,GAAI,EAAO,SAAW,UAEpB,OADA,MAAO,EAAO,MAAM,UAAU,EACvB,MAAO,EAAK,EAAQ,EAAe,CAAS,EAErD,OAAO,EACR", | ||
| "debugId": "408C18CAC640DF8A64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "F2BD269CDA912CB964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
268774128
0.01%298
0.34%