@opencode-ai/cli-linux-x64
Advanced tools
| { | ||
| "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": ";+2BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,OACnC,EAAO,GAAG,oBAAoB,EAAE,SAAU,EAAG,CAC3C,IAAM,EAAU,MAAO,EAAc,QAAQ,EACvC,EAAQ,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,EACxE,QAAQ,OAAO,OAAO,GAAO,KAAO,WAAa,CAAG,EACrD,CACH", | ||
| "debugId": "DF16EA2772FD567B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "DDBC4F65F18C8B7964756E2164756E21", | ||
| "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": ["../schema/src/workspace-event.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WorkspaceEvent from \"./workspace-event.js\"\n\nimport { Schema } from \"effect\"\nimport { Event } from \"./event.js\"\nimport { WorkspaceID } from \"./workspace-id.js\"\n\nexport const ConnectionStatus = Schema.Struct({\n workspaceID: WorkspaceID,\n status: Schema.Literals([\"connected\", \"connecting\", \"disconnected\", \"error\"]),\n}).annotate({ identifier: \"WorkspaceEvent.ConnectionStatus\" })\nexport interface ConnectionStatus extends Schema.Schema.Type<typeof ConnectionStatus> {}\n\nexport const Ready = Event.ephemeral({\n type: \"workspace.ready\",\n schema: {\n name: Schema.String,\n },\n})\n\nexport const Failed = Event.ephemeral({\n type: \"workspace.failed\",\n schema: {\n message: Schema.String,\n },\n})\n\nexport const Status = Event.ephemeral({\n type: \"workspace.status\",\n schema: ConnectionStatus.fields,\n})\n\nexport const Definitions = Event.inventory(Ready, Failed, Status)\n" | ||
| ], | ||
| "mappings": ";wRAMO,IAAM,EAAmB,EAAO,OAAO,CAC5C,YAAa,EACb,OAAQ,EAAO,SAAS,CAAC,YAAa,aAAc,eAAgB,OAAO,CAAC,CAC9E,CAAC,EAAE,SAAS,CAAE,WAAY,iCAAkC,CAAC,EAGhD,EAAQ,EAAM,UAAU,CACnC,KAAM,kBACN,OAAQ,CACN,KAAM,EAAO,MACf,CACF,CAAC,EAEY,EAAS,EAAM,UAAU,CACpC,KAAM,mBACN,OAAQ,CACN,QAAS,EAAO,MAClB,CACF,CAAC,EAEY,EAAS,EAAM,UAAU,CACpC,KAAM,mBACN,OAAQ,EAAiB,MAC3B,CAAC,EAEY,EAAc,EAAM,UAAU,EAAO,EAAQ,CAAM", | ||
| "debugId": "9FCAB0E0718946BB64756E2164756E21", | ||
| "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": ";+2BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,QACnC,EAAO,GAAG,qBAAqB,EAAE,SAAU,EAAG,CAC5C,IAAM,EAAU,MAAO,EAAc,QAAQ,EAC7C,MAAO,EAAQ,KAAK,CAAO,EAC3B,IAAM,EAAY,MAAO,EAAQ,OAAO,CAAO,EAC/C,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "6190AF498043C73B64756E2164756E21", | ||
| "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.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jE,EAAS,cAAgB,EACzB,EAAS,mBAAqB,EAC9B,EAAS,MAAQ,GACV,EAET,IAAI,GAAO,GAAW", | ||
| "debugId": "432C5E392DBC8EB464756E2164756E21", | ||
| "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": ";wZAwBA,IAAI,EAAwB,EAC1B,IAAM,EACJ,EAAE,OAAO,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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7C,EACA,EAAqB,YAAY,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": "777DCC6F4F2ADD3464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/import.ts"], | ||
| "sourcesContent": [ | ||
| "import { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Session } from \"@opencode-ai/schema/session\"\nimport { SessionTransfer } from \"@opencode-ai/schema/session-transfer\"\nimport { Effect, Option, Schema } from \"effect\"\nimport { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.import,\n Effect.fn(\"cli.import\")(function* (input) {\n const text = yield* Effect.tryPromise({\n try: () =>\n input.file.startsWith(\"http://\") || input.file.startsWith(\"https://\")\n ? fetch(input.file).then((response) => {\n if (!response.ok) throw new Error(`Failed to fetch session data: ${response.statusText}`)\n return response.text()\n })\n : Bun.file(input.file).text(),\n catch: (cause) =>\n new Error(`Failed to read session data: ${cause instanceof Error ? cause.message : String(cause)}`),\n })\n const data = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(SessionTransfer.Data))(text)\n const encoded = Schema.encodeSync(SessionTransfer.Data)(data)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const location = yield* Effect.promise(() =>\n client.location.get({\n location: { directory: path.resolve(Option.getOrElse(input.directory, () => process.cwd())) },\n }),\n )\n const response = yield* Effect.promise(() =>\n fetch(new URL(\"/api/session/import\", server.endpoint.url), {\n method: \"POST\",\n headers: { ...Service.headers(server.endpoint), \"content-type\": \"application/json\" },\n body: JSON.stringify({\n ...encoded,\n location: { directory: location.directory, workspaceID: location.workspaceID },\n }),\n }),\n )\n if (response.status === 409) {\n process.stderr.write(`Session already exists${EOL}`)\n return\n }\n if (!response.ok) yield* Effect.fail(new Error(`Failed to import session: ${response.statusText}`))\n const imported = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Struct({ data: Session.Info })))(\n yield* Effect.promise(() => response.text()),\n )\n process.stdout.write(`Imported session: ${imported.data.id}${EOL}`)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";03CAKA,cAAS,WACT,oBAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,SAAU,CAAC,EAAO,CACxC,IAAM,EAAO,MAAO,EAAO,WAAW,CACpC,IAAK,IACH,EAAM,KAAK,WAAW,SAAS,GAAK,EAAM,KAAK,WAAW,UAAU,EAChE,MAAM,EAAM,IAAI,EAAE,KAAK,CAAC,IAAa,CACnC,GAAI,CAAC,EAAS,GAAI,MAAU,MAAM,iCAAiC,EAAS,YAAY,EACxF,OAAO,EAAS,KAAK,EACtB,EACD,IAAI,KAAK,EAAM,IAAI,EAAE,KAAK,EAChC,MAAO,CAAC,IACF,MAAM,gCAAgC,aAAiB,MA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D2C92F4D864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/oauth/page.ts"], | ||
| "sourcesContent": [ | ||
| "// Branded HTML pages for local OAuth callback servers.\n//\n// These are served by the loopback HTTP servers that finish an OAuth exchange\n// (MCP, Codex/ChatGPT, xAI, Snowflake, DigitalOcean, ...). The functions return\n// a fully self-contained HTML string with no external assets, so they work\n// offline and drop into any transport (`res.end(...)`, Effect `response.end`,\n// etc.).\n//\n// The visual language mirrors the OpenCode app: the design tokens are a curated\n// subset of the OC-2 semantic tokens in `packages/ui/src/styles/theme.css`, and\n// the wordmark is the same geometry as `packages/ui/src/components/logo.tsx`.\n// Keep this file in sync with those sources when the brand changes.\n\nexport interface CallbackPageOptions {\n /** Friendly integration name shown as a subtitle, e.g. \"xAI\", \"Snowflake\", \"MCP\". */\n provider?: string\n /** Attempt to close the window shortly after success. Defaults to true. */\n autoClose?: boolean\n}\n\nexport function success(options?: CallbackPageOptions) {\n const provider = options?.provider\n return renderDocument({\n title: \"Authorization successful\",\n body: renderCard({\n status: \"success\",\n headline: \"Authorization successful\",\n message: provider ? `OpenCode is now connected to ${escapeHtml(provider)}.` : \"OpenCode is now authorized.\",\n footnote: \"You can close this window.\",\n }),\n script: options?.autoClose === false ? undefined : AUTO_CLOSE_SCRIPT,\n })\n}\n\nexport function error(detail: string, options?: CallbackPageOptions) {\n const provider = options?.provider\n return renderDocument({\n title: \"Authorization failed\",\n body: renderCard({\n status: \"error\",\n headline: \"Authorization failed\",\n message: provider\n ? `OpenCode couldn't finish connecting to ${escapeHtml(provider)}.`\n : \"OpenCode couldn't complete authorization.\",\n detail,\n footnote: \"Close this window and try again from OpenCode.\",\n }),\n })\n}\n\nexport interface BootstrapOptions {\n /** Same-origin path the in-browser script POSTs the parsed callback to. */\n tokenPath: string\n provider?: string\n}\n\n// For flows where the credential arrives in the URL fragment (implicit grant),\n// the browser must relay it back to the loopback server. This renders a pending\n// page whose script reads the fragment, POSTs it to `tokenPath`, then resolves\n// to the success or error state in place.\nexport function bootstrap(options: BootstrapOptions) {\n return renderDocument({\n title: \"Finishing sign-in\",\n body: renderCard({\n status: \"pending\",\n headline: \"Finishing sign-in\",\n message: options.provider\n ? `Completing your ${escapeHtml(options.provider)} authorization.`\n : \"Completing authorization.\",\n footnote: \"You can close this window once sign-in finishes.\",\n }),\n script: bootstrapScript(options),\n })\n}\n\nexport * as OauthCallbackPage from \"./page.js\"\n\ntype Status = \"pending\" | \"success\" | \"error\"\n\nfunction renderCard(input: { status: Status; headline: string; message: string; detail?: string; footnote: string }) {\n const detail = input.detail?.trim()\n return `<main class=\"card\" id=\"oc-card\" data-status=\"${input.status}\" role=\"status\" aria-live=\"polite\">\n <div class=\"brand\">${WORDMARK}</div>\n <div class=\"status\" aria-hidden=\"true\">\n <span class=\"icon icon-pending\">${ICON_SPINNER}</span>\n <span class=\"icon icon-success\">${ICON_CHECK}</span>\n <span class=\"icon icon-error\">${ICON_CROSS}</span>\n </div>\n <h1 class=\"headline\" id=\"oc-headline\">${escapeHtml(input.headline)}</h1>\n <p class=\"message\" id=\"oc-message\">${input.message}</p>\n <pre class=\"detail\" id=\"oc-detail\"${detail ? \"\" : \" hidden\"}>${detail ? escapeHtml(detail) : \"\"}</pre>\n <p class=\"footnote\" id=\"oc-footnote\">${escapeHtml(input.footnote)}</p>\n </main>`\n}\n\nfunction renderDocument(input: { title: string; body: string; script?: string }) {\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"robots\" content=\"noindex\" />\n <title>${escapeHtml(input.title)} · OpenCode</title>\n <style>${STYLES}</style>\n </head>\n <body>\n ${input.body}${input.script ? `\\n <script>${input.script}</script>` : \"\"}\n </body>\n</html>`\n}\n\nconst AUTO_CLOSE_SCRIPT = `setTimeout(function(){try{window.close()}catch(e){}},2500)`\n\nfunction bootstrapScript(options: BootstrapOptions) {\n return `var PROVIDER=${scriptString(options.provider ?? \"\")};\nvar TOKEN_URL=new URL(${scriptString(options.tokenPath)},window.location.origin).href;\n(function(){\n var card=document.getElementById(\"oc-card\"),headline=document.getElementById(\"oc-headline\"),message=document.getElementById(\"oc-message\"),detail=document.getElementById(\"oc-detail\"),footnote=document.getElementById(\"oc-footnote\");\n function fail(text){card.dataset.status=\"error\";headline.textContent=\"Authorization failed\";message.textContent=PROVIDER?(\"OpenCode couldn't finish connecting to \"+PROVIDER+\".\"):\"OpenCode couldn't complete authorization.\";if(text){detail.textContent=text;detail.hidden=false}footnote.textContent=\"Close this window and try again from OpenCode.\"}\n function ok(){card.dataset.status=\"success\";headline.textContent=\"Authorization successful\";message.textContent=PROVIDER?(\"OpenCode is now connected to \"+PROVIDER+\".\"):\"OpenCode is now authorized.\";detail.hidden=true;footnote.textContent=\"You can close this window.\";setTimeout(function(){try{window.close()}catch(e){}},2500)}\n try{\n var hash=new URLSearchParams((window.location.hash||\"\").slice(1));\n var search=new URLSearchParams(window.location.search||\"\");\n var err=hash.get(\"error\")||search.get(\"error\");\n var errDescription=hash.get(\"error_description\")||search.get(\"error_description\");\n var body=err?{error:err,error_description:errDescription||\"\"}:{access_token:hash.get(\"access_token\")||\"\",expires_in:hash.get(\"expires_in\")||\"0\",state:hash.get(\"state\")||\"\"};\n fetch(TOKEN_URL,{method:\"POST\",headers:{\"Content-Type\":\"application/json\"},body:JSON.stringify(body)}).then(function(res){\n if(!res.ok)return res.text().catch(function(){return\"\"}).then(function(t){throw new Error(t||(\"callback failed (\"+res.status+\")\"))});\n if(err){fail(errDescription||err);return}\n ok();\n }).catch(function(e){fail(String(e&&e.message?e.message:e))});\n }catch(e){fail(String(e&&e.message?e.message:e))}\n})()`\n}\n\nfunction scriptString(value: string) {\n return JSON.stringify(value).replaceAll(\"<\", \"\\\\u003c\")\n}\n\nfunction escapeHtml(value: string) {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\")\n}\n\n// Curated subset of OC-2 tokens (packages/ui/src/styles/theme.css). Default is\n// light; dark applies via prefers-color-scheme. The [data-theme] selectors let a\n// host force a scheme without changing the default.\nconst LIGHT_VARS = `\n --oc-bg: #f8f8f8;\n --oc-card: #fcfcfc;\n --oc-text-strong: #171717;\n --oc-text-base: #6f6f6f;\n --oc-text-weak: #8f8f8f;\n --oc-border-weak: #e5e5e5;\n --oc-icon-strong: #171717;\n --oc-icon-base: #8f8f8f;\n --oc-icon-weak: #dbdbdb;\n --oc-success: #2dba26;\n --oc-error: #ed4831;\n --oc-detail-bg: #fff8f6;\n --oc-detail-border: #fdc3b7;\n --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.10), 0 6px 12px -2px rgba(0,0,0,.05), 0 1px 2px rgba(0,0,0,.06);`\n\nconst DARK_VARS = `\n --oc-bg: #101010;\n --oc-card: #161616;\n --oc-text-strong: rgba(255,255,255,.936);\n --oc-text-base: rgba(255,255,255,.618);\n --oc-text-weak: rgba(255,255,255,.422);\n --oc-border-weak: #282828;\n --oc-icon-strong: #ededed;\n --oc-icon-base: #7e7e7e;\n --oc-icon-weak: #343434;\n --oc-success: #12c905;\n --oc-error: #fc533a;\n --oc-detail-bg: #28110c;\n --oc-detail-border: #6a1206;\n --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.55), 0 6px 12px -2px rgba(0,0,0,.35), 0 1px 2px rgba(0,0,0,.4);`\n\nconst STYLES = `\n :root { color-scheme: light dark;${LIGHT_VARS}\n --oc-font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n --oc-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n }\n @media (prefers-color-scheme: dark) { :root:not([data-theme=\"light\"]) {${DARK_VARS} } }\n :root[data-theme=\"dark\"] {${DARK_VARS} }\n :root[data-theme=\"light\"] {${LIGHT_VARS} }\n\n * { box-sizing: border-box; }\n html, body { margin: 0; height: 100%; }\n body {\n min-height: 100vh;\n display: grid;\n place-items: center;\n padding: 24px;\n background: var(--oc-bg);\n color: var(--oc-text-base);\n font-family: var(--oc-font-sans);\n line-height: 1.5;\n -webkit-font-smoothing: antialiased;\n text-rendering: optimizeLegibility;\n }\n .card {\n width: min(100%, 28rem);\n padding: 2.25rem 2rem 1.75rem;\n background: var(--oc-card);\n border: 1px solid var(--oc-border-weak);\n border-radius: 14px;\n box-shadow: var(--oc-shadow);\n text-align: center;\n }\n .brand { display: flex; justify-content: center; margin-bottom: 1.75rem; }\n .brand svg { height: 19px; width: auto; }\n .status { display: flex; justify-content: center; margin-bottom: 1.125rem; }\n .icon { display: none; line-height: 0; }\n .icon svg { display: block; }\n .card[data-status=\"pending\"] .icon-pending,\n .card[data-status=\"success\"] .icon-success,\n .card[data-status=\"error\"] .icon-error { display: block; }\n .icon-success { color: var(--oc-success); }\n .icon-error { color: var(--oc-error); }\n .icon-pending { color: var(--oc-text-weak); }\n .headline { margin: 0; font-size: 1.1875rem; font-weight: 500; line-height: 1.3; letter-spacing: -0.012em; color: var(--oc-text-strong); }\n .message { margin: 0.5rem 0 0; font-size: 0.9375rem; color: var(--oc-text-base); }\n .detail {\n margin: 1.25rem 0 0;\n padding: 0.75rem 0.875rem;\n text-align: left;\n font-family: var(--oc-font-mono);\n font-size: 0.8125rem;\n line-height: 1.55;\n color: var(--oc-text-strong);\n background: var(--oc-detail-bg);\n border: 1px solid var(--oc-detail-border);\n border-radius: 8px;\n white-space: pre-wrap;\n word-break: break-word;\n max-height: 9.5rem;\n overflow: auto;\n }\n .detail[hidden] { display: none; }\n .footnote { margin: 1.5rem 0 0; font-size: 0.8125rem; color: var(--oc-text-weak); }\n .spinner { animation: oc-spin 0.8s linear infinite; transform-origin: center; }\n @keyframes oc-spin { to { transform: rotate(360deg); } }\n @media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }\n`\n\n// OpenCode wordmark — same path geometry as packages/ui/src/components/logo.tsx (Logo).\nconst WORDMARK = `<svg class=\"wordmark\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 234 42\" fill=\"none\" aria-label=\"OpenCode\" role=\"img\">\n <path d=\"M18 30H6V18H18V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M18 12H6V30H18V12ZM24 36H0V6H24V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M48 30H36V18H48V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M36 30H48V12H36V30ZM54 36H36V42H30V6H54V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M84 24V30H66V24H84Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M84 24H66V30H84V36H60V6H84V24ZM66 18H78V12H66V18Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M108 36H96V18H108V36Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M108 12H96V36H90V6H108V12ZM114 36H108V12H114V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M144 30H126V18H144V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M144 12H126V30H144V36H120V6H144V12Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M168 30H156V18H168V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M168 12H156V30H168V12ZM174 36H150V6H174V36Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M198 30H186V18H198V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M198 12H186V30H198V12ZM204 36H180V6H198V0H204V36Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M234 24V30H216V24H234Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M216 12V18H228V12H216ZM234 24H216V30H234V36H210V6H234V24Z\" fill=\"var(--oc-icon-strong)\" />\n </svg>`\n\nconst ICON_CHECK = `<svg viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m8.5 12.5 2.4 2.4 4.6-5.4\" /></svg>`\n\nconst ICON_CROSS = `<svg viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m9 9 6 6m0-6-6 6\" /></svg>`\n\nconst ICON_SPINNER = `<svg class=\"spinner\" viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" opacity=\"0.2\" /><path d=\"M21 12a9 9 0 0 0-9-9\" /></svg>`\n" | ||
| ], | ||
| "mappings": ";sIAoBO,SAAS,CAAO,CAAC,EAA+B,CACrD,IAAM,EAAW,GAAS,SAC1B,OAAO,EAAe,CACpB,MAAO,2BACP,KAAM,EAAW,CACf,OAAQ,UACR,SAAU,2BACV,QAAS,EAAW,gCAAgC,EAAW,CAAQ,KAAO,8BAC9E,SAAU,4BACZ,CAAC,EACD,OAAQ,GAAS,YAAc,GAAQ,OAAY,CACrD,CAAC,EAGI,SAAS,CAAK,CAAC,EAAgB,EAA+B,CACnE,IAAM,EAAW,GAAS,SAC1B,OAAO,EAAe,CACpB,MAAO,uBACP,KAAM,EAAW,CACf,OAAQ,QACR,SAAU,uBACV,QAAS,EACL,0CAA0C,EAAW,CAAQ,KAC7D,4CACJ,SACA,SAAU,gDACZ,CAAC,CACH,CAAC,EAaI,SAAS,CAAS,CAAC,EAA2B,CACnD,OAAO,EAAe,CACpB,MAAO,oBACP,KAAM,EAAW,CACf,OAAQ,UACR,SAAU,oBACV,QAAS,EAAQ,SACb,mBAAmB,EAAW,EAAQ,QAAQ,mBAC9C,4BACJ,SAAU,kDACZ,CA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AAA,+GAgBZ,EAAS;AAAA,qCACsB;AAAA;AAAA;AAAA;AAAA,2EAIsC;AAAA,8BAC7C;AAAA,+BACC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8DzB,EAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAmBX,EAAa,iOAEb,EAAa,wNAEb,EAAe", | ||
| "debugId": "AF85081DB5546C5B64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "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,kBACjD,EAAiD,MAGhD,IAAM,EAAiB", | ||
| "debugId": "77F4C10E5C2BF32564756E2164756E21", | ||
| "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.js\"\nimport { DecodeError, ResizerUnavailableError, SizeError } from \"../image.js\"\n\nconst JPEG_QUALITIES = [80, 85, 70, 55, 40]\n\nexport const make = Effect.gen(function* () {\n const loadPhoton = yield* Effect.cached(\n // A runtime without a photon wasm artifact (#photon-wasm resolves to the\n // empty string on workerd) has no resizer, by declaration: fail typed\n // before touching URLs or module loading. The path resolution and import\n // for runtimes that DO have an artifact stay inside the guard too — a\n // throw outside it (workerd's undefined import.meta.url was one) is a\n // defect that escapes the ResizerUnavailableError handling and turns any\n // image-bearing prompt into a 500 instead of degrading to passthrough.\n photonWasm === \"\"\n ? Effect.fail(new ResizerUnavailableError())\n : Effect.tryPromise({\n try: async () => {\n ;(\n globalThis as typeof globalThis & { __OPENCODE_PHOTON_WASM_PATH?: string }\n ).__OPENCODE_PHOTON_WASM_PATH = path.isAbsolute(photonWasm)\n ? photonWasm\n : fileURLToPath(new URL(photonWasm, import.meta.url))\n return await import(\"@silvia-odwyer/photon-node\")\n },\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": ";kgCAGA,IAAe,ICDf,oBACA,wBAAS,YAIT,IAAM,EAAiB,CAAC,GAAI,GAAI,GAAI,GAAI,EAAE,EAE7B,EAAO,EAAO,IAAI,SAAU,EAAG,CAC1C,IAAM,EAAa,MAAO,EAAO,OAQ/B,IAAe,GACX,EAAO,KAAK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,EAAS,SAAW,EAAI,EAAI,KAAK,IAAI,EAAG,KAAK,MAAM,EAAS,OAAS,IAAI,CAAC,CACpF,EACN,OAAO,EAAI,KAAK,CAAC,IAAS,EAAK,QAAU,EAAK,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": "3171442DEDBA84A964756E2164756E21", | ||
| "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(` Run \\`opencode service set hostname 0.0.0.0\\` to access the service remotely.${EOL}${EOL}`)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";u9BAAA,cAAS,WAST,IAAe,IAAQ,QACrB,EAAS,SAAS,KAClB,EAAO,GAAG,UAAU,EAAE,SAAU,EAAG,CACjC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,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,MAAM,kFAAkF,IAAM,GAAK,EACnH,CACH", | ||
| "debugId": "29ED20E3B659990464756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/form.ts", "src/commands/handlers/auth/login.ts"], | ||
| "sourcesContent": [ | ||
| "import { confirm, log, multiselect, password, select, text, type Option } from \"@clack/prompts\"\nimport { Effect } from \"effect\"\nimport type { FormAnswer, FormField, FormFields } from \"@opencode-ai/client\"\nimport { openUrl, prompt, requireInteractive } from \"../../../ui/prompt\"\n\nconst skip = Symbol(\"skip\")\nconst custom = Symbol(\"custom\")\n\nexport const answerForm = Effect.fn(\"cli.auth.form\")(function* (fields: FormFields | undefined) {\n if (!fields) return undefined\n yield* requireInteractive(\"Authentication form input requires an interactive terminal\")\n const answer: FormAnswer = {}\n for (const field of fields) {\n if (!active(field, answer)) continue\n const value = yield* answerField(field)\n if (value !== undefined) answer[field.key] = value\n }\n return answer\n})\n\nexport const secret = Effect.fn(\"cli.auth.secret\")(function* (message: string) {\n yield* requireInteractive(\"API key input requires an interactive terminal\")\n return yield* prompt<string>(() => password({ message, validate: (value) => (!value ? \"Required\" : undefined) }))\n})\n\nconst answerField = Effect.fn(\"cli.auth.form.field\")(function* (field: FormField) {\n const message = field.title ?? field.key\n if (field.description) log.info(field.description)\n if (field.type === \"external\") {\n log.info(field.url)\n yield* openUrl(field.url)\n const acknowledged = yield* prompt<boolean>(() =>\n confirm({ message: message || \"Continue after completing this step?\", initialValue: true }),\n )\n if (!acknowledged) return yield* Effect.fail(new Error(`${message || \"External step\"} is required`))\n return true\n }\n if (field.type === \"boolean\") {\n if (field.required) return yield* prompt<boolean>(() => confirm({ message, initialValue: field.default ?? true }))\n const options: Array<Option<boolean | typeof skip>> = [\n { value: true, label: \"Yes\" },\n { value: false, label: \"No\" },\n { value: skip, label: \"Skip\" },\n ]\n const value = yield* prompt<boolean | typeof skip>(() =>\n select<boolean | typeof skip>({\n message,\n options,\n initialValue: field.default ?? skip,\n }),\n )\n if (value === skip) return undefined\n return value\n }\n if (field.type === \"multiselect\") {\n const options: Array<Option<string | typeof custom>> = field.options.map((option) => ({\n value: option.value,\n label: option.label,\n hint: option.description,\n }))\n if (field.custom) options.push({ value: custom, label: \"Type another value\" })\n const values = yield* prompt<Array<string | typeof custom>>(() =>\n multiselect<string | typeof custom>({\n message,\n options,\n initialValues: field.default,\n required: field.required || (field.minItems ?? 0) > 0,\n }),\n )\n const selected = values.filter((value): value is string => value !== custom)\n if (values.includes(custom)) {\n selected.push(yield* prompt<string>(() => text({ message: \"Enter value\", validate: required })))\n }\n if (field.minItems !== undefined && selected.length < field.minItems) {\n return yield* Effect.fail(new Error(`Select at least ${field.minItems}`))\n }\n if (field.maxItems !== undefined && selected.length > field.maxItems) {\n return yield* Effect.fail(new Error(`Select at most ${field.maxItems}`))\n }\n return selected\n }\n if (field.type === \"string\" && field.options) {\n const options: Array<Option<string | typeof custom | typeof skip>> = field.options.map((option) => ({\n value: option.value,\n label: option.label,\n hint: option.description,\n }))\n if (field.custom) options.push({ value: custom, label: \"Type your own answer\" })\n if (!field.required) options.push({ value: skip, label: \"Skip\" })\n const value = yield* prompt<string | typeof custom | typeof skip>(() =>\n select<string | typeof custom | typeof skip>({ message, options, initialValue: field.default }),\n )\n if (value === skip) return undefined\n if (value !== custom) return value\n }\n const value = yield* prompt<string>(() =>\n text({\n message,\n placeholder: field.type === \"string\" ? field.placeholder : undefined,\n initialValue: field.default === undefined ? undefined : String(field.default),\n validate: (input) => validateText(field, input),\n }),\n )\n if (!value && !field.required) return undefined\n if (field.type === \"string\") return value\n return Number(value)\n})\n\nfunction active(field: FormField, answer: FormAnswer) {\n if (field.type === \"external\" || !field.when) return true\n return field.when.every((condition) => {\n const value = answer[condition.key]\n if (value === undefined) return false\n const matches = Array.isArray(value) ? value.includes(String(condition.value)) : value === condition.value\n return condition.op === \"eq\" ? matches : !matches\n })\n}\n\nfunction required(value: string | undefined) {\n return value ? undefined : \"Required\"\n}\n\nfunction validateText(field: Exclude<FormField, { type: \"boolean\" | \"external\" | \"multiselect\" }>, value?: string) {\n if (!value) return field.required ? \"Required\" : undefined\n if (field.type === \"number\" || field.type === \"integer\") {\n const number = Number(value)\n if (!Number.isFinite(number)) return \"Expected a number\"\n if (field.type === \"integer\" && !Number.isInteger(number)) return \"Expected an integer\"\n if (typeof field.minimum === \"number\" && number < field.minimum) return `Must be at least ${field.minimum}`\n if (typeof field.maximum === \"number\" && number > field.maximum) return `Must be at most ${field.maximum}`\n return undefined\n }\n if (field.minLength !== undefined && value.length < field.minLength)\n return `Must be at least ${field.minLength} characters`\n if (field.maxLength !== undefined && value.length > field.maxLength)\n return `Must be at most ${field.maxLength} characters`\n if (field.pattern) {\n try {\n if (!new RegExp(field.pattern).test(value)) return \"Invalid format\"\n } catch {\n return \"Invalid format\"\n }\n }\n if (field.format === \"uri\" && !URL.canParse(value)) return \"Expected a URL\"\n if (field.format === \"email\" && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)) return \"Expected an email address\"\n if (field.format === \"date\") {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return \"Expected a date\"\n const date = new Date(`${value}T00:00:00.000Z`)\n if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) return \"Expected a date\"\n }\n if (field.format === \"date-time\" && Number.isNaN(Date.parse(value))) return \"Expected a date and time\"\n return undefined\n}\n", | ||
| "import { autocomplete, intro, log, outro, select, spinner, text } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport type { FormAnswer, IntegrationInfo, OpenCodeClient } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { handlePromptErrors, openUrl, prompt, requireInteractive } from \"../../../ui/prompt\"\nimport { answerForm, secret } from \"./form\"\nimport {\n createClient,\n connectMethods,\n loadIntegrations,\n location,\n request,\n resolveIntegration,\n resolveMethod,\n type ConnectMethod,\n} from \"./shared\"\n\nconst integrationPriority = new Map([\n [\"opencode\", 0],\n [\"opencode-go\", 1],\n [\"openai\", 2],\n [\"github-copilot\", 3],\n [\"google\", 4],\n [\"anthropic\", 5],\n [\"openrouter\", 6],\n [\"vercel\", 7],\n])\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.login,\n Effect.fn(\"cli.auth.login\")((input) =>\n login({\n target: Option.getOrUndefined(input.target),\n method: Option.getOrUndefined(input.method),\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n }).pipe(handlePromptErrors),\n ),\n)\n\nconst login = Effect.fn(\"cli.auth.login.run\")(function* (input: {\n target?: string\n method?: string\n server?: string\n standalone: boolean\n}) {\n if (!input.target)\n yield* requireInteractive(\"Pass an integration ID or name when running without an interactive terminal\")\n intro(\"Connect an integration\")\n const client = yield* createClient({ server: input.server, standalone: input.standalone })\n const integration = yield* findIntegration(client, input.target)\n const methods = connectMethods(integration)\n if (methods.length === 0) yield* Effect.fail(new Error(`${integration.name} has no interactive login methods`))\n const method = yield* chooseMethod(methods, input.method)\n const answer = method.type === \"command\" ? undefined : yield* answerForm(method.form)\n yield* authenticate(client, integration, method, answer)\n outro(\"Done\")\n})\n\nconst findIntegration = Effect.fn(\"cli.auth.login.integration\")(function* (client: OpenCodeClient, target?: string) {\n if (target && URL.canParse(target)) {\n const protocol = new URL(target).protocol\n if (protocol === \"http:\" || protocol === \"https:\") {\n const progress = spinner()\n progress.start(\"Discovering authentication provider...\")\n yield* request((signal) => client.integration.wellknown.add({ url: target, location }, { signal })).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(\"Authentication provider discovered\"))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Discovery failed\", 1))),\n )\n }\n }\n const integrations = yield* loadIntegrations(client)\n if (target) return yield* resolveIntegration(integrations, target)\n const available = integrations\n .filter((integration) => connectMethods(integration).length > 0)\n .toSorted(\n (a, b) =>\n (integrationPriority.get(a.id) ?? integrationPriority.size) -\n (integrationPriority.get(b.id) ?? integrationPriority.size) ||\n a.name.localeCompare(b.name) ||\n a.id.localeCompare(b.id),\n )\n if (available.length === 0) return yield* Effect.fail(new Error(\"No authentication integrations are available\"))\n const id = yield* prompt<string>(() =>\n autocomplete({\n message: \"Select integration\",\n maxItems: 8,\n options: available.map((integration) => {\n const option = { value: integration.id, label: integration.name, hint: integration.id }\n if (integration.connections.length > 0) return { ...option, hint: \"connected\" }\n if (integration.id === \"opencode\") return { ...option, hint: \"recommended\" }\n return option\n }),\n }),\n )\n return yield* resolveIntegration(available, id)\n})\n\nconst chooseMethod = Effect.fn(\"cli.auth.login.method\")(function* (methods: ConnectMethod[], target?: string) {\n if (target) return yield* resolveMethod(methods, target)\n if (methods.length === 1) return methods[0]\n yield* requireInteractive(\"Pass --method when running without an interactive terminal\")\n const id = yield* prompt<string>(() =>\n select({\n message: \"Select login method\",\n options: methods.map((method) => {\n if (method.type === \"key\") return { value: \"key\", label: method.label ?? \"API key\" }\n return { value: method.id, label: method.label }\n }),\n }),\n )\n return yield* resolveMethod(methods, id)\n})\n\nconst authenticate = Effect.fn(\"cli.auth.login.authenticate\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: ConnectMethod,\n answer?: FormAnswer,\n) {\n if (method.type === \"key\") return yield* keyLogin(client, integration, method, answer)\n if (method.type === \"command\") return yield* commandLogin(client, integration, method)\n return yield* oauthLogin(client, integration, method, answer)\n})\n\nconst keyLogin = Effect.fn(\"cli.auth.login.key\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"key\" }>,\n answer?: FormAnswer,\n) {\n const key = yield* secret(method.label ?? `Enter your ${integration.name} API key`)\n const progress = spinner()\n progress.start(\"Saving credential...\")\n yield* request((signal) =>\n client.integration.connect.key({ integrationID: integration.id, key, answer, location }, { signal }),\n ).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(`Connected to ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))),\n )\n})\n\nconst oauthLogin = Effect.fn(\"cli.auth.login.oauth\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"oauth\" }>,\n answer?: FormAnswer,\n) {\n const progress = spinner()\n progress.start(\"Starting authorization...\")\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n { integrationID: integration.id, methodID: method.id, answer, location },\n { signal },\n ),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID: integration.id, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n progress.stop(\"Authorization started\")\n log.info(attempt.instructions)\n log.info(attempt.url)\n if (process.stdin.isTTY && process.stdout.isTTY) yield* openUrl(attempt.url)\n\n if (attempt.mode === \"code\") {\n yield* requireInteractive(\"This login requires an interactive terminal to enter the authorization code\")\n const code = yield* prompt<string>(() =>\n text({ message: \"Paste the authorization code\", validate: (value) => (!value ? \"Required\" : undefined) }),\n )\n const completing = spinner()\n completing.start(\"Completing authorization...\")\n yield* request((signal) =>\n client.integration.oauth.complete(\n { integrationID: integration.id, attemptID: attempt.attemptID, code, location },\n { signal },\n ),\n ).pipe(\n Effect.tap(() => Effect.sync(() => completing.stop(`Connected to ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => completing.stop(\"Authentication failed\", 1))),\n )\n return\n }\n\n const waiting = spinner()\n waiting.start(\"Waiting for authorization...\")\n const status = yield* waitForOAuth(client, integration.id, attempt.attemptID).pipe(\n Effect.tapCause(() => Effect.sync(() => waiting.stop(\"Authentication failed\", 1))),\n )\n if (status.status === \"complete\") {\n waiting.stop(`Connected to ${integration.name}`)\n return\n }\n waiting.stop(\"Authentication failed\", 1)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n yield* Effect.fail(new Error(\"Authorization expired\"))\n})\n\nconst commandLogin = Effect.fn(\"cli.auth.login.command\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"command\" }>,\n) {\n const progress = spinner()\n progress.start(\"Starting authentication command...\")\n const started = yield* request((signal) =>\n client.integration.command.connect({ integrationID: integration.id, methodID: method.id, location }, { signal }),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.command.cancel(\n {\n integrationID: integration.id,\n attemptID: started.data.attemptID,\n location,\n },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n const status = yield* waitForCommand(client, integration.id, started.data.attemptID, (message) =>\n progress.message(message.trim() || \"Waiting for authentication command...\"),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n if (status.status === \"complete\") {\n progress.stop(`Connected to ${integration.name}`)\n return\n }\n progress.stop(\"Authentication failed\", 1)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n yield* Effect.fail(new Error(\"Authentication expired\"))\n})\n\nconst waitForOAuth = Effect.fn(\"cli.auth.login.oauth.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\nconst waitForCommand = Effect.fn(\"cli.auth.login.command.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n update: (message: string) => void,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.command.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n if (response.data.message) update(response.data.message)\n yield* Effect.sleep(500)\n }\n})\n" | ||
| ], | ||
| "mappings": ";m3CAKA,IAAM,EAAO,OAAO,MAAM,EACpB,EAAS,OAAO,QAAQ,EAEjB,EAAa,EAAO,GAAG,eAAe,EAAE,SAAU,CAAC,EAAgC,CAC9F,GAAI,CAAC,EAAQ,OACb,MAAO,EAAmB,4DAA4D,EACtF,IAAM,EAAqB,CAAC,EAC5B,QAAW,KAAS,EAAQ,CAC1B,GAAI,CAAC,EAAO,EAAO,CAAM,EAAG,SAC5B,IAAM,EAAQ,MAAO,EAAY,CAAK,EACtC,GAAI,IAAU,OAAW,EAAO,EAAM,KAAO,EAE/C,OAAO,EACR,EAEY,EAAS,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAiB,CAE7E,OADA,MAAO,EAAmB,gDAAgD,EACnE,MAAO,EAAe,IAAM,EAAS,CAAE,UAAS,SAAU,CAAC,IAAW,CAAC,EAAQ,WAAa,MAAW,CAAC,CAAC,EACjH,EAEK,EAAc,EAAO,GAAG,qBAAqB,EAAE,SAAU,CAAC,EAAkB,CAChF,IAAM,EAAU,EAAM,OAAS,EAAM,IACrC,GAAI,EAAM,YAAa,EAAI,KAAK,EAAM,WAAW,EACjD,GAAI,EAAM,OAAS,WAAY,CAM7B,GALA,EAAI,KAAK,EAAM,GAAG,EAClB,MAAO,EAAQ,EAAM,GAAG,EAIpB,EAHiB,MAAO,EAAgB,IAC1C,EAAQ,CAAE,QAAS,GAAW,uCAAwC,aAAc,EAAK,CAAC,CAC5F,GACmB,OAAO,MAAO,EAAO,KAAS,MAAM,GAAG,GAAW,6BAA6B,CAAC,EAC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MAAM,wBAAwB,CAAC,EACvD,EAEK,GAAe,EAAO,GAAG,2BAA2B,EAAE,SAAU,CACpE,EACA,EACA,EACA,CACA,MAAO,GAAM,CACX,IAAM,EAAW,MAAO,EAAQ,CAAC,IAC/B,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,EAAG,CAAE,QAAO,CAAC,CACpF,EACA,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,MAAO,EAAO,MAAM,GAAG,GAE1B,EAEK,GAAiB,EAAO,GAAG,6BAA6B,EAAE,SAAU,CACxE,EACA,EACA,EACA,EACA,CACA,MAAO,GAAM,CACX,IAAM,EAAW,MAAO,EAAQ,CAAC,IAC/B,EAAO,YAAY,QAAQ,OAAO,CAAE,gBAAe,YAAW,UAAS,EAAG,CAAE,QAAO,CAAC,CACtF,EACA,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,GAAI,EAAS,KAAK,QAAS,EAAO,EAAS,KAAK,OAAO,EACvD,MAAO,EAAO,MAAM,GAAG,GAE1B", | ||
| "debugId": "EF03E1FE53D5316064756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/mcp.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Mcp from \"./mcp.js\"\n\nimport { Schema } from \"effect\"\nimport { optional, PositiveInt } from \"./schema.js\"\nimport { IntegrationID } from \"./integration-id.js\"\n\nexport class TimeoutConfig extends Schema.Class<TimeoutConfig>(\"Mcp.TimeoutConfig\")({\n startup: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to establish and initialize the MCP server.\",\n }),\n catalog: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to wait for MCP discovery requests such as tools/list and prompts/list.\",\n }),\n execution: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to wait for MCP tool and prompt execution.\",\n }),\n}) {}\n\nexport class LocalConfig extends Schema.Class<LocalConfig>(\"Mcp.LocalConfig\")({\n type: Schema.Literal(\"local\"),\n command: Schema.String.pipe(Schema.Array),\n cwd: Schema.String.pipe(optional).annotate({\n description: \"Working directory for the MCP server process. Relative paths resolve from the workspace directory.\",\n }),\n environment: Schema.Record(Schema.String, Schema.String).pipe(optional),\n disabled: Schema.Boolean.pipe(optional),\n codemode: Schema.Boolean.pipe(optional).annotate({\n description: \"Expose this server's tools through Code Mode. Defaults to true.\",\n }),\n timeout: TimeoutConfig.pipe(optional),\n}) {}\n\nexport class OAuthConfig extends Schema.Class<OAuthConfig>(\"Mcp.OAuthConfig\")({\n client_id: Schema.String.pipe(optional),\n client_secret: Schema.String.pipe(optional),\n scope: Schema.String.pipe(optional),\n callback_port: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })).pipe(optional),\n redirect_uri: Schema.String.pipe(optional),\n}) {}\n\nexport class RemoteConfig extends Schema.Class<RemoteConfig>(\"Mcp.RemoteConfig\")({\n type: Schema.Literal(\"remote\"),\n url: Schema.String,\n headers: Schema.Record(Schema.String, Schema.String).pipe(optional),\n oauth: Schema.Union([OAuthConfig, Schema.Literal(false)]).pipe(optional),\n disabled: Schema.Boolean.pipe(optional),\n codemode: Schema.Boolean.pipe(optional).annotate({\n description: \"Expose this server's tools through Code Mode. Defaults to true.\",\n }),\n timeout: TimeoutConfig.pipe(optional),\n}) {}\n\nexport const ServerConfig = Schema.Union([LocalConfig, RemoteConfig]).pipe(Schema.toTaggedUnion(\"type\"))\nexport type ServerConfig = typeof ServerConfig.Type\n\nconst Connected = Schema.Struct({ status: Schema.Literal(\"connected\") }).annotate({\n identifier: \"Mcp.Status.Connected\",\n})\nconst Pending = Schema.Struct({ status: Schema.Literal(\"pending\") }).annotate({\n identifier: \"Mcp.Status.Pending\",\n})\nconst Disabled = Schema.Struct({ status: Schema.Literal(\"disabled\") }).annotate({\n identifier: \"Mcp.Status.Disabled\",\n})\nconst Failed = Schema.Struct({ status: Schema.Literal(\"failed\"), error: Schema.String }).annotate({\n identifier: \"Mcp.Status.Failed\",\n})\nconst NeedsAuth = Schema.Struct({ status: Schema.Literal(\"needs_auth\") }).annotate({\n identifier: \"Mcp.Status.NeedsAuth\",\n})\n\nexport type Status = typeof Status.Type\nexport const Status = Schema.Union([Connected, Pending, Disabled, Failed, NeedsAuth]).pipe(\n Schema.toTaggedUnion(\"status\"),\n)\n\nexport interface Server extends Schema.Schema.Type<typeof Server> {}\nexport const Server = Schema.Struct({\n name: Schema.String,\n status: Status,\n // Set for remote servers registered as OAuth integrations; lets clients act on the right integration\n // without matching by name, which could collide with provider or plugin integrations.\n integrationID: optional(IntegrationID),\n}).annotate({ identifier: \"Mcp.Server\" })\n\nexport interface Resource extends Schema.Schema.Type<typeof Resource> {}\nexport const Resource = Schema.Struct({\n server: Schema.String,\n name: Schema.String,\n uri: Schema.String,\n description: optional(Schema.String),\n mimeType: optional(Schema.String),\n}).annotate({ identifier: \"Mcp.Resource\" })\n\nexport interface ResourceTemplate extends Schema.Schema.Type<typeof ResourceTemplate> {}\nexport const ResourceTemplate = Schema.Struct({\n server: Schema.String,\n name: Schema.String,\n uriTemplate: Schema.String,\n description: optional(Schema.String),\n mimeType: optional(Schema.String),\n}).annotate({ identifier: \"Mcp.ResourceTemplate\" })\n\nexport interface ResourceCatalog extends Schema.Schema.Type<typeof ResourceCatalog> {}\nexport const ResourceCatalog = Schema.Struct({\n resources: Schema.Array(Resource),\n templates: Schema.Array(ResourceTemplate),\n}).annotate({ identifier: \"Mcp.ResourceCatalog\" })\n\nexport const ResourceContentPart = Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"text\"),\n uri: Schema.String,\n text: Schema.String,\n mimeType: optional(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal(\"blob\"),\n uri: Schema.String,\n blob: Schema.String,\n mimeType: optional(Schema.String),\n }),\n]).pipe(Schema.toTaggedUnion(\"type\"), Schema.annotate({ identifier: \"Mcp.ResourceContentPart\" }))\nexport type ResourceContentPart = typeof ResourceContentPart.Type\n\nexport interface ResourceContent extends Schema.Schema.Type<typeof ResourceContent> {}\nexport const ResourceContent = Schema.Struct({\n server: Schema.String,\n uri: Schema.String,\n contents: Schema.Array(ResourceContentPart),\n}).annotate({ identifier: \"Mcp.ResourceContent\" })\n" | ||
| ], | ||
| "mappings": ";sdAMO,MAAM,UAAsB,EAAO,MAAqB,mBAAmB,EAAE,CAClF,QAAS,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC3C,YAAa,0EACf,CAAC,EACD,QAAS,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC3C,YAAa,sGACf,CAAC,EACD,UAAW,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC7C,YAAa,yEACf,CAAC,CACH,CAAC,CAAE,CAAC,CAEG,MAAM,UAAoB,EAAO,MAAmB,iBAAiB,EAAE,CAC5E,KAAM,EAAO,QAAQ,OAAO,EAC5B,QAAS,EAAO,OAAO,KAAK,EAAO,KAAK,EACxC,IAAK,EAAO,OAAO,KAAK,CAAQ,EAAE,SAAS,CACzC,YAAa,oGACf,CAAC,EACD,YAAa,EAAO,OAAO,EAAO,OAAQ,EAAO,MAAM,EAAE,KAAK,CAAQ,EACtE,SAAU,EAAO,QAAQ,KAAK,CAAQ,EACtC,SAAU,EAAO,QAAQ,KAAK,CAAQ,EAAE,SAAS,CAC/C,YAAa,iEACf,CAAC,EACD,QAAS,EAAc,KAAK,CAAQ,CACtC,CAAC,CAAE,CAAC,CAEG,MAAM,UAAoB,EAAO,MAAmB,iBAAiB,EAAE,CAC5E,UAAW,EAAO,OAAO,KAAK,CAAQ,EACtC,cAAe,EAAO,OAAO,KAAK,CAAQ,EAC1C,MAAO,EAAO,OAAO,KAAK,CAAQ,EAClC,cAAe,EAAO,IAAI,MAAM,EAAO,UAAU,CAAE,QAAS,EAAG,QAAS,KAAM,CAAC,CAAC,EAAE,KAAK,CAAQ,EAC/F,aAAc,EAAO,OAAO,KAAK,CAAQ,CAC3C,CAA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GR,cAAe,EAAS,CAAa,CACvC,CAAC,EAAE,SAAS,CAAE,WAAY,YAAa,CAAC,EAG3B,EAAW,EAAO,OAAO,CACpC,OAAQ,EAAO,OACf,KAAM,EAAO,OACb,IAAK,EAAO,OACZ,YAAa,EAAS,EAAO,MAAM,EACnC,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,EAAE,SAAS,CAAE,WAAY,cAAe,CAAC,EAG7B,EAAmB,EAAO,OAAO,CAC5C,OAAQ,EAAO,OACf,KAAM,EAAO,OACb,YAAa,EAAO,OACpB,YAAa,EAAS,EAAO,MAAM,EACnC,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,EAAE,SAAS,CAAE,WAAY,sBAAuB,CAAC,EAGrC,EAAkB,EAAO,OAAO,CAC3C,UAAW,EAAO,MAAM,CAAQ,EAChC,UAAW,EAAO,MAAM,CAAgB,CAC1C,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAEpC,EAAsB,EAAO,MAAM,CAC9C,EAAO,OAAO,CACZ,KAAM,EAAO,QAAQ,MAAM,EAC3B,IAAK,EAAO,OACZ,KAAM,EAAO,OACb,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,EACD,EAAO,OAAO,CACZ,KAAM,EAAO,QAAQ,MAAM,EAC3B,IAAK,EAAO,OACZ,KAAM,EAAO,OACb,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,CACH,CAAC,EAAE,KAAK,EAAO,cAAc,MAAM,EAAG,EAAO,SAAS,CAAE,WAAY,yBAA0B,CAAC,CAAC,EAInF,EAAkB,EAAO,OAAO,CAC3C,OAAQ,EAAO,OACf,IAAK,EAAO,OACZ,SAAU,EAAO,MAAM,CAAmB,CAC5C,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC", | ||
| "debugId": "D8537D621D3F7E7364756E2164756E21", | ||
| "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/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 endpoint = yield* Service.ensure(yield* ServiceConfig.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, 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": ";u9BAAA,cAAS,WAcT,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAE7B,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,KAC/B,EAAO,GAAG,cAAc,EAAE,SAAU,CAAC,EAAO,CAC1C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,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,UAAS,CAAC,CACnG,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": "984F0A443C95315A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/models.ts"], | ||
| "sourcesContent": [ | ||
| "import { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.models,\n Effect.fn(\"cli.models\")(function* (input) {\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const response = yield* Effect.promise(() => client.model.list({ location: { directory: process.cwd() } }))\n const models = response.data\n .map((model) => `${model.providerID}/${model.id}`)\n .toSorted((a, b) => a.localeCompare(b))\n if (models.length > 0) process.stdout.write(models.join(EOL) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";giCAGA,cAAS,WAKT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,SAAU,CAAC,EAAO,CACxC,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAAS,EAAS,KAAK,CAC3B,QAAS,EAAO,SAAS,IACzB,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAC1C,CAAC,EAEK,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAClF,KACrB,IAAI,CAAC,IAAU,GAAG,EAAM,cAAc,EAAM,IAAI,EAChD,SAAS,CAAC,EAAG,IAAM,EAAE,cAAc,CAAC,CAAC,EACxC,GAAI,EAAO,OAAS,EAAG,QAAQ,OAAO,MAAM,EAAO,KAAK,CAAG,EAAI,CAAG,EACnE,CACH", | ||
| "debugId": "5ACC810CDB66B66064756E2164756E21", | ||
| "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 mismatch = args.mismatch ?? \"ignore\"\n const options = yield* ServiceConfig.options({ checkVersion: mismatch !== \"ignore\" })\n return {\n endpoint: yield* resolveManaged({ ...options, onStart: args.onStart }, mismatch),\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* (options: EnsureOptions, mismatch: NonNullable<Args[\"mismatch\"]>) {\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": ";6eAoBO,IAAM,EAAU,EAAO,GAAG,+BAA+B,EAAE,SAAU,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,EAAW,EAAK,UAAY,SAC5B,EAAU,MAAO,EAAc,QAAQ,CAAE,aAAc,IAAa,QAAS,CAAC,EACpF,MAAO,CACL,SAAU,MAAO,EAAe,IAAK,EAAS,QAAS,EAAK,OAAQ,EAAG,CAAQ,EAC/E,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,CAAC,EAAwB,EAAyC,CACnH,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": "D307D5AF45C3C41664756E2164756E21", | ||
| "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 || input.dangerouslySkipPermissions,\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";mhCAKA,IAAe,IAAQ,QAAQ,EAAS,SAAS,IAAK,CAAC,IACrD,EAAO,IAAI,SAAU,EAAG,CACtB,IAAQ,qBAAsB,MAAO,EAAO,QAAQ,IAAa,wCAAgB,EAC3E,EAAY,QAAQ,KAAK,QAAQ,KAAM,CAAC,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,MAAQ,EAAM,0BAC1C,CAAC,CACH,EACD,CACH", | ||
| "debugId": "3CDA094CF5D81BA864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/logout.ts"], | ||
| "sourcesContent": [ | ||
| "import { autocomplete, intro, outro, spinner } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport type { IntegrationInfo } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { handlePromptErrors, prompt, requireInteractive } from \"../../../ui/prompt\"\nimport { createClient, loadIntegrations, location, request, resolveIntegration } from \"./shared\"\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.logout,\n Effect.fn(\"cli.auth.logout\")((input) =>\n logout({\n target: Option.getOrUndefined(input.target),\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n }).pipe(handlePromptErrors),\n ),\n)\n\nconst logout = Effect.fn(\"cli.auth.logout.run\")(function* (input: {\n target?: string\n server?: string\n standalone: boolean\n}) {\n if (!input.target)\n yield* requireInteractive(\"Pass an integration ID or name when running without an interactive terminal\")\n intro(\"Remove credential\")\n const client = yield* createClient({ server: input.server, standalone: input.standalone })\n const integrations = yield* loadIntegrations(client)\n const integration = yield* chooseIntegration(integrations, input.target)\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n const environment = integration.connections\n .filter((connection) => connection.type === \"env\")\n .map((connection) => connection.name)\n if (environment.length) {\n yield* Effect.fail(\n new Error(\n `${integration.name} is authenticated through ${environment.join(\", \")}; unset the environment variable to disconnect`,\n ),\n )\n }\n yield* Effect.fail(new Error(`No stored credentials for ${integration.name}`))\n }\n const progress = spinner()\n progress.start(\"Removing credential...\")\n yield* Effect.forEach(\n credentials,\n (connection) =>\n request((signal) => client.credential.remove({ credentialID: connection.id, location }, { signal })),\n { concurrency: \"unbounded\", discard: true },\n ).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(`Disconnected from ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Failed to remove credential\", 1))),\n )\n outro(\"Done\")\n})\n\nconst chooseIntegration = Effect.fn(\"cli.auth.logout.integration\")(function* (\n integrations: IntegrationInfo[],\n target?: string,\n) {\n if (target) return yield* resolveIntegration(integrations, target)\n const configured = integrations.filter((integration) =>\n integration.connections.some((connection) => connection.type === \"credential\"),\n )\n if (configured.length === 0) return yield* Effect.fail(new Error(\"No stored credentials found\"))\n const id = yield* prompt<string>(() =>\n autocomplete({\n message: \"Select integration\",\n maxItems: 8,\n options: configured.map((integration) => ({\n value: integration.id,\n label: integration.name,\n hint: integration.connections\n .filter((connection) => connection.type === \"credential\")\n .map((connection) => connection.label)\n .join(\", \"),\n })),\n }),\n )\n return yield* resolveIntegration(configured, id)\n})\n" | ||
| ], | ||
| "mappings": ";2yCAQA,IAAe,IAAQ,QACrB,EAAS,SAAS,KAAK,SAAS,OAChC,EAAO,GAAG,iBAAiB,EAAE,CAAC,IAC5B,EAAO,CACL,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EAAE,KAAK,CAAkB,CAC5B,CACF,EAEM,EAAS,EAAO,GAAG,qBAAqB,EAAE,SAAU,CAAC,EAIxD,CACD,GAAI,CAAC,EAAM,OACT,MAAO,EAAmB,6EAA6E,EACzG,EAAM,mBAAmB,EACzB,IAAM,EAAS,MAAO,EAAa,CAAE,OAAQ,EAAM,OAAQ,WAAY,EAAM,UAAW,CAAC,EACnF,EAAe,MAAO,EAAiB,CAAM,EAC7C,EAAc,MAAO,EAAkB,EAAc,EAAM,MAAM,EACjE,EAAc,EAAY,YAAY,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACnG,GAAI,EAAY,SAAW,EAAG,CAC5B,IAAM,EAAc,EAAY,YAC7B,OAAO,CAAC,IAAe,EAAW,OAAS,KAAK,EAChD,IAAI,CAAC,IAAe,EAAW,IAAI,EACtC,GAAI,EAAY,OACd,MAAO,EAAO,KACR,MACF,GAAG,EAAY,iCAAiC,EAAY,KAAK,IAAI,iDACvE,CACF,EAEF,MAAO,EAAO,KAAS,MAAM,6BAA6B,EAAY,MAAM,CAAC,EAE/E,IAAM,EAAW,EAAQ,EACzB,EAAS,MAAM,wBAAwB,EACvC,MAAO,EAAO,QACZ,EACA,CAAC,IACC,EAAQ,CAAC,IAAW,EAAO,WAAW,OAAO,CAAE,aAAc,EAAW,GAAI,UAAS,EAAG,CAAE,QAAO,CAAC,CAAC,EACrG,CAAE,YAAa,YAAa,QAAS,EAAK,CAC5C,EAAE,KACA,EAAO,IAAI,IAAM,EAAO,KAAK,IAAM,EAAS,KAAK,qBAAqB,EAAY,MAAM,CAAC,CAAC,EAC1F,EAAO,SAAS,IAAM,EAAO,KAAK,IAAM,EAAS,KAAK,8BAA+B,CAAC,CAAC,CAAC,CAC1F,EACA,EAAM,MAAM,EACb,EAEK,EAAoB,EAAO,GAAG,6BAA6B,EAAE,SAAU,CAC3E,EACA,EACA,CACA,GAAI,EAAQ,OAAO,MAAO,EAAmB,EAAc,CAAM,EACjE,IAAM,EAAa,EAAa,OAAO,CAAC,IACtC,EAAY,YAAY,KAAK,CAAC,IAAe,EAAW,OAAS,YAAY,CAC/E,EACA,GAAI,EAAW,SAAW,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,6BAA6B,CAAC,EAC/F,IAAM,EAAK,MAAO,EAAe,IAC/B,EAAa,CACX,QAAS,qBACT,SAAU,EACV,QAAS,EAAW,IAAI,CAAC,KAAiB,CACxC,MAAO,EAAY,GACnB,MAAO,EAAY,KACnB,KAAM,EAAY,YACf,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACvD,IAAI,CAAC,IAAe,EAAW,KAAK,EACpC,KAAK,IAAI,CACd,EAAE,CACJ,CAAC,CACH,EACA,OAAO,MAAO,EAAmB,EAAY,CAAE,EAChD", | ||
| "debugId": "4B6EAF6059DE1C9364756E2164756E21", | ||
| "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/export.ts"], | ||
| "sourcesContent": [ | ||
| "import { autocomplete, cancel, intro, isCancel, log, outro } from \"@clack/prompts\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { errorMessage } from \"../../util/error\"\n\nexport default Runtime.handler(\n Commands.commands.export,\n Effect.fn(\"cli.export\")((input) =>\n Effect.gen(function* () {\n const requested = Option.getOrUndefined(input.session)\n if (!requested && !process.stdin.isTTY) {\n yield* Effect.fail(new Error(\"Pass a session ID when running without an interactive terminal\"))\n }\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const sessionID = requested\n ? requested\n : yield* Effect.gen(function* () {\n intro(\"Export session\", { output: process.stderr })\n const location = yield* Effect.tryPromise({\n try: () => client.location.get({ location: { directory: process.cwd() } }),\n catch: (cause) => cause,\n })\n const page = yield* Effect.tryPromise({\n try: () =>\n client.session.list({\n directory: location.directory,\n workspace: location.workspaceID,\n parentID: null,\n order: \"desc\",\n limit: 50,\n }),\n catch: (cause) => cause,\n })\n if (page.data.length === 0) {\n log.error(\"No sessions found\", { output: process.stderr })\n outro(\"Done\", { output: process.stderr })\n return undefined\n }\n const selected = yield* Effect.tryPromise({\n try: () =>\n autocomplete({\n message: \"Select session to export\",\n maxItems: 10,\n options: page.data.map((session) => ({\n label: session.title,\n value: session.id,\n hint: `${new Date(session.time.updated).toLocaleString()} - ${session.id.slice(-8)}`,\n })),\n output: process.stderr,\n }),\n catch: (cause) => cause,\n })\n if (isCancel(selected)) {\n cancel(\"Cancelled\", { output: process.stderr })\n process.exitCode = 130\n return undefined\n }\n outro(\"Exporting session...\", { output: process.stderr })\n return selected\n })\n if (!sessionID) return\n const data = yield* Effect.tryPromise({\n try: () => client.session.export({ sessionID, sanitize: input.sanitize }),\n catch: (cause) => cause,\n })\n process.stdout.write(JSON.stringify(data, null, 2) + EOL)\n }).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n ),\n)\n" | ||
| ], | ||
| "mappings": ";utCAIA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,CAAC,IACvB,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAY,EAAO,eAAe,EAAM,OAAO,EACrD,GAAI,CAAC,GAAa,CAAC,QAAQ,MAAM,MAC/B,MAAO,EAAO,KAAS,MAAM,gEAAgE,CAAC,EAEhG,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAAS,EAAS,KAAK,CAC3B,QAAS,EAAO,SAAS,IACzB,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAC1C,CAAC,EACK,EAAY,EACd,EACA,MAAO,EAAO,IAAI,SAAU,EAAG,CAC7B,EAAM,iBAAkB,CAAE,OAAQ,QAAQ,MAAO,CAAC,EAClD,IAAM,EAAW,MAAO,EAAO,WAAW,CACxC,IAAK,IAAM,EAAO,SAAS,IAAI,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,EACzE,MAAO,CAAC,IAAU,CACpB,CAAC,EACK,EAAO,MAAO,EAAO,WAAW,CACpC,IAAK,IACH,EAAO,QAAQ,KAAK,CAClB,UAAW,EAAS,UACpB,UAAW,EAAS,YACpB,SAAU,KACV,MAAO,OACP,MAAO,EACT,CAAC,EACH,MAAO,CAAC,IAAU,CACpB,CAAC,EACD,GAAI,EAAK,KAAK,SAAW,EAAG,CAC1B,EAAI,MAAM,oBAAqB,CAAE,OAAQ,QAAQ,MAAO,CAAC,EACzD,EAAM,OAAQ,CAAE,OAAQ,QAAQ,MAAO,CAAC,EACxC,OAEF,IAAM,EAAW,MAAO,EAAO,WAAW,CACxC,IAAK,IACH,EAAa,CACX,QAAS,2BACT,SAAU,GACV,QAAS,EAAK,KAAK,IAAI,CAAC,KAAa,CACnC,MAAO,EAAQ,MACf,MAAO,EAAQ,GACf,KAAM,GAAG,IAAI,KAAK,EAAQ,KAAK,OAAO,EAAE,eAAe,OAAO,EAAQ,GAAG,MAAM,EAAE,GACnF,EAAE,EACF,OAAQ,QAAQ,MAClB,CAAC,EACH,MAAO,CAAC,IAAU,CACpB,CAAC,EACD,GAAI,EAAS,CAAQ,EAAG,CACtB,EAAO,YAAa,CAAE,OAAQ,QAAQ,MAAO,CAAC,EAC9C,QAAQ,SAAW,IACnB,OAGF,OADA,EAAM,uBAAwB,CAAE,OAAQ,QAAQ,MAAO,CAAC,EACjD,EACR,EACL,GAAI,CAAC,EAAW,OAChB,IAAM,EAAO,MAAO,EAAO,WAAW,CACpC,IAAK,IAAM,EAAO,QAAQ,OAAO,CAAE,YAAW,SAAU,EAAM,QAAS,CAAC,EACxE,MAAO,CAAC,IAAU,CACpB,CAAC,EACD,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAM,KAAM,CAAC,EAAI,CAAG,EACzD,EAAE,KACD,EAAO,MAAM,CAAC,IACZ,EAAO,KAAK,IAAM,CAChB,QAAQ,OAAO,MAAM,EAAa,CAAK,EAAI,CAAG,EAC9C,QAAQ,SAAW,EACpB,CACH,CACF,CACF,CACF", | ||
| "debugId": "DF8E152FF462215A64756E2164756E21", | ||
| "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": ";iWAsBA,SAAS,CAAsB,CAAC,EAAO,CACrC,IAAI,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,MAAO,EACP,KAAM,EAAmB,EACzB,UAAW,CACb,EACA,IAAK,CACP,EAQF,SAAS,CAA2B,CAAC,EAAQ,CAC3C,IAAM,EAAW,CAAC,EAClB,QAAa,OAAM,aAAa,EAC9B,OAAQ,OACD,SAAU,CACb,EAAS,KAAK,CAAE,KAAM,SAAU,SAAQ,CAAC,EACzC,KACF,KACK,WACA,YAAa,CAChB,IAAM,EAAsB,EAAQ,KAClC,CAAC,IAAS,EAAK,OAAS,QAAU,EAAK,UAAU,WAAW,QAAQ,GAAK,EAAK,OAAS,QAAU,EAAK,YAAc,iBACtH,EACM,EAAiB,EAAQ,IAAI,CAAC,EAAM,IAAU,CAClD,IAAI,EACJ,OAAQ,EAAK,UACN,OACH,MAAO,CACL,KAAM,OACN,KAAM,EAAK,IACb,MAEG,OACH,GAAI,EAAK,YAAc,kBACrB,OAAO,EAAK,gBAAgB,IAAM,CAChC,KAAM,WACN,SAAU,CACR,IAAK,EAAK,K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EAAE,OAAO,EAAE,QAAQ,CAC3B,CAAC,CACH,CAAC,EACG,EAAiB,CAAC,IAAS,CAC7B,IAAI,EAAI,EACR,OAAQ,GAAM,EAAK,EAAK,MAAM,UAAY,KAAO,EAAK,EAAK,MAAM,OAAS,KAAO,EAAK,iBAIpF,EAAiB,SAGrB,SAAS,CAAgB,CAAC,EAAU,CAAC,EAAG,CACtC,IAAM,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,qBACzB,YAAa,YACf,CAAC,OACE,EAAQ,OACb,EACA,qBAAqB,GACvB,EACM,EAAsB,CAAC,IAAY,CACvC,IAAI,EACJ,OAAO,IAAI,EAAwB,EAAS,CAC1C,QAAS,GACN,EAAK,EAAQ,UAAY,KAAO,EAAK,2BACxC,EACA,QAAS,EACT,aACA,MAAO,EAAQ,KACjB,CAAC,GAEG,EAAW,CAAC,IAAY,EAAoB,CAAO,EAUzD,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,GAAa,EAAiB", | ||
| "debugId": "BA8F4963C0B1E60964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/ai-gateway-provider@3.1.2+cd874a64d6146f19/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": ";8RAEA,IAAI,EAAgB,CAAC,IACZ,EAAuB,CAC5B,QAAS,8CAET,KAAM,aACH,GAAO,CAAC,CACb,CAAC,EAEC,EAAU,EAAc", | ||
| "debugId": "D929B29958F5239264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "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 endpoint = yield* Service.ensure(yield* ServiceConfig.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 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 \"failed\":\n return `failed: ${status.error}`\n default:\n return status.status\n }\n}\n" | ||
| ], | ||
| "mappings": ";m6BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,KAC/B,EAAO,GAAG,cAAc,EAAE,SAAU,EAAG,CACrC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,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,SACH,MAAO,iBAEP,MAAO,UAIb,SAAS,CAAQ,CAAC,EAA6B,CAC7C,OAAQ,EAAO,YACR,aACH,MAAO,2BACJ,SACH,MAAO,WAAW,EAAO,gBAEzB,OAAO,EAAO", | ||
| "debugId": "89DDBA589AB204AD64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/filesystem.ts"], | ||
| "sourcesContent": [ | ||
| "export * as FileSystem from \"./filesystem.js\"\n\nimport { Schema } from \"effect\"\nimport { optional } from \"./schema.js\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { NonNegativeInt, PositiveInt, RelativePath } from \"./schema.js\"\n\nconst Changed = ephemeral({\n type: \"filesystem.changed\",\n schema: {\n file: Schema.String,\n event: Schema.Literals([\"add\", \"change\", \"unlink\"]),\n },\n})\nexport const Event = { Changed, Definitions: inventory(Changed) }\n\nexport interface Entry extends Schema.Schema.Type<typeof Entry> {}\nexport const Entry = Schema.Struct({\n path: RelativePath,\n type: Schema.Literals([\"file\", \"directory\"]),\n}).annotate({ identifier: \"FileSystem.Entry\" })\n\nexport interface Submatch extends Schema.Schema.Type<typeof Submatch> {}\nexport const Submatch = Schema.Struct({\n text: Schema.String,\n start: NonNegativeInt,\n end: NonNegativeInt,\n}).annotate({ identifier: \"FileSystem.Submatch\" })\n\nexport interface Match extends Schema.Schema.Type<typeof Match> {}\nexport const Match = Schema.Struct({\n entry: Entry,\n line: PositiveInt,\n offset: NonNegativeInt,\n text: Schema.String,\n submatches: Schema.Array(Submatch),\n}).annotate({ identifier: \"FileSystem.Match\" })\n\nexport class FindInput extends Schema.Class<FindInput>(\"FileSystem.FindInput\")({\n query: Schema.String,\n type: Schema.Literals([\"file\", \"directory\"]).pipe(optional),\n limit: PositiveInt.pipe(optional),\n}) {}\n" | ||
| ], | ||
| "mappings": ";oVAOA,IAAM,EAAU,EAAU,CACxB,KAAM,qBACN,OAAQ,CACN,KAAM,EAAO,OACb,MAAO,EAAO,SAAS,CAAC,MAAO,SAAU,QAAQ,CAAC,CACpD,CACF,CAAC,EACY,EAAQ,CAAE,UAAS,YAAa,EAAU,CAAO,CAAE,EAGnD,EAAQ,EAAO,OAAO,CACjC,KAAM,EACN,KAAM,EAAO,SAAS,CAAC,OAAQ,WAAW,CAAC,CAC7C,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAGjC,EAAW,EAAO,OAAO,CACpC,KAAM,EAAO,OACb,MAAO,EACP,IAAK,CACP,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAGpC,EAAQ,EAAO,OAAO,CACjC,MAAO,EACP,KAAM,EACN,OAAQ,EACR,KAAM,EAAO,OACb,WAAY,EAAO,MAAM,CAAQ,CACnC,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAEvC,MAAM,UAAkB,EAAO,MAAiB,sBAAsB,EAAE,CAC7E,MAAO,EAAO,OACd,KAAM,EAAO,SAAS,CAAC,OAAQ,WAAW,CAAC,EAAE,KAAK,CAAQ,EAC1D,MAAO,EAAY,KAAK,CAAQ,CAClC,CAAC,CAAE,CAAC", | ||
| "debugId": "72496D64B9EC26E664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/workspace.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Workspace from \"./workspace.js\"\n\nimport { WorkspaceEvent } from \"./workspace-event.js\"\nimport { WorkspaceID } from \"./workspace-id.js\"\n\nexport const ID = WorkspaceID\nexport type ID = WorkspaceID\n\nexport const Event = WorkspaceEvent\n" | ||
| ], | ||
| "mappings": ";iNAKO,IAAM,EAAK,EAGL,EAAQ", | ||
| "debugId": "EC6A4CF9CD9B09B764756E2164756E21", | ||
| "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": ["src/commands/handlers/debug/config.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"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.debug.commands.config,\n Effect.fn(\"cli.debug.config\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const entries = yield* Effect.promise(() => client.config.get({ location: { directory: process.cwd() } }))\n process.stdout.write(JSON.stringify(entries, null, 2) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";m6BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,OACjC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAU,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,IAAI,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EACzG,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAS,KAAM,CAAC,EAAI,CAAG,EAC5D,CACH", | ||
| "debugId": "D9A4A26C27DF103464756E2164756E21", | ||
| "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": ";wOAAA,cAAS,WACT,oBACA,mBAAS,UAAU,eAAM,oBAOzB,IAAe,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,IAC/B,EAAO,GAAG,aAAa,EAAE,SAAU,CAAC,EAAO,CACzC,IAAM,EAAM,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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": "C982C58DAD932A0264756E2164756E21", | ||
| "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 endpoint = yield* Service.ensure(yield* ServiceConfig.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": ";u9BAAA,cAAS,WAST,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAE7B,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,OAC/B,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAO,CAC5C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,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": "B009A7B1E869B44D64756E2164756E21", | ||
| "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/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 endpoint = yield* Service.ensure(yield* ServiceConfig.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": ";m6BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,OACjC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,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": "6CABE1CEE730303164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/mcp/oauth.ts"], | ||
| "sourcesContent": [ | ||
| "export * as MCPOAuth from \"./oauth.js\"\n\nimport { auth, type OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\"\nimport type { OAuthClientInformationMixed, OAuthTokens } from \"@modelcontextprotocol/sdk/shared/auth.js\"\nimport { Deferred, Effect } from \"effect\"\nimport { Credential } from \"@opencode-ai/schema/credential\"\nimport { ConfigMCP } from \"@opencode-ai/schema/config/mcp\"\nimport { OauthCallbackPage } from \"../oauth/page.js\"\nimport type { Integration } from \"../integration.js\"\n\n/** Persists the OAuth artifacts for one MCP server session: DCR client info, PKCE verifier, and tokens. */\nexport interface Store {\n readonly tokens: () => Promise<OAuthTokens | undefined>\n readonly saveTokens: (tokens: OAuthTokens) => Promise<void>\n readonly clientInformation: () => Promise<OAuthClientInformationMixed | undefined>\n readonly saveClientInformation: (info: OAuthClientInformationMixed) => Promise<void>\n readonly codeVerifier: () => Promise<string | undefined>\n readonly saveCodeVerifier: (verifier: string) => Promise<void>\n}\n\nexport interface Options {\n /** Loopback URL the authorization server redirects back to after the user approves. */\n readonly redirectUrl: string\n /** Space-delimited OAuth scopes to request when the server requires specific ones. */\n readonly scope?: string\n /** CSRF state embedded in the authorization request; required by the spec and enforced by some servers.\n * The caller is responsible for validating the value echoed back to the redirect. */\n readonly state?: string\n /** Statically pre-registered client credentials from config; when set, the SDK skips dynamic registration. */\n readonly client?: { readonly id: string; readonly secret?: string }\n /** Invoked by the SDK to drop credentials it has determined are invalid (e.g. a rejected refresh token). */\n readonly invalidate?: (scope: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\") => void | Promise<void>\n /** Receives the authorization URL so the caller can open a browser and capture the eventual code. */\n readonly onRedirect: (url: URL) => void | Promise<void>\n readonly store: Store\n}\n\n/**\n * Builds the MCP SDK's OAuthClientProvider. The SDK drives dynamic client registration, PKCE, and\n * token refresh through these callbacks; we only persist whatever it hands back via `store`.\n */\nexport const provider = (options: Options): OAuthClientProvider => {\n const state = options.state\n const client = options.client\n return {\n redirectUrl: options.redirectUrl,\n clientMetadata: {\n redirect_uris: [options.redirectUrl],\n client_name: \"opencode\",\n client_uri: \"https://opencode.ai\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: client?.secret ? \"client_secret_post\" : \"none\",\n ...(options.scope ? { scope: options.scope } : {}),\n },\n // Only advertise state when the caller supplied one (the interactive flow); the connect-time\n // provider has no redirect to validate, so it omits it.\n ...(state !== undefined ? { state: () => state } : {}),\n // Static client config short-circuits dynamic registration; otherwise the SDK registers and we persist.\n clientInformation: () =>\n client ? { client_id: client.id, client_secret: client.secret } : options.store.clientInformation(),\n saveClientInformation: (info) => options.store.saveClientInformation(info),\n tokens: () => options.store.tokens(),\n saveTokens: (tokens) => options.store.saveTokens(tokens),\n redirectToAuthorization: (url) => options.onRedirect(url),\n ...(options.invalidate ? { invalidateCredentials: options.invalidate } : {}),\n saveCodeVerifier: (verifier) => options.store.saveCodeVerifier(verifier),\n // The SDK only reads the verifier back after saving one earlier in the same flow; a miss means\n // the flow was resumed without its session state, which the SDK surfaces as an auth failure.\n codeVerifier: async () => {\n const verifier = await options.store.codeVerifier()\n if (!verifier) throw new Error(\"Missing PKCE code verifier for MCP OAuth flow\")\n return verifier\n },\n }\n}\n\n/** A Store that keeps OAuth artifacts in memory for the duration of one interactive login attempt. */\nexport const memoryStore = (): Store => {\n let tokens: OAuthTokens | undefined\n let client: OAuthClientInformationMixed | undefined\n let verifier: string | undefined\n return {\n tokens: async () => tokens,\n saveTokens: async (value) => {\n tokens = value\n },\n clientInformation: async () => client,\n saveClientInformation: async (value) => {\n client = value\n },\n codeVerifier: async () => verifier,\n saveCodeVerifier: async (value) => {\n verifier = value\n },\n }\n}\n\n/** Reads the dynamically-registered client info we stash in a credential's metadata, for token refresh. */\nexport const clientFromCredential = (credential: Credential.OAuth) =>\n credential.metadata?.client as OAuthClientInformationMixed | undefined\n\n/** Folds SDK tokens (plus DCR client info and the server URL) into a storable credential. */\nexport const toCredential = (input: {\n readonly methodID: Integration.MethodID\n readonly serverUrl: string\n readonly tokens: OAuthTokens\n readonly client: OAuthClientInformationMixed | undefined\n}) =>\n Credential.OAuth.make({\n type: \"oauth\",\n methodID: input.methodID,\n access: input.tokens.access_token,\n refresh: input.tokens.refresh_token ?? \"\",\n // 0 marks an unknown/non-expiring token; toTokens then omits expires_in so the SDK won't force a refresh.\n expires: input.tokens.expires_in ? Date.now() + input.tokens.expires_in * 1000 : 0,\n metadata: {\n serverUrl: input.serverUrl,\n tokenType: input.tokens.token_type,\n ...(input.tokens.scope ? { scope: input.tokens.scope } : {}),\n ...(input.client ? { client: input.client } : {}),\n },\n })\n\n/** Reconstructs SDK tokens from a stored credential so the connect-time provider can present them. */\nexport const toTokens = (credential: Credential.OAuth): OAuthTokens => {\n const metadata = credential.metadata ?? {}\n return {\n access_token: credential.access,\n token_type: typeof metadata.tokenType === \"string\" ? metadata.tokenType : \"Bearer\",\n ...(credential.refresh ? { refresh_token: credential.refresh } : {}),\n ...(credential.expires ? { expires_in: Math.max(0, Math.floor((credential.expires - Date.now()) / 1000)) } : {}),\n ...(typeof metadata.scope === \"string\" ? { scope: metadata.scope } : {}),\n }\n}\n\n/**\n * Runs the interactive OAuth login for one remote MCP server. Stands up a loopback callback server,\n * lets the SDK drive DCR + PKCE to produce an authorization URL, and returns an attempt whose callback\n * exchanges the redirect code for a storable credential. Scoped: the callback server closes with the scope.\n */\nexport const authorize = (input: {\n readonly name: string\n readonly config: typeof ConfigMCP.Remote.Type\n readonly methodID: Integration.MethodID\n}) =>\n Effect.gen(function* () {\n const oauth = input.config.oauth || undefined\n const store = memoryStore()\n const code = yield* Deferred.make<string, Error>()\n const redirect = oauth?.redirect_uri ? new URL(oauth.redirect_uri) : undefined\n const redirectPath = redirect?.pathname ?? \"/callback\"\n const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(\"base64url\")\n\n // Lazy so runtimes without a loopback listener (workerd) never evaluate node:http.\n const { createServer } = yield* Effect.promise(() => import(\"node:http\"))\n const server = createServer((request, response) => {\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\")\n if (url.pathname !== redirectPath) {\n response.writeHead(404).end(\"Not found\")\n return\n }\n const fail = (reason: string) => {\n Effect.runFork(Deferred.fail(code, new Error(reason)))\n response\n .writeHead(400, { \"Content-Type\": \"text/html\" })\n .end(OauthCallbackPage.error(reason, { provider: input.name }))\n }\n const error = url.searchParams.get(\"error_description\") ?? url.searchParams.get(\"error\")\n if (error) return fail(error)\n // Reject a redirect whose state does not match what we issued: this is the CSRF defense the\n // state parameter exists for, so an attacker can't inject their own authorization code.\n if (url.searchParams.get(\"state\") !== state) return fail(\"OAuth state mismatch\")\n const value = url.searchParams.get(\"code\")\n if (!value) return fail(\"Missing authorization code\")\n Effect.runFork(Deferred.succeed(code, value))\n response.writeHead(200, { \"Content-Type\": \"text/html\" }).end(OauthCallbackPage.success({ provider: input.name }))\n })\n\n // Bind the port the redirect will actually arrive on: an explicit callback_port wins, else the port\n // pinned by redirect_uri, else an ephemeral port. Binding ephemerally while redirect_uri names a fixed\n // port would send the browser somewhere nothing is listening, hanging the attempt until it expires.\n const redirectPort = Number(redirect?.port) || undefined\n const port = yield* Effect.callback<number, Error>((resume) => {\n server.once(\"error\", (error) => resume(Effect.fail(error)))\n server.listen(oauth?.callback_port ?? redirectPort ?? 0, \"127.0.0.1\", () => {\n const address = server.address()\n resume(\n address && typeof address === \"object\"\n ? Effect.succeed(address.port)\n : Effect.fail(new Error(\"Could not determine MCP OAuth callback port\")),\n )\n })\n })\n yield* Effect.addFinalizer(() => Effect.sync(() => server.close()))\n\n let authorizationUrl: URL | undefined\n const oauthProvider = provider({\n redirectUrl: oauth?.redirect_uri ?? `http://127.0.0.1:${port}${redirectPath}`,\n scope: oauth?.scope,\n state,\n client: oauth?.client_id ? { id: oauth.client_id, secret: oauth.client_secret } : undefined,\n onRedirect: (url) => {\n authorizationUrl = url\n },\n store,\n })\n\n const finalize = Effect.gen(function* () {\n const tokens = yield* Effect.promise(() => store.tokens())\n if (!tokens) return yield* Effect.fail(new Error(`MCP server \"${input.name}\" did not return OAuth tokens`))\n const client = yield* Effect.promise(() => store.clientInformation())\n return toCredential({ methodID: input.methodID, serverUrl: input.config.url, tokens, client })\n })\n\n const result = yield* Effect.tryPromise({\n try: () => auth(oauthProvider, { serverUrl: input.config.url, scope: oauth?.scope }),\n catch: (error) => (error instanceof Error ? error : new Error(String(error))),\n })\n\n // The provider may already hold valid tokens (e.g. a re-auth), in which case there is no browser step.\n if (result === \"AUTHORIZED\") {\n return {\n url: input.config.url,\n instructions: `Connected to ${input.name}.`,\n mode: \"auto\" as const,\n callback: finalize,\n }\n }\n if (!authorizationUrl)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" did not provide an authorization URL`))\n\n return {\n url: authorizationUrl.toString(),\n instructions: `Authorize ${input.name} in your browser. This window will close automatically.`,\n mode: \"auto\" as const,\n callback: Deferred.await(code).pipe(\n Effect.flatMap((value) =>\n Effect.tryPromise({\n try: () =>\n auth(oauthProvider, { serverUrl: input.config.url, authorizationCode: value, scope: oauth?.scope }),\n catch: (error) => (error instanceof Error ? error : new Error(String(error))),\n }),\n ),\n Effect.flatMap(() => finalize),\n ),\n }\n })\n" | ||
| ], | ||
| "mappings": ";omBAyCO,IAAM,EAAW,CAAC,IAA0C,CACjE,IAAsB,MAAhB,EACiB,OAAjB,GAAS,EACf,MAAO,CACL,YAAa,EAAQ,YACrB,eAAgB,CACd,cAAe,CAAC,EAAQ,WAAW,EACnC,YAAa,WACb,WAAY,sBACZ,YAAa,CAAC,qBAAsB,eAAe,EACnD,eAAgB,CAAC,MAAM,EACvB,2BAA4B,GAAQ,OAAS,qBAAuB,UAChE,EAAQ,MAAQ,CAAE,MAAO,EAAQ,KAAM,EAAI,CAAC,CAClD,KAGI,IAAU,OAAY,CAAE,MAAO,IAAM,CAAM,EAAI,CAAC,EAEpD,kBAAmB,IACjB,EAAS,CAAE,UAAW,EAAO,GAAI,cAAe,EAAO,MAAO,EAAI,EAAQ,MAAM,kBAAkB,EACpG,sBAAuB,CAAC,IAAS,EAAQ,MAAM,sBAAsB,CAAI,EACzE,OAAQ,IAAM,EAAQ,MAAM,OAAO,EACnC,WAAY,CAAC,IAAW,EAAQ,MAA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AK,CAAC,CAC7E,CAAC,KAGc,aACb,MAAO,CACL,IAAK,EAAM,OAAO,IAClB,aAAc,gBAAgB,EAAM,QACpC,KAAM,OACN,SAAU,CACZ,EAEF,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,eAAe,EAAM,4CAA4C,CAAC,EAExG,MAAO,CACL,IAAK,EAAiB,SAAS,EAC/B,aAAc,aAAa,EAAM,8DACjC,KAAM,OACN,SAAU,EAAS,MAAM,CAAI,EAAE,KAC7B,EAAO,QAAQ,CAAC,IACd,EAAO,WAAW,CAChB,IAAK,IACH,EAAK,EAAe,CAAE,UAAW,EAAM,OAAO,IAAK,kBAAmB,EAAO,MAAO,GAAO,KAAM,CAAC,EACpG,MAAO,CAAC,IAAW,aAAiB,MAAQ,EAAY,MAAM,OAAO,CAAK,CAAC,CAC7E,CAAC,CACH,EACA,EAAO,QAAQ,IAAM,CAAQ,CAC/B,CACF,EACD", | ||
| "debugId": "ADF7E47571B864CE64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/server-process.ts", "src/services/service-registration.ts", "src/services/web-ui.ts", "src/app-assets.ts", "src/commands/handlers/serve.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ServerProcess from \"./server-process\"\n\nimport { NodeServices } from \"@effect/platform-node\"\nimport { Service, type DiscoverOptions } 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 { Effect, Option, Redacted, Schedule } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { Env } from \"./env\"\nimport { ServiceConfig } from \"./services/service-config\"\nimport { ServiceRegistration } from \"./services/service-registration\"\nimport { Updater } from \"./services/updater\"\nimport { WebUi } from \"./services/web-ui\"\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 const global = yield* Global.Service\n if (options.mode === \"service\") yield* Effect.sync(() => process.chdir(global.home))\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const foreground = options.mode === \"default\"\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 const incumbent =\n serviceOptions !== undefined && port !== undefined\n ? yield* Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })\n : undefined\n if (incumbent !== undefined) 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 transform = yield* WebUi.handler()\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\", \"dev\", \"beta\", \"next\", \"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 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(process.env.OPENCODE_FILEWATCHER_DISABLE ?? process.env.OPENCODE_DISABLE_FILEWATCHER),\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 onListen: (address, shutdown) =>\n Effect.gen(function* () {\n if (!config.password) yield* ServiceConfig.password(password)\n return yield* ServiceRegistration.register({\n address,\n password,\n id: instanceID,\n file: serviceOptions.file,\n shutdown,\n })\n }),\n },\n transform,\n ).pipe(\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 (foreground && !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 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", | ||
| "export * as ServiceRegistration from \"./service-registration\"\n\nimport { Service, type Info } from \"@opencode-ai/client/effect/service\"\nimport path from \"node:path\"\nimport { Effect, FileSystem, Schedule, Schema } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { OPENCODE_VERSION } from \"../version\"\n\nconst infoJson = Schema.fromJsonString(Service.Info)\nconst encodeInfo = Schema.encodeEffect(infoJson)\nconst decodeInfo = Schema.decodeUnknownEffect(infoJson)\n\nexport const register = Effect.fnUntraced(function* (options: {\n readonly address: HttpServer.Address\n readonly password: string\n readonly id: string\n readonly file: string\n readonly shutdown: Effect.Effect<void>\n}) {\n const fs = yield* FileSystem.FileSystem\n const temp = options.file + \".\" + options.id + \".tmp\"\n yield* fs.makeDirectory(path.dirname(options.file), { recursive: true })\n const info = {\n id: options.id,\n version: OPENCODE_VERSION,\n url: HttpServer.formatAddress(options.address),\n pid: process.pid,\n password: options.password,\n }\n const encoded = yield* encodeInfo(info)\n const current = fs.readFileString(options.file).pipe(Effect.flatMap(decodeInfo))\n const owns = (found: Info) =>\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, options.file)))\n yield* current.pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(\"managed service registration check failed; shutting down\", {\n cause,\n serviceID: options.id,\n servicePID: process.pid,\n registration: options.file,\n }).pipe(Effect.andThen(Effect.failCause(cause))),\n ),\n Effect.tap((found) =>\n owns(found)\n ? Effect.void\n : Effect.logWarning(\"managed service registration replaced; shutting down\", {\n serviceID: options.id,\n servicePID: process.pid,\n registration: options.file,\n observedServiceID: found.id,\n observedServicePID: found.pid,\n observedVersion: found.version,\n observedURL: found.url,\n }),\n ),\n Effect.filterOrFail(owns),\n Effect.repeat(Schedule.spaced(\"5 seconds\")),\n Effect.ignore,\n Effect.andThen(options.shutdown),\n Effect.forkScoped,\n )\n return current.pipe(\n Effect.flatMap((found) => (owns(found) ? fs.remove(options.file) : Effect.void)),\n Effect.ignore,\n )\n})\n", | ||
| "import { FSUtil } from \"@opencode-ai/util/fs-util\"\nimport { Effect, FileSystem } from \"effect\"\nimport { HttpServerError, HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\"\nimport { createHash } from \"node:crypto\"\nimport { load, type AssetMap } from \"../app-assets\"\n\nexport const handler = Effect.fn(\"cli.web-ui.handler\")(function* (options?: { readonly assets?: AssetMap }) {\n const fileSystem = yield* FileSystem.FileSystem\n const assets = options?.assets\n ? Effect.succeed(options.assets)\n : yield* Effect.cached(load().pipe(Effect.provideService(FileSystem.FileSystem, fileSystem)))\n return <E, R>(api: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>) =>\n api.pipe(\n Effect.catchIf(isRouteNotFound, () =>\n HttpServerRequest.HttpServerRequest.pipe(\n Effect.flatMap((request) => {\n const url = new URL(request.url, \"http://localhost\")\n if (url.pathname === \"/api\" || url.pathname.startsWith(\"/api/\"))\n return Effect.succeed(HttpServerResponse.empty({ status: 404 }))\n return assets.pipe(Effect.flatMap((files) => serveUI(request, url, files)))\n }),\n ),\n ),\n )\n})\n\nfunction serveUI(request: HttpServerRequest.HttpServerRequest, url: URL, assets: AssetMap) {\n const key = url.pathname.replace(/^\\//, \"\")\n const name = assets[key] !== undefined ? key : \"index.html\"\n const file = assets[name]\n if (!file) return Effect.succeed(HttpServerResponse.empty({ status: 404 }))\n if (request.method !== \"GET\" && request.method !== \"HEAD\")\n return Effect.succeed(HttpServerResponse.empty({ status: 405 }))\n const html = name === \"index.html\"\n const revalidate = html || name === \"sw.js\" || name === \"registerSW.js\"\n const headers = {\n \"content-type\": FSUtil.mimeType(name),\n \"cache-control\": revalidate ? \"no-cache\" : \"public, max-age=31536000, immutable\",\n \"content-security-policy\": html\n ? cspForHtml(typeof file === \"string\" ? file : Buffer.from(file).toString())\n : csp(),\n \"x-content-type-options\": \"nosniff\",\n }\n return Effect.succeed(\n request.method === \"HEAD\"\n ? HttpServerResponse.empty({ headers })\n : HttpServerResponse.raw(file, { headers, contentType: headers[\"content-type\"] }),\n )\n}\n\nfunction isRouteNotFound(error: unknown) {\n return error instanceof HttpServerError.HttpServerError && error.reason._tag === \"RouteNotFound\"\n}\n\nfunction csp(hash = \"\") {\n return `default-src 'self'; script-src 'self' 'wasm-unsafe-eval'${hash ? ` 'sha256-${hash}'` : \"\"}; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: blob:; font-src 'self' data:; media-src 'self' data:; connect-src * data: blob:`\n}\n\nfunction cspForHtml(body: string) {\n const match = body.match(\n /<script\\b(?![^>]*\\bsrc\\s*=)[^>]*\\bid=([\"'])oc-theme-preload-script\\1[^>]*>([\\s\\S]*?)<\\/script>/i,\n )\n return csp(match ? createHash(\"sha256\").update(match[2]).digest(\"base64\") : \"\")\n}\n\nexport * as WebUi from \"./web-ui\"\n", | ||
| "import { Effect, FileSystem, Option } from \"effect\"\nimport path from \"node:path\"\nimport { brotliDecompressSync } from \"node:zlib\"\nimport { OPENCODE_LOCAL } from \"./version\"\n\nexport type AssetMap = Readonly<Record<string, string | Uint8Array>>\ntype EncodedAssetMap = Readonly<Record<string, { readonly content: string; readonly encoding: \"utf8\" | \"base64\" }>>\n\nexport const load = Effect.fn(\"cli.app-assets.load\")(function* () {\n const embedded = yield* Effect.tryPromise(() => import(\"virtual:opencode-app-assets\")).pipe(Effect.option)\n if (Option.isSome(embedded) && embedded.value.default.length > 0) return decodeArchive(embedded.value.default)\n if (!OPENCODE_LOCAL) return yield* Effect.fail(new Error(\"Web UI assets are missing from the CLI build\"))\n return decode(yield* sourceAssets())\n})\n\nfunction decodeArchive(archive: string) {\n const body = brotliDecompressSync(Buffer.from(archive, \"base64\")).toString()\n return decode(JSON.parse(body) as EncodedAssetMap)\n}\n\nconst sourceAssets = Effect.fnUntraced(function* () {\n const fs = yield* FileSystem.FileSystem\n const root = path.resolve(import.meta.dirname, \"../../app/dist\")\n const files = yield* fs.readDirectory(root, { recursive: true })\n return Object.fromEntries(\n (yield* Effect.forEach(\n files.filter((file) => !file.endsWith(\".map\")),\n Effect.fnUntraced(function* (file) {\n const target = path.join(root, file)\n if ((yield* fs.stat(target)).type === \"Directory\") return\n const body = Buffer.from(yield* fs.readFile(target))\n const encoding = isText(file) ? \"utf8\" : \"base64\"\n return [file, { encoding, content: body.toString(encoding) }] as const\n }),\n { concurrency: \"unbounded\" },\n )).filter((asset) => asset !== undefined),\n )\n})\n\nfunction decode(assets: EncodedAssetMap): AssetMap {\n return Object.fromEntries(\n Object.entries(assets).map(([key, asset]) => [\n key,\n asset.encoding === \"utf8\" ? asset.content : Buffer.from(asset.content, \"base64\"),\n ]),\n )\n}\n\nfunction isText(file: string) {\n return file === \"_headers\" || /\\.(?:css|html|js|json|svg|txt|webmanifest|xml)$/.test(file)\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": ";urCAQA,sBAAS,gBAAa,0ECLtB,qBAKA,IAAM,EAAW,EAAO,eAAe,EAAQ,IAAI,EAC7C,GAAa,EAAO,aAAa,CAAQ,EACzC,GAAa,EAAO,oBAAoB,CAAQ,EAEzC,GAAW,EAAO,WAAW,SAAU,CAAC,EAMlD,CACD,IAAM,EAAK,MAAO,EAAW,WACvB,EAAO,EAAQ,KAAO,IAAM,EAAQ,GAAK,OAC/C,MAAO,EAAG,cAAc,GAAK,QAAQ,EAAQ,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EACvE,IAAM,EAAO,CACX,GAAI,EAAQ,GACZ,QAAS,EACT,IAAK,EAAW,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InMH,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": "6520F46A7B01089964756E2164756E21", | ||
| "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/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(\n (yield* ServiceConfig.get(Option.getOrUndefined(input.key), Option.getOrUndefined(input.name))) + EOL,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";02BAAA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,IACnC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,QAAQ,OAAO,OACZ,MAAO,EAAc,IAAI,EAAO,eAAe,EAAM,GAAG,EAAG,EAAO,eAAe,EAAM,IAAI,CAAC,GAAK,CACpG,EACD,CACH", | ||
| "debugId": "214EE17A0676E5AB64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/shared.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { OpenCode, type IntegrationInfo, type IntegrationMethod, type OpenCodeClient } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServerConnection } from \"../../../services/server-connection\"\n\nexport const location = { directory: process.cwd() }\n\nexport const createClient = Effect.fn(\"cli.auth.client\")(function* (input: ServerConnection.Args) {\n const server = yield* ServerConnection.resolve(input)\n return OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) })\n})\n\nexport function request<A>(run: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({ try: run, catch: (cause) => cause })\n}\n\nexport const loadIntegrations = Effect.fn(\"cli.auth.integrations\")(function* (client: OpenCodeClient) {\n // The model endpoint is the existing public readiness boundary for the initial plugin generation.\n yield* request((signal) => client.model.default({ location }, { signal }))\n return yield* request((signal) => client.integration.list({ location }, { signal })).pipe(\n Effect.map((response) => response.data),\n )\n})\n\nexport const resolveIntegration = Effect.fn(\"cli.auth.resolve-integration\")(function* (\n integrations: IntegrationInfo[],\n target: string,\n) {\n const normalized = target.replace(/\\/+$/, \"\")\n const byID = integrations.find((integration) => integration.id === normalized)\n if (byID) return byID\n const matches = integrations.filter((integration) => integration.name.toLowerCase() === normalized.toLowerCase())\n if (matches.length === 1) return matches[0]\n if (matches.length > 1) {\n return yield* Effect.fail(\n new Error(\n `Integration name \"${target}\" is ambiguous: ${matches.map((integration) => integration.id).join(\", \")}`,\n ),\n )\n }\n return yield* Effect.fail(new Error(`Integration not found: ${target}`))\n})\n\nexport type ConnectMethod = Exclude<IntegrationMethod, { type: \"env\" }>\n\nexport function connectMethods(integration: IntegrationInfo) {\n return integration.methods\n .filter((method): method is ConnectMethod => method.type !== \"env\")\n .toSorted((a, b) => Number(a.type === \"key\") - Number(b.type === \"key\"))\n}\n\nexport const resolveMethod = Effect.fn(\"cli.auth.resolve-method\")(function* (methods: ConnectMethod[], target: string) {\n const normalized = target.toLowerCase()\n const matches = methods.filter((method) => {\n if (method.type === \"key\") return normalized === \"key\" || method.label?.toLowerCase() === normalized\n return method.id === target || method.label.toLowerCase() === normalized\n })\n if (matches.length === 1) return matches[0]\n if (matches.length > 1) return yield* Effect.fail(new Error(`Authentication method \"${target}\" is ambiguous`))\n const available = methods.map((method) => (method.type === \"key\" ? \"key\" : method.id)).join(\", \")\n return yield* Effect.fail(\n new Error(`Authentication method not found: ${target}${available ? `. Available: ${available}` : \"\"}`),\n )\n})\n" | ||
| ], | ||
| "mappings": ";gNAKO,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAEtC,EAAe,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAA8B,CAChG,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAAK,EACpD,OAAO,EAAS,KAAK,CAAE,QAAS,EAAO,SAAS,IAAK,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAAE,CAAC,EACjG,EAEM,SAAS,CAAU,CAAC,EAA0C,CACnE,OAAO,EAAO,WAAW,CAAE,IAAK,EAAK,MAAO,CAAC,IAAU,CAAM,CAAC,EAGzD,IAAM,EAAmB,EAAO,GAAG,uBAAuB,EAAE,SAAU,CAAC,EAAwB,CAGpG,OADA,MAAO,EAAQ,CAAC,IAAW,EAAO,MAAM,QAAQ,CAAE,UAAS,EAAG,CAAE,QAAO,CAAC,CAAC,EAClE,MAAO,EAAQ,CAAC,IAAW,EAAO,YAAY,KAAK,CAAE,UAAS,EAAG,CAAE,QAAO,CAAC,CAAC,EAAE,KACnF,EAAO,IAAI,CAAC,IAAa,EAAS,IAAI,CACxC,EACD,EAEY,EAAqB,EAAO,GAAG,8BAA8B,EAAE,SAAU,CACpF,EACA,EACA,CACA,IAAM,EAAa,EAAO,QAAQ,OAAQ,EAAE,EACtC,EAAO,EAAa,KAAK,CAAC,IAAgB,EAAY,KAAO,CAAU,EAC7E,GAAI,EAAM,OAAO,EACjB,IAAM,EAAU,EAAa,OAAO,CAAC,IAAgB,EAAY,KAAK,YAAY,IAAM,EAAW,YAAY,CAAC,EAChH,GAAI,EAAQ,SAAW,EAAG,OAAO,EAAQ,GACzC,GAAI,EAAQ,OAAS,EACnB,OAAO,MAAO,EAAO,KACf,MACF,qBAAqB,oBAAyB,EAAQ,IAAI,CAAC,IAAgB,EAAY,EAAE,EAAE,KAAK,IAAI,GACtG,CACF,EAEF,OAAO,MAAO,EAAO,KAAS,MAAM,0BAA0B,GAAQ,CAAC,EACxE,EAIM,SAAS,CAAc,CAAC,EAA8B,CAC3D,OAAO,EAAY,QAChB,OAAO,CAAC,IAAoC,EAAO,OAAS,KAAK,EACjE,SAAS,CAAC,EAAG,IAAM,OAAO,EAAE,OAAS,KAAK,EAAI,OAAO,EAAE,OAAS,KAAK,CAAC,EAGpE,IAAM,EAAgB,EAAO,GAAG,yBAAyB,EAAE,SAAU,CAAC,EAA0B,EAAgB,CACrH,IAAM,EAAa,EAAO,YAAY,EAChC,EAAU,EAAQ,OAAO,CAAC,IAAW,CACzC,GAAI,EAAO,OAAS,MAAO,OAAO,IAAe,OAAS,EAAO,OAAO,YAAY,IAAM,EAC1F,OAAO,EAAO,KAAO,GAAU,EAAO,MAAM,YAAY,IAAM,EAC/D,EACD,GAAI,EAAQ,SAAW,EAAG,OAAO,EAAQ,GACzC,GAAI,EAAQ,OAAS,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,0BAA0B,iBAAsB,CAAC,EAC7G,IAAM,EAAY,EAAQ,IAAI,CAAC,IAAY,EAAO,OAAS,MAAQ,MAAQ,EAAO,EAAG,EAAE,KAAK,IAAI,EAChG,OAAO,MAAO,EAAO,KACf,MAAM,oCAAoC,IAAS,EAAY,gBAAgB,IAAc,IAAI,CACvG,EACD", | ||
| "debugId": "873222A377ABD3A964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "6570C12E689233DF64756E2164756E21", | ||
| "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": ";wUAYA,IAAI,EAAiB,SAGrB,SAAS,CAAY,CAAC,EAAU,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,IAChB,IAAI,EAAkC,EAAS,IACjD,EAAqB,MAAM,CAChC,CAAC,EAEG,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": "7114E7733028FD1164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/command.ts", "../schema/src/websearch.ts", "../schema/src/reference.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Command from \"./command.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.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 description: Schema.String.pipe(optional),\n}).annotate({ identifier: \"Command.Info\" })\n\nexport const Event = {\n Updated,\n Definitions: inventory(Updated),\n}\n", | ||
| "export * as WebSearch from \"./websearch.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.js\"\n\nexport const ID = Schema.String.pipe(Schema.brand(\"WebSearch.ID\"))\nexport type ID = typeof ID.Type\n\nexport interface Provider extends Schema.Schema.Type<typeof Provider> {}\nexport const Provider = Schema.Struct({\n id: ID,\n name: Schema.String,\n}).annotate({ identifier: \"WebSearch.Provider\" })\n\nexport interface Input extends Schema.Schema.Type<typeof Input> {}\nexport const Input = Schema.Struct({\n query: Schema.String,\n providerID: ID.pipe(optional),\n}).annotate({ identifier: \"WebSearch.Input\" })\nexport type ProviderInput = Pick<Input, \"query\">\n\nexport interface Result extends Schema.Schema.Type<typeof Result> {}\nexport const Result = Schema.Struct({\n url: Schema.String,\n title: Schema.String.pipe(optional),\n content: Schema.String.pipe(optional),\n time: Schema.Struct({\n published: Schema.Finite.pipe(optional),\n }),\n}).annotate({ identifier: \"WebSearch.Result\" })\n\nexport class Response extends Schema.Class<Response>(\"WebSearch.Response\")({\n providerID: ID,\n results: Schema.Array(Result),\n}) {}\n\nconst Updated = ephemeral({\n type: \"websearch.updated\",\n schema: {},\n})\nexport const Event = { Updated, Definitions: inventory(Updated) }\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": ";qRAMA,IAAM,EAAU,EAAU,CAAE,KAAM,kBAAmB,OAAQ,CAAC,CAAE,CAAC,EAGpD,EAAO,EAAO,OAAO,CAChC,KAAM,EAAO,OACb,YAAa,EAAO,OAAO,KAAK,CAAQ,CAC1C,CAAC,EAAE,SAAS,CAAE,WAAY,cAAe,CAAC,EAE7B,EAAQ,CACnB,UACA,YAAa,EAAU,CAAO,CAChC,8GCXO,IAAM,EAAK,EAAO,OAAO,KAAK,EAAO,MAAM,cAAc,CAAC,EAIpD,EAAW,EAAO,OAAO,CACpC,GAAI,EACJ,KAAM,EAAO,MACf,CAAC,EAAE,SAAS,CAAE,WAAY,oBAAqB,CAAC,EAGnC,EAAQ,EAAO,OAAO,CACjC,MAAO,EAAO,OACd,WAAY,EAAG,KAAK,CAAQ,CAC9B,CAAC,EAAE,SAAS,CAAE,WAAY,iBAAkB,CAAC,EAIhC,EAAS,EAAO,OAAO,CAClC,IAAK,EAAO,OACZ,MAAO,EAAO,OAAO,KAAK,CAAQ,EAClC,QAAS,EAAO,OAAO,KAAK,CAAQ,EACpC,KAAM,EAAO,OAAO,CAClB,UAAW,EAAO,OAAO,KAAK,CAAQ,CACxC,CAAC,CACH,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAEvC,MAAM,UAAiB,EAAO,MAAgB,oBAAoB,EAAE,CACzE,WAAY,EACZ,QAAS,EAAO,MAAM,CAAM,CAC9B,CAAC,CAAE,CAAC,CAEJ,IAAM,EAAU,EAAU,CACxB,KAAM,oBACN,OAAQ,CAAC,CACX,CAAC,EACY,EAAQ,CAAE,UAAS,YAAa,EAAU,CAAO,CAAE,wGClChE,IAAM,EAAU,EAAU,CAAE,KAAM,oBAAqB,OAAQ,CAAC,CAAE,CAAC,EACtD,EAAQ,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,EAAO,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": "24215781D61D1B3C64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/stats.ts"], | ||
| "sourcesContent": [ | ||
| "import { ClientError, OpenCode, type SessionStatsInfo } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { errorMessage } from \"../../util/error\"\n\nconst handler = Effect.fn(\"cli.stats\")(function* (input: Runtime.Input<typeof Commands.commands.stats>) {\n const days = Option.getOrUndefined(input.days)\n const year = Option.getOrUndefined(input.year)\n const project = Option.getOrUndefined(input.project)\n if ([days !== undefined, year !== undefined, input.all].filter(Boolean).length > 1)\n yield* Effect.fail(new Error(\"--days, --year, and --all cannot be combined\"))\n\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) })\n const range = statsRange({ days, year, all: input.all })\n const projectID =\n project === \".\"\n ? yield* request(server.endpoint.url, (signal) =>\n client.location\n .get({ location: { directory: process.cwd() } }, { signal })\n .then((location) => location.project.id),\n )\n : project\n const details = input.models || input.tools || input.cost || input.full\n const stats = yield* request(server.endpoint.url, (signal) =>\n client.session.stats(\n {\n from: range.from,\n to: range.to,\n project: projectID,\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\",\n tools: input.json || input.tools || input.full ? \"detail\" : details ? \"none\" : \"summary\",\n },\n { signal },\n ),\n )\n const output = input.json\n ? JSON.stringify(stats, null, 2)\n : renderStats(stats, {\n label: range.label,\n scope: project === undefined ? \"all projects\" : project === \".\" ? \"current project\" : \"selected project\",\n models: input.models || input.full,\n tools: input.tools || input.full,\n cost: input.cost || input.full,\n limit: input.limit,\n color: process.stdout.isTTY && process.env.NO_COLOR === undefined,\n width: process.stdout.columns ?? 80,\n })\n process.stdout.write(output + EOL)\n})\n\nexport default Runtime.handler(Commands.commands.stats, (input) =>\n handler(input).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n)\n\nexport function request<A>(url: string, run: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: () => run(AbortSignal.timeout(30_000)),\n catch: (cause) =>\n cause instanceof ClientError && cause.reason === \"Transport\"\n ? new Error(`Could not reach server at ${url}`, { cause })\n : cause,\n })\n}\n\ntype RenderOptions = {\n label: string\n scope: string\n models: boolean\n tools: boolean\n cost: boolean\n limit: number\n color: boolean\n width: number\n}\n\nconst colors = terminalPalette()\n\nexport function renderStats(stats: SessionStatsInfo, options: RenderOptions) {\n const totalTokens = tokenTotal(stats.tokens)\n const toolTotals = stats.tools.mode === \"none\" ? undefined : stats.tools.totals\n const terminalTools = toolTotals ? toolTotals.succeeded + toolTotals.failed : 0\n const toolRate = !toolTotals || terminalTools === 0 ? undefined : (toolTotals.succeeded / terminalTools) * 100\n const primary = `1;${colors.primary}`\n const sessionLine = [\n metricCount(stats.sessions, \"session\", options.color),\n stats.subagents > 0 ? metricCount(stats.subagents, \"subagent\", options.color) : undefined,\n ]\n .filter((value) => value !== undefined)\n .join(\" · \")\n const toolSummary = !toolTotals\n ? \"tool stats unavailable\"\n : toolRate === undefined\n ? \"no tool calls\"\n : `${style(formatPercent(toolRate), primary, options.color)} tool success`\n const details = options.models || options.tools || options.cost\n const empty = stats.sessions === 0 && stats.prompts === 0 && stats.steps === 0\n const heading = `${style(\"opencode stats\", primary, options.color)} ${style(`· ${options.label} · ${options.scope}`, \"2\", options.color)}`\n const lines = details\n ? [style(`${options.label} · ${options.scope}`, \"2\", options.color)]\n : empty\n ? [\n heading,\n \"\",\n style(\"no activity in this range\", \"2\", options.color),\n \"\",\n style(\"opencode.ai\", \"2\", options.color),\n ]\n : [\n heading,\n \"\",\n ...renderActivity(stats.activity, stats.range.from, stats.range.to, options.color, options.width),\n \"\",\n sessionLine,\n `${metricCount(stats.prompts, \"prompt\", options.color)} · ${metricCount(stats.steps, \"step\", options.color)} · ${metricCount(totalTokens, \"token\", options.color)}`,\n `${toolSummary} · ${metricCount(stats.activeDays, \"active day\", options.color)} · best streak ${style(stats.streak.toString(), primary, options.color)} day${stats.streak === 1 ? \"\" : \"s\"}`,\n \"\",\n style(\"opencode.ai\", \"2\", options.color),\n ]\n\n if (options.cost) lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderCost(stats))\n if (options.models)\n lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderModels(stats, options.limit, options.width))\n if (options.tools) lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderTools(stats, options.limit, options.width))\n return lines.join(EOL)\n}\n\nfunction statsRange(input: { days?: number; year?: number; all: boolean }) {\n const now = new Date()\n const to = now.getTime() + 1\n if (input.all) return { from: undefined, to, label: \"all time\" }\n if (input.days !== undefined) {\n const from = new Date(now.getFullYear(), now.getMonth(), now.getDate())\n from.setDate(from.getDate() - Math.max(0, input.days - 1))\n return {\n from: from.getTime(),\n to,\n label: input.days === 0 || input.days === 1 ? \"today\" : `last ${input.days} days`,\n }\n }\n const year = input.year ?? now.getFullYear()\n return {\n from: new Date(year, 0, 1).getTime(),\n to: year === now.getFullYear() ? to : new Date(year + 1, 0, 1).getTime(),\n label: year === now.getFullYear() ? `${year} so far` : year.toString(),\n }\n}\n\nfunction renderActivity(\n activity: SessionStatsInfo[\"activity\"],\n from: number,\n to: number,\n color: boolean,\n width: number,\n) {\n const values = new Map(activity.map((day) => [day.date, day.steps]))\n const rangeStart = dateOrdinal(new Date(from))\n const rangeEnd = dateOrdinal(new Date(to - 1))\n const end = new Date(to - 1)\n end.setHours(12, 0, 0, 0)\n end.setDate(end.getDate() + (7 - mondayIndex(end) - 1))\n const start = new Date(from)\n start.setHours(12, 0, 0, 0)\n start.setDate(start.getDate() - mondayIndex(start))\n const maxWeeks = Math.max(1, Math.min(53, width - 4))\n const totalWeeks = Math.floor((dateOrdinal(end) - dateOrdinal(start)) / 7) + 1\n const latest = new Date(end)\n latest.setDate(latest.getDate() - (maxWeeks - 1) * 7)\n if (start < latest) start.setTime(latest.getTime())\n\n const active = [...values.values()].filter((value) => value > 0)\n const levels = [...new Set(active)].sort((a, b) => a - b)\n const weekStarts = Array.from({ length: Math.floor((dateOrdinal(end) - dateOrdinal(start)) / 7) + 1 }, (_, week) => {\n const date = new Date(start)\n date.setDate(date.getDate() + week * 7)\n return date\n })\n const weeks = weekStarts.map((week) =>\n Array.from({ length: 7 }, (_, day) => {\n const date = new Date(week)\n date.setDate(date.getDate() + day)\n const ordinal = dateOrdinal(date)\n if (ordinal < rangeStart || ordinal > rangeEnd) return \" \"\n return activityGlyph(values.get(dateKey(date)) ?? 0, levels, color)\n }),\n )\n const weekdays = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"]\n return [\n style(totalWeeks > maxWeeks ? `activity · last ${maxWeeks} weeks` : \"activity\", `1;${colors.primary}`, color),\n ` ${style(monthLabels(weekStarts), \"2\", color)}`,\n ...weekdays.flatMap((label, day) => [\n `${style(label, \"2\", color)} ${weeks.map((week) => week[day]).join(\"\")}`,\n ...(day === weekdays.length - 1 ? [] : [\"\"]),\n ]),\n \"\",\n ` ${style(\"less\", \"2\", color)} ${[0, 1, 2, 3, 4].map((level) => paintActivity(level, color)).join(\"\")} ${style(\"more\", \"2\", color)}`,\n ]\n}\n\nfunction renderCost(stats: SessionStatsInfo) {\n const input = stats.tokens.input + stats.tokens.cache.read + stats.tokens.cache.write\n const cached = input === 0 ? 0 : (stats.tokens.cache.read / input) * 100\n return [\n \"COST & TOKENS\",\n row(\"cost\", `$${stats.cost.toFixed(2)}`),\n row(\"input\", formatNumber(stats.tokens.input)),\n row(\"output\", formatNumber(stats.tokens.output)),\n row(\"reasoning\", formatNumber(stats.tokens.reasoning)),\n row(\"cache read\", formatNumber(stats.tokens.cache.read)),\n row(\"cache write\", formatNumber(stats.tokens.cache.write)),\n row(\"cached input\", formatPercent(cached)),\n ]\n}\n\nfunction renderModels(stats: SessionStatsInfo, limit: number, width: number) {\n if (stats.models.length === 0) return [\"MODELS\", \" no model usage\"]\n const models = stats.models.slice(0, limit)\n const more = stats.models.length - models.length\n if (width < 68)\n return [\n \"MODELS\",\n ...models.flatMap((item) => [\n truncate(\n `${item.model.providerID}/${item.model.id}${item.model.variant ? `#${item.model.variant}` : \"\"}`,\n width,\n ),\n ` ${formatNumber(tokenTotal(item.tokens))} tokens · ${formatNumber(item.steps)} steps · $${item.cost.toFixed(2)}`,\n ]),\n ...(more > 0 ? [\"\", `+${more.toLocaleString(\"en-US\")} more model${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n return [\n \"MODELS\",\n tableHeader(\"model\", \"tokens\", \"steps\", \"cost\"),\n ...models.map((item) =>\n tableRow(\n `${item.model.providerID}/${item.model.id}${item.model.variant ? `#${item.model.variant}` : \"\"}`,\n formatNumber(tokenTotal(item.tokens)),\n formatNumber(item.steps),\n `$${item.cost.toFixed(2)}`,\n ),\n ),\n ...(more > 0 ? [\"\", `+${more.toLocaleString(\"en-US\")} more model${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n}\n\nfunction renderTools(stats: SessionStatsInfo, limit: number, width: number) {\n if (stats.tools.mode !== \"detail\") return [\"TOOL RELIABILITY\", \" tool details unavailable\"]\n if (stats.tools.usage.length === 0) return [\"TOOL RELIABILITY\", \" no tool calls\"]\n const tools = stats.tools.usage.slice(0, limit)\n const more = stats.tools.usage.length - tools.length\n if (width < 68)\n return [\n \"TOOL RELIABILITY\",\n ...tools.flatMap((tool) => {\n const terminal = tool.succeeded + tool.failed\n return [\n truncate(tool.name, width),\n ` ${formatNumber(tool.calls)} calls · ${terminal === 0 ? \"-\" : formatPercent((tool.failed / terminal) * 100)} error · ${tool.durationP50 === undefined ? \"-\" : formatDuration(tool.durationP50)} p50`,\n ]\n }),\n \"\",\n `${formatNumber(stats.tools.totals.succeeded + stats.tools.totals.failed)} finished calls · ${formatNumber(stats.tools.totals.unfinished)} unfinished`,\n ...(more > 0 ? [`+${more.toLocaleString(\"en-US\")} more tool${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n return [\n \"TOOL RELIABILITY\",\n tableHeader(\"tool\", \"calls\", \"error\", \"p50\"),\n ...tools.map((tool) => {\n const terminal = tool.succeeded + tool.failed\n return tableRow(\n tool.name,\n formatNumber(tool.calls),\n terminal === 0 ? \"-\" : formatPercent((tool.failed / terminal) * 100),\n tool.durationP50 === undefined ? \"-\" : formatDuration(tool.durationP50),\n )\n }),\n \"\",\n `${formatNumber(stats.tools.totals.succeeded + stats.tools.totals.failed)} finished calls · ${formatNumber(stats.tools.totals.unfinished)} unfinished`,\n ...(more > 0 ? [`+${more.toLocaleString(\"en-US\")} more tool${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n}\n\nfunction row(label: string, value: string) {\n return ` ${label.padEnd(20)}${value}`\n}\n\nfunction tableHeader(label: string, second: string, third: string, fourth: string) {\n return tableRow(label, second, third, fourth)\n}\n\nfunction tableRow(label: string, second: string, third: string, fourth: string) {\n return `${truncate(label, 34).padEnd(34)}${second.padStart(10)}${third.padStart(12)}${fourth.padStart(12)}`\n}\n\nfunction truncate(value: string, width: number) {\n return value.length <= width ? value : value.slice(0, width - 1) + \"…\"\n}\n\nfunction tokenTotal(tokens: SessionStatsInfo[\"tokens\"]) {\n return tokens.input + tokens.output + tokens.reasoning + tokens.cache.read + tokens.cache.write\n}\n\nfunction formatNumber(value: number) {\n if (value >= 1_000_000_000) return `${trimDecimal(value / 1_000_000_000)}b`\n if (value >= 1_000_000) return `${trimDecimal(value / 1_000_000)}m`\n if (value >= 1_000) return `${trimDecimal(value / 1_000)}k`\n return Math.round(value).toLocaleString(\"en-US\")\n}\n\nfunction trimDecimal(value: number) {\n return value.toFixed(1).replace(/\\.0$/, \"\")\n}\n\nfunction formatPercent(value: number) {\n return `${value.toFixed(value >= 10 ? 1 : 2)}%`\n}\n\nfunction formatDuration(value: number) {\n if (value < 1_000) return `${Math.round(value)}ms`\n return `${trimDecimal(value / 1_000)}s`\n}\n\nfunction metricCount(value: number, noun: string, color: boolean) {\n return `${style(formatNumber(value), `1;${colors.primary}`, color)} ${noun}${value === 1 ? \"\" : \"s\"}`\n}\n\nfunction style(value: string, code: string, color: boolean) {\n return color ? `\\x1b[${code}m${value}\\x1b[0m` : value\n}\n\nfunction activityGlyph(value: number, levels: number[], color: boolean) {\n if (value === 0) return paintActivity(0, color)\n const index = levels.indexOf(value)\n const level = Math.max(1, Math.ceil(((index + 1) / levels.length) * 4))\n return paintActivity(level, color)\n}\n\nfunction paintActivity(level: number, color: boolean) {\n const glyph = [\"·\", \"░\", \"▒\", \"▓\", \"█\"][level]\n if (!color) return glyph\n if (level === 0) return `\\x1b[2m${glyph}\\x1b[22m`\n return `\\x1b[${colors.activity[level - 1]}m${glyph}\\x1b[39m`\n}\n\nfunction terminalPalette() {\n const background = Number(process.env.COLORFGBG?.split(\";\").at(-1))\n if (Number.isFinite(background) && background >= 7)\n return {\n primary: \"38;2;59;125;216\",\n activity: [\"38;2;153;169;192\", \"38;2;122;155;200\", \"38;2;90;140;208\", \"38;2;59;125;216\"],\n }\n if (Number.isFinite(background))\n return {\n primary: \"38;2;250;178;131\",\n activity: [\"38;2;117;99;87\", \"38;2;161;125;102\", \"38;2;206;152;116\", \"38;2;250;178;131\"],\n }\n return { primary: \"36\", activity: [\"2;36\", \"36\", \"1;36\", \"1;96\"] }\n}\n\nfunction monthLabels(weeks: Date[]) {\n const line: string[] = []\n weeks.reduce((previous, week, index) => {\n const middle = new Date(week)\n middle.setDate(middle.getDate() + 3)\n const month = middle.getMonth()\n if (month === previous) return previous\n Intl.DateTimeFormat(\"en-US\", { month: \"short\" })\n .format(middle)\n .split(\"\")\n .forEach((character, offset) => {\n line[index + offset] = character\n })\n return month\n }, -1)\n return Array.from({ length: Math.max(weeks.length, line.length) }, (_, index) => line[index] ?? \" \")\n .join(\"\")\n .trimEnd()\n}\n\nfunction mondayIndex(date: Date) {\n return (date.getDay() + 6) % 7\n}\n\nfunction dateKey(date: Date) {\n return [\n date.getFullYear(),\n String(date.getMonth() + 1).padStart(2, \"0\"),\n String(date.getDate()).padStart(2, \"0\"),\n ].join(\"-\")\n}\n\nfunction dateOrdinal(date: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C,EAAG,IAAU,EAAK,IAAU,GAAG,EAChG,KAAK,EAAE,EACP,QAAQ,EAGb,SAAS,CAAW,CAAC,EAAY,CAC/B,OAAQ,EAAK,OAAO,EAAI,GAAK,EAG/B,SAAS,EAAO,CAAC,EAAY,CAC3B,MAAO,CACL,EAAK,YAAY,EACjB,OAAO,EAAK,SAAS,EAAI,CAAC,EAAE,SAAS,EAAG,GAAG,EAC3C,OAAO,EAAK,QAAQ,CAAC,EAAE,SAAS,EAAG,GAAG,CACxC,EAAE,KAAK,GAAG,EAGZ,SAAS,CAAW,CAAC,EAAY,CAC/B,OAAO,KAAK,MAAM,KAAK,IAAI,EAAK,YAAY,EAAG,EAAK,SAAS,EAAG,EAAK,QAAQ,CAAC,EAAI,QAAU", | ||
| "debugId": "5E3E3E3E9DD88A0664756E2164756E21", | ||
| "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": ";qVAaA,IAAI,EAAiB,SAGjB,EAAsB,EAAE,OAAO,CACjC,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,IACpB,IAAI,EAAkC,EAAS,CACpD,SAAU,gBACV,IAAK,EAAG,UAAW,GAAG,IAAU,IAChC,QAAS,EACT,MAAO,EAAQ,MACf,eAAgB,EAChB,0BAA2B,EAC7B,CAAC,EAEG,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": "B33C13F0B010A8E464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/remove.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { readFile, rename, writeFile } from \"node:fs/promises\"\nimport { Effect } from \"effect\"\nimport { applyEdits, modify, parse, type ParseError } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Config } from \"../../../config\"\nimport { resolveConfigPath } from \"../mcp/add\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.remove,\n Effect.fn(\"cli.plugin.remove\")(function* (input) {\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(global.config))\n const server = yield* Effect.promise(() => removePluginConfig(configPath, input.package))\n const config = yield* Config.Service\n const info = yield* config.get()\n const tui = configured(info.plugins, input.package)\n if (tui)\n yield* config.update((draft) => {\n draft.plugins = draft.plugins?.filter((entry) => !matches(entry, input.package))\n })\n\n const removed = [server ? configPath : undefined, tui ? config.path : undefined].filter(\n (file) => file !== undefined,\n )\n process.stdout.write(\n removed.length\n ? `Plugin \"${input.package}\" removed from ${removed.join(\", \")}${EOL}`\n : `Plugin \"${input.package}\" is not configured${EOL}`,\n )\n }),\n)\n\nexport async function removePluginConfig(configPath: string, spec: string) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return undefined\n throw error\n })\n if (text === undefined) return false\n const errors: ParseError[] = []\n const config: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length || typeof config !== \"object\" || config === null || Array.isArray(config))\n throw new Error(`Invalid global configuration: ${configPath}`)\n const plugins = \"plugins\" in config ? config.plugins : undefined\n if (plugins !== undefined && !Array.isArray(plugins)) throw new Error(`Invalid plugins configuration: ${configPath}`)\n if (!configured(plugins, spec)) return false\n\n const updated = applyEdits(\n text,\n modify(\n text,\n [\"plugins\"],\n plugins?.filter((entry) => !matches(entry, spec)),\n {\n formattingOptions: { tabSize: 2, insertSpaces: true },\n },\n ),\n )\n const temporary = configPath + \".tmp\"\n await writeFile(temporary, updated.endsWith(\"\\n\") ? updated : updated + \"\\n\", { mode: 0o600 })\n await rename(temporary, configPath)\n return true\n}\n\nfunction configured(plugins: readonly unknown[] | undefined, spec: string) {\n return plugins?.some((entry) => matches(entry, spec)) ?? false\n}\n\nfunction matches(entry: unknown, spec: string) {\n return entry === spec || (typeof entry === \"object\" && entry !== null && \"package\" in entry && entry.package === spec)\n}\n" | ||
| ], | ||
| "mappings": ";itBAAA,cAAS,WAET,mBAAS,YAAU,eAAQ,oBAS3B,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,OAClC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,IAAM,EAAS,MAAO,EAAO,QACvB,EAAa,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAO,MAAM,CAAC,EACzE,EAAS,MAAO,EAAO,QAAQ,IAAM,EAAmB,EAAY,EAAM,OAAO,CAAC,EAClF,EAAS,MAAO,EAAO,QACvB,EAAO,MAAO,EAAO,IAAI,EACzB,EAAM,EAAW,EAAK,QAAS,EAAM,OAAO,E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,EAAM,CAAE,KAAM,GAAM,CAAC,EAC7F,MAAM,EAAO,EAAW,CAAU,EAC3B,GAGT,SAAS,CAAU,CAAC,EAAyC,EAAc,CACzE,OAAO,GAAS,KAAK,CAAC,IAAU,EAAQ,EAAO,CAAI,CAAC,GAAK,GAG3D,SAAS,CAAO,CAAC,EAAgB,EAAc,CAC7C,OAAO,IAAU,GAAS,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,EAAM,UAAY", | ||
| "debugId": "AABB0F36D3B15AA864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/set.ts"], | ||
| "sourcesContent": [ | ||
| "import { 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.set,\n Effect.fn(\"cli.service.set\")(function* (input) {\n yield* ServiceConfig.set(input.key, input.value, Option.getOrUndefined(input.nestedValue))\n }),\n)\n" | ||
| ], | ||
| "mappings": ";02BAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,IACnC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,MAAO,EAAc,IAAI,EAAM,IAAK,EAAM,MAAO,EAAO,eAAe,EAAM,WAAW,CAAC,EAC1F,CACH", | ||
| "debugId": "CF6C3E41EEDAD8DF64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/workspace/driver.ts", "../core/src/workspace/sql.ts", "../core/src/workspace.ts", "../core/src/environment/files.ts", "../core/src/environment/exec-defaults.ts", "../core/src/environment/local.ts", "../core/src/environment/memory.ts", "../core/src/environment/environment.ts", "../core/src/environment/index.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WorkspaceDriver from \"./driver.js\"\n\nimport { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { Context, Effect, Layer, Schema } from \"effect\"\nimport type { Scope } from \"effect\"\nimport type { Driver as EnvironmentDriver } from \"../environment/driver.js\"\n\n/**\n * Smallest provider-owned JSON value required to reconnect to the same\n * provider resource. Core stores it opaquely and hands it back; only the\n * owning driver reads inside.\n */\nexport const Binding = Schema.Record(Schema.String, Schema.Json)\nexport type Binding = typeof Binding.Type\n\nexport class Error extends Schema.TaggedError<Error>()(\"WorkspaceDriver.Error\", {\n message: Schema.optional(Schema.String),\n cause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport class ProviderNotFound extends Schema.TaggedError<ProviderNotFound>()(\"WorkspaceDriver.ProviderNotFound\", {\n provider: Schema.String,\n}) {}\n\nexport interface Interface {\n /**\n * Get-or-create the provider resource backing this logical workspace.\n *\n * MUST be idempotent per `workspaceID`: core retries the same ID after\n * failures and process crashes, including a crash between a successful\n * create and the binding being persisted, and another process may race the\n * same ID. Key the resource by `workspaceID` (a provider tag or a\n * deterministic name) and adopt an existing match instead of creating a\n * duplicate.\n */\n readonly create: (input: {\n readonly workspaceID: Workspace.ID\n }) => Effect.Effect<{ readonly binding: Binding }, Error>\n readonly connect: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding\n readonly saveBinding: (binding: Binding) => Effect.Effect<void>\n }) => Effect.Effect<EnvironmentDriver, Error, Scope.Scope>\n readonly suspendForIdle: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding\n readonly saveBinding: (binding: Binding) => Effect.Effect<void>\n }) => Effect.Effect<void, Error>\n /**\n * Release the provider resource for this workspace.\n *\n * `binding` is null when none was persisted: the workspace was never\n * provisioned, or provisioning was interrupted mid-create. Look up any\n * resource previously created for `workspaceID` and clean it up, treating\n * absence as success.\n */\n readonly destroy: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding | null\n }) => Effect.Effect<void, Error>\n}\n\nexport const make = (driver: Interface) => driver\n\nexport interface Registry {\n readonly get: (provider: string) => Effect.Effect<Interface, ProviderNotFound>\n}\n\nexport class RegistryService extends Context.Service<RegistryService, Registry>()(\n \"@opencode/WorkspaceDriverRegistry\",\n) {}\n\nexport const registry = (drivers: Readonly<Record<string, Interface>>): Registry => ({\n get: (provider) => {\n const driver = Object.hasOwn(drivers, provider) ? drivers[provider] : undefined\n return driver ? Effect.succeed(driver) : Effect.fail(new ProviderNotFound({ provider }))\n },\n})\n\nexport const registryNode = (drivers: Readonly<Record<string, Interface>>) =>\n makeGlobalNode({\n service: RegistryService,\n layer: Layer.succeed(RegistryService, RegistryService.of(registry(drivers))),\n deps: [],\n })\n\nexport const node = registryNode({})\n", | ||
| "import { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { integer, sqliteTable, text } from \"drizzle-orm/sqlite-core\"\nimport type { WorkspaceDriver } from \"./driver.js\"\n\nexport const WorkspaceTable = sqliteTable(\"workspace\", {\n id: text().$type<Workspace.ID>().primaryKey(),\n provider: text().notNull(),\n binding: text({ mode: \"json\" }).$type<WorkspaceDriver.Binding>(),\n created_at: integer().notNull(),\n last_used_at: integer().notNull(),\n})\n", | ||
| "export * as Workspace from \"./workspace.js\"\n\nimport { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { eq } from \"drizzle-orm\"\nimport { Clock, Context, Deferred, Duration, Effect, Exit, FiberSet, Layer, Ref, Schedule, Schema, Scope } from \"effect\"\nimport { systemError } from \"effect/PlatformError\"\nimport { make } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver as EnvironmentDriver } from \"./environment/driver.js\"\nimport { Database } from \"./database/database.js\"\nimport { KeyedMutex } from \"./effect/keyed-mutex.js\"\nimport { WorkspaceDriver } from \"./workspace/driver.js\"\nimport { WorkspaceTable } from \"./workspace/sql.js\"\n\nexport const ID = Workspace.ID\nexport type ID = Workspace.ID\n\nexport class Info extends Schema.Class<Info>(\"Workspace.Info\")({\n id: ID,\n provider: Schema.String,\n binding: WorkspaceDriver.Binding,\n createdAt: Schema.Number,\n lastUsedAt: Schema.Number,\n}) {}\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\"Workspace.NotFound\", { workspaceID: ID }) {}\n\nexport interface Interface {\n /** Instantly commits a logical workspace ID. No provider work happens here. */\n readonly create: (provider: string) => Effect.Effect<ID, WorkspaceDriver.ProviderNotFound>\n /** Starts or joins the shared attempt that makes the backing resource real, then returns it. */\n readonly provision: (\n workspaceID: ID,\n ) => Effect.Effect<Info, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n readonly connect: (\n workspaceID: ID,\n ) => Effect.Effect<EnvironmentDriver, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n readonly destroy: (\n workspaceID: ID,\n ) => Effect.Effect<void, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n}\n\nexport interface Options {\n readonly idleThreshold?: Duration.Input\n readonly pollInterval?: Duration.Input\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/Workspace\") {}\n\ninterface Connection {\n readonly driver: WorkspaceDriver.Interface\n readonly environment: EnvironmentDriver\n readonly saveBinding: (binding: WorkspaceDriver.Binding) => Effect.Effect<void>\n readonly lastActivity: Ref.Ref<number>\n readonly active: Ref.Ref<number>\n readonly scope: Scope.Closeable\n}\n\ntype ReadinessError = NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound\n\nexport const configured = (options: Options = {}) =>\n makeGlobalNode({\n service: Service,\n layer: layer(options),\n deps: [Database.node, WorkspaceDriver.node],\n })\n\nconst layer = (options: Options) =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const db = (yield* Database.Service).db\n const registry = yield* WorkspaceDriver.RegistryService\n const lifetime = yield* Scope.Scope\n const connections = new Map<ID, Connection>()\n // Destroy cancels the racing provision body by settling the deferred.\n const attempts = new Map<ID, Deferred.Deferred<Info, ReadinessError>>()\n const locks = KeyedMutex.makeUnsafe<ID>()\n const fork = yield* FiberSet.makeRuntime<never, void, never>()\n const idleThreshold = Duration.toMillis(options.idleThreshold ?? Duration.minutes(20))\n\n const load = Effect.fn(\"Workspace.load\")(function* (workspaceID: ID) {\n const row = yield* db\n .select()\n .from(WorkspaceTable)\n .where(eq(WorkspaceTable.id, workspaceID))\n .get()\n .pipe(Effect.orDie)\n if (!row) return yield* new NotFound({ workspaceID })\n return row\n })\n\n const saveBinding = (workspaceID: ID, binding: WorkspaceDriver.Binding) =>\n db.update(WorkspaceTable).set({ binding }).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)\n\n const info = (row: typeof WorkspaceTable.$inferSelect, binding: WorkspaceDriver.Binding) =>\n new Info({\n id: row.id,\n provider: row.provider,\n binding,\n createdAt: row.created_at,\n lastUsedAt: row.last_used_at,\n })\n\n const provision = Effect.fn(\"Workspace.provision\")((workspaceID: ID) =>\n Effect.suspend(() => {\n const existing = attempts.get(workspaceID)\n if (existing) return Deferred.await(existing)\n\n const attempt = Deferred.makeUnsafe<Info, ReadinessError>()\n attempts.set(workspaceID, attempt)\n fork(\n locks\n .withLock(workspaceID)(\n Effect.gen(function* () {\n const row = yield* load(workspaceID)\n if (row.binding) return info(row, row.binding)\n const driver = yield* registry.get(row.provider)\n const result = yield* driver.create({ workspaceID })\n yield* saveBinding(workspaceID, result.binding)\n return info(row, result.binding)\n }),\n )\n .pipe(\n Effect.raceFirst(Deferred.await(attempt)),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (attempts.get(workspaceID) === attempt) attempts.delete(workspaceID)\n Deferred.doneUnsafe(attempt, exit)\n }),\n ),\n Effect.exit,\n Effect.asVoid,\n ),\n )\n return Deferred.await(attempt)\n }),\n )\n\n const open = Effect.fn(\"Workspace.open\")(function* (workspaceID: ID) {\n const existing = connections.get(workspaceID)\n if (existing) return existing\n\n const row = yield* load(workspaceID)\n // Bindings are persisted before provision resolves and never nulled; a raced\n // destroy deletes the whole row and surfaces as NotFound from load above.\n if (!row.binding) return yield* Effect.die(`workspace ${workspaceID} has no binding after provision`)\n const driver = yield* registry.get(row.provider)\n const persistBinding = (binding: WorkspaceDriver.Binding) => saveBinding(workspaceID, binding)\n const scope = yield* Scope.fork(lifetime)\n const environment = yield* driver\n .connect({ workspaceID, binding: row.binding, saveBinding: persistBinding })\n .pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),\n )\n const now = yield* Clock.currentTimeMillis\n const connection: Connection = {\n driver,\n environment,\n saveBinding: persistBinding,\n lastActivity: yield* Ref.make(now),\n active: yield* Ref.make(0),\n scope,\n }\n connections.set(workspaceID, connection)\n yield* db\n .update(WorkspaceTable)\n .set({ last_used_at: now })\n .where(eq(WorkspaceTable.id, workspaceID))\n .run()\n .pipe(Effect.orDie)\n return connection\n })\n\n yield* Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis\n yield* Effect.forEach(\n [...connections.entries()],\n ([workspaceID, expected]) =>\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const connection = connections.get(workspaceID)\n if (connection !== expected || (yield* Ref.get(connection.active)) > 0) return\n const lastActivity = yield* Ref.get(connection.lastActivity)\n if (now - lastActivity < idleThreshold) return\n const row = yield* load(workspaceID)\n if (!row.binding) return\n // Deliberate: a racing spawn blocks, then wakes cleanly. Unlocking mid-suspend could reattach a sandbox being terminated.\n yield* connection.driver.suspendForIdle({\n workspaceID,\n binding: row.binding,\n saveBinding: connection.saveBinding,\n })\n yield* db\n .update(WorkspaceTable)\n .set({ last_used_at: lastActivity })\n .where(eq(WorkspaceTable.id, workspaceID))\n .run()\n .pipe(Effect.orDie)\n connections.delete(workspaceID)\n yield* Scope.close(connection.scope, Exit.void)\n }).pipe(Effect.catchCause((cause) => Effect.logError(\"workspace idle suspension failed\", cause))),\n ),\n { concurrency: \"unbounded\", discard: true },\n )\n }).pipe(Effect.repeat(Schedule.spaced(options.pollInterval ?? Duration.minutes(1))), Effect.forkScoped)\n\n return Service.of({\n create: Effect.fn(\"Workspace.create\")(function* (provider) {\n yield* registry.get(provider)\n const workspaceID = ID.create()\n const now = yield* Clock.currentTimeMillis\n yield* db\n .insert(WorkspaceTable)\n .values({ id: workspaceID, provider, binding: null, created_at: now, last_used_at: now })\n .run()\n .pipe(Effect.orDie)\n return workspaceID\n }),\n provision,\n connect: Effect.fn(\"Workspace.connect\")(function* (workspaceID) {\n const spawner = make((command) =>\n Effect.acquireRelease(\n // A live connection implies the binding is already persisted, so skip the provision hop.\n Effect.suspend(() => (connections.has(workspaceID) ? Effect.void : provision(workspaceID))).pipe(\n Effect.andThen(\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const connection = yield* open(workspaceID)\n yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)\n yield* Ref.update(connection.active, (active) => active + 1)\n return connection\n }),\n ),\n ),\n Effect.mapError((cause) =>\n systemError({\n _tag: \"Unknown\",\n module: \"Workspace\",\n method: \"spawn\",\n description: `Failed to wake workspace ${workspaceID}`,\n cause,\n }),\n ),\n ),\n (connection) =>\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n yield* Ref.update(connection.active, (active) => active - 1)\n yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)\n }),\n ),\n ).pipe(Effect.flatMap((connection) => connection.environment.spawner.spawn(command))),\n )\n // Overrides are connection-bound; per-spawn routing is required before any driver ships them, so they are deliberately omitted.\n return { spawner }\n }),\n destroy: Effect.fn(\"Workspace.destroy\")(function* (workspaceID) {\n // Settling the shared attempt cancels its racing provision body and fails\n // waiters with NotFound before teardown commits. Accepted tradeoffs: if the\n // locked teardown below fails, those waiters saw NotFound for a workspace\n // that still exists (the next provision retries it), and a provision racing\n // this window may briefly succeed before teardown destroys its fresh binding.\n const attempt = attempts.get(workspaceID)\n if (attempt) {\n attempts.delete(workspaceID)\n Deferred.doneUnsafe(attempt, Exit.fail(new NotFound({ workspaceID })))\n }\n yield* locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const row = yield* load(workspaceID)\n const connection = connections.get(workspaceID)\n connections.delete(workspaceID)\n if (connection) yield* Scope.close(connection.scope, Exit.void)\n // Null binding still reaches the driver: an interrupted or crashed\n // provision may have created a resource that was never persisted. A\n // provider missing from the registry cannot block deleting a\n // never-provisioned row.\n yield* registry.get(row.provider).pipe(\n Effect.flatMap((driver) => driver.destroy({ workspaceID, binding: row.binding })),\n Effect.catchTag(\"WorkspaceDriver.ProviderNotFound\", (error) =>\n row.binding ? Effect.fail(error) : Effect.void,\n ),\n )\n yield* db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)\n }),\n )\n }),\n })\n }),\n )\n\nexport const node = configured()\n\n// TODO(workspace-plan): add the boot janitor and ~23h safety snapshot rotation in a later PR.\n// TODO(workspace-plan): make cold wake interruptible with a re-pin loop against janitor races.\n// TODO(workspace-plan): consider extracting a keyed shared-attempt helper (join/cancel, drop-on-settle) beside\n// KeyedMutex at end-of-series consolidation; filesystem/search.ts and session/run-coordinator.ts hand-roll the same\n// shape. Audited stdlib alternatives (rc.111): RcMap fails twice (refcount release cancels in-flight work when the\n// last waiter leaves, and one finalizer path cannot express idle-suspend vs destroy); Cache interrupts the shared\n// lookup when its last awaiter is interrupted and cannot fail waiters with NotFound on invalidation.\n", | ||
| "import { Effect, Schema } from \"effect\"\n\nexport const FileType = Schema.Literals([\"file\", \"directory\", \"symlink\", \"other\"])\nexport type FileType = typeof FileType.Type\n\nexport interface FileInfo {\n readonly type: FileType\n readonly size: number\n readonly mtimeMs: number\n}\n\nexport interface DirEntry {\n readonly name: string\n readonly type: FileType\n}\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\"Environment.NotFound\", {\n path: Schema.String,\n}) {}\n\nexport class WrongKind extends Schema.TaggedError<WrongKind>()(\"Environment.WrongKind\", {\n path: Schema.String,\n actual: FileType,\n}) {}\n\nexport class Failed extends Schema.TaggedError<Failed>()(\"Environment.Failed\", {\n path: Schema.String,\n cause: Schema.Defect(),\n}) {}\n\nexport interface FilesImpl {\n /**\n * Content operations (`read`, `list`) follow final symlinks; metadata operations (`stat` and entry\n * tags returned by `list`) do not. `info` describes the target file whose bytes are returned.\n * The process-backed default caps collected output at 64 MiB; larger whole-file reads fail with\n * `Failed`, so callers must use ranges for larger files.\n */\n readonly read: (\n path: string,\n range?: { readonly offset: number; readonly length: number },\n ) => Effect.Effect<{ readonly info: FileInfo; readonly bytes: Uint8Array }, NotFound | WrongKind | Failed>\n readonly write: (path: string, bytes: Uint8Array) => Effect.Effect<void, Failed>\n /** Describes the path entry itself, so a final symlink is reported as `symlink` rather than followed. */\n readonly stat: (path: string) => Effect.Effect<FileInfo, NotFound | Failed>\n /** Follows a final symlink to the listed directory while preserving each returned entry's own type. */\n readonly list: (path: string) => Effect.Effect<ReadonlyArray<DirEntry>, NotFound | WrongKind | Failed>\n readonly remove: (path: string) => Effect.Effect<void, Failed>\n readonly move: (from: string, to: string) => Effect.Effect<void, NotFound | Failed>\n readonly mkdir: (path: string) => Effect.Effect<void, Failed>\n}\n\nexport interface Files extends FilesImpl {}\n\n/**\n * Derives a follow-stat kind from the lstat-like Files contract. A dangling\n * symlink fails with `NotFound`.\n */\nexport const typeFollowing = (files: Files, path: string) =>\n files.stat(path).pipe(\n Effect.flatMap((info) =>\n info.type === \"symlink\"\n ? files.read(path, { offset: 0, length: 0 }).pipe(\n Effect.map((result) => result.info.type),\n Effect.catchTag(\"Environment.WrongKind\", (error) => Effect.succeed(error.actual)),\n )\n : Effect.succeed(info.type),\n ),\n )\n\nexport * as EnvironmentFiles from \"./files.js\"\n", | ||
| "import { Effect, Stream } from \"effect\"\nimport { ChildProcess } from \"effect/unstable/process\"\nimport type { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport { collectStream } from \"@opencode-ai/util/process\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FileType, type FilesImpl } from \"./files.js\"\n\n/**\n * Files derived from spawning processes: one process per intent, \"$1\" is\n * always the target path. Scripts report classification through an exit-code\n * protocol (44/45/46) so failures never require parsing localized error text;\n * LC_ALL=C pins the one stderr match that remains. Requires GNU coreutils and\n * findutils in the target image — BSD and busybox userlands will not work.\n * Malformed output from these scripts is our own bug and dies as a defect.\n */\n\nconst MAX_DATA_BYTES = 64 * 1024 * 1024\nconst MAX_ERROR_BYTES = 64 * 1024\nconst NOT_FOUND = 44\nconst WRONG_KIND = 45\nconst FAILED = 46\nconst TAB = \"\\t\"\n\nconst loadMetadata = (flags = \"\") => `\nmetadata=$(stat ${flags} -c '%F${TAB}%s${TAB}%Y' -- \"$1\" 2>&1) || {\n case \"$metadata\" in\n *'No such file or directory'*|*'Not a directory'*) exit ${NOT_FOUND} ;;\n *) printf '%s' \"$metadata\" >&2; exit ${FAILED} ;;\n esac\n}\n`\n\nconst statScript = `\n${loadMetadata()}\nprintf '%s\\n' \"$metadata\"\n`\n\nconst readScript = `\n${loadMetadata(\"-L\")}\nkind=\\${metadata%%${TAB}*}\nif [ \"$kind\" != 'regular file' ] && [ \"$kind\" != 'regular empty file' ]; then\n printf '%s' \"$kind\" >&2\n exit ${WRONG_KIND}\nfi\nprintf '%s\\n' \"$metadata\"\nif [ \"$2\" = range ]; then\n dd if=\"$1\" iflag=skip_bytes,count_bytes skip=\"$3\" count=\"$4\" status=none\nelse\n cat -- \"$1\"\nfi\n`\n\nconst listScript = `\n${loadMetadata(\"-L\")}\nkind=\\${metadata%%${TAB}*}\nif [ \"$kind\" != directory ]; then\n printf '%s' \"$kind\" >&2\n exit ${WRONG_KIND}\nfi\nfind -H \"$1\" -mindepth 1 -maxdepth 1 -printf '%y\\\\0%f\\\\0'\n`\n\nconst moveScript = `\n${loadMetadata()}\nmv -- \"$1\" \"$2\"\n`\n\ninterface Result {\n readonly exitCode: number\n readonly stdout: Uint8Array\n readonly stderr: Uint8Array\n}\n\nexport const execDefaults = (spawner: ChildProcessSpawner[\"Service\"]): FilesImpl => {\n const run = (\n path: string,\n script: string,\n args: ReadonlyArray<string> = [],\n stdin?: Uint8Array,\n ): Effect.Effect<Result, Failed> =>\n Effect.scoped(\n Effect.gen(function* () {\n const command = ChildProcess.make(\"sh\", [\"-c\", script, \"sh\", path, ...args], {\n env: { LC_ALL: \"C\" },\n extendEnv: true,\n stdin: stdin === undefined ? undefined : Stream.make(stdin),\n })\n const handle = yield* spawner.spawn(command).pipe(Effect.mapError((cause) => new Failed({ path, cause })))\n const [stdout, stderr, exitCode] = yield* Effect.all(\n [\n collectStream(handle.stdout, MAX_DATA_BYTES),\n collectStream(handle.stderr, MAX_ERROR_BYTES),\n handle.exitCode,\n ],\n { concurrency: \"unbounded\" },\n ).pipe(Effect.mapError((cause) => new Failed({ path, cause })))\n if (stdout.truncated || stderr.truncated) {\n return yield* new Failed({ path, cause: new Error(\"Process output exceeded its collection limit\") })\n }\n return { exitCode, stdout: stdout.buffer, stderr: stderr.buffer }\n }),\n )\n\n const classify = <A>(\n path: string,\n result: Result,\n success: (stdout: Uint8Array) => A,\n ): Effect.Effect<A, NotFound | WrongKind | Failed> => {\n if (result.exitCode === 0) return Effect.sync(() => success(result.stdout))\n if (result.exitCode === NOT_FOUND) return Effect.fail(new NotFound({ path }))\n if (result.exitCode === WRONG_KIND) {\n return Effect.fail(new WrongKind({ path, actual: parseType(new TextDecoder().decode(result.stderr)) }))\n }\n return Effect.fail(processFailure(path, result))\n }\n\n const complete = (path: string, result: Result) =>\n result.exitCode === 0 ? Effect.void : Effect.fail(processFailure(path, result))\n\n return {\n stat: (path) => run(path, statScript).pipe(Effect.flatMap((result) => classifyPlain(path, result, parseInfo))),\n read: (path, range) =>\n run(\n path,\n readScript,\n range === undefined ? [\"whole\"] : [\"range\", String(range.offset), String(range.length)],\n ).pipe(\n Effect.flatMap((result) =>\n classify(path, result, (stdout) => {\n const newline = stdout.indexOf(10)\n if (newline < 0) throw new Error(\"Missing read metadata header\")\n return {\n info: parseInfo(stdout.slice(0, newline)),\n bytes: stdout.slice(newline + 1),\n }\n }),\n ),\n ),\n write: (path, bytes) =>\n run(path, `mkdir -p \"$(dirname \"$1\")\" && cat > \"$1\"`, [], bytes).pipe(\n Effect.flatMap((result) => complete(path, result)),\n ),\n list: (path) => run(path, listScript).pipe(Effect.flatMap((result) => classify(path, result, parseList))),\n remove: (path) => run(path, `rm -rf -- \"$1\"`).pipe(Effect.flatMap((result) => complete(path, result))),\n move: (from, to) =>\n run(from, moveScript, [to]).pipe(Effect.flatMap((result) => classifyPlain(from, result, () => undefined))),\n mkdir: (path) => run(path, `mkdir -p -- \"$1\"`).pipe(Effect.flatMap((result) => complete(path, result))),\n }\n}\n\n/** `classify` for scripts whose protocol never reports WrongKind. */\nconst classifyPlain = <A>(\n path: string,\n result: Result,\n success: (stdout: Uint8Array) => A,\n): Effect.Effect<A, NotFound | Failed> => {\n if (result.exitCode === 0) return Effect.sync(() => success(result.stdout))\n if (result.exitCode === NOT_FOUND) return Effect.fail(new NotFound({ path }))\n return Effect.fail(processFailure(path, result))\n}\n\nconst processFailure = (path: string, result: Result) =>\n new Failed({\n path,\n cause: new Error(new TextDecoder().decode(result.stderr).trim() || `Process exited with code ${result.exitCode}`),\n })\n\nconst parseInfo = (bytes: Uint8Array): FileInfo => {\n const [rawType, rawSize, rawMtime] = new TextDecoder().decode(bytes).trim().split(TAB)\n const size = Number(rawSize)\n const mtimeMs = Number(rawMtime) * 1_000\n if (!rawType || !Number.isFinite(size) || !Number.isFinite(mtimeMs)) throw new Error(\"Invalid stat output\")\n return { type: parseType(rawType), size, mtimeMs }\n}\n\nconst parseType = (value: string): FileType => {\n if (value === \"regular file\" || value === \"regular empty file\" || value === \"f\") return \"file\"\n if (value === \"directory\" || value === \"d\") return \"directory\"\n if (value === \"symbolic link\" || value === \"l\") return \"symlink\"\n return \"other\"\n}\n\nconst parseList = (bytes: Uint8Array) => {\n const fields = new TextDecoder().decode(bytes).split(\"\\0\")\n fields.pop()\n if (fields.length % 2 !== 0) throw new Error(\"Invalid find output\")\n return Array.from({ length: fields.length / 2 }, (_, index) => ({\n name: fields[index * 2 + 1],\n type: parseType(fields[index * 2]),\n }))\n}\n\nexport * as EnvironmentExecDefaults from \"./exec-defaults.js\"\n", | ||
| "import fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { Effect } from \"effect\"\nimport type { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver } from \"./driver.js\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FilesImpl, type FileType } from \"./files.js\"\n\n/**\n * The host filesystem binding. Deliberately raw node:fs rather than effect's\n * FileSystem service or FSUtil: the contract needs lstat semantics (stat\n * reports \"symlink\") and typed directory entries, and effect's node\n * FileSystem provides neither — its stat always follows symlinks and\n * readDirectory returns names only. FSUtil hits the same gap and its\n * readDirectoryEntries already bypasses to raw node readdir internally.\n * Nothing above the environment seam touches node:fs.\n */\nexport const makeLocalDriver = (spawner: ChildProcessSpawner[\"Service\"]): Driver => {\n const overrides: FilesImpl = {\n read: (value, range) =>\n Effect.gen(function* () {\n const info = yield* stat(value, true)\n if (info.type !== \"file\") return yield* new WrongKind({ path: value, actual: info.type })\n if (range === undefined) {\n const bytes = yield* attempt(value, () => fs.readFile(value), true)\n return { info, bytes }\n }\n const bytes = yield* attempt(\n value,\n async () => {\n const handle = await fs.open(value, \"r\")\n try {\n const buffer = new Uint8Array(range.length)\n const result = await handle.read(buffer, 0, range.length, range.offset)\n return buffer.subarray(0, result.bytesRead)\n } finally {\n await handle.close()\n }\n },\n true,\n )\n return { info, bytes }\n }),\n stat: (value) => stat(value, false),\n list: (value) =>\n Effect.gen(function* () {\n const info = yield* stat(value, true)\n if (info.type !== \"directory\") return yield* new WrongKind({ path: value, actual: info.type })\n const entries = yield* attempt(value, () => fs.readdir(value, { withFileTypes: true }), true)\n return entries.map((entry) => ({ name: entry.name, type: fileType(entry) }))\n }),\n write: (value, bytes) =>\n attempt(value, async () => {\n await fs.mkdir(path.dirname(value), { recursive: true })\n await fs.writeFile(value, bytes)\n }),\n remove: (value) => attempt(value, () => fs.rm(value, { recursive: true, force: true })),\n move: (from, to) =>\n Effect.gen(function* () {\n yield* stat(from, false)\n const destination = yield* stat(to, false).pipe(\n Effect.map((info) => (info.type === \"directory\" ? path.join(to, path.basename(from)) : to)),\n Effect.catchIf(\n (error) => error instanceof NotFound,\n () => Effect.succeed(to),\n ),\n )\n yield* attempt(from, () => fs.rename(from, destination))\n }),\n mkdir: (value) => attempt(value, () => fs.mkdir(value, { recursive: true }).then(() => undefined)),\n }\n\n return { spawner, overrides }\n}\n\nconst stat = (value: string, follow: boolean) =>\n attempt(value, () => (follow ? fs.stat(value) : fs.lstat(value)), true).pipe(\n Effect.map((stats): FileInfo => ({ type: fileType(stats), size: stats.size, mtimeMs: stats.mtimeMs })),\n )\n\nconst fileType = (entry: { isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean }): FileType => {\n if (entry.isFile()) return \"file\"\n if (entry.isDirectory()) return \"directory\"\n if (entry.isSymbolicLink()) return \"symlink\"\n return \"other\"\n}\n\nfunction attempt<A>(value: string, run: () => Promise<A>): Effect.Effect<A, Failed>\nfunction attempt<A>(value: string, run: () => Promise<A>, missing: true): Effect.Effect<A, NotFound | Failed>\nfunction attempt<A>(value: string, run: () => Promise<A>, missing = false) {\n return Effect.tryPromise({\n try: run,\n catch: (cause) =>\n missing && isMissing(cause) ? new NotFound({ path: value }) : new Failed({ path: value, cause }),\n })\n}\n\nconst isMissing = (cause: unknown) =>\n cause !== null &&\n typeof cause === \"object\" &&\n \"code\" in cause &&\n (cause.code === \"ENOENT\" || cause.code === \"ENOTDIR\")\n\nexport * as EnvironmentLocal from \"./local.js\"\n", | ||
| "import path from \"node:path\"\nimport { Effect, PlatformError } from \"effect\"\nimport { make } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver } from \"./driver.js\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FilesImpl, type FileType } from \"./files.js\"\n\ntype Node =\n | { readonly type: \"file\"; readonly bytes: Uint8Array; readonly mtimeMs: number }\n | { readonly type: \"directory\"; readonly mtimeMs: number }\n | { readonly type: \"symlink\"; readonly target: string; readonly mtimeMs: number }\n\nexport interface MemoryDriver extends Driver {\n readonly symlink: (target: string, path: string) => Effect.Effect<void, Failed>\n}\n\nexport const makeMemoryDriver = (): MemoryDriver => {\n const nodes = new Map<string, Node>([[\"/\", { type: \"directory\", mtimeMs: Date.now() }]])\n const key = (value: string) => path.posix.resolve(\"/\", value)\n const info = (node: Node): FileInfo => ({\n type: node.type,\n size:\n node.type === \"file\"\n ? node.bytes.length\n : node.type === \"symlink\"\n ? new TextEncoder().encode(node.target).length\n : 0,\n mtimeMs: node.mtimeMs,\n })\n const resolveKey = (value: string, followFinal: boolean, seen = new Set<string>()): string | undefined => {\n const normalized = key(value)\n const parts = normalized.split(\"/\").filter(Boolean)\n const base = \"/\"\n const walk = (current: string, index: number): string | undefined => {\n if (index === parts.length) return current\n const part = parts[index]\n const candidate = path.posix.join(current, part)\n const node = nodes.get(candidate)\n if (node?.type !== \"symlink\" || (!followFinal && index === parts.length - 1)) return walk(candidate, index + 1)\n if (seen.has(candidate)) return undefined\n seen.add(candidate)\n const target = path.posix.resolve(path.posix.dirname(candidate), node.target)\n return resolveKey(path.posix.join(target, ...parts.slice(index + 1)), followFinal, seen)\n }\n return walk(base, 0)\n }\n const lookup = (value: string) => nodes.get(resolveKey(value, false) ?? key(value))\n const requireParent = (value: string) => {\n const parentPath = path.posix.dirname(key(value))\n const parent = nodes.get(resolveKey(parentPath, true) ?? parentPath)\n if (!parent) throw new Error(`Parent directory does not exist: ${path.posix.dirname(value)}`)\n if (parent.type !== \"directory\") throw new Error(`Parent is not a directory: ${path.posix.dirname(value)}`)\n }\n const mkdirSync = (value: string) => {\n const target = resolveKey(value, false) ?? key(value)\n const existing = nodes.get(target)\n if (existing?.type === \"directory\") return\n if (existing) throw new Error(`Path is not a directory: ${value}`)\n const parent = path.posix.dirname(target)\n if (parent !== target) mkdirSync(parent)\n nodes.set(target, { type: \"directory\", mtimeMs: Date.now() })\n }\n const failed = (value: string, cause: unknown) => new Failed({ path: value, cause })\n const overrides: FilesImpl = {\n stat: (value) => {\n const node = lookup(value)\n return node ? Effect.succeed(info(node)) : Effect.fail(new NotFound({ path: value }))\n },\n read: (value, range) => {\n const original = lookup(value)\n if (!original) return Effect.fail(new NotFound({ path: value }))\n if (original.type === \"directory\") return Effect.fail(new WrongKind({ path: value, actual: \"directory\" }))\n const resolved = resolveKey(value, true)\n const node = resolved === undefined ? undefined : nodes.get(resolved)\n if (!node) return Effect.fail(new NotFound({ path: value }))\n if (node.type !== \"file\") return Effect.fail(new WrongKind({ path: value, actual: node.type }))\n const bytes = range === undefined ? node.bytes : node.bytes.subarray(range.offset, range.offset + range.length)\n return Effect.succeed({ info: info(node), bytes: bytes.slice() })\n },\n write: (value, bytes) =>\n Effect.try({\n try: () => {\n mkdirSync(path.posix.dirname(key(value)))\n const existing = lookup(value)\n if (existing?.type === \"directory\") throw new Error(`Path is a directory: ${value}`)\n const target = existing?.type === \"symlink\" ? resolveKey(value, true) : resolveKey(value, false)\n if (!target) throw new Error(`Cannot resolve symlink: ${value}`)\n requireParent(target)\n nodes.set(target, { type: \"file\", bytes: bytes.slice(), mtimeMs: Date.now() })\n },\n catch: (cause) => failed(value, cause),\n }),\n list: (value) => {\n const target = resolveKey(value, true) ?? key(value)\n const node = nodes.get(target)\n if (!node) return Effect.fail(new NotFound({ path: value }))\n if (node.type !== \"directory\") return Effect.fail(new WrongKind({ path: value, actual: node.type }))\n const entries = [...nodes.entries()]\n .filter(([entry]) => entry !== target && path.posix.dirname(entry) === target)\n .map(([entry, child]) => ({ name: path.posix.basename(entry), type: child.type satisfies FileType }))\n .sort((a, b) => a.name.localeCompare(b.name))\n return Effect.succeed(entries)\n },\n remove: (value) =>\n Effect.sync(() => {\n const target = resolveKey(value, false) ?? key(value)\n for (const entry of nodes.keys()) {\n if (entry === target || entry.startsWith(`${target}/`)) nodes.delete(entry)\n }\n }),\n move: (from, to) => {\n const source = resolveKey(from, false) ?? key(from)\n const node = nodes.get(source)\n if (!node) return Effect.fail(new NotFound({ path: from }))\n return Effect.try({\n try: () => {\n const requested = resolveKey(to, false) ?? key(to)\n const destination =\n nodes.get(requested)?.type === \"directory\"\n ? path.posix.join(requested, path.posix.basename(source))\n : requested\n if (node.type === \"directory\" && destination.startsWith(`${source}/`)) {\n throw new Error(`Cannot move a directory into itself: ${from}`)\n }\n const existing = nodes.get(destination)\n if (node.type === \"directory\" && existing && existing.type !== \"directory\") {\n throw new Error(`Cannot overwrite a non-directory with a directory: ${to}`)\n }\n requireParent(destination)\n const moved = [...nodes.entries()].filter(([entry]) => entry === source || entry.startsWith(`${source}/`))\n for (const [entry] of moved) nodes.delete(entry)\n for (const [entry, child] of moved) nodes.set(`${destination}${entry.slice(source.length)}`, child)\n },\n catch: (cause) => failed(from, cause),\n })\n },\n mkdir: (value) => Effect.try({ try: () => mkdirSync(value), catch: (cause) => failed(value, cause) }),\n }\n\n const spawner = make((command) =>\n Effect.suspend(() => {\n const description = command._tag === \"StandardCommand\" ? command.command : \"pipeline\"\n return Effect.fail(\n PlatformError.systemError({\n _tag: \"Unknown\",\n module: \"EnvironmentMemory\",\n method: \"spawn\",\n pathOrDescriptor: description,\n cause: failed(description, new Error(\"The memory driver cannot spawn processes\")),\n }),\n )\n }),\n )\n\n return {\n spawner,\n overrides,\n symlink: (target, value) =>\n Effect.try({\n try: () => {\n requireParent(value)\n nodes.set(resolveKey(value, false) ?? key(value), { type: \"symlink\", target, mtimeMs: Date.now() })\n },\n catch: (cause) => failed(value, cause),\n }),\n }\n}\n\nexport * as EnvironmentMemory from \"./memory.js\"\n", | ||
| "import { CrossSpawnSpawner } from \"@opencode-ai/util/cross-spawn-spawner\"\nimport { makeLocationNode } from \"@opencode-ai/util/effect/app-node\"\nimport { Context, Effect, Layer } from \"effect\"\nimport { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Files } from \"./files.js\"\nimport { makeFiles } from \"./index.js\"\nimport { makeLocalDriver } from \"./local.js\"\nimport { Location } from \"../location.js\"\nimport { Workspace } from \"../workspace.js\"\n\nexport interface Interface {\n readonly files: Files\n readonly spawner: ChildProcessSpawner[\"Service\"]\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/Environment\") {}\n\nconst layer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner\n const location = yield* Location.Service\n const workspace = yield* Workspace.Service\n const driver = location.workspaceID\n ? yield* workspace.connect(location.workspaceID).pipe(\n // Environment has no error channel; an unknown or destroyed placement is a configuration defect by design.\n Effect.mapError(\n (cause) => new Error(`Failed to bind Environment to workspace ${location.workspaceID}`, { cause }),\n ),\n Effect.orDie,\n )\n : makeLocalDriver(spawner)\n return Service.of({ files: makeFiles(driver), spawner: driver.spawner })\n }),\n)\n\nexport const node = makeLocationNode({\n service: Service,\n layer,\n deps: [CrossSpawnSpawner.node, Location.node, Workspace.node],\n})\n\nexport * as EnvironmentService from \"./environment.js\"\n", | ||
| "export * as Environment from \"./index.js\"\n\nexport { type Driver } from \"./driver.js\"\nexport {\n type DirEntry,\n Failed,\n type FileInfo,\n type Files,\n type FilesImpl,\n type FileType,\n NotFound,\n typeFollowing,\n WrongKind,\n} from \"./files.js\"\nexport { execDefaults } from \"./exec-defaults.js\"\nexport { makeLocalDriver } from \"./local.js\"\nexport { makeMemoryDriver, type MemoryDriver } from \"./memory.js\"\nexport { type Interface, node, Service } from \"./environment.js\"\n\nimport type { Driver } from \"./driver.js\"\nimport { execDefaults } from \"./exec-defaults.js\"\nimport type { Files } from \"./files.js\"\n\nexport const makeFiles = (driver: Driver): Files => ({\n ...execDefaults(driver.spawner),\n ...driver.overrides,\n})\n" | ||
| ], | ||
| "mappings": ";21BAaO,IAAM,GAAU,EAAO,OAAO,EAAO,OAAQ,EAAO,IAAI,EAGxD,MAAM,WAAc,EAAO,YAAmB,EAAE,wBAAyB,CAC9E,QAAS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,OAAS,kBAAoB,EAAQ,QAAU,WAC3E,OAAO,EAAO,KACZ,GAAc,YAAY,CACxB,KAAM,UACN,OAAQ,oBACR,OAAQ,QACR,iBAAkB,EAClB,MAAO,EAAO,EAAiB,MAAM,0CAA0C,CAAC,CAClF,CAAC,CACH,EACD,CACH,EAIE,YACA,QAAS,CAAC,EAAQ,IAChB,EAAO,IAAI,CACT,IAAK,IAAM,CACT,EAAc,CAAK,EACnB,EAAM,IAAI,EAAW,EAAO,EAAK,GAAK,EAAI,CAAK,EAAG,CAAE,KAAM,UAAW,SAAQ,QAAS,KAAK,IAAI,CAAE,CAAC,GAEpG,MAAO,CAAC,IAAU,EAAO,EAAO,CAAK,CACvC,CAAC,CACL,GCrJK,MAAM,UAAgB,EAAQ,QAA4B,EAAE,uBAAuB,CAAE,CAAC,CAE7F,IAAM,GAAQ,EAAM,OAClB,EACA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAU,MAAO,GACjB,EAAW,MAAO,GAAS,QAC3B,EAAY,MAAO,EAAU,QAC7B,EAAS,EAAS,YACpB,MAAO,EAAU,QAAQ,EAAS,WAAW,EAAE,KAE7C,EAAO,SACL,CAAC,IAAc,MAAM,2CAA2C,EAAS,cAAe,CAAE,OAAM,CAAC,CACnG,EACA,EAAO,KACT,EACA,GAAgB,CAAO,EAC3B,OAAO,EAAQ,GAAG,CAAE,MAAO,GAAU,CAAM,EAAG,QAAS,EAAO,OAAQ,CAAC,EACxE,CACH,EAEa,GAAO,GAAiB,CACnC,QAAS,EACT,SACA,KAAM,CAAC,GAAkB,KAAM,GAAS,KAAM,EAAU,IAAI,CAC9D,CAAC,ECjBM,IAAM,GAAY,CAAC,KAA2B,IAChD,GAAa,EAAO,OAAO,KAC3B,EAAO,SACZ", | ||
| "debugId": "5BA6DD7497B65E9264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/unset.ts"], | ||
| "sourcesContent": [ | ||
| "import { 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.unset,\n Effect.fn(\"cli.service.unset\")(function* (input) {\n yield* ServiceConfig.unset(input.key, Option.getOrUndefined(input.name))\n }),\n)\n" | ||
| ], | ||
| "mappings": ";02BAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,MACnC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,MAAO,EAAc,MAAM,EAAM,IAAK,EAAO,eAAe,EAAM,IAAI,CAAC,EACxE,CACH", | ||
| "debugId": "E3E11B23E96E297C64756E2164756E21", | ||
| "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\"\nimport { Global } from \"@opencode-ai/util/global\"\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({\n server: serverURL,\n standalone: input.standalone,\n mismatch: \"replace\",\n })\n const config = yield* Config.Service\n const global = yield* Global.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: Option.getOrUndefined(input.replay) ?? resolved.mini?.replay ?? true,\n replayLimit: Option.getOrUndefined(input.replayLimit) ?? resolved.mini?.replay_limit,\n demo: input.demo,\n tuiConfig: resolved,\n config: {\n update: (update) => runServicePromise(config.update(update)),\n },\n paths: { home: global.home, state: global.state, log: global.log },\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";qkCAQA,IAAe,IAAQ,QAAQ,EAAS,SAAS,KAAM,CAAC,IACtD,EAAO,IAAI,SAAU,EAAG,CACtB,IAAQ,UAAS,wBAAyB,MAAO,EAAO,QAAQ,IAAa,wCAAa,EAC1F,MAAO,EAAO,QAAQ,SAAY,EAAqB,CAAC,EACxD,IAAM,EAAY,EAAO,eAAe,EAAM,MAAM,EAC9C,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EACR,WAAY,EAAM,WAClB,SAAU,SACZ,CAAC,EACK,EAAS,MAAO,EAAO,QACvB,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,EAAO,eAAe,EAAM,MAAM,GAAK,EAAS,MAAM,QAAU,GACxE,YAAa,EAAO,eAAe,EAAM,WAAW,GAAK,EAAS,MAAM,aACxE,KAAM,EAAM,KACZ,UAAW,EACX,OAAQ,CACN,OAAQ,CAAC,IAAW,EAAkB,EAAO,OAAO,CAAM,CAAC,CAC7D,EACA,MAAO,CAAE,KAAM,EAAO,KAAM,MAAO,EAAO,MAAO,IAAK,EAAO,GAAI,CACnE,CAAC,CACH,EACD,CACH", | ||
| "debugId": "73648F091F8C2EB564756E2164756E21", | ||
| "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/auth/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { createClient, loadIntegrations } from \"./shared\"\nimport { errorMessage } from \"../../../util/error\"\n\nexport default Runtime.handler(Commands.commands.auth.commands.list, (input) =>\n list(input).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n)\n\nconst list = Effect.fn(\"cli.auth.list\")(function* (input) {\n const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })\n const integrations = (yield* loadIntegrations(client)).filter((integration) => integration.connections.length > 0)\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify(\n integrations.map((integration) => ({\n id: integration.id,\n name: integration.name,\n connections: integration.connections,\n })),\n null,\n 2,\n ) + EOL,\n )\n return\n }\n const rows = integrations.flatMap((integration) =>\n integration.connections.map((connection) => ({\n integration: integration.name,\n source: connection.type === \"credential\" ? connection.label : connection.name,\n type: connection.type === \"credential\" ? \"stored\" : \"environment\",\n })),\n )\n if (rows.length === 0) {\n process.stdout.write(\"No authenticated integrations\" + EOL)\n return\n }\n const width = Math.max(...rows.map((row) => row.integration.length)) + 2\n process.stdout.write(\n rows.map((row) => row.integration.padEnd(width) + row.source.padEnd(28) + row.type).join(EOL) + EOL,\n )\n})\n" | ||
| ], | ||
| "mappings": ";ymCAAA,cAAS,WAOT,IAAe,IAAQ,QAAQ,EAAS,SAAS,KAAK,SAAS,KAAM,CAAC,IACpE,EAAK,CAAK,EAAE,KACV,EAAO,MAAM,CAAC,IACZ,EAAO,KAAK,IAAM,CAChB,QAAQ,OAAO,MAAM,EAAa,CAAK,EAAI,CAAG,EAC9C,QAAQ,SAAW,EACpB,CACH,CACF,CACF,EAEM,EAAO,EAAO,GAAG,eAAe,EAAE,SAAU,CAAC,EAAO,CACxD,IAAM,EAAS,MAAO,EAAa,CAAE,OAAQ,EAAO,eAAe,EAAM,MAAM,EAAG,WAAY,EAAM,UAAW,CAAC,EAC1G,GAAgB,MAAO,EAAiB,CAAM,GAAG,OAAO,CAAC,IAAgB,EAAY,YAAY,OAAS,CAAC,EACjH,GAAI,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UACH,EAAa,IAAI,CAAC,KAAiB,CACjC,GAAI,EAAY,GAChB,KAAM,EAAY,KAClB,YAAa,EAAY,WAC3B,EAAE,EACF,KACA,CACF,EAAI,CACN,EACA,OAEF,IAAM,EAAO,EAAa,QAAQ,CAAC,IACjC,EAAY,YAAY,IAAI,CAAC,KAAgB,CAC3C,YAAa,EAAY,KACzB,OAAQ,EAAW,OAAS,aAAe,EAAW,MAAQ,EAAW,KACzE,KAAM,EAAW,OAAS,aAAe,SAAW,aACtD,EAAE,CACJ,EACA,GAAI,EAAK,SAAW,EAAG,CACrB,QAAQ,OAAO,MAAM,gCAAkC,CAAG,EAC1D,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAK,IAAI,CAAC,IAAQ,EAAI,YAAY,MAAM,CAAC,EAAI,EACvE,QAAQ,OAAO,MACb,EAAK,IAAI,CAAC,IAAQ,EAAI,YAAY,OAAO,CAAK,EAAI,EAAI,OAAO,OAAO,EAAE,EAAI,EAAI,IAAI,EAAE,KAAK,CAAG,EAAI,CAClG,EACD", | ||
| "debugId": "05372AD263C2F16864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "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": ";mhCAAA,cAAS,WAOT,IAAM,EAAU,IAAI,IAAI,CAAC,SAAU,MAAO,OAAQ,UAAW,QAAS,OAAQ,KAAK,CAAC,EAUrE,IAAQ,QACrB,EAAS,SAAS,IAClB,EAAO,GAAG,SAAS,EAAE,SAAU,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,EAAU,MAAO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AC7F,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": "B5C1B77A74DE93A564756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "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();\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AS,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": "B30C4AA95639698064756E2164756E21", | ||
| "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\"\nimport { Env } from \"./env\"\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 paths: { home: string; state: string; log: string }\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 environment = input.server.reconnect ? Env.session() : undefined\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 environment,\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 environment,\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, paths: input.paths }),\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 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 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": ";stBAGA,qBAAS,wBCDT,kBACA,mBAAS,oBACT,oBACA,qBAAS,YAEF,IAAM,EAA0B,0DASvC,SAAS,CAAW,CAAC,EAA4C,CAC/D,IAAM,EAAa,EAAgC,EAAK,KAAK,EAAW,YAAY,CAAC,EACrF,MAAO,MACC,eAAc,CAAC,EAAO,CAC1B,GAAI,CAAC,EAAO,OACZ,OAAO,EAAW,eAAe,CAAK,QAElC,YAAW,CAAC,EAAO,EAAS,CAChC,GAAI,CAAC,EAAO,OACZ,MAAM,EAAW,YAAY,EAAO,CAAO,EAAE,MAAM,IAAG,CAAG,OAAS,EAEtE,EAGF,SAAS,CAAM,CAAC,EAA2D,CACzE,MAAO,CACL,SAAS,CAAC,EAAU,CAClB,IAAI,EAAa,GAEjB,OADA,QAAQ,GAAG,EAAM,CAAQ,EAClB,IAAM,CACX,GAAI,CAAC,EAAY,OACjB,EAAa,GACb,QAAQ,IAAI,EAAM,CAAQ,GAGhC,EAGF,SAAS,CAAW,CAClB,EACA,EACkC,CAClC,GAAI,CAAC,QAAQ,IAAI,sBAAuB,OACxC,IAAM,EAAQ,IAAI,KAAK,EACpB,YAAY,EACZ,QAAQ,QAAS,EAAE,EACnB,QAAQ,UAAW,GAAG,EACnB,EAAS,EAAK,KAAK,EAAS,SAAU,GAAG,KAAS,EAAY,WAAW,EACzE,EAAO,CAAC,IACZ,KAAK,UAAU,EAAM,CAAC,EAAM,IAAW,OAAO,IAAU,SAAW,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B,OAAO,EAAQ;AAAA,EAAO,EAGxB,SAAS,CAAQ,CAAC,EAAyB,CAEzC,GADA,EAAqB,EACjB,EAAM,cAAgB,SAAc,CAAC,OAAO,UAAU,EAAM,WAAW,GAAK,EAAM,aAAe,GACnG,EAAK,2CAA2C,EAElD,GAAI,EAAM,MAAQ,CAAC,EAAM,UAAY,CAAC,EAAM,QAAS,EAAK,yCAAyC,EAGrG,SAAS,CAAc,EAAW,CAChC,IAAM,EAAO,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": "E188D5ABAB522A3164756E2164756E21", | ||
| "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": ";+2BAMA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,KACnC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,MAAO,EAAQ,KAAK,MAAO,EAAc,QAAQ,CAAC,EACnD,CACH", | ||
| "debugId": "7FBFFF7DC2F38B5764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/add.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\"\nimport { Effect } from \"effect\"\nimport { applyEdits, modify, parse, type ParseError } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { resolveConfigPath } from \"../mcp/add\"\nimport { Config } from \"../../../config\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.add,\n Effect.fn(\"cli.plugin.add\")(function* (input) {\n if (!(yield* Effect.promise(() => Npm.isRegistryPackage(input.package))))\n return yield* Effect.fail(\n new Error(\"Plugin target must be an npm registry package name, version, tag, or semver range\"),\n )\n const npm = yield* Npm.Service\n const installed = yield* npm.add(input.package, { subpaths: [\"server\", \"\"] })\n const tui = yield* npm.resolve(input.package, { subpaths: [\"tui\"] })\n const target = configurationTarget(installed.entrypoint, tui.entrypoint)\n if (!target)\n return yield* Effect.fail(new Error(`Plugin package has no server or TUI entrypoint: ${input.package}`))\n\n if (target === \"server\") {\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(global.config))\n const changed = yield* Effect.promise(() => writePluginConfig(configPath, input.package))\n process.stdout.write(\n changed\n ? `Plugin \"${input.package}\" installed and added to ${configPath}${EOL}`\n : `Plugin \"${input.package}\" is already configured in ${configPath}${EOL}`,\n )\n return\n }\n\n const config = yield* Config.Service\n yield* config.update((draft) => {\n if (configured(draft.plugins, input.package)) return\n draft.plugins = [...(draft.plugins ?? []), input.package]\n })\n process.stdout.write(`TUI plugin \"${input.package}\" installed and added to ${config.path}${EOL}`)\n }),\n)\n\nexport function configurationTarget(server?: string, tui?: string) {\n if (server) return \"server\" as const\n if (tui) return \"tui\" as const\n}\n\nexport async function writePluginConfig(configPath: string, spec: string) {\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 errors: ParseError[] = []\n const config: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length || typeof config !== \"object\" || config === null || Array.isArray(config))\n throw new Error(`Invalid global configuration: ${configPath}`)\n const plugins = \"plugins\" in config ? config.plugins : undefined\n if (plugins !== undefined && !Array.isArray(plugins)) throw new Error(`Invalid plugins configuration: ${configPath}`)\n if (configured(plugins, spec)) return false\n\n const updated = applyEdits(\n text,\n modify(text, [\"plugins\"], [...(plugins ?? []), spec], { formattingOptions: { tabSize: 2, insertSpaces: true } }),\n )\n await mkdir(path.dirname(configPath), { recursive: true })\n const temporary = configPath + \".tmp\"\n await writeFile(temporary, updated.endsWith(\"\\n\") ? updated : updated + \"\\n\", { mode: 0o600 })\n await rename(temporary, configPath)\n return true\n}\n\nfunction configured(plugins: readonly unknown[] | undefined, spec: string) {\n return plugins?.some(\n (entry) =>\n entry === spec || (typeof entry === \"object\" && entry !== null && \"package\" in entry && entry.package === spec),\n )\n}\n" | ||
| ], | ||
| "mappings": ";8tBAAA,cAAS,WACT,oBACA,gBAAS,cAAO,YAAU,eAAQ,oBAUlC,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,IAClC,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAO,CAC5C,GAAI,EAAE,MAAO,EAAO,QAAQ,IAAM,EAAI,kBAAkB,EAAM,OAAO,CAAC,GACpE,OAAO,MAAO,EAAO,KACf,MAAM,mFAAmF,CAC/F,EACF,IAAM,EAAM,MAAO,EAAI,QACjB,EAAY,MAAO,EAAI,IAAI,EAAM,QAAS,CAAE,SA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xF,MAAU,MAAM,iCAAiC,GAAY,EAC/D,IAAM,EAAU,YAAa,EAAS,EAAO,QAAU,OACvD,GAAI,IAAY,QAAa,CAAC,MAAM,QAAQ,CAAO,EAAG,MAAU,MAAM,kCAAkC,GAAY,EACpH,GAAI,EAAW,EAAS,CAAI,EAAG,MAAO,GAEtC,IAAM,EAAU,EACd,EACA,EAAO,EAAM,CAAC,SAAS,EAAG,CAAC,GAAI,GAAW,CAAC,EAAI,CAAI,EAAG,CAAE,kBAAmB,CAAE,QAAS,EAAG,aAAc,EAAK,CAAE,CAAC,CACjH,EACA,MAAM,EAAM,EAAK,QAAQ,CAAU,EAAG,CAAE,UAAW,EAAK,CAAC,EACzD,IAAM,EAAY,EAAa,OAG/B,OAFA,MAAM,EAAU,EAAW,EAAQ,SAAS;AAAA,CAAI,EAAI,EAAU,EAAU;AAAA,EAAM,CAAE,KAAM,GAAM,CAAC,EAC7F,MAAM,EAAO,EAAW,CAAU,EAC3B,GAGT,SAAS,CAAU,CAAC,EAAyC,EAAc,CACzE,OAAO,GAAS,KACd,CAAC,IACC,IAAU,GAAS,OAAO,IAAU,UAAY,IAAU,OAAQ,YAAa,IAAS,EAAM,UAAY,CAC9G", | ||
| "debugId": "F9822C0D465D4ECB64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "93AE568BA7AA677264756E2164756E21", | ||
| "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 env: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n})\nexport type Info = typeof Info.Type\n\nconst keys = [\"hostname\", \"port\", \"password\", \"env\"] 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 === \"dev\" || channel === \"beta\" || 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 === \"dev\" || channel === \"beta\" || 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\" || key === \"env\") 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* (input: { readonly checkVersion?: boolean } = {}) {\n const { file, legacyRegistrationFiles } = yield* paths\n yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))\n return {\n file,\n version: input.checkVersion ? OPENCODE_VERSION : undefined,\n env: (yield* read()).env,\n command: [\n ...selfCommand(),\n \"serve\",\n \"--service\",\n ],\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.orElseSucceed(() => ({}) 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, name?: string) {\n if (key === undefined) {\n const { password: _password, ...safe } = yield* read()\n return JSON.stringify(safe, null, 2)\n }\n const selected = configKey(key)\n if (selected !== \"env\" && name !== undefined) throw new Error(`Usage: opencode service get ${selected}`)\n switch (selected) {\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 case \"env\": {\n const env = (yield* read()).env ?? {}\n return name === undefined ? JSON.stringify(env, null, 2) : (env[name] ?? \"\")\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, nestedValue?: string) {\n const selected = configKey(key)\n if (selected !== \"env\" && nestedValue !== undefined)\n throw new Error(`Usage: opencode service set ${selected} <value>`)\n switch (selected) {\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 case \"env\": {\n if (nestedValue === undefined) throw new Error(\"Usage: opencode service set env <key> <value>\")\n yield* Service.stop(yield* options())\n const existing = yield* read()\n yield* write({ ...existing, env: { ...existing.env, [value]: nestedValue } })\n return\n }\n }\n})\n\nexport const unset = Effect.fn(\"cli.service-config.unset\")(function* (key: string, name?: string) {\n const selected = configKey(key)\n if (selected !== \"env\" && name !== undefined) throw new Error(`Usage: opencode service unset ${selected}`)\n switch (selected) {\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 case \"env\": {\n if (name === undefined) throw new Error(\"Usage: opencode service unset env <key>\")\n yield* Service.stop(yield* options())\n const existing = yield* read()\n const { [name]: _removed, ...env } = existing.env ?? {}\n const { env: _existingEnv, ...rest } = existing\n yield* write(Object.keys(env).length === 0 ? rest : { ...rest, env })\n return\n }\n }\n})\n\nexport * as ServiceConfig from \"./service-config\"\n" | ||
| ], | ||
| "mappings": ";ylBAKA,sBAAS,eACT,oBAOO,IAAM,EAAO,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,EACvC,IAAK,EAAO,SAAS,EAAO,OAAO,EAAO,OAAQ,EAAO,MAAM,CAAC,CAClE,CAAC,EAMD,IAAM,EAAa,EAAO,oBAAoB,EAAO,eAAe,CAAI,CAAC,EACnE,EAAqB,EAAO,oBAAoB,EAAO,eAAe,EAAQ,IAAI,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EAAW,EAAU,CAAG,EAC9B,GAAI,IAAa,OAAS,IAAS,OAAW,MAAU,MAAM,iCAAiC,GAAU,EACzG,OAAQ,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,KACK,MAAO,CACV,GAAI,IAAS,OAAW,MAAU,MAAM,yCAAyC,EACjF,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAM,EAAW,MAAO,EAAK,IACpB,GAAO,KAAa,GAAQ,EAAS,KAAO,CAAC,GAC9C,IAAK,KAAiB,GAAS,EACvC,MAAO,EAAM,OAAO,KAAK,CAAG,EAAE,SAAW,EAAI,EAAO,IAAK,EAAM,KAAI,CAAC,EACpE,MACF,GAEH", | ||
| "debugId": "2D3DC95CDBC35BF564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../protocol/src/client.ts"], | ||
| "sourcesContent": [ | ||
| "import { InvalidRequestError, SessionNotFoundError } from \"./errors.js\"\nimport { makeDefaultApi } from \"./api.js\"\nimport type { Api } from \"./api.js\"\nimport type { Context } from \"effect\"\nimport { HttpApiMiddleware } from \"effect/unstable/httpapi\"\nimport type { EventGroup } from \"./groups/event.js\"\n\nclass LocationMiddleware extends HttpApiMiddleware.Service<LocationMiddleware>()(\n \"@opencode-ai/client/LocationMiddleware\",\n) {}\n\nclass SessionLocationMiddleware extends HttpApiMiddleware.Service<SessionLocationMiddleware>()(\n \"@opencode-ai/client/SessionLocationMiddleware\",\n { error: [InvalidRequestError, SessionNotFoundError] },\n) {}\n\ntype ClientApiShape = Api<\n Context.Service.Identifier<typeof LocationMiddleware>,\n Context.Service.Shape<typeof LocationMiddleware>,\n Context.Service.Identifier<typeof SessionLocationMiddleware>,\n Context.Service.Shape<typeof SessionLocationMiddleware>,\n Context.Service.Identifier<typeof SessionLocationMiddleware>,\n Context.Service.Shape<typeof SessionLocationMiddleware>,\n typeof EventGroup\n>\n\nexport const ClientApi: ClientApiShape = makeDefaultApi({\n locationMiddleware: LocationMiddleware,\n // The real server uses a form-specific middleware with an undocumented `global` sentinel branch.\n // The generated client only needs a middleware identity for API typing.\n formLocationMiddleware: SessionLocationMiddleware,\n sessionLocationMiddleware: SessionLocationMiddleware,\n})\n\nexport const groupNames = {\n \"server.health\": \"health\",\n \"server.server\": \"server\",\n \"server.debug\": \"debug\",\n \"server.migration\": \"migration\",\n \"server.location\": \"location\",\n \"server.agent\": \"agent\",\n \"server.plugin\": \"plugin\",\n \"server.session\": \"session\",\n \"server.message\": \"message\",\n \"server.model\": \"model\",\n \"server.generate\": \"generate\",\n \"server.provider\": \"provider\",\n \"server.integration\": \"integration\",\n \"server.websearch\": \"websearch\",\n \"server.credential\": \"credential\",\n \"server.form\": \"form\",\n \"server.permission\": \"permission\",\n \"server.fs\": \"file\",\n \"server.command\": \"command\",\n \"server.skill\": \"skill\",\n \"server.event\": \"event\",\n \"server.pty\": \"pty\",\n \"server.shell\": \"shell\",\n \"server.mcp\": \"mcp\",\n \"server.reference\": \"reference\",\n \"server.project\": \"project\",\n \"server.worktree\": \"worktree\",\n \"server.vcs\": \"vcs\",\n \"server.config\": \"config\",\n} as const\n\nexport const promiseOmitEndpoints = new Set([\"pty.connect\"])\nexport const effectOmitEndpoints = new Set([\"fs.read\", \"pty.connect\"])\n" | ||
| ], | ||
| "mappings": ";giCAOA,MAAM,UAA2B,EAAkB,QAA4B,EAC7E,wCACF,CAAE,CAAC,CAEH,MAAM,UAAkC,EAAkB,QAAmC,EAC3F,gDACA,CAAE,MAAO,CAAC,EAAqB,CAAoB,CAAE,CACvD,CAAE,CAAC,CAYI,IAAM,EAA4B,EAAe,CACtD,mBAAoB,EAGpB,uBAAwB,EACxB,0BAA2B,CAC7B,CAAC,EAEY,EAAa,CACxB,gBAAiB,SACjB,gBAAiB,SACjB,eAAgB,QAChB,mBAAoB,YACpB,kBAAmB,WACnB,eAAgB,QAChB,gBAAiB,SACjB,iBAAkB,UAClB,iBAAkB,UAClB,eAAgB,QAChB,kBAAmB,WACnB,kBAAmB,WACnB,qBAAsB,cACtB,mBAAoB,YACpB,oBAAqB,aACrB,cAAe,OACf,oBAAqB,aACrB,YAAa,OACb,iBAAkB,UAClB,eAAgB,QAChB,eAAgB,QAChB,aAAc,MACd,eAAgB,QAChB,aAAc,MACd,mBAAoB,YACpB,iBAAkB,UAClB,kBAAmB,WACnB,aAAc,MACd,gBAAiB,QACnB,EAEa,EAAuB,IAAI,IAAI,CAAC,aAAa,CAAC,EAC9C,EAAsB,IAAI,IAAI,CAAC,UAAW,aAAa,CAAC", | ||
| "debugId": "7BC06388B594A2EA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/config/mcp.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ConfigMCP from \"./mcp.js\"\n\nimport { Schema } from \"effect\"\nimport { Mcp } from \"../mcp.js\"\nimport { optional } from \"../schema.js\"\n\nexport const Timeout = Mcp.TimeoutConfig\nexport type Timeout = Mcp.TimeoutConfig\nexport const Local = Mcp.LocalConfig\nexport type Local = Mcp.LocalConfig\nexport const OAuth = Mcp.OAuthConfig\nexport type OAuth = Mcp.OAuthConfig\nexport const Remote = Mcp.RemoteConfig\nexport type Remote = Mcp.RemoteConfig\nexport const Server = Mcp.ServerConfig\n\nexport class Info extends Schema.Class<Info>(\"Config.MCP\")({\n timeout: Timeout.pipe(optional),\n servers: Schema.Record(Schema.String, Server).pipe(optional),\n}) {}\n" | ||
| ], | ||
| "mappings": ";2TAMO,IAAM,EAAU,EAAI,cAEd,EAAQ,EAAI,YAEZ,EAAQ,EAAI,YAEZ,EAAS,EAAI,aAEb,EAAS,EAAI,aAEnB,MAAM,UAAa,EAAO,MAAY,YAAY,EAAE,CACzD,QAAS,EAAQ,KAAK,CAAQ,EAC9B,QAAS,EAAO,OAAO,EAAO,OAAQ,CAAM,EAAE,KAAK,CAAQ,CAC7D,CAAC,CAAE,CAAC", | ||
| "debugId": "E2EFA00924B40D1E64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode, type PluginInfo } 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\"\nimport { Config } from \"../../../config\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { discoverTuiPlugins, tuiPluginDirectories } from \"@opencode-ai/tui/plugin/discovery\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.list,\n Effect.fn(\"cli.plugin.list\")(function* (input) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.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 config = yield* Config.Service\n const global = yield* Global.Service\n const info = yield* config.get()\n const discovered = yield* Effect.promise(() =>\n tuiPluginDirectories(process.cwd(), global.config).then(discoverTuiPlugins),\n )\n const output = format(\n response.data,\n [\n ...(info.plugins ?? []).flatMap((entry) => {\n const target = typeof entry === \"string\" ? entry : entry.package\n return target.startsWith(\"-\") ? [] : [{ target, source: \"configured\" as const }]\n }),\n ...discovered.map((target) => ({ target, source: \"discovered\" as const })),\n ],\n input.builtin,\n )\n if (!output) {\n process.stdout.write(\"No plugins found\" + EOL)\n return\n }\n process.stdout.write(output + EOL)\n }),\n)\n\nexport function format(\n plugins: readonly PluginInfo[],\n tui: ReadonlyArray<{ readonly target: string; readonly source: \"configured\" | \"discovered\" }>,\n builtin = false,\n) {\n const server = plugins\n .filter((plugin) => builtin || plugin.source.type !== \"builtin\")\n .toSorted((a, b) => name(a).localeCompare(name(b)))\n .map((plugin) => `${name(plugin)} (${plugin.status})`)\n const advertised = plugins.flatMap((plugin) =>\n plugin.status === \"active\" && plugin.tui && plugin.source.type === \"package\"\n ? [{ target: plugin.source.package, source: \"advertised\" as const }]\n : [],\n )\n const targets = [...tui, ...advertised]\n .filter((plugin, index, all) => all.findIndex((candidate) => candidate.target === plugin.target) === index)\n .toSorted((a, b) => a.target.localeCompare(b.target))\n .map((plugin) => `${plugin.target} (${plugin.source})`)\n return [\n targets.length ? [\"TUI\", ...targets].join(EOL) : undefined,\n server.length ? [\"Server\", ...server].join(EOL) : undefined,\n ]\n .filter((section) => section !== undefined)\n .join(EOL + EOL)\n}\n\nfunction name(plugin: PluginInfo) {\n if (plugin.id) return plugin.id\n if (plugin.source.type === \"package\") return plugin.source.package\n if (plugin.source.type === \"local\") return plugin.source.path\n return plugin.source.type\n}\n" | ||
| ], | ||
| "mappings": ";o/BAAA,cAAS,WAWT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,KAClC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EACrG,EAA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,EACnD,IAAI,CAAC,IAAW,GAAG,EAAO,WAAW,EAAO,SAAS,EACxD,MAAO,CACL,EAAQ,OAAS,CAAC,MAAO,GAAG,CAAO,EAAE,KAAK,CAAG,EAAI,OACjD,EAAO,OAAS,CAAC,SAAU,GAAG,CAAM,EAAE,KAAK,CAAG,EAAI,MACpD,EACG,OAAO,CAAC,IAAY,IAAY,MAAS,EACzC,KAAK,EAAM,CAAG,EAGnB,SAAS,CAAI,CAAC,EAAoB,CAChC,GAAI,EAAO,GAAI,OAAO,EAAO,GAC7B,GAAI,EAAO,OAAO,OAAS,UAAW,OAAO,EAAO,OAAO,QAC3D,GAAI,EAAO,OAAO,OAAS,QAAS,OAAO,EAAO,OAAO,KACzD,OAAO,EAAO,OAAO", | ||
| "debugId": "160C0665046456CB64756E2164756E21", | ||
| "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\"\nimport { Env } from \"../env\"\nimport { errorMessage } from \"../util/error\"\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({\n baseUrl: endpoint.url,\n headers: Service.headers(endpoint),\n // Bun's default five-minute deadline terminates the event stream used by long-running sessions.\n fetch: ((request: RequestInfo | URL, init?: RequestInit) =>\n fetch(request, { ...init, timeout: false } as BunFetchRequestInit)) as typeof fetch,\n })\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 environment: input.server.service ? Env.session() : undefined,\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\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 LocationRef,\n OpenCodeClient,\n SessionMessageAssistantTool,\n SessionMessageInfo,\n ToolContent,\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 { nonEmptyToolContent, 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 metadata: Record<string, JsonValue>\n content: ToolContent[]\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.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.inbox.delivered\") {\n if (event.data.inboxID === 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.id), {\n id: partID(event.id),\n timestamp: time,\n assistantMessageID: event.data.assistantMessageID,\n tool: event.data.name,\n input: {},\n metadata: {},\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.id))\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.id))\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.id)\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 metadata: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.progress\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.id))\n if (current) {\n current.metadata = event.data.metadata\n }\n continue\n }\n if (event.type === \"session.tool.success\") {\n const key = toolKey(event.data.assistantMessageID, event.data.id)\n const current = tools.get(key) ?? fallbackTool(event)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.id,\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 metadata: event.data.metadata,\n content: event.data.content,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n partID: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n id: event.data.id,\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 metadata: event.data.metadata,\n content: event.data.content,\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.id)\n const current = tools.get(key) ?? fallbackTool(event)\n const error = event.data.error.message\n const metadata = event.data.metadata ?? current.metadata\n const content = event.data.content ?? nonEmptyToolContent(current.content)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.id,\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 metadata,\n content,\n error: event.data.error,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n partID: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n id: event.data.id,\n tool: current.tool,\n state: {\n status: \"error\",\n input: current.input,\n error,\n metadata: {\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 (content && toolOutputText(current.tool, content).trim())\n await input.renderTool({\n ...tool,\n state: {\n status: \"completed\",\n input: current.input,\n metadata,\n content,\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 (input.compatibility === \"v1\" && event.data.error.message === \"The provider response ended unexpectedly.\") {\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 partID: projectedPartID(message.id, `tool-${item.id}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"tool\",\n id: 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: { metadata: item.state.metadata, content: item.state.content },\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: { metadata: item.state.metadata, content: item.state.content },\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 (item.state.content && toolOutputText(item.name, item.state.content).trim()) {\n await input.renderTool({\n ...item,\n state: {\n status: \"completed\",\n input: item.state.input,\n metadata: item.state.metadata,\n content: item.state.content,\n },\n })\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, id: string) {\n return `${messageID}\\u0000${id}`\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; id: 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 metadata: {},\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": ";+wCAGA,eAAS,qBACT,qBCMA,cAAS,WACT,mBAAS,mGCXT,cAAS,YAEF,IAAM,EAAQ,CACnB,SAAU,WACV,YAAa,UACb,kBAAmB,kBACnB,iBAAkB,iBACpB,EAEO,SAAS,CAAO,IAAI,EAAmB,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,GACb,EACA,EAEE,EAAO,CAAC,EAAc,EAAmB,IAAkC,CAC/E,GAAI,EAAM,SAAW,OAAQ,MAAO,GAEpC,OADA,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S,IAGjH,eAAe,EAAU,CAAC,EAAmC,EAAmB,CAC9E,IAAM,EAAO,EAAe,EAAM,CAAS,EAC3C,GAAI,EAAK,OAAS,QAAS,CAGzB,GAFA,EAAG,MAAM,EACT,EAAG,QAAQ,EAAG,MAAM,YAAc,EAAK,KAAM,EAAG,MAAM,YAAc,EAAK,KAAK,EAC1E,EAAK,MAAM,KAAK,EAAG,EAAG,QAAQ,EAAK,IAAI,EAC3C,EAAG,MAAM,EACT,OAEF,EAAG,QACD,EAAG,MAAM,YAAc,EAAK,KAC5B,EAAG,MAAM,YAAc,EAAK,MAC5B,EAAK,YAAc,EAAG,MAAM,SAAW,EAAK,YAAc,EAAG,MAAM,YAAc,EACnF,EAGF,eAAe,EAAe,CAAC,EAAmC,EAAmB,CACnF,IAAM,EAAO,EAAe,EAAM,CAAS,EAC3C,EAAG,QAAQ,EAAG,MAAM,YAAc,SAAK,EAAG,MAAM,YAAc,GAAG,EAAK,cAAc,EAI/E,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": "8B4A09E79895D96664756E2164756E21", | ||
| "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/@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": ";wZAuBA,IAAI,EAAsB,KAAM,CAC9B,WAAW,CAAC,EAAS,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,CA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,EACT,MAAO,EAAQ,KACjB,GACM,EAAkB,CAAC,IAChB,IAAI,EACT,EACA,EAAqB,MAAM,CAC7B,EAEI,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": "CAC7DE6F37FD978864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "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\"\nimport { errorMessage } from \"../../../util/error\"\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(() =>\n timeline.failure(cancelled ? \"Authorization cancelled\" : errorMessage(Cause.squash(exit.cause))),\n ).pipe(Effect.ignore)\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 ...(server ? { answer: { 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" | ||
| ], | ||
| "mappings": ";wrCAYA,EAAwB,EACxB,IAAM,GAAiB,CAAC,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,QAAG,EAClE,GAAe,KACf,EAAS,CACb,OAAQ,EAAK,UAAU,CAAC,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,EAA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MAAO,EAAQ,CAAC,IAC/B,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,EAAG,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", | ||
| "debugId": "3D0BE8F1BB895E7264756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "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": ";+2BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,MACnC,EAAO,GAAG,mBAAmB,EAAE,SAAU,EAAG,CAC1C,IAAM,EAAY,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EACtE,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "C7090F2242BA364564756E2164756E21", | ||
| "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+mistral@3.0.51+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 var _a, _b, _c, _d, _e;\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 const cacheReadTokens = (_e = (_d = (_b = usage.num_cached_tokens) != null ? _b : (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _d : (_c = usage.prompt_token_details) == null ? void 0 : _c.cached_tokens) != null ? _e : 0;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens || 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 structuredContent = [];\n let hasNativeReasoning = false;\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n structuredContent.push({ type: \"text\", 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 const native = part.providerOptions?.mistral?.thinking;\n if (native?.type === \"thinking\") {\n hasNativeReasoning = true;\n structuredContent.push(native);\n break;\n }\n structuredContent.push({ type: \"text\", 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: hasNativeReasoning ? structuredContent : 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 call 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 promptCacheKey: z.string().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 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 ...frequencyPenalty != null ? { frequency_penalty: frequencyPenalty } : {},\n ...presencePenalty != null ? { presence_penalty: presencePenalty } : {},\n stop: stopSequences,\n random_seed: seed,\n reasoning_effort: options.reasoningEffort,\n prompt_cache_key: options.promptCacheKey,\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 content.push({\n type: \"reasoning\",\n text: reasoningText,\n providerMetadata: { mistral: { thinking: part } }\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 let activeThinking = 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 activeThinking = mergeThinking(activeThinking, part);\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 if (reasoningDelta.length > 0) {\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 providerMetadata: { mistral: { thinking: activeThinking } }\n });\n activeReasoningId = null;\n activeThinking = 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 providerMetadata: { mistral: { thinking: activeThinking } }\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 mergeThinking(current, next) {\n if (current === null) return { ...next, thinking: [...next.thinking] };\n current.thinking.push(...next.thinking);\n if (next.closed !== void 0) current.closed = next.closed;\n if (next.signature !== void 0) current.signature = next.signature;\n return current;\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 mistralThinkingContentSchema = z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"tool_reference\"),\n tool: z3.string(),\n title: z3.string(),\n url: z3.string().nullish(),\n favicon: z3.string().nullish(),\n description: z3.string().nullish()\n }),\n z3.object({\n type: z3.literal(\"reference\"),\n reference_ids: z3.array(z3.union([z3.string(), z3.number().int()]))\n })\n]);\nvar mistralThinkChunkSchema = z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.array(mistralThinkingContentSchema),\n closed: z3.boolean().optional(),\n signature: z3.string().nullish()\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 mistralThinkChunkSchema\n ])\n )\n]).nullish();\nvar mistralUsageSchema = z3.object({\n prompt_tokens: z3.number(),\n completion_tokens: z3.number(),\n total_tokens: z3.number(),\n num_cached_tokens: z3.number().nullish(),\n prompt_tokens_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish(),\n prompt_token_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish()\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/mistral-speech-model.ts\nimport {\n combineHeaders as combineHeaders3,\n createJsonResponseHandler as createJsonResponseHandler3,\n parseProviderOptions as parseProviderOptions2,\n postToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\n\n// src/mistral-speech-model-options.ts\nimport { z as z5 } from \"zod/v4\";\nvar mistralSpeechModelOptions = z5.object({\n /**\n * Base64-encoded reference audio for one-off voice cloning.\n *\n * When provided, this takes precedence over the standard `voice` option.\n */\n refAudio: z5.string().min(1).optional()\n});\n\n// src/mistral-speech-model.ts\nvar MistralSpeechModel = 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 text,\n voice,\n outputFormat = \"mp3\",\n instructions,\n speed,\n language,\n providerOptions\n }) {\n const warnings = [];\n const mistralOptions = await parseProviderOptions2({\n provider: \"mistral\",\n providerOptions,\n schema: mistralSpeechModelOptions\n });\n let responseFormat = \"mp3\";\n if ([\"pcm\", \"wav\", \"mp3\", \"flac\", \"opus\"].includes(outputFormat)) {\n responseFormat = outputFormat;\n } else {\n warnings.push({\n type: \"unsupported\",\n feature: \"outputFormat\",\n details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`\n });\n }\n if (instructions != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"instructions\",\n details: \"Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery.\"\n });\n }\n if (speed != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"speed\",\n details: \"Mistral speech models do not support the `speed` option. It was ignored.\"\n });\n }\n if (language != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"language\",\n details: \"Mistral speech models do not support the `language` option. Language is inferred from the input text and voice.\"\n });\n }\n const refAudio = mistralOptions == null ? void 0 : mistralOptions.refAudio;\n const requestBody = {\n model: this.modelId,\n input: text,\n voice_id: refAudio == null ? voice : void 0,\n ref_audio: refAudio,\n response_format: responseFormat,\n stream: false\n };\n const requestBodyValues = {\n ...requestBody,\n ref_audio: refAudio == null ? void 0 : \"[redacted]\"\n };\n return { requestBody, requestBodyValues, warnings };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e;\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 { requestBody, requestBodyValues, warnings } = await this.getArgs(options);\n const {\n value: response,\n responseHeaders,\n rawValue: rawResponse\n } = await postToApi({\n url: `${this.config.baseURL}/audio/speech`,\n headers: combineHeaders3(\n { \"Content-Type\": \"application/json\" },\n (_e = (_d = this.config).headers) == null ? void 0 : _e.call(_d),\n options.headers\n ),\n body: {\n content: JSON.stringify(requestBody),\n values: requestBodyValues\n },\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler3(\n mistralSpeechResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n return {\n audio: response.audio_data,\n warnings,\n request: {\n body: JSON.stringify(requestBodyValues)\n },\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawResponse\n }\n };\n }\n};\nvar mistralSpeechResponseSchema = z6.object({\n audio_data: z6.string()\n});\n\n// src/version.ts\nvar VERSION = true ? \"3.0.51\" : \"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 createSpeechModel = (modelId) => new MistralSpeechModel(modelId, {\n provider: \"mistral.speech\",\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.speech = createSpeechModel;\n provider.speechModel = createSpeechModel;\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": ";+WAuBA,SAAS,CAAmB,CAAC,EAAO,CAClC,IAAI,EAAI,EAAI,EAAI,EAAI,EACpB,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,IAA2B,cAArB,EACyB,kBAAzB,GAAmB,EACnB,GAAmB,GAAM,GAAM,EAAK,EAAM,oBAAsB,KAAO,GAAM,EAAK,EAAM,wBAA0B,KAAY,OAAI,EAAG,gBAAkB,KAAO,GAAM,EAAK,EAAM,uBAAyB,KAAY,OAAI,EAAG,gBAAk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,EAGG,GAAiB,SAGrB,SAAS,EAAa,CAAC,EAAU,CAAC,EAAG,CACnC,IAAI,EACJ,IAAM,GAAW,EAAK,EAAqB,EAAQ,OAAO,IAAM,KAAO,EAAK,4BACtE,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,kBACzB,YAAa,SACf,CAAC,OACE,EAAQ,OACb,EACA,kBAAkB,IACpB,EACM,EAAkB,CAAC,IAAY,IAAI,GAAyB,EAAS,CACzE,SAAU,eACV,UACA,QAAS,EACT,MAAO,EAAQ,MACf,WAAY,EAAQ,UACtB,CAAC,EACK,EAAuB,CAAC,IAAY,IAAI,GAAsB,EAAS,CAC3E,SAAU,oBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAoB,CAAC,IAAY,IAAI,GAAmB,EAAS,CACrE,SAAU,iBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAW,QAAQ,CAAC,EAAS,CACjC,GAAI,WACF,MAAU,MACR,mEACF,EAEF,OAAO,EAAgB,CAAO,GAchC,OAZA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,KAAO,EAChB,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,cAAgB,EACzB,EAAS,mBAAqB,EAC9B,EAAS,OAAS,EAClB,EAAS,YAAc,EACvB,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAU,GAAc", | ||
| "debugId": "F99F99FDE5E396EA64756E2164756E21", | ||
| "names": [] | ||
| } |
+1
-1
| { | ||
| "name": "@opencode-ai/cli-linux-x64", | ||
| "version": "0.0.0-dev-18110", | ||
| "version": "0.0.0-dev-18111", | ||
| "license": "MIT", | ||
@@ -5,0 +5,0 @@ "repository": { |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/oauth/page.ts"], | ||
| "sourcesContent": [ | ||
| "// Branded HTML pages for local OAuth callback servers.\n//\n// These are served by the loopback HTTP servers that finish an OAuth exchange\n// (MCP, Codex/ChatGPT, xAI, Snowflake, DigitalOcean, ...). The functions return\n// a fully self-contained HTML string with no external assets, so they work\n// offline and drop into any transport (`res.end(...)`, Effect `response.end`,\n// etc.).\n//\n// The visual language mirrors the OpenCode app: the design tokens are a curated\n// subset of the OC-2 semantic tokens in `packages/ui/src/styles/theme.css`, and\n// the wordmark is the same geometry as `packages/ui/src/components/logo.tsx`.\n// Keep this file in sync with those sources when the brand changes.\n\nexport interface CallbackPageOptions {\n /** Friendly integration name shown as a subtitle, e.g. \"xAI\", \"Snowflake\", \"MCP\". */\n provider?: string\n /** Attempt to close the window shortly after success. Defaults to true. */\n autoClose?: boolean\n}\n\nexport function success(options?: CallbackPageOptions) {\n const provider = options?.provider\n return renderDocument({\n title: \"Authorization successful\",\n body: renderCard({\n status: \"success\",\n headline: \"Authorization successful\",\n message: provider ? `OpenCode is now connected to ${escapeHtml(provider)}.` : \"OpenCode is now authorized.\",\n footnote: \"You can close this window.\",\n }),\n script: options?.autoClose === false ? undefined : AUTO_CLOSE_SCRIPT,\n })\n}\n\nexport function error(detail: string, options?: CallbackPageOptions) {\n const provider = options?.provider\n return renderDocument({\n title: \"Authorization failed\",\n body: renderCard({\n status: \"error\",\n headline: \"Authorization failed\",\n message: provider\n ? `OpenCode couldn't finish connecting to ${escapeHtml(provider)}.`\n : \"OpenCode couldn't complete authorization.\",\n detail,\n footnote: \"Close this window and try again from OpenCode.\",\n }),\n })\n}\n\nexport interface BootstrapOptions {\n /** Same-origin path the in-browser script POSTs the parsed callback to. */\n tokenPath: string\n provider?: string\n}\n\n// For flows where the credential arrives in the URL fragment (implicit grant),\n// the browser must relay it back to the loopback server. This renders a pending\n// page whose script reads the fragment, POSTs it to `tokenPath`, then resolves\n// to the success or error state in place.\nexport function bootstrap(options: BootstrapOptions) {\n return renderDocument({\n title: \"Finishing sign-in\",\n body: renderCard({\n status: \"pending\",\n headline: \"Finishing sign-in\",\n message: options.provider\n ? `Completing your ${escapeHtml(options.provider)} authorization.`\n : \"Completing authorization.\",\n footnote: \"You can close this window once sign-in finishes.\",\n }),\n script: bootstrapScript(options),\n })\n}\n\nexport * as OauthCallbackPage from \"./page.js\"\n\ntype Status = \"pending\" | \"success\" | \"error\"\n\nfunction renderCard(input: { status: Status; headline: string; message: string; detail?: string; footnote: string }) {\n const detail = input.detail?.trim()\n return `<main class=\"card\" id=\"oc-card\" data-status=\"${input.status}\" role=\"status\" aria-live=\"polite\">\n <div class=\"brand\">${WORDMARK}</div>\n <div class=\"status\" aria-hidden=\"true\">\n <span class=\"icon icon-pending\">${ICON_SPINNER}</span>\n <span class=\"icon icon-success\">${ICON_CHECK}</span>\n <span class=\"icon icon-error\">${ICON_CROSS}</span>\n </div>\n <h1 class=\"headline\" id=\"oc-headline\">${escapeHtml(input.headline)}</h1>\n <p class=\"message\" id=\"oc-message\">${input.message}</p>\n <pre class=\"detail\" id=\"oc-detail\"${detail ? \"\" : \" hidden\"}>${detail ? escapeHtml(detail) : \"\"}</pre>\n <p class=\"footnote\" id=\"oc-footnote\">${escapeHtml(input.footnote)}</p>\n </main>`\n}\n\nfunction renderDocument(input: { title: string; body: string; script?: string }) {\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"robots\" content=\"noindex\" />\n <title>${escapeHtml(input.title)} · OpenCode</title>\n <style>${STYLES}</style>\n </head>\n <body>\n ${input.body}${input.script ? `\\n <script>${input.script}</script>` : \"\"}\n </body>\n</html>`\n}\n\nconst AUTO_CLOSE_SCRIPT = `setTimeout(function(){try{window.close()}catch(e){}},2500)`\n\nfunction bootstrapScript(options: BootstrapOptions) {\n return `var PROVIDER=${scriptString(options.provider ?? \"\")};\nvar TOKEN_URL=new URL(${scriptString(options.tokenPath)},window.location.origin).href;\n(function(){\n var card=document.getElementById(\"oc-card\"),headline=document.getElementById(\"oc-headline\"),message=document.getElementById(\"oc-message\"),detail=document.getElementById(\"oc-detail\"),footnote=document.getElementById(\"oc-footnote\");\n function fail(text){card.dataset.status=\"error\";headline.textContent=\"Authorization failed\";message.textContent=PROVIDER?(\"OpenCode couldn't finish connecting to \"+PROVIDER+\".\"):\"OpenCode couldn't complete authorization.\";if(text){detail.textContent=text;detail.hidden=false}footnote.textContent=\"Close this window and try again from OpenCode.\"}\n function ok(){card.dataset.status=\"success\";headline.textContent=\"Authorization successful\";message.textContent=PROVIDER?(\"OpenCode is now connected to \"+PROVIDER+\".\"):\"OpenCode is now authorized.\";detail.hidden=true;footnote.textContent=\"You can close this window.\";setTimeout(function(){try{window.close()}catch(e){}},2500)}\n try{\n var hash=new URLSearchParams((window.location.hash||\"\").slice(1));\n var search=new URLSearchParams(window.location.search||\"\");\n var err=hash.get(\"error\")||search.get(\"error\");\n var errDescription=hash.get(\"error_description\")||search.get(\"error_description\");\n var body=err?{error:err,error_description:errDescription||\"\"}:{access_token:hash.get(\"access_token\")||\"\",expires_in:hash.get(\"expires_in\")||\"0\",state:hash.get(\"state\")||\"\"};\n fetch(TOKEN_URL,{method:\"POST\",headers:{\"Content-Type\":\"application/json\"},body:JSON.stringify(body)}).then(function(res){\n if(!res.ok)return res.text().catch(function(){return\"\"}).then(function(t){throw new Error(t||(\"callback failed (\"+res.status+\")\"))});\n if(err){fail(errDescription||err);return}\n ok();\n }).catch(function(e){fail(String(e&&e.message?e.message:e))});\n }catch(e){fail(String(e&&e.message?e.message:e))}\n})()`\n}\n\nfunction scriptString(value: string) {\n return JSON.stringify(value).replaceAll(\"<\", \"\\\\u003c\")\n}\n\nfunction escapeHtml(value: string) {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\")\n}\n\n// Curated subset of OC-2 tokens (packages/ui/src/styles/theme.css). Default is\n// light; dark applies via prefers-color-scheme. The [data-theme] selectors let a\n// host force a scheme without changing the default.\nconst LIGHT_VARS = `\n --oc-bg: #f8f8f8;\n --oc-card: #fcfcfc;\n --oc-text-strong: #171717;\n --oc-text-base: #6f6f6f;\n --oc-text-weak: #8f8f8f;\n --oc-border-weak: #e5e5e5;\n --oc-icon-strong: #171717;\n --oc-icon-base: #8f8f8f;\n --oc-icon-weak: #dbdbdb;\n --oc-success: #2dba26;\n --oc-error: #ed4831;\n --oc-detail-bg: #fff8f6;\n --oc-detail-border: #fdc3b7;\n --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.10), 0 6px 12px -2px rgba(0,0,0,.05), 0 1px 2px rgba(0,0,0,.06);`\n\nconst DARK_VARS = `\n --oc-bg: #101010;\n --oc-card: #161616;\n --oc-text-strong: rgba(255,255,255,.936);\n --oc-text-base: rgba(255,255,255,.618);\n --oc-text-weak: rgba(255,255,255,.422);\n --oc-border-weak: #282828;\n --oc-icon-strong: #ededed;\n --oc-icon-base: #7e7e7e;\n --oc-icon-weak: #343434;\n --oc-success: #12c905;\n --oc-error: #fc533a;\n --oc-detail-bg: #28110c;\n --oc-detail-border: #6a1206;\n --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.55), 0 6px 12px -2px rgba(0,0,0,.35), 0 1px 2px rgba(0,0,0,.4);`\n\nconst STYLES = `\n :root { color-scheme: light dark;${LIGHT_VARS}\n --oc-font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n --oc-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n }\n @media (prefers-color-scheme: dark) { :root:not([data-theme=\"light\"]) {${DARK_VARS} } }\n :root[data-theme=\"dark\"] {${DARK_VARS} }\n :root[data-theme=\"light\"] {${LIGHT_VARS} }\n\n * { box-sizing: border-box; }\n html, body { margin: 0; height: 100%; }\n body {\n min-height: 100vh;\n display: grid;\n place-items: center;\n padding: 24px;\n background: var(--oc-bg);\n color: var(--oc-text-base);\n font-family: var(--oc-font-sans);\n line-height: 1.5;\n -webkit-font-smoothing: antialiased;\n text-rendering: optimizeLegibility;\n }\n .card {\n width: min(100%, 28rem);\n padding: 2.25rem 2rem 1.75rem;\n background: var(--oc-card);\n border: 1px solid var(--oc-border-weak);\n border-radius: 14px;\n box-shadow: var(--oc-shadow);\n text-align: center;\n }\n .brand { display: flex; justify-content: center; margin-bottom: 1.75rem; }\n .brand svg { height: 19px; width: auto; }\n .status { display: flex; justify-content: center; margin-bottom: 1.125rem; }\n .icon { display: none; line-height: 0; }\n .icon svg { display: block; }\n .card[data-status=\"pending\"] .icon-pending,\n .card[data-status=\"success\"] .icon-success,\n .card[data-status=\"error\"] .icon-error { display: block; }\n .icon-success { color: var(--oc-success); }\n .icon-error { color: var(--oc-error); }\n .icon-pending { color: var(--oc-text-weak); }\n .headline { margin: 0; font-size: 1.1875rem; font-weight: 500; line-height: 1.3; letter-spacing: -0.012em; color: var(--oc-text-strong); }\n .message { margin: 0.5rem 0 0; font-size: 0.9375rem; color: var(--oc-text-base); }\n .detail {\n margin: 1.25rem 0 0;\n padding: 0.75rem 0.875rem;\n text-align: left;\n font-family: var(--oc-font-mono);\n font-size: 0.8125rem;\n line-height: 1.55;\n color: var(--oc-text-strong);\n background: var(--oc-detail-bg);\n border: 1px solid var(--oc-detail-border);\n border-radius: 8px;\n white-space: pre-wrap;\n word-break: break-word;\n max-height: 9.5rem;\n overflow: auto;\n }\n .detail[hidden] { display: none; }\n .footnote { margin: 1.5rem 0 0; font-size: 0.8125rem; color: var(--oc-text-weak); }\n .spinner { animation: oc-spin 0.8s linear infinite; transform-origin: center; }\n @keyframes oc-spin { to { transform: rotate(360deg); } }\n @media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }\n`\n\n// OpenCode wordmark — same path geometry as packages/ui/src/components/logo.tsx (Logo).\nconst WORDMARK = `<svg class=\"wordmark\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 234 42\" fill=\"none\" aria-label=\"OpenCode\" role=\"img\">\n <path d=\"M18 30H6V18H18V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M18 12H6V30H18V12ZM24 36H0V6H24V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M48 30H36V18H48V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M36 30H48V12H36V30ZM54 36H36V42H30V6H54V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M84 24V30H66V24H84Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M84 24H66V30H84V36H60V6H84V24ZM66 18H78V12H66V18Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M108 36H96V18H108V36Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M108 12H96V36H90V6H108V12ZM114 36H108V12H114V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M144 30H126V18H144V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M144 12H126V30H144V36H120V6H144V12Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M168 30H156V18H168V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M168 12H156V30H168V12ZM174 36H150V6H174V36Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M198 30H186V18H198V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M198 12H186V30H198V12ZM204 36H180V6H198V0H204V36Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M234 24V30H216V24H234Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M216 12V18H228V12H216ZM234 24H216V30H234V36H210V6H234V24Z\" fill=\"var(--oc-icon-strong)\" />\n </svg>`\n\nconst ICON_CHECK = `<svg viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m8.5 12.5 2.4 2.4 4.6-5.4\" /></svg>`\n\nconst ICON_CROSS = `<svg viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m9 9 6 6m0-6-6 6\" /></svg>`\n\nconst ICON_SPINNER = `<svg class=\"spinner\" viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" opacity=\"0.2\" /><path d=\"M21 12a9 9 0 0 0-9-9\" /></svg>`\n" | ||
| ], | ||
| "mappings": ";sIAoBO,SAAS,CAAO,CAAC,EAA+B,CACrD,IAAM,EAAW,GAAS,SAC1B,OAAO,EAAe,CACpB,MAAO,2BACP,KAAM,EAAW,CACf,OAAQ,UACR,SAAU,2BACV,QAAS,EAAW,gCAAgC,EAAW,CAAQ,KAAO,8BAC9E,SAAU,4BACZ,CAAC,EACD,OAAQ,GAAS,YAAc,GAAQ,OAAY,CACrD,CAAC,EAGI,SAAS,CAAK,CAAC,EAAgB,EAA+B,CACnE,IAAM,EAAW,GAAS,SAC1B,OAAO,EAAe,CACpB,MAAO,uBACP,KAAM,EAAW,CACf,OAAQ,QACR,SAAU,uBACV,QAAS,EACL,0CAA0C,EAAW,CAAQ,KAC7D,4CACJ,SACA,SAAU,gDACZ,CAAC,CACH,CAAC,EAaI,SAAS,CAAS,CAAC,EAA2B,CACnD,OAAO,EAAe,CACpB,MAAO,oBACP,KAAM,EAAW,CACf,OAAQ,UACR,SAAU,oBACV,QAAS,EAAQ,SACb,mBAAmB,EAAW,EAAQ,QAAQ,mBAC9C,4BACJ,SAAU,kDACZ,CAAC,EACD,OAAQ,EAAgB,CAAO,CACjC,CAAC,EAOH,SAAS,CAAU,CAAC,EAAiG,CACnH,IAAM,EAAS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ACC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8DzB,EAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAmBX,EAAa,iOAEb,EAAa,wNAEb,EAAe", | ||
| "debugId": "C0F4AC5704051AA564756E2164756E21", | ||
| "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": ";+2BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,QACnC,EAAO,GAAG,qBAAqB,EAAE,SAAU,EAAG,CAC5C,IAAM,EAAU,MAAO,EAAc,QAAQ,EAC7C,MAAO,EAAQ,KAAK,CAAO,EAC3B,IAAM,EAAY,MAAO,EAAQ,OAAO,CAAO,EAC/C,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "6190AF498043C73B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/server-process.ts", "src/services/service-registration.ts", "src/services/web-ui.ts", "src/app-assets.ts", "src/commands/handlers/serve.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ServerProcess from \"./server-process\"\n\nimport { NodeServices } from \"@effect/platform-node\"\nimport { Service, type DiscoverOptions } 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 { Effect, Option, Redacted, Schedule } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { Env } from \"./env\"\nimport { ServiceConfig } from \"./services/service-config\"\nimport { ServiceRegistration } from \"./services/service-registration\"\nimport { Updater } from \"./services/updater\"\nimport { WebUi } from \"./services/web-ui\"\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 const global = yield* Global.Service\n if (options.mode === \"service\") yield* Effect.sync(() => process.chdir(global.home))\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const foreground = options.mode === \"default\"\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 const incumbent =\n serviceOptions !== undefined && port !== undefined\n ? yield* Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })\n : undefined\n if (incumbent !== undefined) 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 transform = yield* WebUi.handler()\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\", \"dev\", \"beta\", \"next\", \"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 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(process.env.OPENCODE_FILEWATCHER_DISABLE ?? process.env.OPENCODE_DISABLE_FILEWATCHER),\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 onListen: (address, shutdown) =>\n Effect.gen(function* () {\n if (!config.password) yield* ServiceConfig.password(password)\n return yield* ServiceRegistration.register({\n address,\n password,\n id: instanceID,\n file: serviceOptions.file,\n shutdown,\n })\n }),\n },\n transform,\n ).pipe(\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 (foreground && !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 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", | ||
| "export * as ServiceRegistration from \"./service-registration\"\n\nimport { Service, type Info } from \"@opencode-ai/client/effect/service\"\nimport path from \"node:path\"\nimport { Effect, FileSystem, Schedule, Schema } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { OPENCODE_VERSION } from \"../version\"\n\nconst infoJson = Schema.fromJsonString(Service.Info)\nconst encodeInfo = Schema.encodeEffect(infoJson)\nconst decodeInfo = Schema.decodeUnknownEffect(infoJson)\n\nexport const register = Effect.fnUntraced(function* (options: {\n readonly address: HttpServer.Address\n readonly password: string\n readonly id: string\n readonly file: string\n readonly shutdown: Effect.Effect<void>\n}) {\n const fs = yield* FileSystem.FileSystem\n const temp = options.file + \".\" + options.id + \".tmp\"\n yield* fs.makeDirectory(path.dirname(options.file), { recursive: true })\n const info = {\n id: options.id,\n version: OPENCODE_VERSION,\n url: HttpServer.formatAddress(options.address),\n pid: process.pid,\n password: options.password,\n }\n const encoded = yield* encodeInfo(info)\n const current = fs.readFileString(options.file).pipe(Effect.flatMap(decodeInfo))\n const owns = (found: Info) =>\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, options.file)))\n yield* current.pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(\"managed service registration check failed; shutting down\", {\n cause,\n serviceID: options.id,\n servicePID: process.pid,\n registration: options.file,\n }).pipe(Effect.andThen(Effect.failCause(cause))),\n ),\n Effect.tap((found) =>\n owns(found)\n ? Effect.void\n : Effect.logWarning(\"managed service registration replaced; shutting down\", {\n serviceID: options.id,\n servicePID: process.pid,\n registration: options.file,\n observedServiceID: found.id,\n observedServicePID: found.pid,\n observedVersion: found.version,\n observedURL: found.url,\n }),\n ),\n Effect.filterOrFail(owns),\n Effect.repeat(Schedule.spaced(\"5 seconds\")),\n Effect.ignore,\n Effect.andThen(options.shutdown),\n Effect.forkScoped,\n )\n return current.pipe(\n Effect.flatMap((found) => (owns(found) ? fs.remove(options.file) : Effect.void)),\n Effect.ignore,\n )\n})\n", | ||
| "import { FSUtil } from \"@opencode-ai/util/fs-util\"\nimport { Effect, FileSystem } from \"effect\"\nimport { HttpServerError, HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\"\nimport { createHash } from \"node:crypto\"\nimport { load, type AssetMap } from \"../app-assets\"\n\nexport const handler = Effect.fn(\"cli.web-ui.handler\")(function* (options?: { readonly assets?: AssetMap }) {\n const fileSystem = yield* FileSystem.FileSystem\n const assets = options?.assets\n ? Effect.succeed(options.assets)\n : yield* Effect.cached(load().pipe(Effect.provideService(FileSystem.FileSystem, fileSystem)))\n return <E, R>(api: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>) =>\n api.pipe(\n Effect.catchIf(isRouteNotFound, () =>\n HttpServerRequest.HttpServerRequest.pipe(\n Effect.flatMap((request) => {\n const url = new URL(request.url, \"http://localhost\")\n if (url.pathname === \"/api\" || url.pathname.startsWith(\"/api/\"))\n return Effect.succeed(HttpServerResponse.empty({ status: 404 }))\n return assets.pipe(Effect.flatMap((files) => serveUI(request, url, files)))\n }),\n ),\n ),\n )\n})\n\nfunction serveUI(request: HttpServerRequest.HttpServerRequest, url: URL, assets: AssetMap) {\n const key = url.pathname.replace(/^\\//, \"\")\n const name = assets[key] !== undefined ? key : \"index.html\"\n const file = assets[name]\n if (!file) return Effect.succeed(HttpServerResponse.empty({ status: 404 }))\n if (request.method !== \"GET\" && request.method !== \"HEAD\")\n return Effect.succeed(HttpServerResponse.empty({ status: 405 }))\n const html = name === \"index.html\"\n const revalidate = html || name === \"sw.js\" || name === \"registerSW.js\"\n const headers = {\n \"content-type\": FSUtil.mimeType(name),\n \"cache-control\": revalidate ? \"no-cache\" : \"public, max-age=31536000, immutable\",\n \"content-security-policy\": html\n ? cspForHtml(typeof file === \"string\" ? file : Buffer.from(file).toString())\n : csp(),\n \"x-content-type-options\": \"nosniff\",\n }\n return Effect.succeed(\n request.method === \"HEAD\"\n ? HttpServerResponse.empty({ headers })\n : HttpServerResponse.raw(file, { headers, contentType: headers[\"content-type\"] }),\n )\n}\n\nfunction isRouteNotFound(error: unknown) {\n return error instanceof HttpServerError.HttpServerError && error.reason._tag === \"RouteNotFound\"\n}\n\nfunction csp(hash = \"\") {\n return `default-src 'self'; script-src 'self' 'wasm-unsafe-eval'${hash ? ` 'sha256-${hash}'` : \"\"}; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: blob:; font-src 'self' data:; media-src 'self' data:; connect-src * data: blob:`\n}\n\nfunction cspForHtml(body: string) {\n const match = body.match(\n /<script\\b(?![^>]*\\bsrc\\s*=)[^>]*\\bid=([\"'])oc-theme-preload-script\\1[^>]*>([\\s\\S]*?)<\\/script>/i,\n )\n return csp(match ? createHash(\"sha256\").update(match[2]).digest(\"base64\") : \"\")\n}\n\nexport * as WebUi from \"./web-ui\"\n", | ||
| "import { Effect, FileSystem, Option } from \"effect\"\nimport path from \"node:path\"\nimport { brotliDecompressSync } from \"node:zlib\"\nimport { OPENCODE_LOCAL } from \"./version\"\n\nexport type AssetMap = Readonly<Record<string, string | Uint8Array>>\ntype EncodedAssetMap = Readonly<Record<string, { readonly content: string; readonly encoding: \"utf8\" | \"base64\" }>>\n\nexport const load = Effect.fn(\"cli.app-assets.load\")(function* () {\n const embedded = yield* Effect.tryPromise(() => import(\"virtual:opencode-app-assets\")).pipe(Effect.option)\n if (Option.isSome(embedded) && embedded.value.default.length > 0) return decodeArchive(embedded.value.default)\n if (!OPENCODE_LOCAL) return yield* Effect.fail(new Error(\"Web UI assets are missing from the CLI build\"))\n return decode(yield* sourceAssets())\n})\n\nfunction decodeArchive(archive: string) {\n const body = brotliDecompressSync(Buffer.from(archive, \"base64\")).toString()\n return decode(JSON.parse(body) as EncodedAssetMap)\n}\n\nconst sourceAssets = Effect.fnUntraced(function* () {\n const fs = yield* FileSystem.FileSystem\n const root = path.resolve(import.meta.dirname, \"../../app/dist\")\n const files = yield* fs.readDirectory(root, { recursive: true })\n return Object.fromEntries(\n (yield* Effect.forEach(\n files.filter((file) => !file.endsWith(\".map\")),\n Effect.fnUntraced(function* (file) {\n const target = path.join(root, file)\n if ((yield* fs.stat(target)).type === \"Directory\") return\n const body = Buffer.from(yield* fs.readFile(target))\n const encoding = isText(file) ? \"utf8\" : \"base64\"\n return [file, { encoding, content: body.toString(encoding) }] as const\n }),\n { concurrency: \"unbounded\" },\n )).filter((asset) => asset !== undefined),\n )\n})\n\nfunction decode(assets: EncodedAssetMap): AssetMap {\n return Object.fromEntries(\n Object.entries(assets).map(([key, asset]) => [\n key,\n asset.encoding === \"utf8\" ? asset.content : Buffer.from(asset.content, \"base64\"),\n ]),\n )\n}\n\nfunction isText(file: string) {\n return file === \"_headers\" || /\\.(?:css|html|js|json|svg|txt|webmanifest|xml)$/.test(file)\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": ";urCAQA,sBAAS,gBAAa,0ECLtB,qBAKA,IAAM,EAAW,EAAO,eAAe,EAAQ,IAAI,EAC7C,GAAa,EAAO,aAAa,CAAQ,EACzC,GAAa,EAAO,oBAAoB,CAAQ,EAEzC,GAAW,EAAO,WAAW,SAAU,CAAC,EAMlD,CACD,IAAM,EAAK,MAAO,EAAW,WACvB,EAAO,EAAQ,KAAO,IAAM,EAAQ,GAAK,OAC/C,MAAO,EAAG,cAAc,GAAK,QAAQ,EAAQ,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EACvE,IAAM,EAAO,CACX,GAAI,EAAQ,GACZ,QAAS,EACT,IAAK,EAAW,cAAc,EAAQ,OAAO,EAC7C,IAAK,QAAQ,IACb,SAAU,EAAQ,QACpB,EACM,EAAU,MAAO,GAAW,CAAI,EAChC,EAAU,EAAG,eAAe,EAAQ,IAAI,EAAE,KAAK,EAAO,QAAQ,EAAU,CAAC,EACzE,EAAO,CAAC,IACZ,EAAM,KAAO,EAAK,IAClB,EAAM,UAAY,EAAK,SACvB,EAAM,MAAQ,EAAK,KACnB,EAAM,MAAQ,EAAK,KACnB,EAAM,WAAa,EAAK,SA8B1B,OA7BA,MAAO,EAAG,gBAAgB,EAAM,EAAS,CAAE,KAAM,GAAM,CAAC,EAAE,KAAK,EAAO,QAAQ,EAAG,OAAO,EAAM,EAAQ,IAAI,CAAC,CAAC,EAC5G,MAAO,EAAQ,KACb,EAAO,WAAW,CAAC,IACjB,EAAO,WAAW,2DAA4D,CAC5E,QACA,UAAW,EAAQ,GACnB,WAA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I,IAAI,KAAc,KAAY,IAG1E,SAAS,CAAM,CAAC,EAAgB,CAC9B,OAAO,IAAU,KAAO,GAAO,YAAY,IAAM,OAGnD,SAAS,CAAY,CAAC,EAAyB,CAC7C,GAAI,OAAO,IAAU,UAAY,IAAU,KAAM,MAAO,GACxD,GAAI,SAAU,GAAS,EAAM,OAAS,aAAc,MAAO,GAC3D,MAAO,UAAW,GAAS,EAAa,EAAM,KAAK,EAGrD,SAAS,EAAiB,EAAG,CAC3B,OAAO,EAAO,SAAe,CAAC,IAAW,CACvC,IAAM,EAAQ,IAAM,EAAO,EAAO,IAAI,EAItC,GAHA,QAAQ,MAAM,KAAK,MAAO,CAAK,EAC/B,QAAQ,MAAM,KAAK,QAAS,CAAK,EACjC,QAAQ,MAAM,OAAO,EACjB,QAAQ,MAAM,eAAiB,QAAQ,MAAM,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,EInMH,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": "6520F46A7B01089964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/remove.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { readFile, rename, writeFile } from \"node:fs/promises\"\nimport { Effect } from \"effect\"\nimport { applyEdits, modify, parse, type ParseError } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Config } from \"../../../config\"\nimport { resolveConfigPath } from \"../mcp/add\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.remove,\n Effect.fn(\"cli.plugin.remove\")(function* (input) {\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(global.config))\n const server = yield* Effect.promise(() => removePluginConfig(configPath, input.package))\n const config = yield* Config.Service\n const info = yield* config.get()\n const tui = configured(info.plugins, input.package)\n if (tui)\n yield* config.update((draft) => {\n draft.plugins = draft.plugins?.filter((entry) => !matches(entry, input.package))\n })\n\n const removed = [server ? configPath : undefined, tui ? config.path : undefined].filter(\n (file) => file !== undefined,\n )\n process.stdout.write(\n removed.length\n ? `Plugin \"${input.package}\" removed from ${removed.join(\", \")}${EOL}`\n : `Plugin \"${input.package}\" is not configured${EOL}`,\n )\n }),\n)\n\nexport async function removePluginConfig(configPath: string, spec: string) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return undefined\n throw error\n })\n if (text === undefined) return false\n const errors: ParseError[] = []\n const config: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length || typeof config !== \"object\" || config === null || Array.isArray(config))\n throw new Error(`Invalid global configuration: ${configPath}`)\n const plugins = \"plugins\" in config ? config.plugins : undefined\n if (plugins !== undefined && !Array.isArray(plugins)) throw new Error(`Invalid plugins configuration: ${configPath}`)\n if (!configured(plugins, spec)) return false\n\n const updated = applyEdits(\n text,\n modify(\n text,\n [\"plugins\"],\n plugins?.filter((entry) => !matches(entry, spec)),\n {\n formattingOptions: { tabSize: 2, insertSpaces: true },\n },\n ),\n )\n const temporary = configPath + \".tmp\"\n await writeFile(temporary, updated.endsWith(\"\\n\") ? updated : updated + \"\\n\", { mode: 0o600 })\n await rename(temporary, configPath)\n return true\n}\n\nfunction configured(plugins: readonly unknown[] | undefined, spec: string) {\n return plugins?.some((entry) => matches(entry, spec)) ?? false\n}\n\nfunction matches(entry: unknown, spec: string) {\n return entry === spec || (typeof entry === \"object\" && entry !== null && \"package\" in entry && entry.package === spec)\n}\n" | ||
| ], | ||
| "mappings": ";itBAAA,cAAS,WAET,mBAAS,YAAU,eAAQ,oBAS3B,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,OAClC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,IAAM,EAAS,MAAO,EAAO,QACvB,EAAa,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAO,MAAM,CAAC,EACzE,EAAS,MAAO,EAAO,QAAQ,IAAM,EAAmB,EAAY,EAAM,OAAO,CAAC,EAClF,EAAS,MAAO,EAAO,QACvB,EAAO,MAAO,EAAO,IAAI,EACzB,EAAM,EAAW,EAAK,QAAS,EAAM,OAAO,EAClD,GAAI,EACF,MAAO,EAAO,OAAO,CAAC,IAAU,CAC9B,EAAM,QAAU,EAAM,SAAS,OAAO,CAAC,IAAU,CAAC,EAAQ,EAAO,EAAM,OAAO,CAAC,EAChF,EAEH,IAAM,EAAU,CAAC,EAAS,EAAa,OAAW,EAAM,EAAO,KAAO,MAAS,EAAE,OAC/E,CAAC,IAAS,IAAS,MACrB,EACA,QAAQ,OAAO,MACb,EAAQ,OACJ,WAAW,EAAM,yBAAyB,EAAQ,KAAK,IAAI,IAAI,IAC/D,WAAW,EAAM,6BAA6B,GACpD,EACD,CACH,EAEA,eAAsB,CAAkB,CAAC,EAAoB,EAAc,CACzE,IAAM,EAAO,MAAM,EAAS,EAAY,MAAM,EAAE,MAAM,CAAC,IAAU,CAC/D,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,SAAU,GAAS,EAAM,OAAS,SAAU,OAC/F,MAAM,EACP,EACD,GAAI,IAAS,OAAW,MAAO,GAC/B,IAAM,EAAuB,CAAC,EACxB,EAAkB,EAAM,EAAM,EAAQ,CAAE,mBAAoB,EAAK,CAAC,EACxE,GAAI,EAAO,QAAU,OAAO,IAAW,UAAY,IAAW,MAAQ,MAAM,QAAQ,CAAM,EACxF,MAAU,MAAM,iCAAiC,GAAY,EAC/D,IAAM,EAAU,YAAa,EAAS,EAAO,QAAU,OACvD,GAAI,IAAY,QAAa,CAAC,MAAM,QAAQ,CAAO,EAAG,MAAU,MAAM,kCAAkC,GAAY,EACpH,GAAI,CAAC,EAAW,EAAS,CAAI,EAAG,MAAO,GAEvC,IAAM,EAAU,EACd,EACA,EACE,EACA,CAAC,SAAS,EACV,GAAS,OAAO,CAAC,IAAU,CAAC,EAAQ,EAAO,CAAI,CAAC,EAChD,CACE,kBAAmB,CAAE,QAAS,EAAG,aAAc,EAAK,CACtD,CACF,CACF,EACM,EAAY,EAAa,OAG/B,OAFA,MAAM,EAAU,EAAW,EAAQ,SAAS;AAAA,CAAI,EAAI,EAAU,EAAU;AAAA,EAAM,CAAE,KAAM,GAAM,CAAC,EAC7F,MAAM,EAAO,EAAW,CAAU,EAC3B,GAGT,SAAS,CAAU,CAAC,EAAyC,EAAc,CACzE,OAAO,GAAS,KAAK,CAAC,IAAU,EAAQ,EAAO,CAAI,CAAC,GAAK,GAG3D,SAAS,CAAO,CAAC,EAAgB,EAAc,CAC7C,OAAO,IAAU,GAAS,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,EAAM,UAAY", | ||
| "debugId": "AABB0F36D3B15AA864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../protocol/src/client.ts"], | ||
| "sourcesContent": [ | ||
| "import { InvalidRequestError, SessionNotFoundError } from \"./errors.js\"\nimport { makeDefaultApi } from \"./api.js\"\nimport type { Api } from \"./api.js\"\nimport type { Context } from \"effect\"\nimport { HttpApiMiddleware } from \"effect/unstable/httpapi\"\nimport type { EventGroup } from \"./groups/event.js\"\n\nclass LocationMiddleware extends HttpApiMiddleware.Service<LocationMiddleware>()(\n \"@opencode-ai/client/LocationMiddleware\",\n) {}\n\nclass SessionLocationMiddleware extends HttpApiMiddleware.Service<SessionLocationMiddleware>()(\n \"@opencode-ai/client/SessionLocationMiddleware\",\n { error: [InvalidRequestError, SessionNotFoundError] },\n) {}\n\ntype ClientApiShape = Api<\n Context.Service.Identifier<typeof LocationMiddleware>,\n Context.Service.Shape<typeof LocationMiddleware>,\n Context.Service.Identifier<typeof SessionLocationMiddleware>,\n Context.Service.Shape<typeof SessionLocationMiddleware>,\n Context.Service.Identifier<typeof SessionLocationMiddleware>,\n Context.Service.Shape<typeof SessionLocationMiddleware>,\n typeof EventGroup\n>\n\nexport const ClientApi: ClientApiShape = makeDefaultApi({\n locationMiddleware: LocationMiddleware,\n // The real server uses a form-specific middleware with an undocumented `global` sentinel branch.\n // The generated client only needs a middleware identity for API typing.\n formLocationMiddleware: SessionLocationMiddleware,\n sessionLocationMiddleware: SessionLocationMiddleware,\n})\n\nexport const groupNames = {\n \"server.health\": \"health\",\n \"server.server\": \"server\",\n \"server.debug\": \"debug\",\n \"server.migration\": \"migration\",\n \"server.location\": \"location\",\n \"server.agent\": \"agent\",\n \"server.plugin\": \"plugin\",\n \"server.session\": \"session\",\n \"server.message\": \"message\",\n \"server.model\": \"model\",\n \"server.generate\": \"generate\",\n \"server.provider\": \"provider\",\n \"server.integration\": \"integration\",\n \"server.websearch\": \"websearch\",\n \"server.credential\": \"credential\",\n \"server.form\": \"form\",\n \"server.permission\": \"permission\",\n \"server.fs\": \"file\",\n \"server.command\": \"command\",\n \"server.skill\": \"skill\",\n \"server.event\": \"event\",\n \"server.pty\": \"pty\",\n \"server.shell\": \"shell\",\n \"server.mcp\": \"mcp\",\n \"server.reference\": \"reference\",\n \"server.project\": \"project\",\n \"server.worktree\": \"worktree\",\n \"server.vcs\": \"vcs\",\n \"server.config\": \"config\",\n} as const\n\nexport const promiseOmitEndpoints = new Set([\"pty.connect\"])\nexport const effectOmitEndpoints = new Set([\"fs.read\", \"pty.connect\"])\n" | ||
| ], | ||
| "mappings": ";giCAOA,MAAM,UAA2B,EAAkB,QAA4B,EAC7E,wCACF,CAAE,CAAC,CAEH,MAAM,UAAkC,EAAkB,QAAmC,EAC3F,gDACA,CAAE,MAAO,CAAC,EAAqB,CAAoB,CAAE,CACvD,CAAE,CAAC,CAYI,IAAM,EAA4B,EAAe,CACtD,mBAAoB,EAGpB,uBAAwB,EACxB,0BAA2B,CAC7B,CAAC,EAEY,EAAa,CACxB,gBAAiB,SACjB,gBAAiB,SACjB,eAAgB,QAChB,mBAAoB,YACpB,kBAAmB,WACnB,eAAgB,QAChB,gBAAiB,SACjB,iBAAkB,UAClB,iBAAkB,UAClB,eAAgB,QAChB,kBAAmB,WACnB,kBAAmB,WACnB,qBAAsB,cACtB,mBAAoB,YACpB,oBAAqB,aACrB,cAAe,OACf,oBAAqB,aACrB,YAAa,OACb,iBAAkB,UAClB,eAAgB,QAChB,eAAgB,QAChB,aAAc,MACd,eAAgB,QAChB,aAAc,MACd,mBAAoB,YACpB,iBAAkB,UAClB,kBAAmB,WACnB,aAAc,MACd,gBAAiB,QACnB,EAEa,EAAuB,IAAI,IAAI,CAAC,aAAa,CAAC,EAC9C,EAAsB,IAAI,IAAI,CAAC,UAAW,aAAa,CAAC", | ||
| "debugId": "7BC06388B594A2EA64756E2164756E21", | ||
| "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": ";+2BAMA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,KACnC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,MAAO,EAAQ,KAAK,MAAO,EAAc,QAAQ,CAAC,EACnD,CACH", | ||
| "debugId": "7FBFFF7DC2F38B5764756E2164756E21", | ||
| "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": ";wZAwBA,IAAI,EAAwB,EAC1B,IAAM,EACJ,EAAE,OAAO,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,EACx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AAI,EACT,EACA,EAAqB,MAAM,CAC7B,EAEI,EAAwB,CAAC,IAAY,IAAI,EAC7C,EACA,EAAqB,YAAY,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": "27444F908518DACA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/logout.ts"], | ||
| "sourcesContent": [ | ||
| "import { autocomplete, intro, outro, spinner } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport type { IntegrationInfo } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { handlePromptErrors, prompt, requireInteractive } from \"../../../ui/prompt\"\nimport { createClient, loadIntegrations, location, request, resolveIntegration } from \"./shared\"\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.logout,\n Effect.fn(\"cli.auth.logout\")((input) =>\n logout({\n target: Option.getOrUndefined(input.target),\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n }).pipe(handlePromptErrors),\n ),\n)\n\nconst logout = Effect.fn(\"cli.auth.logout.run\")(function* (input: {\n target?: string\n server?: string\n standalone: boolean\n}) {\n if (!input.target)\n yield* requireInteractive(\"Pass an integration ID or name when running without an interactive terminal\")\n intro(\"Remove credential\")\n const client = yield* createClient({ server: input.server, standalone: input.standalone })\n const integrations = yield* loadIntegrations(client)\n const integration = yield* chooseIntegration(integrations, input.target)\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n const environment = integration.connections\n .filter((connection) => connection.type === \"env\")\n .map((connection) => connection.name)\n if (environment.length) {\n yield* Effect.fail(\n new Error(\n `${integration.name} is authenticated through ${environment.join(\", \")}; unset the environment variable to disconnect`,\n ),\n )\n }\n yield* Effect.fail(new Error(`No stored credentials for ${integration.name}`))\n }\n const progress = spinner()\n progress.start(\"Removing credential...\")\n yield* Effect.forEach(\n credentials,\n (connection) =>\n request((signal) => client.credential.remove({ credentialID: connection.id, location }, { signal })),\n { concurrency: \"unbounded\", discard: true },\n ).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(`Disconnected from ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Failed to remove credential\", 1))),\n )\n outro(\"Done\")\n})\n\nconst chooseIntegration = Effect.fn(\"cli.auth.logout.integration\")(function* (\n integrations: IntegrationInfo[],\n target?: string,\n) {\n if (target) return yield* resolveIntegration(integrations, target)\n const configured = integrations.filter((integration) =>\n integration.connections.some((connection) => connection.type === \"credential\"),\n )\n if (configured.length === 0) return yield* Effect.fail(new Error(\"No stored credentials found\"))\n const id = yield* prompt<string>(() =>\n autocomplete({\n message: \"Select integration\",\n maxItems: 8,\n options: configured.map((integration) => ({\n value: integration.id,\n label: integration.name,\n hint: integration.connections\n .filter((connection) => connection.type === \"credential\")\n .map((connection) => connection.label)\n .join(\", \"),\n })),\n }),\n )\n return yield* resolveIntegration(configured, id)\n})\n" | ||
| ], | ||
| "mappings": ";2yCAQA,IAAe,IAAQ,QACrB,EAAS,SAAS,KAAK,SAAS,OAChC,EAAO,GAAG,iBAAiB,EAAE,CAAC,IAC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GAAG,6BAA6B,EAAE,SAAU,CAC3E,EACA,EACA,CACA,GAAI,EAAQ,OAAO,MAAO,EAAmB,EAAc,CAAM,EACjE,IAAM,EAAa,EAAa,OAAO,CAAC,IACtC,EAAY,YAAY,KAAK,CAAC,IAAe,EAAW,OAAS,YAAY,CAC/E,EACA,GAAI,EAAW,SAAW,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,6BAA6B,CAAC,EAC/F,IAAM,EAAK,MAAO,EAAe,IAC/B,EAAa,CACX,QAAS,qBACT,SAAU,EACV,QAAS,EAAW,IAAI,CAAC,KAAiB,CACxC,MAAO,EAAY,GACnB,MAAO,EAAY,KACnB,KAAM,EAAY,YACf,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACvD,IAAI,CAAC,IAAe,EAAW,KAAK,EACpC,KAAK,IAAI,CACd,EAAE,CACJ,CAAC,CACH,EACA,OAAO,MAAO,EAAmB,EAAY,CAAE,EAChD", | ||
| "debugId": "4B6EAF6059DE1C9364756E2164756E21", | ||
| "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/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\"\nimport { Env } from \"./env\"\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 paths: { home: string; state: string; log: string }\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 environment = input.server.reconnect ? Env.session() : undefined\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 environment,\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 environment,\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, paths: input.paths }),\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 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 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": ";stBAGA,qBAAS,wBCDT,kBACA,mBAAS,oBACT,oBACA,qBAAS,YAEF,IAAM,EAA0B,0DASvC,SAAS,CAAW,CAAC,EAA4C,CAC/D,IAAM,EAAa,EAAgC,EAAK,KAAK,EAAW,YAAY,CAAC,EACrF,MAAO,MACC,eAAc,CAAC,EAAO,CAC1B,GAAI,CAAC,EAAO,OACZ,OAAO,EAAW,eAAe,CAAK,QAElC,YAAW,CAAC,EAAO,EAAS,CAChC,GAAI,CAAC,EAAO,OACZ,MAAM,EAAW,YAAY,EAAO,CAAO,EAAE,MAAM,IAAG,CAAG,OAAS,EAEtE,EAGF,SAAS,CAAM,CAAC,EAA2D,CACzE,MAAO,CACL,SA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": "E188D5ABAB522A3164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "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\"\nimport { errorMessage } from \"../../../util/error\"\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(() =>\n timeline.failure(cancelled ? \"Authorization cancelled\" : errorMessage(Cause.squash(exit.cause))),\n ).pipe(Effect.ignore)\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 ...(server ? { answer: { 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" | ||
| ], | ||
| "mappings": ";wrCAYA,EAAwB,EACxB,IAAM,GAAiB,CAAC,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,QAAG,EAClE,GAAe,KACf,EAAS,CACb,OAAQ,EAAK,UAAU,CAAC,EACxB,MAAO,EAAK,UAAU,CAAC,EACvB,WAAY,EAAK,kBAAkB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"import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { createClient, loadIntegrations } from \"./shared\"\nimport { errorMessage } from \"../../../util/error\"\n\nexport default Runtime.handler(Commands.commands.auth.commands.list, (input) =>\n list(input).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n)\n\nconst list = Effect.fn(\"cli.auth.list\")(function* (input) {\n const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })\n const integrations = (yield* loadIntegrations(client)).filter((integration) => integration.connections.length > 0)\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify(\n integrations.map((integration) => ({\n id: integration.id,\n name: integration.name,\n connections: integration.connections,\n })),\n null,\n 2,\n ) + EOL,\n )\n return\n }\n const rows = integrations.flatMap((integration) =>\n integration.connections.map((connection) => ({\n integration: integration.name,\n source: connection.type === \"credential\" ? connection.label : connection.name,\n type: connection.type === \"credential\" ? \"stored\" : \"environment\",\n })),\n )\n if (rows.length === 0) {\n process.stdout.write(\"No authenticated integrations\" + EOL)\n return\n }\n const width = Math.max(...rows.map((row) => row.integration.length)) + 2\n process.stdout.write(\n rows.map((row) => row.integration.padEnd(width) + row.source.padEnd(28) + row.type).join(EOL) + EOL,\n )\n})\n" | ||
| ], | ||
| "mappings": ";ymCAAA,cAAS,WAOT,IAAe,IAAQ,QAAQ,EAAS,SAAS,KAAK,SAAS,KAAM,CAAC,IACpE,EAAK,CAAK,EAAE,KACV,EAAO,MAAM,CAAC,IACZ,EAAO,KAAK,IAAM,CAChB,QAAQ,OAAO,MAAM,EAAa,CAAK,EAAI,CAAG,EAC9C,QAAQ,SAAW,EACpB,CACH,CACF,CACF,EAEM,EAAO,EAAO,GAAG,eAAe,EAAE,SAAU,CAAC,EAAO,CACxD,IAAM,EAAS,MAAO,EAAa,CAAE,OAAQ,EAAO,eAAe,EAAM,MAAM,EAAG,WAAY,EAAM,UAAW,CAAC,EAC1G,GAAgB,MAAO,EAAiB,CAAM,GAAG,OAAO,CAAC,IAAgB,EAAY,YAAY,OAAS,CAAC,EACjH,GAAI,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UACH,EAAa,IAAI,CAAC,KAAiB,CACjC,GAAI,EAAY,GAChB,KAAM,EAAY,KAClB,YAAa,EAAY,WAC3B,EAAE,EACF,KACA,CACF,EAAI,CACN,EACA,OAEF,IAAM,EAAO,EAAa,QAAQ,CAAC,IACjC,EAAY,YAAY,IAAI,CAAC,KAAgB,CAC3C,YAAa,EAAY,KACzB,OAAQ,EAAW,OAAS,aAAe,EAAW,MAAQ,EAAW,KACzE,KAAM,EAAW,OAAS,aAAe,SAAW,aACtD,EAAE,CACJ,EACA,GAAI,EAAK,SAAW,EAAG,CACrB,QAAQ,OAAO,MAAM,gCAAkC,CAAG,EAC1D,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAK,IAAI,CAAC,IAAQ,EAAI,YAAY,MAAM,CAAC,EAAI,EACvE,QAAQ,OAAO,MACb,EAAK,IAAI,CAAC,IAAQ,EAAI,YAAY,OAAO,CAAK,EAAI,EAAI,OAAO,OAAO,EAAE,EAAI,EAAI,IAAI,EAAE,KAAK,CAAG,EAAI,CAClG,EACD", | ||
| "debugId": "05372AD263C2F16864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "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": ";wUAYA,IAAI,EAAiB,SAGrB,SAAS,CAAY,CAAC,EAAU,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,IAChB,IAAI,EAAkC,EAAS,IACjD,EAAqB,MAAM,CAChC,CAAC,EAEG,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": "7114E7733028FD1164756E2164756E21", | ||
| "names": [] | ||
| } |
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}\nv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AAC,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": "B845AFBAA6A2544664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/import.ts"], | ||
| "sourcesContent": [ | ||
| "import { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Session } from \"@opencode-ai/schema/session\"\nimport { SessionTransfer } from \"@opencode-ai/schema/session-transfer\"\nimport { Effect, Option, Schema } from \"effect\"\nimport { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.import,\n Effect.fn(\"cli.import\")(function* (input) {\n const text = yield* Effect.tryPromise({\n try: () =>\n input.file.startsWith(\"http://\") || input.file.startsWith(\"https://\")\n ? fetch(input.file).then((response) => {\n if (!response.ok) throw new Error(`Failed to fetch session data: ${response.statusText}`)\n return response.text()\n })\n : Bun.file(input.file).text(),\n catch: (cause) =>\n new Error(`Failed to read session data: ${cause instanceof Error ? cause.message : String(cause)}`),\n })\n const data = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(SessionTransfer.Data))(text)\n const encoded = Schema.encodeSync(SessionTransfer.Data)(data)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const location = yield* Effect.promise(() =>\n client.location.get({\n location: { directory: path.resolve(Option.getOrElse(input.directory, () => process.cwd())) },\n }),\n )\n const response = yield* Effect.promise(() =>\n fetch(new URL(\"/api/session/import\", server.endpoint.url), {\n method: \"POST\",\n headers: { ...Service.headers(server.endpoint), \"content-type\": \"application/json\" },\n body: JSON.stringify({\n ...encoded,\n location: { directory: location.directory, workspaceID: location.workspaceID },\n }),\n }),\n )\n if (response.status === 409) {\n process.stderr.write(`Session already exists${EOL}`)\n return\n }\n if (!response.ok) yield* Effect.fail(new Error(`Failed to import session: ${response.statusText}`))\n const imported = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Struct({ data: Session.Info })))(\n yield* Effect.promise(() => response.text()),\n )\n process.stdout.write(`Imported session: ${imported.data.id}${EOL}`)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";03CAKA,cAAS,WACT,oBAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,SAAU,CAAC,EAAO,CACxC,IAAM,EAAO,MAAO,EAAO,WAAW,CACpC,IAAK,IACH,EAAM,KAAK,WAAW,SAAS,GAAK,EAAM,KAAK,WAAW,UAAU,EAChE,MAAM,EAAM,IAAI,EAAE,KAAK,CAAC,IAAa,CACnC,GAAI,CAAC,EAAS,GAAI,MAAU,MAAM,iCAAiC,EAAS,YAAY,EACxF,OAAO,EAAS,KAAK,EACtB,EACD,IAAI,KAAK,EAAM,IAAI,EAAE,KAAK,EAChC,MAAO,CAAC,IACF,MAAM,gCAAgC,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,GAAG,CACtG,CAAC,EACK,EAAO,MAAO,EAAO,oBAAoB,EAAO,eAAe,EAAgB,IAAI,CAAC,EAAE,CAAI,EAC1F,EAAU,EAAO,WAAW,EAAgB,IAAI,EAAE,CAAI,EACtD,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAAS,EAAS,KAAK,CAC3B,QAAS,EAAO,SAAS,IACzB,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAC1C,CAAC,EACK,EAAW,MAAO,EAAO,QAAQ,IACrC,EAAO,SAAS,IAAI,CAClB,SAAU,CAAE,UAAW,EAAK,QAAQ,EAAO,UAAU,EAAM,UAAW,IAAM,QAAQ,IAAI,CAAC,CAAC,CAAE,CAC9F,CAAC,CACH,EACM,EAAW,MAAO,EAAO,QAAQ,IACrC,MAAM,IAAI,IAAI,sBAAuB,EAAO,SAAS,GAAG,EAAG,CACzD,OAAQ,OACR,QAAS,IAAK,EAAQ,QAAQ,EAAO,QAAQ,EAAG,eAAgB,kBAAmB,EACnF,KAAM,KAAK,UAAU,IAChB,EACH,SAAU,CAAE,UAAW,EAAS,UAAW,YAAa,EAAS,WAAY,CAC/E,CAAC,CACH,CAAC,CACH,EACA,GAAI,EAAS,SAAW,IAAK,CAC3B,QAAQ,OAAO,MAAM,yBAAyB,GAAK,EACnD,OAEF,GAAI,CAAC,EAAS,GAAI,MAAO,EAAO,KAAS,MAAM,6BAA6B,EAAS,YAAY,CAAC,EAClG,IAAM,EAAW,MAAO,EAAO,oBAAoB,EAAO,eAAe,EAAO,OAAO,CAAE,KAAM,EAAQ,IAAK,CAAC,CAAC,CAAC,EAC7G,MAAO,EAAO,QAAQ,IAAM,EAAS,KAAK,CAAC,CAC7C,EACA,QAAQ,OAAO,MAAM,qBAAqB,EAAS,KAAK,KAAK,GAAK,EACnE,CACH", | ||
| "debugId": "2B2AA16D2C92F4D864756E2164756E21", | ||
| "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/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": ";+2BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,OACnC,EAAO,GAAG,oBAAoB,EAAE,SAAU,EAAG,CAC3C,IAAM,EAAU,MAAO,EAAc,QAAQ,EACvC,EAAQ,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,EACxE,QAAQ,OAAO,OAAO,GAAO,KAAO,WAAa,CAAG,EACrD,CACH", | ||
| "debugId": "DF16EA2772FD567B64756E2164756E21", | ||
| "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\"\nimport { Env } from \"../env\"\nimport { errorMessage } from \"../util/error\"\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({\n baseUrl: endpoint.url,\n headers: Service.headers(endpoint),\n // Bun's default five-minute deadline terminates the event stream used by long-running sessions.\n fetch: ((request: RequestInfo | URL, init?: RequestInit) =>\n fetch(request, { ...init, timeout: false } as BunFetchRequestInit)) as typeof fetch,\n })\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 environment: input.server.service ? Env.session() : undefined,\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\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 LocationRef,\n OpenCodeClient,\n SessionMessageAssistantTool,\n SessionMessageInfo,\n ToolContent,\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 { nonEmptyToolContent, 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 metadata: Record<string, JsonValue>\n content: ToolContent[]\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.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.inbox.delivered\") {\n if (event.data.inboxID === 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.id), {\n id: partID(event.id),\n timestamp: time,\n assistantMessageID: event.data.assistantMessageID,\n tool: event.data.name,\n input: {},\n metadata: {},\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.id))\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.id))\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.id)\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 metadata: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.progress\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.id))\n if (current) {\n current.metadata = event.data.metadata\n }\n continue\n }\n if (event.type === \"session.tool.success\") {\n const key = toolKey(event.data.assistantMessageID, event.data.id)\n const current = tools.get(key) ?? fallbackTool(event)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.id,\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 metadata: event.data.metadata,\n content: event.data.content,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n partID: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n id: event.data.id,\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 metadata: event.data.metadata,\n content: event.data.content,\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.id)\n const current = tools.get(key) ?? fallbackTool(event)\n const error = event.data.error.message\n const metadata = event.data.metadata ?? current.metadata\n const content = event.data.content ?? nonEmptyToolContent(current.content)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.id,\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 metadata,\n content,\n error: event.data.error,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n partID: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n id: event.data.id,\n tool: current.tool,\n state: {\n status: \"error\",\n input: current.input,\n error,\n metadata: {\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 (content && toolOutputText(current.tool, content).trim())\n await input.renderTool({\n ...tool,\n state: {\n status: \"completed\",\n input: current.input,\n metadata,\n content,\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 (input.compatibility === \"v1\" && event.data.error.message === \"The provider response ended unexpectedly.\") {\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 partID: projectedPartID(message.id, `tool-${item.id}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"tool\",\n id: 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: { metadata: item.state.metadata, content: item.state.content },\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: { metadata: item.state.metadata, content: item.state.content },\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 (item.state.content && toolOutputText(item.name, item.state.content).trim()) {\n await input.renderTool({\n ...item,\n state: {\n status: \"completed\",\n input: item.state.input,\n metadata: item.state.metadata,\n content: item.state.content,\n },\n })\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, id: string) {\n return `${messageID}\\u0000${id}`\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; id: 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 metadata: {},\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.TE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AS,QAAS,CAGzB,GAFA,EAAG,MAAM,EACT,EAAG,QAAQ,EAAG,MAAM,YAAc,EAAK,KAAM,EAAG,MAAM,YAAc,EAAK,KAAK,EAC1E,EAAK,MAAM,KAAK,EAAG,EAAG,QAAQ,EAAK,IAAI,EAC3C,EAAG,MAAM,EACT,OAEF,EAAG,QACD,EAAG,MAAM,YAAc,EAAK,KAC5B,EAAG,MAAM,YAAc,EAAK,MAC5B,EAAK,YAAc,EAAG,MAAM,SAAW,EAAK,YAAc,EAAG,MAAM,YAAc,EACnF,EAGF,eAAe,EAAe,CAAC,EAAmC,EAAmB,CACnF,IAAM,EAAO,EAAe,EAAM,CAAS,EAC3C,EAAG,QAAQ,EAAG,MAAM,YAAc,SAAK,EAAG,MAAM,YAAc,GAAG,EAAK,cAAc,EAI/E,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": "8B4A09E79895D96664756E2164756E21", | ||
| "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": "DDBC4F65F18C8B7964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/unset.ts"], | ||
| "sourcesContent": [ | ||
| "import { 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.unset,\n Effect.fn(\"cli.service.unset\")(function* (input) {\n yield* ServiceConfig.unset(input.key, Option.getOrUndefined(input.name))\n }),\n)\n" | ||
| ], | ||
| "mappings": ";02BAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,MACnC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,MAAO,EAAc,MAAM,EAAM,IAAK,EAAO,eAAe,EAAM,IAAI,CAAC,EACxE,CACH", | ||
| "debugId": "E3E11B23E96E297C64756E2164756E21", | ||
| "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 endpoint = yield* Service.ensure(yield* ServiceConfig.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": ";u9BAAA,cAAS,WAST,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAE7B,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,OAC/B,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAO,CAC5C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,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": "B009A7B1E869B44D64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "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(` Run \\`opencode service set hostname 0.0.0.0\\` to access the service remotely.${EOL}${EOL}`)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";u9BAAA,cAAS,WAST,IAAe,IAAQ,QACrB,EAAS,SAAS,KAClB,EAAO,GAAG,UAAU,EAAE,SAAU,EAAG,CACjC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,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,MAAM,kFAAkF,IAAM,GAAK,EACnH,CACH", | ||
| "debugId": "29ED20E3B659990464756E2164756E21", | ||
| "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": ";qVAaA,IAAI,EAAiB,SAGjB,EAAsB,EAAE,OAAO,CACjC,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,IACpB,IAAI,EAAkC,EAAS,CACpD,SAAU,gBACV,IAAK,EAAG,UAAW,GAAG,IAAU,IAChC,QAAS,EACT,MAAO,EAAQ,MACf,eAAgB,EAChB,0BAA2B,EAC7B,CAAC,EAEG,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": "E7221602F939C1DF64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "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": ";+2BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,MACnC,EAAO,GAAG,mBAAmB,EAAE,SAAU,EAAG,CAC1C,IAAM,EAAY,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EACtE,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "C7090F2242BA364564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "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 endpoint = yield* Service.ensure(yield* ServiceConfig.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 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 \"failed\":\n return `failed: ${status.error}`\n default:\n return status.status\n }\n}\n" | ||
| ], | ||
| "mappings": ";m6BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,KAC/B,EAAO,GAAG,cAAc,EAAE,SAAU,EAAG,CACrC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,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,SACH,MAAO,iBAEP,MAAO,UAIb,SAAS,CAAQ,CAAC,EAA6B,CAC7C,OAAQ,EAAO,YACR,aACH,MAAO,2BACJ,SACH,MAAO,WAAW,EAAO,gBAEzB,OAAO,EAAO", | ||
| "debugId": "89DDBA589AB204AD64756E2164756E21", | ||
| "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, type PluginInfo } 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\"\nimport { Config } from \"../../../config\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { discoverTuiPlugins, tuiPluginDirectories } from \"@opencode-ai/tui/plugin/discovery\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.list,\n Effect.fn(\"cli.plugin.list\")(function* (input) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.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 config = yield* Config.Service\n const global = yield* Global.Service\n const info = yield* config.get()\n const discovered = yield* Effect.promise(() =>\n tuiPluginDirectories(process.cwd(), global.config).then(discoverTuiPlugins),\n )\n const output = format(\n response.data,\n [\n ...(info.plugins ?? []).flatMap((entry) => {\n const target = typeof entry === \"string\" ? entry : entry.package\n return target.startsWith(\"-\") ? [] : [{ target, source: \"configured\" as const }]\n }),\n ...discovered.map((target) => ({ target, source: \"discovered\" as const })),\n ],\n input.builtin,\n )\n if (!output) {\n process.stdout.write(\"No plugins found\" + EOL)\n return\n }\n process.stdout.write(output + EOL)\n }),\n)\n\nexport function format(\n plugins: readonly PluginInfo[],\n tui: ReadonlyArray<{ readonly target: string; readonly source: \"configured\" | \"discovered\" }>,\n builtin = false,\n) {\n const server = plugins\n .filter((plugin) => builtin || plugin.source.type !== \"builtin\")\n .toSorted((a, b) => name(a).localeCompare(name(b)))\n .map((plugin) => `${name(plugin)} (${plugin.status})`)\n const advertised = plugins.flatMap((plugin) =>\n plugin.status === \"active\" && plugin.tui && plugin.source.type === \"package\"\n ? [{ target: plugin.source.package, source: \"advertised\" as const }]\n : [],\n )\n const targets = [...tui, ...advertised]\n .filter((plugin, index, all) => all.findIndex((candidate) => candidate.target === plugin.target) === index)\n .toSorted((a, b) => a.target.localeCompare(b.target))\n .map((plugin) => `${plugin.target} (${plugin.source})`)\n return [\n targets.length ? [\"TUI\", ...targets].join(EOL) : undefined,\n server.length ? [\"Server\", ...server].join(EOL) : undefined,\n ]\n .filter((section) => section !== undefined)\n .join(EOL + EOL)\n}\n\nfunction name(plugin: PluginInfo) {\n if (plugin.id) return plugin.id\n if (plugin.source.type === \"package\") return plugin.source.package\n if (plugin.source.type === \"local\") return plugin.source.path\n return plugin.source.type\n}\n" | ||
| ], | ||
| "mappings": ";o/BAAA,cAAS,WAWT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,KAClC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,E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,GAAG,CAAU,EACnC,OAAO,CAAC,EAAQ,EAAO,IAAQ,EAAI,UAAU,CAAC,IAAc,EAAU,SAAW,EAAO,MAAM,IAAM,CAAK,EACzG,SAAS,CAAC,EAAG,IAAM,EAAE,OAAO,cAAc,EAAE,MAAM,CAAC,EACnD,IAAI,CAAC,IAAW,GAAG,EAAO,WAAW,EAAO,SAAS,EACxD,MAAO,CACL,EAAQ,OAAS,CAAC,MAAO,GAAG,CAAO,EAAE,KAAK,CAAG,EAAI,OACjD,EAAO,OAAS,CAAC,SAAU,GAAG,CAAM,EAAE,KAAK,CAAG,EAAI,MACpD,EACG,OAAO,CAAC,IAAY,IAAY,MAAS,EACzC,KAAK,EAAM,CAAG,EAGnB,SAAS,CAAI,CAAC,EAAoB,CAChC,GAAI,EAAO,GAAI,OAAO,EAAO,GAC7B,GAAI,EAAO,OAAO,OAAS,UAAW,OAAO,EAAO,OAAO,QAC3D,GAAI,EAAO,OAAO,OAAS,QAAS,OAAO,EAAO,OAAO,KACzD,OAAO,EAAO,OAAO", | ||
| "debugId": "160C0665046456CB64756E2164756E21", | ||
| "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 endpoint = yield* Service.ensure(yield* ServiceConfig.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, 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": ";u9BAAA,cAAS,WAcT,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAE7B,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,KAC/B,EAAO,GAAG,cAAc,EAAE,SAAU,CAAC,EAAO,CAC1C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EA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"sources": ["src/commands/handlers/auth/form.ts", "src/commands/handlers/auth/login.ts"], | ||
| "sourcesContent": [ | ||
| "import { confirm, log, multiselect, password, select, text, type Option } from \"@clack/prompts\"\nimport { Effect } from \"effect\"\nimport type { FormAnswer, FormField, FormFields } from \"@opencode-ai/client\"\nimport { openUrl, prompt, requireInteractive } from \"../../../ui/prompt\"\n\nconst skip = Symbol(\"skip\")\nconst custom = Symbol(\"custom\")\n\nexport const answerForm = Effect.fn(\"cli.auth.form\")(function* (fields: FormFields | undefined) {\n if (!fields) return undefined\n yield* requireInteractive(\"Authentication form input requires an interactive terminal\")\n const answer: FormAnswer = {}\n for (const field of fields) {\n if (!active(field, answer)) continue\n const value = yield* answerField(field)\n if (value !== undefined) answer[field.key] = value\n }\n return answer\n})\n\nexport const secret = Effect.fn(\"cli.auth.secret\")(function* (message: string) {\n yield* requireInteractive(\"API key input requires an interactive terminal\")\n return yield* prompt<string>(() => password({ message, validate: (value) => (!value ? \"Required\" : undefined) }))\n})\n\nconst answerField = Effect.fn(\"cli.auth.form.field\")(function* (field: FormField) {\n const message = field.title ?? field.key\n if (field.description) log.info(field.description)\n if (field.type === \"external\") {\n log.info(field.url)\n yield* openUrl(field.url)\n const acknowledged = yield* prompt<boolean>(() =>\n confirm({ message: message || \"Continue after completing this step?\", initialValue: true }),\n )\n if (!acknowledged) return yield* Effect.fail(new Error(`${message || \"External step\"} is required`))\n return true\n }\n if (field.type === \"boolean\") {\n if (field.required) return yield* prompt<boolean>(() => confirm({ message, initialValue: field.default ?? true }))\n const options: Array<Option<boolean | typeof skip>> = [\n { value: true, label: \"Yes\" },\n { value: false, label: \"No\" },\n { value: skip, label: \"Skip\" },\n ]\n const value = yield* prompt<boolean | typeof skip>(() =>\n select<boolean | typeof skip>({\n message,\n options,\n initialValue: field.default ?? skip,\n }),\n )\n if (value === skip) return undefined\n return value\n }\n if (field.type === \"multiselect\") {\n const options: Array<Option<string | typeof custom>> = field.options.map((option) => ({\n value: option.value,\n label: option.label,\n hint: option.description,\n }))\n if (field.custom) options.push({ value: custom, label: \"Type another value\" })\n const values = yield* prompt<Array<string | typeof custom>>(() =>\n multiselect<string | typeof custom>({\n message,\n options,\n initialValues: field.default,\n required: field.required || (field.minItems ?? 0) > 0,\n }),\n )\n const selected = values.filter((value): value is string => value !== custom)\n if (values.includes(custom)) {\n selected.push(yield* prompt<string>(() => text({ message: \"Enter value\", validate: required })))\n }\n if (field.minItems !== undefined && selected.length < field.minItems) {\n return yield* Effect.fail(new Error(`Select at least ${field.minItems}`))\n }\n if (field.maxItems !== undefined && selected.length > field.maxItems) {\n return yield* Effect.fail(new Error(`Select at most ${field.maxItems}`))\n }\n return selected\n }\n if (field.type === \"string\" && field.options) {\n const options: Array<Option<string | typeof custom | typeof skip>> = field.options.map((option) => ({\n value: option.value,\n label: option.label,\n hint: option.description,\n }))\n if (field.custom) options.push({ value: custom, label: \"Type your own answer\" })\n if (!field.required) options.push({ value: skip, label: \"Skip\" })\n const value = yield* prompt<string | typeof custom | typeof skip>(() =>\n select<string | typeof custom | typeof skip>({ message, options, initialValue: field.default }),\n )\n if (value === skip) return undefined\n if (value !== custom) return value\n }\n const value = yield* prompt<string>(() =>\n text({\n message,\n placeholder: field.type === \"string\" ? field.placeholder : undefined,\n initialValue: field.default === undefined ? undefined : String(field.default),\n validate: (input) => validateText(field, input),\n }),\n )\n if (!value && !field.required) return undefined\n if (field.type === \"string\") return value\n return Number(value)\n})\n\nfunction active(field: FormField, answer: FormAnswer) {\n if (field.type === \"external\" || !field.when) return true\n return field.when.every((condition) => {\n const value = answer[condition.key]\n if (value === undefined) return false\n const matches = Array.isArray(value) ? value.includes(String(condition.value)) : value === condition.value\n return condition.op === \"eq\" ? matches : !matches\n })\n}\n\nfunction required(value: string | undefined) {\n return value ? undefined : \"Required\"\n}\n\nfunction validateText(field: Exclude<FormField, { type: \"boolean\" | \"external\" | \"multiselect\" }>, value?: string) {\n if (!value) return field.required ? \"Required\" : undefined\n if (field.type === \"number\" || field.type === \"integer\") {\n const number = Number(value)\n if (!Number.isFinite(number)) return \"Expected a number\"\n if (field.type === \"integer\" && !Number.isInteger(number)) return \"Expected an integer\"\n if (typeof field.minimum === \"number\" && number < field.minimum) return `Must be at least ${field.minimum}`\n if (typeof field.maximum === \"number\" && number > field.maximum) return `Must be at most ${field.maximum}`\n return undefined\n }\n if (field.minLength !== undefined && value.length < field.minLength)\n return `Must be at least ${field.minLength} characters`\n if (field.maxLength !== undefined && value.length > field.maxLength)\n return `Must be at most ${field.maxLength} characters`\n if (field.pattern) {\n try {\n if (!new RegExp(field.pattern).test(value)) return \"Invalid format\"\n } catch {\n return \"Invalid format\"\n }\n }\n if (field.format === \"uri\" && !URL.canParse(value)) return \"Expected a URL\"\n if (field.format === \"email\" && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)) return \"Expected an email address\"\n if (field.format === \"date\") {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return \"Expected a date\"\n const date = new Date(`${value}T00:00:00.000Z`)\n if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) return \"Expected a date\"\n }\n if (field.format === \"date-time\" && Number.isNaN(Date.parse(value))) return \"Expected a date and time\"\n return undefined\n}\n", | ||
| "import { autocomplete, intro, log, outro, select, spinner, text } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport type { FormAnswer, IntegrationInfo, OpenCodeClient } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { handlePromptErrors, openUrl, prompt, requireInteractive } from \"../../../ui/prompt\"\nimport { answerForm, secret } from \"./form\"\nimport {\n createClient,\n connectMethods,\n loadIntegrations,\n location,\n request,\n resolveIntegration,\n resolveMethod,\n type ConnectMethod,\n} from \"./shared\"\n\nconst integrationPriority = new Map([\n [\"opencode\", 0],\n [\"opencode-go\", 1],\n [\"openai\", 2],\n [\"github-copilot\", 3],\n [\"google\", 4],\n [\"anthropic\", 5],\n [\"openrouter\", 6],\n [\"vercel\", 7],\n])\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.login,\n Effect.fn(\"cli.auth.login\")((input) =>\n login({\n target: Option.getOrUndefined(input.target),\n method: Option.getOrUndefined(input.method),\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n }).pipe(handlePromptErrors),\n ),\n)\n\nconst login = Effect.fn(\"cli.auth.login.run\")(function* (input: {\n target?: string\n method?: string\n server?: string\n standalone: boolean\n}) {\n if (!input.target)\n yield* requireInteractive(\"Pass an integration ID or name when running without an interactive terminal\")\n intro(\"Connect an integration\")\n const client = yield* createClient({ server: input.server, standalone: input.standalone })\n const integration = yield* findIntegration(client, input.target)\n const methods = connectMethods(integration)\n if (methods.length === 0) yield* Effect.fail(new Error(`${integration.name} has no interactive login methods`))\n const method = yield* chooseMethod(methods, input.method)\n const answer = method.type === \"command\" ? undefined : yield* answerForm(method.form)\n yield* authenticate(client, integration, method, answer)\n outro(\"Done\")\n})\n\nconst findIntegration = Effect.fn(\"cli.auth.login.integration\")(function* (client: OpenCodeClient, target?: string) {\n if (target && URL.canParse(target)) {\n const protocol = new URL(target).protocol\n if (protocol === \"http:\" || protocol === \"https:\") {\n const progress = spinner()\n progress.start(\"Discovering authentication provider...\")\n yield* request((signal) => client.integration.wellknown.add({ url: target, location }, { signal })).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(\"Authentication provider discovered\"))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Discovery failed\", 1))),\n )\n }\n }\n const integrations = yield* loadIntegrations(client)\n if (target) return yield* resolveIntegration(integrations, target)\n const available = integrations\n .filter((integration) => connectMethods(integration).length > 0)\n .toSorted(\n (a, b) =>\n (integrationPriority.get(a.id) ?? integrationPriority.size) -\n (integrationPriority.get(b.id) ?? integrationPriority.size) ||\n a.name.localeCompare(b.name) ||\n a.id.localeCompare(b.id),\n )\n if (available.length === 0) return yield* Effect.fail(new Error(\"No authentication integrations are available\"))\n const id = yield* prompt<string>(() =>\n autocomplete({\n message: \"Select integration\",\n maxItems: 8,\n options: available.map((integration) => {\n const option = { value: integration.id, label: integration.name, hint: integration.id }\n if (integration.connections.length > 0) return { ...option, hint: \"connected\" }\n if (integration.id === \"opencode\") return { ...option, hint: \"recommended\" }\n return option\n }),\n }),\n )\n return yield* resolveIntegration(available, id)\n})\n\nconst chooseMethod = Effect.fn(\"cli.auth.login.method\")(function* (methods: ConnectMethod[], target?: string) {\n if (target) return yield* resolveMethod(methods, target)\n if (methods.length === 1) return methods[0]\n yield* requireInteractive(\"Pass --method when running without an interactive terminal\")\n const id = yield* prompt<string>(() =>\n select({\n message: \"Select login method\",\n options: methods.map((method) => {\n if (method.type === \"key\") return { value: \"key\", label: method.label ?? \"API key\" }\n return { value: method.id, label: method.label }\n }),\n }),\n )\n return yield* resolveMethod(methods, id)\n})\n\nconst authenticate = Effect.fn(\"cli.auth.login.authenticate\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: ConnectMethod,\n answer?: FormAnswer,\n) {\n if (method.type === \"key\") return yield* keyLogin(client, integration, method, answer)\n if (method.type === \"command\") return yield* commandLogin(client, integration, method)\n return yield* oauthLogin(client, integration, method, answer)\n})\n\nconst keyLogin = Effect.fn(\"cli.auth.login.key\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"key\" }>,\n answer?: FormAnswer,\n) {\n const key = yield* secret(method.label ?? `Enter your ${integration.name} API key`)\n const progress = spinner()\n progress.start(\"Saving credential...\")\n yield* request((signal) =>\n client.integration.connect.key({ integrationID: integration.id, key, answer, location }, { signal }),\n ).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(`Connected to ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))),\n )\n})\n\nconst oauthLogin = Effect.fn(\"cli.auth.login.oauth\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"oauth\" }>,\n answer?: FormAnswer,\n) {\n const progress = spinner()\n progress.start(\"Starting authorization...\")\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n { integrationID: integration.id, methodID: method.id, answer, location },\n { signal },\n ),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID: integration.id, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n progress.stop(\"Authorization started\")\n log.info(attempt.instructions)\n log.info(attempt.url)\n if (process.stdin.isTTY && process.stdout.isTTY) yield* openUrl(attempt.url)\n\n if (attempt.mode === \"code\") {\n yield* requireInteractive(\"This login requires an interactive terminal to enter the authorization code\")\n const code = yield* prompt<string>(() =>\n text({ message: \"Paste the authorization code\", validate: (value) => (!value ? \"Required\" : undefined) }),\n )\n const completing = spinner()\n completing.start(\"Completing authorization...\")\n yield* request((signal) =>\n client.integration.oauth.complete(\n { integrationID: integration.id, attemptID: attempt.attemptID, code, location },\n { signal },\n ),\n ).pipe(\n Effect.tap(() => Effect.sync(() => completing.stop(`Connected to ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => completing.stop(\"Authentication failed\", 1))),\n )\n return\n }\n\n const waiting = spinner()\n waiting.start(\"Waiting for authorization...\")\n const status = yield* waitForOAuth(client, integration.id, attempt.attemptID).pipe(\n Effect.tapCause(() => Effect.sync(() => waiting.stop(\"Authentication failed\", 1))),\n )\n if (status.status === \"complete\") {\n waiting.stop(`Connected to ${integration.name}`)\n return\n }\n waiting.stop(\"Authentication failed\", 1)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n yield* Effect.fail(new Error(\"Authorization expired\"))\n})\n\nconst commandLogin = Effect.fn(\"cli.auth.login.command\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"command\" }>,\n) {\n const progress = spinner()\n progress.start(\"Starting authentication command...\")\n const started = yield* request((signal) =>\n client.integration.command.connect({ integrationID: integration.id, methodID: method.id, location }, { signal }),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.command.cancel(\n {\n integrationID: integration.id,\n attemptID: started.data.attemptID,\n location,\n },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n const status = yield* waitForCommand(client, integration.id, started.data.attemptID, (message) =>\n progress.message(message.trim() || \"Waiting for authentication command...\"),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n if (status.status === \"complete\") {\n progress.stop(`Connected to ${integration.name}`)\n return\n }\n progress.stop(\"Authentication failed\", 1)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n yield* Effect.fail(new Error(\"Authentication expired\"))\n})\n\nconst waitForOAuth = Effect.fn(\"cli.auth.login.oauth.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\nconst waitForCommand = Effect.fn(\"cli.auth.login.command.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n update: (message: string) => void,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.command.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n if (response.data.message) update(response.data.message)\n yield* Effect.sleep(500)\n }\n})\n" | ||
| ], | ||
| "mappings": ";m3CAKA,IAAM,EAAO,OAAO,MAAM,EACpB,EAAS,OAAO,QAAQ,EAEjB,EAAa,EAAO,GAAG,eAAe,EAAE,SAAU,CAAC,EAAgC,CAC9F,GAAI,CAAC,EAAQ,OACb,MAAO,EAAmB,4DAA4D,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,EAAO,YAAY,QAAQ,OAAO,CAAE,gBAAe,YAAW,UAAS,EAAG,CAAE,QAAO,CAAC,CACtF,EACA,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,GAAI,EAAS,KAAK,QAAS,EAAO,EAAS,KAAK,OAAO,EACvD,MAAO,EAAO,MAAM,GAAG,GAE1B", | ||
| "debugId": "EF03E1FE53D5316064756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/models.ts"], | ||
| "sourcesContent": [ | ||
| "import { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.models,\n Effect.fn(\"cli.models\")(function* (input) {\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const response = yield* Effect.promise(() => client.model.list({ location: { directory: process.cwd() } }))\n const models = response.data\n .map((model) => `${model.providerID}/${model.id}`)\n .toSorted((a, b) => a.localeCompare(b))\n if (models.length > 0) process.stdout.write(models.join(EOL) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";giCAGA,cAAS,WAKT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,SAAU,CAAC,EAAO,CACxC,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAAS,EAAS,KAAK,CAC3B,QAAS,EAAO,SAAS,IACzB,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAC1C,CAAC,EAEK,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAClF,KACrB,IAAI,CAAC,IAAU,GAAG,EAAM,cAAc,EAAM,IAAI,EAChD,SAAS,CAAC,EAAG,IAAM,EAAE,cAAc,CAAC,CAAC,EACxC,GAAI,EAAO,OAAS,EAAG,QAAQ,OAAO,MAAM,EAAO,KAAK,CAAG,EAAI,CAAG,EACnE,CACH", | ||
| "debugId": "5ACC810CDB66B66064756E2164756E21", | ||
| "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,kBACjD,EAAiD,MAGhD,IAAM,EAAiB", | ||
| "debugId": "4F085DEBA64DB8EE64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "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 endpoint = yield* Service.ensure(yield* ServiceConfig.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": ";m6BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,OACjC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,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": "6CABE1CEE730303164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/config.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"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.debug.commands.config,\n Effect.fn(\"cli.debug.config\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const entries = yield* Effect.promise(() => client.config.get({ location: { directory: process.cwd() } }))\n process.stdout.write(JSON.stringify(entries, null, 2) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";m6BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,OACjC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAU,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,IAAI,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EACzG,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAS,KAAM,CAAC,EAAI,CAAG,EAC5D,CACH", | ||
| "debugId": "D9A4A26C27DF103464756E2164756E21", | ||
| "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": ";yXAuBA,IAAI,EAA6B,EAAE,OAAO,CASxC,SAAU,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,EAA+B,CAC/D,YAAa,EACb,eAAgB,CAAC,IAAS,EAAK,OACjC,CAAC,E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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,GAAqB,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": "FA0EEE2D9DAF936964756E2164756E21", | ||
| "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(\n (yield* ServiceConfig.get(Option.getOrUndefined(input.key), Option.getOrUndefined(input.name))) + EOL,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";02BAAA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,IACnC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,QAAQ,OAAO,OACZ,MAAO,EAAc,IAAI,EAAO,eAAe,EAAM,GAAG,EAAG,EAAO,eAAe,EAAM,IAAI,CAAC,GAAK,CACpG,EACD,CACH", | ||
| "debugId": "214EE17A0676E5AB64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/set.ts"], | ||
| "sourcesContent": [ | ||
| "import { 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.set,\n Effect.fn(\"cli.service.set\")(function* (input) {\n yield* ServiceConfig.set(input.key, input.value, Option.getOrUndefined(input.nestedValue))\n }),\n)\n" | ||
| ], | ||
| "mappings": ";02BAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,IACnC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,MAAO,EAAc,IAAI,EAAM,IAAK,EAAM,MAAO,EAAO,eAAe,EAAM,WAAW,CAAC,EAC1F,CACH", | ||
| "debugId": "CF6C3E41EEDAD8DF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "6570C12E689233DF64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/ai-gateway-provider@3.1.2+cd874a64d6146f19/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": ";8RAEA,IAAI,EAAgB,CAAC,IACZ,EAAuB,CAC5B,QAAS,8CAET,KAAM,aACH,GAAO,CAAC,CACb,CAAC,EAEC,EAAU,EAAc", | ||
| "debugId": "D929B29958F5239264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/export.ts"], | ||
| "sourcesContent": [ | ||
| "import { autocomplete, cancel, intro, isCancel, log, outro } from \"@clack/prompts\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { errorMessage } from \"../../util/error\"\n\nexport default Runtime.handler(\n Commands.commands.export,\n Effect.fn(\"cli.export\")((input) =>\n Effect.gen(function* () {\n const requested = Option.getOrUndefined(input.session)\n if (!requested && !process.stdin.isTTY) {\n yield* Effect.fail(new Error(\"Pass a session ID when running without an interactive terminal\"))\n }\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const sessionID = requested\n ? requested\n : yield* Effect.gen(function* () {\n intro(\"Export session\", { output: process.stderr })\n const location = yield* Effect.tryPromise({\n try: () => client.location.get({ location: { directory: process.cwd() } }),\n catch: (cause) => cause,\n })\n const page = yield* Effect.tryPromise({\n try: () =>\n client.session.list({\n directory: location.directory,\n workspace: location.workspaceID,\n parentID: null,\n order: \"desc\",\n limit: 50,\n }),\n catch: (cause) => cause,\n })\n if (page.data.length === 0) {\n log.error(\"No sessions found\", { output: process.stderr })\n outro(\"Done\", { output: process.stderr })\n return undefined\n }\n const selected = yield* Effect.tryPromise({\n try: () =>\n autocomplete({\n message: \"Select session to export\",\n maxItems: 10,\n options: page.data.map((session) => ({\n label: session.title,\n value: session.id,\n hint: `${new Date(session.time.updated).toLocaleString()} - ${session.id.slice(-8)}`,\n })),\n output: process.stderr,\n }),\n catch: (cause) => cause,\n })\n if (isCancel(selected)) {\n cancel(\"Cancelled\", { output: process.stderr })\n process.exitCode = 130\n return undefined\n }\n outro(\"Exporting session...\", { output: process.stderr })\n return selected\n })\n if (!sessionID) return\n const data = yield* Effect.tryPromise({\n try: () => client.session.export({ sessionID, sanitize: input.sanitize }),\n catch: (cause) => cause,\n })\n process.stdout.write(JSON.stringify(data, null, 2) + EOL)\n }).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n ),\n)\n" | ||
| ], | ||
| "mappings": ";utCAIA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,CAAC,IACvB,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAY,EAAO,eAAe,EAAM,OAAO,EACrD,GAAI,CAAC,GAAa,CAAC,QAAQ,MAAM,MAC/B,MAAO,EAAO,KAAS,MAAM,gEAAgE,CAAC,EAEhG,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAA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M,EAAO,MAAO,EAAO,WAAW,CACpC,IAAK,IAAM,EAAO,QAAQ,OAAO,CAAE,YAAW,SAAU,EAAM,QAAS,CAAC,EACxE,MAAO,CAAC,IAAU,CACpB,CAAC,EACD,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAM,KAAM,CAAC,EAAI,CAAG,EACzD,EAAE,KACD,EAAO,MAAM,CAAC,IACZ,EAAO,KAAK,IAAM,CAChB,QAAQ,OAAO,MAAM,EAAa,CAAK,EAAI,CAAG,EAC9C,QAAQ,SAAW,EACpB,CACH,CACF,CACF,CACF", | ||
| "debugId": "DF8E152FF462215A64756E2164756E21", | ||
| "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/mcp/oauth.ts"], | ||
| "sourcesContent": [ | ||
| "export * as MCPOAuth from \"./oauth.js\"\n\nimport { auth, type OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\"\nimport type { OAuthClientInformationMixed, OAuthTokens } from \"@modelcontextprotocol/sdk/shared/auth.js\"\nimport { Deferred, Effect } from \"effect\"\nimport { Credential } from \"@opencode-ai/schema/credential\"\nimport { ConfigMCP } from \"@opencode-ai/schema/config/mcp\"\nimport { OauthCallbackPage } from \"../oauth/page.js\"\nimport type { Integration } from \"../integration.js\"\n\n/** Persists the OAuth artifacts for one MCP server session: DCR client info, PKCE verifier, and tokens. */\nexport interface Store {\n readonly tokens: () => Promise<OAuthTokens | undefined>\n readonly saveTokens: (tokens: OAuthTokens) => Promise<void>\n readonly clientInformation: () => Promise<OAuthClientInformationMixed | undefined>\n readonly saveClientInformation: (info: OAuthClientInformationMixed) => Promise<void>\n readonly codeVerifier: () => Promise<string | undefined>\n readonly saveCodeVerifier: (verifier: string) => Promise<void>\n}\n\nexport interface Options {\n /** Loopback URL the authorization server redirects back to after the user approves. */\n readonly redirectUrl: string\n /** Space-delimited OAuth scopes to request when the server requires specific ones. */\n readonly scope?: string\n /** CSRF state embedded in the authorization request; required by the spec and enforced by some servers.\n * The caller is responsible for validating the value echoed back to the redirect. */\n readonly state?: string\n /** Statically pre-registered client credentials from config; when set, the SDK skips dynamic registration. */\n readonly client?: { readonly id: string; readonly secret?: string }\n /** Invoked by the SDK to drop credentials it has determined are invalid (e.g. a rejected refresh token). */\n readonly invalidate?: (scope: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\") => void | Promise<void>\n /** Receives the authorization URL so the caller can open a browser and capture the eventual code. */\n readonly onRedirect: (url: URL) => void | Promise<void>\n readonly store: Store\n}\n\n/**\n * Builds the MCP SDK's OAuthClientProvider. The SDK drives dynamic client registration, PKCE, and\n * token refresh through these callbacks; we only persist whatever it hands back via `store`.\n */\nexport const provider = (options: Options): OAuthClientProvider => {\n const state = options.state\n const client = options.client\n return {\n redirectUrl: options.redirectUrl,\n clientMetadata: {\n redirect_uris: [options.redirectUrl],\n client_name: \"opencode\",\n client_uri: \"https://opencode.ai\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: client?.secret ? \"client_secret_post\" : \"none\",\n ...(options.scope ? { scope: options.scope } : {}),\n },\n // Only advertise state when the caller supplied one (the interactive flow); the connect-time\n // provider has no redirect to validate, so it omits it.\n ...(state !== undefined ? { state: () => state } : {}),\n // Static client config short-circuits dynamic registration; otherwise the SDK registers and we persist.\n clientInformation: () =>\n client ? { client_id: client.id, client_secret: client.secret } : options.store.clientInformation(),\n saveClientInformation: (info) => options.store.saveClientInformation(info),\n tokens: () => options.store.tokens(),\n saveTokens: (tokens) => options.store.saveTokens(tokens),\n redirectToAuthorization: (url) => options.onRedirect(url),\n ...(options.invalidate ? { invalidateCredentials: options.invalidate } : {}),\n saveCodeVerifier: (verifier) => options.store.saveCodeVerifier(verifier),\n // The SDK only reads the verifier back after saving one earlier in the same flow; a miss means\n // the flow was resumed without its session state, which the SDK surfaces as an auth failure.\n codeVerifier: async () => {\n const verifier = await options.store.codeVerifier()\n if (!verifier) throw new Error(\"Missing PKCE code verifier for MCP OAuth flow\")\n return verifier\n },\n }\n}\n\n/** A Store that keeps OAuth artifacts in memory for the duration of one interactive login attempt. */\nexport const memoryStore = (): Store => {\n let tokens: OAuthTokens | undefined\n let client: OAuthClientInformationMixed | undefined\n let verifier: string | undefined\n return {\n tokens: async () => tokens,\n saveTokens: async (value) => {\n tokens = value\n },\n clientInformation: async () => client,\n saveClientInformation: async (value) => {\n client = value\n },\n codeVerifier: async () => verifier,\n saveCodeVerifier: async (value) => {\n verifier = value\n },\n }\n}\n\n/** Reads the dynamically-registered client info we stash in a credential's metadata, for token refresh. */\nexport const clientFromCredential = (credential: Credential.OAuth) =>\n credential.metadata?.client as OAuthClientInformationMixed | undefined\n\n/** Folds SDK tokens (plus DCR client info and the server URL) into a storable credential. */\nexport const toCredential = (input: {\n readonly methodID: Integration.MethodID\n readonly serverUrl: string\n readonly tokens: OAuthTokens\n readonly client: OAuthClientInformationMixed | undefined\n}) =>\n Credential.OAuth.make({\n type: \"oauth\",\n methodID: input.methodID,\n access: input.tokens.access_token,\n refresh: input.tokens.refresh_token ?? \"\",\n // 0 marks an unknown/non-expiring token; toTokens then omits expires_in so the SDK won't force a refresh.\n expires: input.tokens.expires_in ? Date.now() + input.tokens.expires_in * 1000 : 0,\n metadata: {\n serverUrl: input.serverUrl,\n tokenType: input.tokens.token_type,\n ...(input.tokens.scope ? { scope: input.tokens.scope } : {}),\n ...(input.client ? { client: input.client } : {}),\n },\n })\n\n/** Reconstructs SDK tokens from a stored credential so the connect-time provider can present them. */\nexport const toTokens = (credential: Credential.OAuth): OAuthTokens => {\n const metadata = credential.metadata ?? {}\n return {\n access_token: credential.access,\n token_type: typeof metadata.tokenType === \"string\" ? metadata.tokenType : \"Bearer\",\n ...(credential.refresh ? { refresh_token: credential.refresh } : {}),\n ...(credential.expires ? { expires_in: Math.max(0, Math.floor((credential.expires - Date.now()) / 1000)) } : {}),\n ...(typeof metadata.scope === \"string\" ? { scope: metadata.scope } : {}),\n }\n}\n\n/**\n * Runs the interactive OAuth login for one remote MCP server. Stands up a loopback callback server,\n * lets the SDK drive DCR + PKCE to produce an authorization URL, and returns an attempt whose callback\n * exchanges the redirect code for a storable credential. Scoped: the callback server closes with the scope.\n */\nexport const authorize = (input: {\n readonly name: string\n readonly config: typeof ConfigMCP.Remote.Type\n readonly methodID: Integration.MethodID\n}) =>\n Effect.gen(function* () {\n const oauth = input.config.oauth || undefined\n const store = memoryStore()\n const code = yield* Deferred.make<string, Error>()\n const redirect = oauth?.redirect_uri ? new URL(oauth.redirect_uri) : undefined\n const redirectPath = redirect?.pathname ?? \"/callback\"\n const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(\"base64url\")\n\n // Lazy so runtimes without a loopback listener (workerd) never evaluate node:http.\n const { createServer } = yield* Effect.promise(() => import(\"node:http\"))\n const server = createServer((request, response) => {\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\")\n if (url.pathname !== redirectPath) {\n response.writeHead(404).end(\"Not found\")\n return\n }\n const fail = (reason: string) => {\n Effect.runFork(Deferred.fail(code, new Error(reason)))\n response\n .writeHead(400, { \"Content-Type\": \"text/html\" })\n .end(OauthCallbackPage.error(reason, { provider: input.name }))\n }\n const error = url.searchParams.get(\"error_description\") ?? url.searchParams.get(\"error\")\n if (error) return fail(error)\n // Reject a redirect whose state does not match what we issued: this is the CSRF defense the\n // state parameter exists for, so an attacker can't inject their own authorization code.\n if (url.searchParams.get(\"state\") !== state) return fail(\"OAuth state mismatch\")\n const value = url.searchParams.get(\"code\")\n if (!value) return fail(\"Missing authorization code\")\n Effect.runFork(Deferred.succeed(code, value))\n response.writeHead(200, { \"Content-Type\": \"text/html\" }).end(OauthCallbackPage.success({ provider: input.name }))\n })\n\n // Bind the port the redirect will actually arrive on: an explicit callback_port wins, else the port\n // pinned by redirect_uri, else an ephemeral port. Binding ephemerally while redirect_uri names a fixed\n // port would send the browser somewhere nothing is listening, hanging the attempt until it expires.\n const redirectPort = Number(redirect?.port) || undefined\n const port = yield* Effect.callback<number, Error>((resume) => {\n server.once(\"error\", (error) => resume(Effect.fail(error)))\n server.listen(oauth?.callback_port ?? redirectPort ?? 0, \"127.0.0.1\", () => {\n const address = server.address()\n resume(\n address && typeof address === \"object\"\n ? Effect.succeed(address.port)\n : Effect.fail(new Error(\"Could not determine MCP OAuth callback port\")),\n )\n })\n })\n yield* Effect.addFinalizer(() => Effect.sync(() => server.close()))\n\n let authorizationUrl: URL | undefined\n const oauthProvider = provider({\n redirectUrl: oauth?.redirect_uri ?? `http://127.0.0.1:${port}${redirectPath}`,\n scope: oauth?.scope,\n state,\n client: oauth?.client_id ? { id: oauth.client_id, secret: oauth.client_secret } : undefined,\n onRedirect: (url) => {\n authorizationUrl = url\n },\n store,\n })\n\n const finalize = Effect.gen(function* () {\n const tokens = yield* Effect.promise(() => store.tokens())\n if (!tokens) return yield* Effect.fail(new Error(`MCP server \"${input.name}\" did not return OAuth tokens`))\n const client = yield* Effect.promise(() => store.clientInformation())\n return toCredential({ methodID: input.methodID, serverUrl: input.config.url, tokens, client })\n })\n\n const result = yield* Effect.tryPromise({\n try: () => auth(oauthProvider, { serverUrl: input.config.url, scope: oauth?.scope }),\n catch: (error) => (error instanceof Error ? error : new Error(String(error))),\n })\n\n // The provider may already hold valid tokens (e.g. a re-auth), in which case there is no browser step.\n if (result === \"AUTHORIZED\") {\n return {\n url: input.config.url,\n instructions: `Connected to ${input.name}.`,\n mode: \"auto\" as const,\n callback: finalize,\n }\n }\n if (!authorizationUrl)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" did not provide an authorization URL`))\n\n return {\n url: authorizationUrl.toString(),\n instructions: `Authorize ${input.name} in your browser. This window will close automatically.`,\n mode: \"auto\" as const,\n callback: Deferred.await(code).pipe(\n Effect.flatMap((value) =>\n Effect.tryPromise({\n try: () =>\n auth(oauthProvider, { serverUrl: input.config.url, authorizationCode: value, scope: oauth?.scope }),\n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CAAC,CACH,EACA,EAAO,QAAQ,IAAM,CAAQ,CAC/B,CACF,EACD", | ||
| "debugId": "0B30E60E972B89C064756E2164756E21", | ||
| "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/auth/shared.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { OpenCode, type IntegrationInfo, type IntegrationMethod, type OpenCodeClient } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServerConnection } from \"../../../services/server-connection\"\n\nexport const location = { directory: process.cwd() }\n\nexport const createClient = Effect.fn(\"cli.auth.client\")(function* (input: ServerConnection.Args) {\n const server = yield* ServerConnection.resolve(input)\n return OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) })\n})\n\nexport function request<A>(run: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({ try: run, catch: (cause) => cause })\n}\n\nexport const loadIntegrations = Effect.fn(\"cli.auth.integrations\")(function* (client: OpenCodeClient) {\n // The model endpoint is the existing public readiness boundary for the initial plugin generation.\n yield* request((signal) => client.model.default({ location }, { signal }))\n return yield* request((signal) => client.integration.list({ location }, { signal })).pipe(\n Effect.map((response) => response.data),\n )\n})\n\nexport const resolveIntegration = Effect.fn(\"cli.auth.resolve-integration\")(function* (\n integrations: IntegrationInfo[],\n target: string,\n) {\n const normalized = target.replace(/\\/+$/, \"\")\n const byID = integrations.find((integration) => integration.id === normalized)\n if (byID) return byID\n const matches = integrations.filter((integration) => integration.name.toLowerCase() === normalized.toLowerCase())\n if (matches.length === 1) return matches[0]\n if (matches.length > 1) {\n return yield* Effect.fail(\n new Error(\n `Integration name \"${target}\" is ambiguous: ${matches.map((integration) => integration.id).join(\", \")}`,\n ),\n )\n }\n return yield* Effect.fail(new Error(`Integration not found: ${target}`))\n})\n\nexport type ConnectMethod = Exclude<IntegrationMethod, { type: \"env\" }>\n\nexport function connectMethods(integration: IntegrationInfo) {\n return integration.methods\n .filter((method): method is ConnectMethod => method.type !== \"env\")\n .toSorted((a, b) => Number(a.type === \"key\") - Number(b.type === \"key\"))\n}\n\nexport const resolveMethod = Effect.fn(\"cli.auth.resolve-method\")(function* (methods: ConnectMethod[], target: string) {\n const normalized = target.toLowerCase()\n const matches = methods.filter((method) => {\n if (method.type === \"key\") return normalized === \"key\" || method.label?.toLowerCase() === normalized\n return method.id === target || method.label.toLowerCase() === normalized\n })\n if (matches.length === 1) return matches[0]\n if (matches.length > 1) return yield* Effect.fail(new Error(`Authentication method \"${target}\" is ambiguous`))\n const available = methods.map((method) => (method.type === \"key\" ? \"key\" : method.id)).join(\", \")\n return yield* Effect.fail(\n new Error(`Authentication method not found: ${target}${available ? `. Available: ${available}` : \"\"}`),\n )\n})\n" | ||
| ], | ||
| "mappings": ";gNAKO,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAEtC,EAAe,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAA8B,CAChG,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAAK,EACpD,OAAO,EAAS,KAAK,CAAE,QAAS,EAAO,SAAS,IAAK,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAAE,CAAC,EACjG,EAEM,SAAS,CAAU,CAAC,EAA0C,CACnE,OAAO,EAAO,WAAW,CAAE,IAAK,EAAK,MAAO,CAAC,IAAU,CAAM,CAAC,EAGzD,IAAM,EAAmB,EAAO,GAAG,uBAAuB,EAAE,SAAU,CAAC,EAAwB,CAGpG,OADA,MAAO,EAAQ,CAAC,IAAW,EAAO,MAAM,QAAQ,CAAE,UAAS,EAAG,CAAE,QAAO,CAAC,CAAC,EAClE,MAAO,EAAQ,CAAC,IAAW,EAAO,YAAY,KAAK,CAAE,UAAS,EAAG,CAAE,QAAO,CAAC,CAAC,EAAE,KACnF,EAAO,IAAI,CAAC,IAAa,EAAS,IAAI,CACxC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O,EAAO,KACf,MAAM,oCAAoC,IAAS,EAAY,gBAAgB,IAAc,IAAI,CACvG,EACD", | ||
| "debugId": "873222A377ABD3A964756E2164756E21", | ||
| "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/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 env: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n})\nexport type Info = typeof Info.Type\n\nconst keys = [\"hostname\", \"port\", \"password\", \"env\"] 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 === \"dev\" || channel === \"beta\" || 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 === \"dev\" || channel === \"beta\" || 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\" || key === \"env\") 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* (input: { readonly checkVersion?: boolean } = {}) {\n const { file, legacyRegistrationFiles } = yield* paths\n yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))\n return {\n file,\n version: input.checkVersion ? OPENCODE_VERSION : undefined,\n env: (yield* read()).env,\n command: [\n ...selfCommand(),\n \"serve\",\n \"--service\",\n ],\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.orElseSucceed(() => ({}) 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, name?: string) {\n if (key === undefined) {\n const { password: _password, ...safe } = yield* read()\n return JSON.stringify(safe, null, 2)\n }\n const selected = configKey(key)\n if (selected !== \"env\" && name !== undefined) throw new Error(`Usage: opencode service get ${selected}`)\n switch (selected) {\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 case \"env\": {\n const env = (yield* read()).env ?? {}\n return name === undefined ? JSON.stringify(env, null, 2) : (env[name] ?? \"\")\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, nestedValue?: string) {\n const selected = configKey(key)\n if (selected !== \"env\" && nestedValue !== undefined)\n throw new Error(`Usage: opencode service set ${selected} <value>`)\n switch (selected) {\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 case \"env\": {\n if (nestedValue === undefined) throw new Error(\"Usage: opencode service set env <key> <value>\")\n yield* Service.stop(yield* options())\n const existing = yield* read()\n yield* write({ ...existing, env: { ...existing.env, [value]: nestedValue } })\n return\n }\n }\n})\n\nexport const unset = Effect.fn(\"cli.service-config.unset\")(function* (key: string, name?: string) {\n const selected = configKey(key)\n if (selected !== \"env\" && name !== undefined) throw new Error(`Usage: opencode service unset ${selected}`)\n switch (selected) {\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 case \"env\": {\n if (name === undefined) throw new Error(\"Usage: opencode service unset env <key>\")\n yield* Service.stop(yield* options())\n const existing = yield* read()\n const { [name]: _removed, ...env } = existing.env ?? {}\n const { env: _existingEnv, ...rest } = existing\n yield* write(Object.keys(env).length === 0 ? rest : { ...rest,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I,EAAO,IAAK,EAAM,KAAI,CAAC,EACpE,MACF,GAEH", | ||
| "debugId": "2D3DC95CDBC35BF564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "93AE568BA7AA677264756E2164756E21", | ||
| "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": ";wZAuBA,IAAI,EAAsB,KAAM,CAC9B,WAAW,CAAC,EAAS,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,QAAS,EAAe,KAAK,OAAO,QAAQ,EAAG,CAAO,EACtD,SAAU,EACR,CACE,MAAO,KAAK,QACZ,SACA,MAAO,MAAM,QAAQ,IAAI,EAAM,IAAI,CAAC,IAAS,EAAW,CAAI,CAAC,CAAC,EAC9D,KAAM,GAAQ,KAAO,MAAM,EAAW,CAAI,EAAS,OACnD,IACA,WACI,EAAK,EAAgB,YAAc,KAAO,EAAK,CAAC,CACtD,EACA,CAAE,iBAAkB,EAAM,CAC5B,EACA,sBAAuB,EAA+B,CACpD,YAAa,EACb,eAAgB,CAAC,IAAU,CACzB,IAAI,EAAK,EACT,OAAQ,GAAO,EAAM,EAAM,QAAU,KAAY,OAAI,EAAI,UAAY,KAAO,EAAM,gBAEtF,CAAC,EACD,0BAA2B,EACzB,CACF,EACA,cACA,MAAO,KAAK,OAAO,KACrB,CAAC,EACD,MAAO,CACL,OAAQ,EA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K,GAG5B,CAAC,EACD,MAAO,IACF,EACH,OAAQ,CACV,EAEJ,EAGI,EAAiB,SAGrB,SAAS,CAAe,CAAC,EAAU,CAAC,EAAG,CACrC,IAAI,EACJ,IAAM,EAAU,GACb,EAAK,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,IAChB,IAAI,EACT,EACA,EAAqB,MAAM,CAC7B,EAEI,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": "BA2E184966DFA6CE64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/workspace/driver.ts", "../core/src/workspace/sql.ts", "../core/src/workspace.ts", "../core/src/environment/files.ts", "../core/src/environment/exec-defaults.ts", "../core/src/environment/local.ts", "../core/src/environment/memory.ts", "../core/src/environment/environment.ts", "../core/src/environment/index.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WorkspaceDriver from \"./driver.js\"\n\nimport { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { Context, Effect, Layer, Schema } from \"effect\"\nimport type { Scope } from \"effect\"\nimport type { Driver as EnvironmentDriver } from \"../environment/driver.js\"\n\n/**\n * Smallest provider-owned JSON value required to reconnect to the same\n * provider resource. Core stores it opaquely and hands it back; only the\n * owning driver reads inside.\n */\nexport const Binding = Schema.Record(Schema.String, Schema.Json)\nexport type Binding = typeof Binding.Type\n\nexport class Error extends Schema.TaggedError<Error>()(\"WorkspaceDriver.Error\", {\n message: Schema.optional(Schema.String),\n cause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport class ProviderNotFound extends Schema.TaggedError<ProviderNotFound>()(\"WorkspaceDriver.ProviderNotFound\", {\n provider: Schema.String,\n}) {}\n\nexport interface Interface {\n /**\n * Get-or-create the provider resource backing this logical workspace.\n *\n * MUST be idempotent per `workspaceID`: core retries the same ID after\n * failures and process crashes, including a crash between a successful\n * create and the binding being persisted, and another process may race the\n * same ID. Key the resource by `workspaceID` (a provider tag or a\n * deterministic name) and adopt an existing match instead of creating a\n * duplicate.\n */\n readonly create: (input: {\n readonly workspaceID: Workspace.ID\n }) => Effect.Effect<{ readonly binding: Binding }, Error>\n readonly connect: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding\n readonly saveBinding: (binding: Binding) => Effect.Effect<void>\n }) => Effect.Effect<EnvironmentDriver, Error, Scope.Scope>\n readonly suspendForIdle: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding\n readonly saveBinding: (binding: Binding) => Effect.Effect<void>\n }) => Effect.Effect<void, Error>\n /**\n * Release the provider resource for this workspace.\n *\n * `binding` is null when none was persisted: the workspace was never\n * provisioned, or provisioning was interrupted mid-create. Look up any\n * resource previously created for `workspaceID` and clean it up, treating\n * absence as success.\n */\n readonly destroy: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding | null\n }) => Effect.Effect<void, Error>\n}\n\nexport const make = (driver: Interface) => driver\n\nexport interface Registry {\n readonly get: (provider: string) => Effect.Effect<Interface, ProviderNotFound>\n}\n\nexport class RegistryService extends Context.Service<RegistryService, Registry>()(\n \"@opencode/WorkspaceDriverRegistry\",\n) {}\n\nexport const registry = (drivers: Readonly<Record<string, Interface>>): Registry => ({\n get: (provider) => {\n const driver = Object.hasOwn(drivers, provider) ? drivers[provider] : undefined\n return driver ? Effect.succeed(driver) : Effect.fail(new ProviderNotFound({ provider }))\n },\n})\n\nexport const registryNode = (drivers: Readonly<Record<string, Interface>>) =>\n makeGlobalNode({\n service: RegistryService,\n layer: Layer.succeed(RegistryService, RegistryService.of(registry(drivers))),\n deps: [],\n })\n\nexport const node = registryNode({})\n", | ||
| "import { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { integer, sqliteTable, text } from \"drizzle-orm/sqlite-core\"\nimport type { WorkspaceDriver } from \"./driver.js\"\n\nexport const WorkspaceTable = sqliteTable(\"workspace\", {\n id: text().$type<Workspace.ID>().primaryKey(),\n provider: text().notNull(),\n binding: text({ mode: \"json\" }).$type<WorkspaceDriver.Binding>(),\n created_at: integer().notNull(),\n last_used_at: integer().notNull(),\n})\n", | ||
| "export * as Workspace from \"./workspace.js\"\n\nimport { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { eq } from \"drizzle-orm\"\nimport { Clock, Context, Deferred, Duration, Effect, Exit, FiberSet, Layer, Ref, Schedule, Schema, Scope } from \"effect\"\nimport { systemError } from \"effect/PlatformError\"\nimport { make } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver as EnvironmentDriver } from \"./environment/driver.js\"\nimport { Database } from \"./database/database.js\"\nimport { KeyedMutex } from \"./effect/keyed-mutex.js\"\nimport { WorkspaceDriver } from \"./workspace/driver.js\"\nimport { WorkspaceTable } from \"./workspace/sql.js\"\n\nexport const ID = Workspace.ID\nexport type ID = Workspace.ID\n\nexport class Info extends Schema.Class<Info>(\"Workspace.Info\")({\n id: ID,\n provider: Schema.String,\n binding: WorkspaceDriver.Binding,\n createdAt: Schema.Number,\n lastUsedAt: Schema.Number,\n}) {}\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\"Workspace.NotFound\", { workspaceID: ID }) {}\n\nexport interface Interface {\n /** Instantly commits a logical workspace ID. No provider work happens here. */\n readonly create: (provider: string) => Effect.Effect<ID, WorkspaceDriver.ProviderNotFound>\n /** Starts or joins the shared attempt that makes the backing resource real, then returns it. */\n readonly provision: (\n workspaceID: ID,\n ) => Effect.Effect<Info, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n readonly connect: (\n workspaceID: ID,\n ) => Effect.Effect<EnvironmentDriver, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n readonly destroy: (\n workspaceID: ID,\n ) => Effect.Effect<void, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n}\n\nexport interface Options {\n readonly idleThreshold?: Duration.Input\n readonly pollInterval?: Duration.Input\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/Workspace\") {}\n\ninterface Connection {\n readonly driver: WorkspaceDriver.Interface\n readonly environment: EnvironmentDriver\n readonly saveBinding: (binding: WorkspaceDriver.Binding) => Effect.Effect<void>\n readonly lastActivity: Ref.Ref<number>\n readonly active: Ref.Ref<number>\n readonly scope: Scope.Closeable\n}\n\ntype ReadinessError = NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound\n\nexport const configured = (options: Options = {}) =>\n makeGlobalNode({\n service: Service,\n layer: layer(options),\n deps: [Database.node, WorkspaceDriver.node],\n })\n\nconst layer = (options: Options) =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const db = (yield* Database.Service).db\n const registry = yield* WorkspaceDriver.RegistryService\n const lifetime = yield* Scope.Scope\n const connections = new Map<ID, Connection>()\n // Destroy cancels the racing provision body by settling the deferred.\n const attempts = new Map<ID, Deferred.Deferred<Info, ReadinessError>>()\n const locks = KeyedMutex.makeUnsafe<ID>()\n const fork = yield* FiberSet.makeRuntime<never, void, never>()\n const idleThreshold = Duration.toMillis(options.idleThreshold ?? Duration.minutes(20))\n\n const load = Effect.fn(\"Workspace.load\")(function* (workspaceID: ID) {\n const row = yield* db\n .select()\n .from(WorkspaceTable)\n .where(eq(WorkspaceTable.id, workspaceID))\n .get()\n .pipe(Effect.orDie)\n if (!row) return yield* new NotFound({ workspaceID })\n return row\n })\n\n const saveBinding = (workspaceID: ID, binding: WorkspaceDriver.Binding) =>\n db.update(WorkspaceTable).set({ binding }).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)\n\n const info = (row: typeof WorkspaceTable.$inferSelect, binding: WorkspaceDriver.Binding) =>\n new Info({\n id: row.id,\n provider: row.provider,\n binding,\n createdAt: row.created_at,\n lastUsedAt: row.last_used_at,\n })\n\n const provision = Effect.fn(\"Workspace.provision\")((workspaceID: ID) =>\n Effect.suspend(() => {\n const existing = attempts.get(workspaceID)\n if (existing) return Deferred.await(existing)\n\n const attempt = Deferred.makeUnsafe<Info, ReadinessError>()\n attempts.set(workspaceID, attempt)\n fork(\n locks\n .withLock(workspaceID)(\n Effect.gen(function* () {\n const row = yield* load(workspaceID)\n if (row.binding) return info(row, row.binding)\n const driver = yield* registry.get(row.provider)\n const result = yield* driver.create({ workspaceID })\n yield* saveBinding(workspaceID, result.binding)\n return info(row, result.binding)\n }),\n )\n .pipe(\n Effect.raceFirst(Deferred.await(attempt)),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (attempts.get(workspaceID) === attempt) attempts.delete(workspaceID)\n Deferred.doneUnsafe(attempt, exit)\n }),\n ),\n Effect.exit,\n Effect.asVoid,\n ),\n )\n return Deferred.await(attempt)\n }),\n )\n\n const open = Effect.fn(\"Workspace.open\")(function* (workspaceID: ID) {\n const existing = connections.get(workspaceID)\n if (existing) return existing\n\n const row = yield* load(workspaceID)\n // Bindings are persisted before provision resolves and never nulled; a raced\n // destroy deletes the whole row and surfaces as NotFound from load above.\n if (!row.binding) return yield* Effect.die(`workspace ${workspaceID} has no binding after provision`)\n const driver = yield* registry.get(row.provider)\n const persistBinding = (binding: WorkspaceDriver.Binding) => saveBinding(workspaceID, binding)\n const scope = yield* Scope.fork(lifetime)\n const environment = yield* driver\n .connect({ workspaceID, binding: row.binding, saveBinding: persistBinding })\n .pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),\n )\n const now = yield* Clock.currentTimeMillis\n const connection: Connection = {\n driver,\n environment,\n saveBinding: persistBinding,\n lastActivity: yield* Ref.make(now),\n active: yield* Ref.make(0),\n scope,\n }\n connections.set(workspaceID, connection)\n yield* db\n .update(WorkspaceTable)\n .set({ last_used_at: now })\n .where(eq(WorkspaceTable.id, workspaceID))\n .run()\n .pipe(Effect.orDie)\n return connection\n })\n\n yield* Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis\n yield* Effect.forEach(\n [...connections.entries()],\n ([workspaceID, expected]) =>\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const connection = connections.get(workspaceID)\n if (connection !== expected || (yield* Ref.get(connection.active)) > 0) return\n const lastActivity = yield* Ref.get(connection.lastActivity)\n if (now - lastActivity < idleThreshold) return\n const row = yield* load(workspaceID)\n if (!row.binding) return\n // Deliberate: a racing spawn blocks, then wakes cleanly. Unlocking mid-suspend could reattach a sandbox being terminated.\n yield* connection.driver.suspendForIdle({\n workspaceID,\n binding: row.binding,\n saveBinding: connection.saveBinding,\n })\n yield* db\n .update(WorkspaceTable)\n .set({ last_used_at: lastActivity })\n .where(eq(WorkspaceTable.id, workspaceID))\n .run()\n .pipe(Effect.orDie)\n connections.delete(workspaceID)\n yield* Scope.close(connection.scope, Exit.void)\n }).pipe(Effect.catchCause((cause) => Effect.logError(\"workspace idle suspension failed\", cause))),\n ),\n { concurrency: \"unbounded\", discard: true },\n )\n }).pipe(Effect.repeat(Schedule.spaced(options.pollInterval ?? Duration.minutes(1))), Effect.forkScoped)\n\n return Service.of({\n create: Effect.fn(\"Workspace.create\")(function* (provider) {\n yield* registry.get(provider)\n const workspaceID = ID.create()\n const now = yield* Clock.currentTimeMillis\n yield* db\n .insert(WorkspaceTable)\n .values({ id: workspaceID, provider, binding: null, created_at: now, last_used_at: now })\n .run()\n .pipe(Effect.orDie)\n return workspaceID\n }),\n provision,\n connect: Effect.fn(\"Workspace.connect\")(function* (workspaceID) {\n const spawner = make((command) =>\n Effect.acquireRelease(\n // A live connection implies the binding is already persisted, so skip the provision hop.\n Effect.suspend(() => (connections.has(workspaceID) ? Effect.void : provision(workspaceID))).pipe(\n Effect.andThen(\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const connection = yield* open(workspaceID)\n yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)\n yield* Ref.update(connection.active, (active) => active + 1)\n return connection\n }),\n ),\n ),\n Effect.mapError((cause) =>\n systemError({\n _tag: \"Unknown\",\n module: \"Workspace\",\n method: \"spawn\",\n description: `Failed to wake workspace ${workspaceID}`,\n cause,\n }),\n ),\n ),\n (connection) =>\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n yield* Ref.update(connection.active, (active) => active - 1)\n yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)\n }),\n ),\n ).pipe(Effect.flatMap((connection) => connection.environment.spawner.spawn(command))),\n )\n // Overrides are connection-bound; per-spawn routing is required before any driver ships them, so they are deliberately omitted.\n return { spawner }\n }),\n destroy: Effect.fn(\"Workspace.destroy\")(function* (workspaceID) {\n // Settling the shared attempt cancels its racing provision body and fails\n // waiters with NotFound before teardown commits. Accepted tradeoffs: if the\n // locked teardown below fails, those waiters saw NotFound for a workspace\n // that still exists (the next provision retries it), and a provision racing\n // this window may briefly succeed before teardown destroys its fresh binding.\n const attempt = attempts.get(workspaceID)\n if (attempt) {\n attempts.delete(workspaceID)\n Deferred.doneUnsafe(attempt, Exit.fail(new NotFound({ workspaceID })))\n }\n yield* locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const row = yield* load(workspaceID)\n const connection = connections.get(workspaceID)\n connections.delete(workspaceID)\n if (connection) yield* Scope.close(connection.scope, Exit.void)\n // Null binding still reaches the driver: an interrupted or crashed\n // provision may have created a resource that was never persisted. A\n // provider missing from the registry cannot block deleting a\n // never-provisioned row.\n yield* registry.get(row.provider).pipe(\n Effect.flatMap((driver) => driver.destroy({ workspaceID, binding: row.binding })),\n Effect.catchTag(\"WorkspaceDriver.ProviderNotFound\", (error) =>\n row.binding ? Effect.fail(error) : Effect.void,\n ),\n )\n yield* db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)\n }),\n )\n }),\n })\n }),\n )\n\nexport const node = configured()\n\n// TODO(workspace-plan): add the boot janitor and ~23h safety snapshot rotation in a later PR.\n// TODO(workspace-plan): make cold wake interruptible with a re-pin loop against janitor races.\n// TODO(workspace-plan): consider extracting a keyed shared-attempt helper (join/cancel, drop-on-settle) beside\n// KeyedMutex at end-of-series consolidation; filesystem/search.ts and session/run-coordinator.ts hand-roll the same\n// shape. Audited stdlib alternatives (rc.111): RcMap fails twice (refcount release cancels in-flight work when the\n// last waiter leaves, and one finalizer path cannot express idle-suspend vs destroy); Cache interrupts the shared\n// lookup when its last awaiter is interrupted and cannot fail waiters with NotFound on invalidation.\n", | ||
| "import { Effect, Schema } from \"effect\"\n\nexport const FileType = Schema.Literals([\"file\", \"directory\", \"symlink\", \"other\"])\nexport type FileType = typeof FileType.Type\n\nexport interface FileInfo {\n readonly type: FileType\n readonly size: number\n readonly mtimeMs: number\n}\n\nexport interface DirEntry {\n readonly name: string\n readonly type: FileType\n}\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\"Environment.NotFound\", {\n path: Schema.String,\n}) {}\n\nexport class WrongKind extends Schema.TaggedError<WrongKind>()(\"Environment.WrongKind\", {\n path: Schema.String,\n actual: FileType,\n}) {}\n\nexport class Failed extends Schema.TaggedError<Failed>()(\"Environment.Failed\", {\n path: Schema.String,\n cause: Schema.Defect(),\n}) {}\n\nexport interface FilesImpl {\n /**\n * Content operations (`read`, `list`) follow final symlinks; metadata operations (`stat` and entry\n * tags returned by `list`) do not. `info` describes the target file whose bytes are returned.\n * The process-backed default caps collected output at 64 MiB; larger whole-file reads fail with\n * `Failed`, so callers must use ranges for larger files.\n */\n readonly read: (\n path: string,\n range?: { readonly offset: number; readonly length: number },\n ) => Effect.Effect<{ readonly info: FileInfo; readonly bytes: Uint8Array }, NotFound | WrongKind | Failed>\n readonly write: (path: string, bytes: Uint8Array) => Effect.Effect<void, Failed>\n /** Describes the path entry itself, so a final symlink is reported as `symlink` rather than followed. */\n readonly stat: (path: string) => Effect.Effect<FileInfo, NotFound | Failed>\n /** Follows a final symlink to the listed directory while preserving each returned entry's own type. */\n readonly list: (path: string) => Effect.Effect<ReadonlyArray<DirEntry>, NotFound | WrongKind | Failed>\n readonly remove: (path: string) => Effect.Effect<void, Failed>\n readonly move: (from: string, to: string) => Effect.Effect<void, NotFound | Failed>\n readonly mkdir: (path: string) => Effect.Effect<void, Failed>\n}\n\nexport interface Files extends FilesImpl {}\n\n/**\n * Derives a follow-stat kind from the lstat-like Files contract. A dangling\n * symlink fails with `NotFound`.\n */\nexport const typeFollowing = (files: Files, path: string) =>\n files.stat(path).pipe(\n Effect.flatMap((info) =>\n info.type === \"symlink\"\n ? files.read(path, { offset: 0, length: 0 }).pipe(\n Effect.map((result) => result.info.type),\n Effect.catchTag(\"Environment.WrongKind\", (error) => Effect.succeed(error.actual)),\n )\n : Effect.succeed(info.type),\n ),\n )\n\nexport * as EnvironmentFiles from \"./files.js\"\n", | ||
| "import { Effect, Stream } from \"effect\"\nimport { ChildProcess } from \"effect/unstable/process\"\nimport type { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport { collectStream } from \"@opencode-ai/util/process\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FileType, type FilesImpl } from \"./files.js\"\n\n/**\n * Files derived from spawning processes: one process per intent, \"$1\" is\n * always the target path. Scripts report classification through an exit-code\n * protocol (44/45/46) so failures never require parsing localized error text;\n * LC_ALL=C pins the one stderr match that remains. Requires GNU coreutils and\n * findutils in the target image — BSD and busybox userlands will not work.\n * Malformed output from these scripts is our own bug and dies as a defect.\n */\n\nconst MAX_DATA_BYTES = 64 * 1024 * 1024\nconst MAX_ERROR_BYTES = 64 * 1024\nconst NOT_FOUND = 44\nconst WRONG_KIND = 45\nconst FAILED = 46\nconst TAB = \"\\t\"\n\nconst loadMetadata = (flags = \"\") => `\nmetadata=$(stat ${flags} -c '%F${TAB}%s${TAB}%Y' -- \"$1\" 2>&1) || {\n case \"$metadata\" in\n *'No such file or directory'*|*'Not a directory'*) exit ${NOT_FOUND} ;;\n *) printf '%s' \"$metadata\" >&2; exit ${FAILED} ;;\n esac\n}\n`\n\nconst statScript = `\n${loadMetadata()}\nprintf '%s\\n' \"$metadata\"\n`\n\nconst readScript = `\n${loadMetadata(\"-L\")}\nkind=\\${metadata%%${TAB}*}\nif [ \"$kind\" != 'regular file' ] && [ \"$kind\" != 'regular empty file' ]; then\n printf '%s' \"$kind\" >&2\n exit ${WRONG_KIND}\nfi\nprintf '%s\\n' \"$metadata\"\nif [ \"$2\" = range ]; then\n dd if=\"$1\" iflag=skip_bytes,count_bytes skip=\"$3\" count=\"$4\" status=none\nelse\n cat -- \"$1\"\nfi\n`\n\nconst listScript = `\n${loadMetadata(\"-L\")}\nkind=\\${metadata%%${TAB}*}\nif [ \"$kind\" != directory ]; then\n printf '%s' \"$kind\" >&2\n exit ${WRONG_KIND}\nfi\nfind -H \"$1\" -mindepth 1 -maxdepth 1 -printf '%y\\\\0%f\\\\0'\n`\n\nconst moveScript = `\n${loadMetadata()}\nmv -- \"$1\" \"$2\"\n`\n\ninterface Result {\n readonly exitCode: number\n readonly stdout: Uint8Array\n readonly stderr: Uint8Array\n}\n\nexport const execDefaults = (spawner: ChildProcessSpawner[\"Service\"]): FilesImpl => {\n const run = (\n path: string,\n script: string,\n args: ReadonlyArray<string> = [],\n stdin?: Uint8Array,\n ): Effect.Effect<Result, Failed> =>\n Effect.scoped(\n Effect.gen(function* () {\n const command = ChildProcess.make(\"sh\", [\"-c\", script, \"sh\", path, ...args], {\n env: { LC_ALL: \"C\" },\n extendEnv: true,\n stdin: stdin === undefined ? undefined : Stream.make(stdin),\n })\n const handle = yield* spawner.spawn(command).pipe(Effect.mapError((cause) => new Failed({ path, cause })))\n const [stdout, stderr, exitCode] = yield* Effect.all(\n [\n collectStream(handle.stdout, MAX_DATA_BYTES),\n collectStream(handle.stderr, MAX_ERROR_BYTES),\n handle.exitCode,\n ],\n { concurrency: \"unbounded\" },\n ).pipe(Effect.mapError((cause) => new Failed({ path, cause })))\n if (stdout.truncated || stderr.truncated) {\n return yield* new Failed({ path, cause: new Error(\"Process output exceeded its collection limit\") })\n }\n return { exitCode, stdout: stdout.buffer, stderr: stderr.buffer }\n }),\n )\n\n const classify = <A>(\n path: string,\n result: Result,\n success: (stdout: Uint8Array) => A,\n ): Effect.Effect<A, NotFound | WrongKind | Failed> => {\n if (result.exitCode === 0) return Effect.sync(() => success(result.stdout))\n if (result.exitCode === NOT_FOUND) return Effect.fail(new NotFound({ path }))\n if (result.exitCode === WRONG_KIND) {\n return Effect.fail(new WrongKind({ path, actual: parseType(new TextDecoder().decode(result.stderr)) }))\n }\n return Effect.fail(processFailure(path, result))\n }\n\n const complete = (path: string, result: Result) =>\n result.exitCode === 0 ? Effect.void : Effect.fail(processFailure(path, result))\n\n return {\n stat: (path) => run(path, statScript).pipe(Effect.flatMap((result) => classifyPlain(path, result, parseInfo))),\n read: (path, range) =>\n run(\n path,\n readScript,\n range === undefined ? [\"whole\"] : [\"range\", String(range.offset), String(range.length)],\n ).pipe(\n Effect.flatMap((result) =>\n classify(path, result, (stdout) => {\n const newline = stdout.indexOf(10)\n if (newline < 0) throw new Error(\"Missing read metadata header\")\n return {\n info: parseInfo(stdout.slice(0, newline)),\n bytes: stdout.slice(newline + 1),\n }\n }),\n ),\n ),\n write: (path, bytes) =>\n run(path, `mkdir -p \"$(dirname \"$1\")\" && cat > \"$1\"`, [], bytes).pipe(\n Effect.flatMap((result) => complete(path, result)),\n ),\n list: (path) => run(path, listScript).pipe(Effect.flatMap((result) => classify(path, result, parseList))),\n remove: (path) => run(path, `rm -rf -- \"$1\"`).pipe(Effect.flatMap((result) => complete(path, result))),\n move: (from, to) =>\n run(from, moveScript, [to]).pipe(Effect.flatMap((result) => classifyPlain(from, result, () => undefined))),\n mkdir: (path) => run(path, `mkdir -p -- \"$1\"`).pipe(Effect.flatMap((result) => complete(path, result))),\n }\n}\n\n/** `classify` for scripts whose protocol never reports WrongKind. */\nconst classifyPlain = <A>(\n path: string,\n result: Result,\n success: (stdout: Uint8Array) => A,\n): Effect.Effect<A, NotFound | Failed> => {\n if (result.exitCode === 0) return Effect.sync(() => success(result.stdout))\n if (result.exitCode === NOT_FOUND) return Effect.fail(new NotFound({ path }))\n return Effect.fail(processFailure(path, result))\n}\n\nconst processFailure = (path: string, result: Result) =>\n new Failed({\n path,\n cause: new Error(new TextDecoder().decode(result.stderr).trim() || `Process exited with code ${result.exitCode}`),\n })\n\nconst parseInfo = (bytes: Uint8Array): FileInfo => {\n const [rawType, rawSize, rawMtime] = new TextDecoder().decode(bytes).trim().split(TAB)\n const size = Number(rawSize)\n const mtimeMs = Number(rawMtime) * 1_000\n if (!rawType || !Number.isFinite(size) || !Number.isFinite(mtimeMs)) throw new Error(\"Invalid stat output\")\n return { type: parseType(rawType), size, mtimeMs }\n}\n\nconst parseType = (value: string): FileType => {\n if (value === \"regular file\" || value === \"regular empty file\" || value === \"f\") return \"file\"\n if (value === \"directory\" || value === \"d\") return \"directory\"\n if (value === \"symbolic link\" || value === \"l\") return \"symlink\"\n return \"other\"\n}\n\nconst parseList = (bytes: Uint8Array) => {\n const fields = new TextDecoder().decode(bytes).split(\"\\0\")\n fields.pop()\n if (fields.length % 2 !== 0) throw new Error(\"Invalid find output\")\n return Array.from({ length: fields.length / 2 }, (_, index) => ({\n name: fields[index * 2 + 1],\n type: parseType(fields[index * 2]),\n }))\n}\n\nexport * as EnvironmentExecDefaults from \"./exec-defaults.js\"\n", | ||
| "import fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { Effect } from \"effect\"\nimport type { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver } from \"./driver.js\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FilesImpl, type FileType } from \"./files.js\"\n\n/**\n * The host filesystem binding. Deliberately raw node:fs rather than effect's\n * FileSystem service or FSUtil: the contract needs lstat semantics (stat\n * reports \"symlink\") and typed directory entries, and effect's node\n * FileSystem provides neither — its stat always follows symlinks and\n * readDirectory returns names only. FSUtil hits the same gap and its\n * readDirectoryEntries already bypasses to raw node readdir internally.\n * Nothing above the environment seam touches node:fs.\n */\nexport const makeLocalDriver = (spawner: ChildProcessSpawner[\"Service\"]): Driver => {\n const overrides: FilesImpl = {\n read: (value, range) =>\n Effect.gen(function* () {\n const info = yield* stat(value, true)\n if (info.type !== \"file\") return yield* new WrongKind({ path: value, actual: info.type })\n if (range === undefined) {\n const bytes = yield* attempt(value, () => fs.readFile(value), true)\n return { info, bytes }\n }\n const bytes = yield* attempt(\n value,\n async () => {\n const handle = await fs.open(value, \"r\")\n try {\n const buffer = new Uint8Array(range.length)\n const result = await handle.read(buffer, 0, range.length, range.offset)\n return buffer.subarray(0, result.bytesRead)\n } finally {\n await handle.close()\n }\n },\n true,\n )\n return { info, bytes }\n }),\n stat: (value) => stat(value, false),\n list: (value) =>\n Effect.gen(function* () {\n const info = yield* stat(value, true)\n if (info.type !== \"directory\") return yield* new WrongKind({ path: value, actual: info.type })\n const entries = yield* attempt(value, () => fs.readdir(value, { withFileTypes: true }), true)\n return entries.map((entry) => ({ name: entry.name, type: fileType(entry) }))\n }),\n write: (value, bytes) =>\n attempt(value, async () => {\n await fs.mkdir(path.dirname(value), { recursive: true })\n await fs.writeFile(value, bytes)\n }),\n remove: (value) => attempt(value, () => fs.rm(value, { recursive: true, force: true })),\n move: (from, to) =>\n Effect.gen(function* () {\n yield* stat(from, false)\n const destination = yield* stat(to, false).pipe(\n Effect.map((info) => (info.type === \"directory\" ? path.join(to, path.basename(from)) : to)),\n Effect.catchIf(\n (error) => error instanceof NotFound,\n () => Effect.succeed(to),\n ),\n )\n yield* attempt(from, () => fs.rename(from, destination))\n }),\n mkdir: (value) => attempt(value, () => fs.mkdir(value, { recursive: true }).then(() => undefined)),\n }\n\n return { spawner, overrides }\n}\n\nconst stat = (value: string, follow: boolean) =>\n attempt(value, () => (follow ? fs.stat(value) : fs.lstat(value)), true).pipe(\n Effect.map((stats): FileInfo => ({ type: fileType(stats), size: stats.size, mtimeMs: stats.mtimeMs })),\n )\n\nconst fileType = (entry: { isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean }): FileType => {\n if (entry.isFile()) return \"file\"\n if (entry.isDirectory()) return \"directory\"\n if (entry.isSymbolicLink()) return \"symlink\"\n return \"other\"\n}\n\nfunction attempt<A>(value: string, run: () => Promise<A>): Effect.Effect<A, Failed>\nfunction attempt<A>(value: string, run: () => Promise<A>, missing: true): Effect.Effect<A, NotFound | Failed>\nfunction attempt<A>(value: string, run: () => Promise<A>, missing = false) {\n return Effect.tryPromise({\n try: run,\n catch: (cause) =>\n missing && isMissing(cause) ? new NotFound({ path: value }) : new Failed({ path: value, cause }),\n })\n}\n\nconst isMissing = (cause: unknown) =>\n cause !== null &&\n typeof cause === \"object\" &&\n \"code\" in cause &&\n (cause.code === \"ENOENT\" || cause.code === \"ENOTDIR\")\n\nexport * as EnvironmentLocal from \"./local.js\"\n", | ||
| "import path from \"node:path\"\nimport { Effect, PlatformError } from \"effect\"\nimport { make } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver } from \"./driver.js\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FilesImpl, type FileType } from \"./files.js\"\n\ntype Node =\n | { readonly type: \"file\"; readonly bytes: Uint8Array; readonly mtimeMs: number }\n | { readonly type: \"directory\"; readonly mtimeMs: number }\n | { readonly type: \"symlink\"; readonly target: string; readonly mtimeMs: number }\n\nexport interface MemoryDriver extends Driver {\n readonly symlink: (target: string, path: string) => Effect.Effect<void, Failed>\n}\n\nexport const makeMemoryDriver = (): MemoryDriver => {\n const nodes = new Map<string, Node>([[\"/\", { type: \"directory\", mtimeMs: Date.now() }]])\n const key = (value: string) => path.posix.resolve(\"/\", value)\n const info = (node: Node): FileInfo => ({\n type: node.type,\n size:\n node.type === \"file\"\n ? node.bytes.length\n : node.type === \"symlink\"\n ? new TextEncoder().encode(node.target).length\n : 0,\n mtimeMs: node.mtimeMs,\n })\n const resolveKey = (value: string, followFinal: boolean, seen = new Set<string>()): string | undefined => {\n const normalized = key(value)\n const parts = normalized.split(\"/\").filter(Boolean)\n const base = \"/\"\n const walk = (current: string, index: number): string | undefined => {\n if (index === parts.length) return current\n const part = parts[index]\n const candidate = path.posix.join(current, part)\n const node = nodes.get(candidate)\n if (node?.type !== \"symlink\" || (!followFinal && index === parts.length - 1)) return walk(candidate, index + 1)\n if (seen.has(candidate)) return undefined\n seen.add(candidate)\n const target = path.posix.resolve(path.posix.dirname(candidate), node.target)\n return resolveKey(path.posix.join(target, ...parts.slice(index + 1)), followFinal, seen)\n }\n return walk(base, 0)\n }\n const lookup = (value: string) => nodes.get(resolveKey(value, false) ?? key(value))\n const requireParent = (value: string) => {\n const parentPath = path.posix.dirname(key(value))\n const parent = nodes.get(resolveKey(parentPath, true) ?? parentPath)\n if (!parent) throw new Error(`Parent directory does not exist: ${path.posix.dirname(value)}`)\n if (parent.type !== \"directory\") throw new Error(`Parent is not a directory: ${path.posix.dirname(value)}`)\n }\n const mkdirSync = (value: string) => {\n const target = resolveKey(value, false) ?? key(value)\n const existing = nodes.get(target)\n if (existing?.type === \"directory\") return\n if (existing) throw new Error(`Path is not a directory: ${value}`)\n const parent = path.posix.dirname(target)\n if (parent !== target) mkdirSync(parent)\n nodes.set(target, { type: \"directory\", mtimeMs: Date.now() })\n }\n const failed = (value: string, cause: unknown) => new Failed({ path: value, cause })\n const overrides: FilesImpl = {\n stat: (value) => {\n const node = lookup(value)\n return node ? Effect.succeed(info(node)) : Effect.fail(new NotFound({ path: value }))\n },\n read: (value, range) => {\n const original = lookup(value)\n if (!original) return Effect.fail(new NotFound({ path: value }))\n if (original.type === \"directory\") return Effect.fail(new WrongKind({ path: value, actual: \"directory\" }))\n const resolved = resolveKey(value, true)\n const node = resolved === undefined ? undefined : nodes.get(resolved)\n if (!node) return Effect.fail(new NotFound({ path: value }))\n if (node.type !== \"file\") return Effect.fail(new WrongKind({ path: value, actual: node.type }))\n const bytes = range === undefined ? node.bytes : node.bytes.subarray(range.offset, range.offset + range.length)\n return Effect.succeed({ info: info(node), bytes: bytes.slice() })\n },\n write: (value, bytes) =>\n Effect.try({\n try: () => {\n mkdirSync(path.posix.dirname(key(value)))\n const existing = lookup(value)\n if (existing?.type === \"directory\") throw new Error(`Path is a directory: ${value}`)\n const target = existing?.type === \"symlink\" ? resolveKey(value, true) : resolveKey(value, false)\n if (!target) throw new Error(`Cannot resolve symlink: ${value}`)\n requireParent(target)\n nodes.set(target, { type: \"file\", bytes: bytes.slice(), mtimeMs: Date.now() })\n },\n catch: (cause) => failed(value, cause),\n }),\n list: (value) => {\n const target = resolveKey(value, true) ?? key(value)\n const node = nodes.get(target)\n if (!node) return Effect.fail(new NotFound({ path: value }))\n if (node.type !== \"directory\") return Effect.fail(new WrongKind({ path: value, actual: node.type }))\n const entries = [...nodes.entries()]\n .filter(([entry]) => entry !== target && path.posix.dirname(entry) === target)\n .map(([entry, child]) => ({ name: path.posix.basename(entry), type: child.type satisfies FileType }))\n .sort((a, b) => a.name.localeCompare(b.name))\n return Effect.succeed(entries)\n },\n remove: (value) =>\n Effect.sync(() => {\n const target = resolveKey(value, false) ?? key(value)\n for (const entry of nodes.keys()) {\n if (entry === target || entry.startsWith(`${target}/`)) nodes.delete(entry)\n }\n }),\n move: (from, to) => {\n const source = resolveKey(from, false) ?? key(from)\n const node = nodes.get(source)\n if (!node) return Effect.fail(new NotFound({ path: from }))\n return Effect.try({\n try: () => {\n const requested = resolveKey(to, false) ?? key(to)\n const destination =\n nodes.get(requested)?.type === \"directory\"\n ? path.posix.join(requested, path.posix.basename(source))\n : requested\n if (node.type === \"directory\" && destination.startsWith(`${source}/`)) {\n throw new Error(`Cannot move a directory into itself: ${from}`)\n }\n const existing = nodes.get(destination)\n if (node.type === \"directory\" && existing && existing.type !== \"directory\") {\n throw new Error(`Cannot overwrite a non-directory with a directory: ${to}`)\n }\n requireParent(destination)\n const moved = [...nodes.entries()].filter(([entry]) => entry === source || entry.startsWith(`${source}/`))\n for (const [entry] of moved) nodes.delete(entry)\n for (const [entry, child] of moved) nodes.set(`${destination}${entry.slice(source.length)}`, child)\n },\n catch: (cause) => failed(from, cause),\n })\n },\n mkdir: (value) => Effect.try({ try: () => mkdirSync(value), catch: (cause) => failed(value, cause) }),\n }\n\n const spawner = make((command) =>\n Effect.suspend(() => {\n const description = command._tag === \"StandardCommand\" ? command.command : \"pipeline\"\n return Effect.fail(\n PlatformError.systemError({\n _tag: \"Unknown\",\n module: \"EnvironmentMemory\",\n method: \"spawn\",\n pathOrDescriptor: description,\n cause: failed(description, new Error(\"The memory driver cannot spawn processes\")),\n }),\n )\n }),\n )\n\n return {\n spawner,\n overrides,\n symlink: (target, value) =>\n Effect.try({\n try: () => {\n requireParent(value)\n nodes.set(resolveKey(value, false) ?? key(value), { type: \"symlink\", target, mtimeMs: Date.now() })\n },\n catch: (cause) => failed(value, cause),\n }),\n }\n}\n\nexport * as EnvironmentMemory from \"./memory.js\"\n", | ||
| "import { CrossSpawnSpawner } from \"@opencode-ai/util/cross-spawn-spawner\"\nimport { makeLocationNode } from \"@opencode-ai/util/effect/app-node\"\nimport { Context, Effect, Layer } from \"effect\"\nimport { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Files } from \"./files.js\"\nimport { makeFiles } from \"./index.js\"\nimport { makeLocalDriver } from \"./local.js\"\nimport { Location } from \"../location.js\"\nimport { Workspace } from \"../workspace.js\"\n\nexport interface Interface {\n readonly files: Files\n readonly spawner: ChildProcessSpawner[\"Service\"]\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/Environment\") {}\n\nconst layer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner\n const location = yield* Location.Service\n const workspace = yield* Workspace.Service\n const driver = location.workspaceID\n ? yield* workspace.connect(location.workspaceID).pipe(\n // Environment has no error channel; an unknown or destroyed placement is a configuration defect by design.\n Effect.mapError(\n (cause) => new Error(`Failed to bind Environment to workspace ${location.workspaceID}`, { cause }),\n ),\n Effect.orDie,\n )\n : makeLocalDriver(spawner)\n return Service.of({ files: makeFiles(driver), spawner: driver.spawner })\n }),\n)\n\nexport const node = makeLocationNode({\n service: Service,\n layer,\n deps: [CrossSpawnSpawner.node, Location.node, Workspace.node],\n})\n\nexport * as EnvironmentService from \"./environment.js\"\n", | ||
| "export * as Environment from \"./index.js\"\n\nexport { type Driver } from \"./driver.js\"\nexport {\n type DirEntry,\n Failed,\n type FileInfo,\n type Files,\n type FilesImpl,\n type FileType,\n NotFound,\n typeFollowing,\n WrongKind,\n} from \"./files.js\"\nexport { execDefaults } from \"./exec-defaults.js\"\nexport { makeLocalDriver } from \"./local.js\"\nexport { makeMemoryDriver, type MemoryDriver } from \"./memory.js\"\nexport { type Interface, node, Service } from \"./environment.js\"\n\nimport type { Driver } from \"./driver.js\"\nimport { execDefaults } from \"./exec-defaults.js\"\nimport type { Files } from \"./files.js\"\n\nexport const makeFiles = (driver: Driver): Files => ({\n ...execDefaults(driver.spawner),\n ...driver.overrides,\n})\n" | ||
| ], | ||
| "mappings": ";21BAaO,IAAM,GAAU,EAAO,OAAO,EAAO,OAAQ,EAAO,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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\"\nimport { Global } from \"@opencode-ai/util/global\"\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({\n server: serverURL,\n standalone: input.standalone,\n mismatch: \"replace\",\n })\n const config = yield* Config.Service\n const global = yield* Global.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: Option.getOrUndefined(input.replay) ?? resolved.mini?.replay ?? true,\n replayLimit: Option.getOrUndefined(input.replayLimit) ?? resolved.mini?.replay_limit,\n demo: input.demo,\n tuiConfig: resolved,\n config: {\n update: (update) => runServicePromise(config.update(update)),\n },\n paths: { home: global.home, state: global.state, log: global.log },\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";qkCAQA,IAAe,IAAQ,QAAQ,EAAS,SAAS,KAAM,CAAC,IACtD,EAAO,IAAI,SAAU,EAAG,CACtB,IAAQ,UAAS,wBAAyB,MAAO,EAAO,QAAQ,IAAa,wCAAa,EAC1F,MAAO,EAAO,QAAQ,SAAY,EAAqB,CAAC,EACxD,IAAM,EAAY,EAAO,eAAe,EAAM,MAAM,EAC9C,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EACR,WAAY,EAAM,WAClB,SAAU,SACZ,CAAC,EACK,EAAS,MAAO,EAAO,QACvB,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,EAAO,eAAe,EAAM,MAAM,GAAK,EAAS,MAAM,QAAU,GACxE,YAAa,EAAO,eAAe,EAAM,WAAW,GAAK,EAAS,MAAM,aACxE,KAAM,EAAM,KACZ,UAAW,EACX,OAAQ,CACN,OAAQ,CAAC,IAAW,EAAkB,EAAO,OAAO,CAAM,CAAC,CAC7D,EACA,MAAO,CAAE,KAAM,EAAO,KAAM,MAAO,EAAO,MAAO,IAAK,EAAO,GAAI,CACnE,CAAC,CACH,EACD,CACH", | ||
| "debugId": "73648F091F8C2EB564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+mistral@3.0.51+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 var _a, _b, _c, _d, _e;\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 const cacheReadTokens = (_e = (_d = (_b = usage.num_cached_tokens) != null ? _b : (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _d : (_c = usage.prompt_token_details) == null ? void 0 : _c.cached_tokens) != null ? _e : 0;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens || 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 structuredContent = [];\n let hasNativeReasoning = false;\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n structuredContent.push({ type: \"text\", 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 const native = part.providerOptions?.mistral?.thinking;\n if (native?.type === \"thinking\") {\n hasNativeReasoning = true;\n structuredContent.push(native);\n break;\n }\n structuredContent.push({ type: \"text\", 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: hasNativeReasoning ? structuredContent : 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 call 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 promptCacheKey: z.string().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 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 ...frequencyPenalty != null ? { frequency_penalty: frequencyPenalty } : {},\n ...presencePenalty != null ? { presence_penalty: presencePenalty } : {},\n stop: stopSequences,\n random_seed: seed,\n reasoning_effort: options.reasoningEffort,\n prompt_cache_key: options.promptCacheKey,\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 content.push({\n type: \"reasoning\",\n text: reasoningText,\n providerMetadata: { mistral: { thinking: part } }\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 let activeThinking = 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 activeThinking = mergeThinking(activeThinking, part);\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 if (reasoningDelta.length > 0) {\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 providerMetadata: { mistral: { thinking: activeThinking } }\n });\n activeReasoningId = null;\n activeThinking = 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 providerMetadata: { mistral: { thinking: activeThinking } }\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 mergeThinking(current, next) {\n if (current === null) return { ...next, thinking: [...next.thinking] };\n current.thinking.push(...next.thinking);\n if (next.closed !== void 0) current.closed = next.closed;\n if (next.signature !== void 0) current.signature = next.signature;\n return current;\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 mistralThinkingContentSchema = z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"tool_reference\"),\n tool: z3.string(),\n title: z3.string(),\n url: z3.string().nullish(),\n favicon: z3.string().nullish(),\n description: z3.string().nullish()\n }),\n z3.object({\n type: z3.literal(\"reference\"),\n reference_ids: z3.array(z3.union([z3.string(), z3.number().int()]))\n })\n]);\nvar mistralThinkChunkSchema = z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.array(mistralThinkingContentSchema),\n closed: z3.boolean().optional(),\n signature: z3.string().nullish()\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 mistralThinkChunkSchema\n ])\n )\n]).nullish();\nvar mistralUsageSchema = z3.object({\n prompt_tokens: z3.number(),\n completion_tokens: z3.number(),\n total_tokens: z3.number(),\n num_cached_tokens: z3.number().nullish(),\n prompt_tokens_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish(),\n prompt_token_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish()\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/mistral-speech-model.ts\nimport {\n combineHeaders as combineHeaders3,\n createJsonResponseHandler as createJsonResponseHandler3,\n parseProviderOptions as parseProviderOptions2,\n postToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\n\n// src/mistral-speech-model-options.ts\nimport { z as z5 } from \"zod/v4\";\nvar mistralSpeechModelOptions = z5.object({\n /**\n * Base64-encoded reference audio for one-off voice cloning.\n *\n * When provided, this takes precedence over the standard `voice` option.\n */\n refAudio: z5.string().min(1).optional()\n});\n\n// src/mistral-speech-model.ts\nvar MistralSpeechModel = 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 text,\n voice,\n outputFormat = \"mp3\",\n instructions,\n speed,\n language,\n providerOptions\n }) {\n const warnings = [];\n const mistralOptions = await parseProviderOptions2({\n provider: \"mistral\",\n providerOptions,\n schema: mistralSpeechModelOptions\n });\n let responseFormat = \"mp3\";\n if ([\"pcm\", \"wav\", \"mp3\", \"flac\", \"opus\"].includes(outputFormat)) {\n responseFormat = outputFormat;\n } else {\n warnings.push({\n type: \"unsupported\",\n feature: \"outputFormat\",\n details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`\n });\n }\n if (instructions != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"instructions\",\n details: \"Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery.\"\n });\n }\n if (speed != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"speed\",\n details: \"Mistral speech models do not support the `speed` option. It was ignored.\"\n });\n }\n if (language != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"language\",\n details: \"Mistral speech models do not support the `language` option. Language is inferred from the input text and voice.\"\n });\n }\n const refAudio = mistralOptions == null ? void 0 : mistralOptions.refAudio;\n const requestBody = {\n model: this.modelId,\n input: text,\n voice_id: refAudio == null ? voice : void 0,\n ref_audio: refAudio,\n response_format: responseFormat,\n stream: false\n };\n const requestBodyValues = {\n ...requestBody,\n ref_audio: refAudio == null ? void 0 : \"[redacted]\"\n };\n return { requestBody, requestBodyValues, warnings };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e;\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 { requestBody, requestBodyValues, warnings } = await this.getArgs(options);\n const {\n value: response,\n responseHeaders,\n rawValue: rawResponse\n } = await postToApi({\n url: `${this.config.baseURL}/audio/speech`,\n headers: combineHeaders3(\n { \"Content-Type\": \"application/json\" },\n (_e = (_d = this.config).headers) == null ? void 0 : _e.call(_d),\n options.headers\n ),\n body: {\n content: JSON.stringify(requestBody),\n values: requestBodyValues\n },\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler3(\n mistralSpeechResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n return {\n audio: response.audio_data,\n warnings,\n request: {\n body: JSON.stringify(requestBodyValues)\n },\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawResponse\n }\n };\n }\n};\nvar mistralSpeechResponseSchema = z6.object({\n audio_data: z6.string()\n});\n\n// src/version.ts\nvar VERSION = true ? \"3.0.51\" : \"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 createSpeechModel = (modelId) => new MistralSpeechModel(modelId, {\n provider: \"mistral.speech\",\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.speech = createSpeechModel;\n provider.speechModel = createSpeechModel;\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": ";+WAuBA,SAAS,CAAmB,CAAC,EAAO,CAClC,IAAI,EAAI,EAAI,EAAI,EAAI,EACpB,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,IAA2B,cAArB,EACyB,kBAAzB,GAAmB,EACnB,GAAmB,GAAM,GAAM,EAAK,EAAM,oBAAsB,KAAO,GAAM,EAAK,EAAM,wBAA0B,KAAY,OAAI,EAAG,gBAAkB,KAAO,GAAM,EAAK,EAAM,uBAAyB,KAAY,OAAI,EAAG,gBAAkB,KAAO,EAAK,EAC/P,MAAO,CACL,YAAa,CACX,MAAO,EACP,QAAS,EAAe,EACxB,UAAW,GAA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GAAW,EAAK,EAAqB,EAAQ,OAAO,IAAM,KAAO,EAAK,4BACtE,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,kBACzB,YAAa,SACf,CAAC,OACE,EAAQ,OACb,EACA,kBAAkB,IACpB,EACM,EAAkB,CAAC,IAAY,IAAI,GAAyB,EAAS,CACzE,SAAU,eACV,UACA,QAAS,EACT,MAAO,EAAQ,MACf,WAAY,EAAQ,UACtB,CAAC,EACK,EAAuB,CAAC,IAAY,IAAI,GAAsB,EAAS,CAC3E,SAAU,oBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAoB,CAAC,IAAY,IAAI,GAAmB,EAAS,CACrE,SAAU,iBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAW,QAAQ,CAAC,EAAS,CACjC,GAAI,WACF,MAAU,MACR,mEACF,EAEF,OAAO,EAAgB,CAAO,GAchC,OAZA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,KAAO,EAChB,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,cAAgB,EACzB,EAAS,mBAAqB,EAC9B,EAAS,OAAS,EAClB,EAAS,YAAc,EACvB,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAU,GAAc", | ||
| "debugId": "DE384D05B541FB3D64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/add.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\"\nimport { Effect } from \"effect\"\nimport { applyEdits, modify, parse, type ParseError } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { resolveConfigPath } from \"../mcp/add\"\nimport { Config } from \"../../../config\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.add,\n Effect.fn(\"cli.plugin.add\")(function* (input) {\n if (!(yield* Effect.promise(() => Npm.isRegistryPackage(input.package))))\n return yield* Effect.fail(\n new Error(\"Plugin target must be an npm registry package name, version, tag, or semver range\"),\n )\n const npm = yield* Npm.Service\n const installed = yield* npm.add(input.package, { subpaths: [\"server\", \"\"] })\n const tui = yield* npm.resolve(input.package, { subpaths: [\"tui\"] })\n const target = configurationTarget(installed.entrypoint, tui.entrypoint)\n if (!target)\n return yield* Effect.fail(new Error(`Plugin package has no server or TUI entrypoint: ${input.package}`))\n\n if (target === \"server\") {\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(global.config))\n const changed = yield* Effect.promise(() => writePluginConfig(configPath, input.package))\n process.stdout.write(\n changed\n ? `Plugin \"${input.package}\" installed and added to ${configPath}${EOL}`\n : `Plugin \"${input.package}\" is already configured in ${configPath}${EOL}`,\n )\n return\n }\n\n const config = yield* Config.Service\n yield* config.update((draft) => {\n if (configured(draft.plugins, input.package)) return\n draft.plugins = [...(draft.plugins ?? []), input.package]\n })\n process.stdout.write(`TUI plugin \"${input.package}\" installed and added to ${config.path}${EOL}`)\n }),\n)\n\nexport function configurationTarget(server?: string, tui?: string) {\n if (server) return \"server\" as const\n if (tui) return \"tui\" as const\n}\n\nexport async function writePluginConfig(configPath: string, spec: string) {\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 errors: ParseError[] = []\n const config: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length || typeof config !== \"object\" || config === null || Array.isArray(config))\n throw new Error(`Invalid global configuration: ${configPath}`)\n const plugins = \"plugins\" in config ? config.plugins : undefined\n if (plugins !== undefined && !Array.isArray(plugins)) throw new Error(`Invalid plugins configuration: ${configPath}`)\n if (configured(plugins, spec)) return false\n\n const updated = applyEdits(\n text,\n modify(text, [\"plugins\"], [...(plugins ?? []), spec], { formattingOptions: { tabSize: 2, insertSpaces: true } }),\n )\n await mkdir(path.dirname(configPath), { recursive: true })\n const temporary = configPath + \".tmp\"\n await writeFile(temporary, updated.endsWith(\"\\n\") ? updated : updated + \"\\n\", { mode: 0o600 })\n await rename(temporary, configPath)\n return true\n}\n\nfunction configured(plugins: readonly unknown[] | undefined, spec: string) {\n return plugins?.some(\n (entry) =>\n entry === spec || (typeof entry === \"object\" && entry !== null && \"package\" in entry && entry.package === spec),\n )\n}\n" | ||
| ], | ||
| "mappings": ";8tBAAA,cAAS,WACT,oBACA,gBAAS,cAAO,YAAU,eAAQ,oBAUlC,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,IAClC,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAO,CAC5C,GAAI,EAAE,MAAO,EAAO,QAAQ,IAAM,EAAI,kBAAkB,EAAM,OAAO,CAAC,GACpE,OAAO,MAAO,EAAO,KACf,MAAM,mFAAmF,CAC/F,EACF,IAAM,EAAM,MAAO,EAAI,QACjB,EAAY,MAAO,EAAI,IAAI,EAAM,QAAS,CAAE,SAAU,CAAC,SAAU,EAAE,CAAE,CAAC,EACtE,EAAM,MAAO,EAAI,QAAQ,EAAM,QAAS,CAAE,SAAU,CAAC,KAAK,CAAE,CAAC,EAC7D,EAAS,EAAoB,EAAU,WAAY,EAAI,UAAU,EACvE,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,mDAAmD,EAAM,SAAS,CAAC,EAEzG,GAAI,IAAW,SAAU,CACvB,IAAM,EAAS,MAAO,EAAO,QACvB,EAAa,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAO,MAAM,CAAC,EACzE,EAAU,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAY,EAAM,OA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,EAAK,CAAC,EACzD,IAAM,EAAY,EAAa,OAG/B,OAFA,MAAM,EAAU,EAAW,EAAQ,SAAS;AAAA,CAAI,EAAI,EAAU,EAAU;AAAA,EAAM,CAAE,KAAM,GAAM,CAAC,EAC7F,MAAM,EAAO,EAAW,CAAU,EAC3B,GAGT,SAAS,CAAU,CAAC,EAAyC,EAAc,CACzE,OAAO,GAAS,KACd,CAAC,IACC,IAAU,GAAS,OAAO,IAAU,UAAY,IAAU,OAAQ,YAAa,IAAS,EAAM,UAAY,CAC9G", | ||
| "debugId": "F9822C0D465D4ECB64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/workspace.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Workspace from \"./workspace.js\"\n\nimport { WorkspaceEvent } from \"./workspace-event.js\"\nimport { WorkspaceID } from \"./workspace-id.js\"\n\nexport const ID = WorkspaceID\nexport type ID = WorkspaceID\n\nexport const Event = WorkspaceEvent\n" | ||
| ], | ||
| "mappings": ";iNAKO,IAAM,EAAK,EAGL,EAAQ", | ||
| "debugId": "A6B22A251F4FB95A64756E2164756E21", | ||
| "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+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": ";iWAsBA,SAAS,CAAsB,CAAC,EAAO,C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AAC,EAAU,CAAC,EAAG,CACtC,IAAM,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,qBACzB,YAAa,YACf,CAAC,OACE,EAAQ,OACb,EACA,qBAAqB,GACvB,EACM,EAAsB,CAAC,IAAY,CACvC,IAAI,EACJ,OAAO,IAAI,EAAwB,EAAS,CAC1C,QAAS,GACN,EAAK,EAAQ,UAAY,KAAO,EAAK,2BACxC,EACA,QAAS,EACT,aACA,MAAO,EAAQ,KACjB,CAAC,GAEG,EAAW,CAAC,IAAY,EAAoB,CAAO,EAUzD,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,GAAa,EAAiB", | ||
| "debugId": "C3A6B32ABF5310B064756E2164756E21", | ||
| "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.js\"\nimport { DecodeError, ResizerUnavailableError, SizeError } from \"../image.js\"\n\nconst JPEG_QUALITIES = [80, 85, 70, 55, 40]\n\nexport const make = Effect.gen(function* () {\n const loadPhoton = yield* Effect.cached(\n // A runtime without a photon wasm artifact (#photon-wasm resolves to the\n // empty string on workerd) has no resizer, by declaration: fail typed\n // before touching URLs or module loading. The path resolution and import\n // for runtimes that DO have an artifact stay inside the guard too — a\n // throw outside it (workerd's undefined import.meta.url was one) is a\n // defect that escapes the ResizerUnavailableError handling and turns any\n // image-bearing prompt into a 500 instead of degrading to passthrough.\n photonWasm === \"\"\n ? Effect.fail(new ResizerUnavailableError())\n : Effect.tryPromise({\n try: async () => {\n ;(\n globalThis as typeof globalThis & { __OPENCODE_PHOTON_WASM_PATH?: string }\n ).__OPENCODE_PHOTON_WASM_PATH = path.isAbsolute(photonWasm)\n ? photonWasm\n : fileURLToPath(new URL(photonWasm, import.meta.url))\n return await import(\"@silvia-odwyer/photon-node\")\n },\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": ";kgCAGA,IAAe,ICDf,oBACA,wBAAS,YAIT,IAAM,EAAiB,CAAC,GAAI,GAAI,GAAI,GAAI,EAAE,EAE7B,EAAO,EAAO,IAAI,SAAU,EAAG,CAC1C,IAAM,EAAa,MAAO,EAAO,OAQ/B,IAAe,GACX,EAAO,KAAK,IAAI,CAAyB,EACzC,EAAO,WAAW,CAChB,IAAK,UAED,WACA,4BAA8B,EAAK,WAAW,CAAU,EACtD,EACA,EAAc,IAAI,IAAI,EAAY,YAAY,GAAG,CAAC,EAC/C,KAAa,2CAEtB,MAAO,IAAM,IAAI,CACnB,CAAC,CACP,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,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AAU,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": "0E8E1B64BA67693E64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/workspace-event.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WorkspaceEvent from \"./workspace-event.js\"\n\nimport { Schema } from \"effect\"\nimport { Event } from \"./event.js\"\nimport { WorkspaceID } from \"./workspace-id.js\"\n\nexport const ConnectionStatus = Schema.Struct({\n workspaceID: WorkspaceID,\n status: Schema.Literals([\"connected\", \"connecting\", \"disconnected\", \"error\"]),\n}).annotate({ identifier: \"WorkspaceEvent.ConnectionStatus\" })\nexport interface ConnectionStatus extends Schema.Schema.Type<typeof ConnectionStatus> {}\n\nexport const Ready = Event.ephemeral({\n type: \"workspace.ready\",\n schema: {\n name: Schema.String,\n },\n})\n\nexport const Failed = Event.ephemeral({\n type: \"workspace.failed\",\n schema: {\n message: Schema.String,\n },\n})\n\nexport const Status = Event.ephemeral({\n type: \"workspace.status\",\n schema: ConnectionStatus.fields,\n})\n\nexport const Definitions = Event.inventory(Ready, Failed, Status)\n" | ||
| ], | ||
| "mappings": ";wRAMO,IAAM,EAAmB,EAAO,OAAO,CAC5C,YAAa,EACb,OAAQ,EAAO,SAAS,CAAC,YAAa,aAAc,eAAgB,OAAO,CAAC,CAC9E,CAAC,EAAE,SAAS,CAAE,WAAY,iCAAkC,CAAC,EAGhD,EAAQ,EAAM,UAAU,CACnC,KAAM,kBACN,OAAQ,CACN,KAAM,EAAO,MACf,CACF,CAAC,EAEY,EAAS,EAAM,UAAU,CACpC,KAAM,mBACN,OAAQ,CACN,QAAS,EAAO,MAClB,CACF,CAAC,EAEY,EAAS,EAAM,UAAU,CACpC,KAAM,mBACN,OAAQ,EAAiB,MAC3B,CAAC,EAEY,EAAc,EAAM,UAAU,EAAO,EAAQ,CAAM", | ||
| "debugId": "51A8ACF7E79F8F7664756E2164756E21", | ||
| "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": ";wOAAA,cAAS,WACT,oBACA,mBAAS,UAAU,eAAM,oBAOzB,IAAe,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,IAC/B,EAAO,GAAG,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,OAA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,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": "C982C58DAD932A0264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/config/mcp.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ConfigMCP from \"./mcp.js\"\n\nimport { Schema } from \"effect\"\nimport { Mcp } from \"../mcp.js\"\nimport { optional } from \"../schema.js\"\n\nexport const Timeout = Mcp.TimeoutConfig\nexport type Timeout = Mcp.TimeoutConfig\nexport const Local = Mcp.LocalConfig\nexport type Local = Mcp.LocalConfig\nexport const OAuth = Mcp.OAuthConfig\nexport type OAuth = Mcp.OAuthConfig\nexport const Remote = Mcp.RemoteConfig\nexport type Remote = Mcp.RemoteConfig\nexport const Server = Mcp.ServerConfig\n\nexport class Info extends Schema.Class<Info>(\"Config.MCP\")({\n timeout: Timeout.pipe(optional),\n servers: Schema.Record(Schema.String, Server).pipe(optional),\n}) {}\n" | ||
| ], | ||
| "mappings": ";2TAMO,IAAM,EAAU,EAAI,cAEd,EAAQ,EAAI,YAEZ,EAAQ,EAAI,YAEZ,EAAS,EAAI,aAEb,EAAS,EAAI,aAEnB,MAAM,UAAa,EAAO,MAAY,YAAY,EAAE,CACzD,QAAS,EAAQ,KAAK,CAAQ,EAC9B,QAAS,EAAO,OAAO,EAAO,OAAQ,CAAM,EAAE,KAAK,CAAQ,CAC7D,CAAC,CAAE,CAAC", | ||
| "debugId": "5678C48313E95E8364756E2164756E21", | ||
| "names": [] | ||
| } |
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": ";mhCAAA,cAAS,WAOT,IAAM,EAAU,IAAI,IAAI,CAAC,SAAU,MAAO,OAAQ,UAAW,QAAS,OAAQ,KAAK,CAAC,EAUrE,IAAQ,QACrB,EAAS,SAAS,IAClB,EAAO,GAAG,SAAS,EAAE,SAAU,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,EAAU,MAAO,EAAe,EAAU,EAAM,QAAS,CAAM,EAC/D,EAAU,IAAI,QAAQ,EAAQ,QAAQ,CAAQ,CAAC,EACrD,QAAW,KAAU,EAAM,OAAQ,CACjC,IAAM,EAAQ,EAAO,QAAQ,GAAG,EAChC,GAAI,EAAQ,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,wCAAw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G,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": "B5C1B77A74DE93A564756E2164756E21", | ||
| "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 mismatch = args.mismatch ?? \"ignore\"\n const options = yield* ServiceConfig.options({ checkVersion: mismatch !== \"ignore\" })\n return {\n endpoint: yield* resolveManaged({ ...options, onStart: args.onStart }, mismatch),\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* (options: EnsureOptions, mismatch: NonNullable<Args[\"mismatch\"]>) {\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": ";6eAoBO,IAAM,EAAU,EAAO,GAAG,+BAA+B,EAAE,SAAU,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,EAAW,EAAK,UAAY,SAC5B,EAAU,MAAO,EAAc,QAAQ,CAAE,aAAc,IAAa,QAAS,CAAC,EACpF,MAAO,CACL,SAAU,MAAO,EAAe,IAAK,EAAS,QAAS,EAAK,OAAQ,EAAG,CAAQ,EAC/E,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,CAAC,EAAwB,EAAyC,CACnH,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": "D307D5AF45C3C41664756E2164756E21", | ||
| "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 || input.dangerouslySkipPermissions,\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";mhCAKA,IAAe,IAAQ,QAAQ,EAAS,SAAS,IAAK,CAAC,IACrD,EAAO,IAAI,SAAU,EAAG,CACtB,IAAQ,qBAAsB,MAAO,EAAO,QAAQ,IAAa,wCAAgB,EAC3E,EAAY,QAAQ,KAAK,QAAQ,KAAM,CAAC,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,MAAQ,EAAM,0BAC1C,CAAC,CACH,EACD,CACH", | ||
| "debugId": "3CDA094CF5D81BA864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/filesystem.ts"], | ||
| "sourcesContent": [ | ||
| "export * as FileSystem from \"./filesystem.js\"\n\nimport { Schema } from \"effect\"\nimport { optional } from \"./schema.js\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { NonNegativeInt, PositiveInt, RelativePath } from \"./schema.js\"\n\nconst Changed = ephemeral({\n type: \"filesystem.changed\",\n schema: {\n file: Schema.String,\n event: Schema.Literals([\"add\", \"change\", \"unlink\"]),\n },\n})\nexport const Event = { Changed, Definitions: inventory(Changed) }\n\nexport interface Entry extends Schema.Schema.Type<typeof Entry> {}\nexport const Entry = Schema.Struct({\n path: RelativePath,\n type: Schema.Literals([\"file\", \"directory\"]),\n}).annotate({ identifier: \"FileSystem.Entry\" })\n\nexport interface Submatch extends Schema.Schema.Type<typeof Submatch> {}\nexport const Submatch = Schema.Struct({\n text: Schema.String,\n start: NonNegativeInt,\n end: NonNegativeInt,\n}).annotate({ identifier: \"FileSystem.Submatch\" })\n\nexport interface Match extends Schema.Schema.Type<typeof Match> {}\nexport const Match = Schema.Struct({\n entry: Entry,\n line: PositiveInt,\n offset: NonNegativeInt,\n text: Schema.String,\n submatches: Schema.Array(Submatch),\n}).annotate({ identifier: \"FileSystem.Match\" })\n\nexport class FindInput extends Schema.Class<FindInput>(\"FileSystem.FindInput\")({\n query: Schema.String,\n type: Schema.Literals([\"file\", \"directory\"]).pipe(optional),\n limit: PositiveInt.pipe(optional),\n}) {}\n" | ||
| ], | ||
| "mappings": ";oVAOA,IAAM,EAAU,EAAU,CACxB,KAAM,qBACN,OAAQ,CACN,KAAM,EAAO,OACb,MAAO,EAAO,SAAS,CAAC,MAAO,SAAU,QAAQ,CAAC,CACpD,CACF,CAAC,EACY,EAAQ,CAAE,UAAS,YAAa,EAAU,CAAO,CAAE,EAGnD,EAAQ,EAAO,OAAO,CACjC,KAAM,EACN,KAAM,EAAO,SAAS,CAAC,OAAQ,WAAW,CAAC,CAC7C,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAGjC,EAAW,EAAO,OAAO,CACpC,KAAM,EAAO,OACb,MAAO,EACP,IAAK,CACP,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAGpC,EAAQ,EAAO,OAAO,CACjC,MAAO,EACP,KAAM,EACN,OAAQ,EACR,KAAM,EAAO,OACb,WAAY,EAAO,MAAM,CAAQ,CACnC,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAEvC,MAAM,UAAkB,EAAO,MAAiB,sBAAsB,EAAE,CAC7E,MAAO,EAAO,OACd,KAAM,EAAO,SAAS,CAAC,OAAQ,WAAW,CAAC,EAAE,KAAK,CAAQ,EAC1D,MAAO,EAAY,KAAK,CAAQ,CAClC,CAAC,CAAE,CAAC", | ||
| "debugId": "F188FB6EF5EF875664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/stats.ts"], | ||
| "sourcesContent": [ | ||
| "import { ClientError, OpenCode, type SessionStatsInfo } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { errorMessage } from \"../../util/error\"\n\nconst handler = Effect.fn(\"cli.stats\")(function* (input: Runtime.Input<typeof Commands.commands.stats>) {\n const days = Option.getOrUndefined(input.days)\n const year = Option.getOrUndefined(input.year)\n const project = Option.getOrUndefined(input.project)\n if ([days !== undefined, year !== undefined, input.all].filter(Boolean).length > 1)\n yield* Effect.fail(new Error(\"--days, --year, and --all cannot be combined\"))\n\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) })\n const range = statsRange({ days, year, all: input.all })\n const projectID =\n project === \".\"\n ? yield* request(server.endpoint.url, (signal) =>\n client.location\n .get({ location: { directory: process.cwd() } }, { signal })\n .then((location) => location.project.id),\n )\n : project\n const details = input.models || input.tools || input.cost || input.full\n const stats = yield* request(server.endpoint.url, (signal) =>\n client.session.stats(\n {\n from: range.from,\n to: range.to,\n project: projectID,\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\",\n tools: input.json || input.tools || input.full ? \"detail\" : details ? \"none\" : \"summary\",\n },\n { signal },\n ),\n )\n const output = input.json\n ? JSON.stringify(stats, null, 2)\n : renderStats(stats, {\n label: range.label,\n scope: project === undefined ? \"all projects\" : project === \".\" ? \"current project\" : \"selected project\",\n models: input.models || input.full,\n tools: input.tools || input.full,\n cost: input.cost || input.full,\n limit: input.limit,\n color: process.stdout.isTTY && process.env.NO_COLOR === undefined,\n width: process.stdout.columns ?? 80,\n })\n process.stdout.write(output + EOL)\n})\n\nexport default Runtime.handler(Commands.commands.stats, (input) =>\n handler(input).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n)\n\nexport function request<A>(url: string, run: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: () => run(AbortSignal.timeout(30_000)),\n catch: (cause) =>\n cause instanceof ClientError && cause.reason === \"Transport\"\n ? new Error(`Could not reach server at ${url}`, { cause })\n : cause,\n })\n}\n\ntype RenderOptions = {\n label: string\n scope: string\n models: boolean\n tools: boolean\n cost: boolean\n limit: number\n color: boolean\n width: number\n}\n\nconst colors = terminalPalette()\n\nexport function renderStats(stats: SessionStatsInfo, options: RenderOptions) {\n const totalTokens = tokenTotal(stats.tokens)\n const toolTotals = stats.tools.mode === \"none\" ? undefined : stats.tools.totals\n const terminalTools = toolTotals ? toolTotals.succeeded + toolTotals.failed : 0\n const toolRate = !toolTotals || terminalTools === 0 ? undefined : (toolTotals.succeeded / terminalTools) * 100\n const primary = `1;${colors.primary}`\n const sessionLine = [\n metricCount(stats.sessions, \"session\", options.color),\n stats.subagents > 0 ? metricCount(stats.subagents, \"subagent\", options.color) : undefined,\n ]\n .filter((value) => value !== undefined)\n .join(\" · \")\n const toolSummary = !toolTotals\n ? \"tool stats unavailable\"\n : toolRate === undefined\n ? \"no tool calls\"\n : `${style(formatPercent(toolRate), primary, options.color)} tool success`\n const details = options.models || options.tools || options.cost\n const empty = stats.sessions === 0 && stats.prompts === 0 && stats.steps === 0\n const heading = `${style(\"opencode stats\", primary, options.color)} ${style(`· ${options.label} · ${options.scope}`, \"2\", options.color)}`\n const lines = details\n ? [style(`${options.label} · ${options.scope}`, \"2\", options.color)]\n : empty\n ? [\n heading,\n \"\",\n style(\"no activity in this range\", \"2\", options.color),\n \"\",\n style(\"opencode.ai\", \"2\", options.color),\n ]\n : [\n heading,\n \"\",\n ...renderActivity(stats.activity, stats.range.from, stats.range.to, options.color, options.width),\n \"\",\n sessionLine,\n `${metricCount(stats.prompts, \"prompt\", options.color)} · ${metricCount(stats.steps, \"step\", options.color)} · ${metricCount(totalTokens, \"token\", options.color)}`,\n `${toolSummary} · ${metricCount(stats.activeDays, \"active day\", options.color)} · best streak ${style(stats.streak.toString(), primary, options.color)} day${stats.streak === 1 ? \"\" : \"s\"}`,\n \"\",\n style(\"opencode.ai\", \"2\", options.color),\n ]\n\n if (options.cost) lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderCost(stats))\n if (options.models)\n lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderModels(stats, options.limit, options.width))\n if (options.tools) lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderTools(stats, options.limit, options.width))\n return lines.join(EOL)\n}\n\nfunction statsRange(input: { days?: number; year?: number; all: boolean }) {\n const now = new Date()\n const to = now.getTime() + 1\n if (input.all) return { from: undefined, to, label: \"all time\" }\n if (input.days !== undefined) {\n const from = new Date(now.getFullYear(), now.getMonth(), now.getDate())\n from.setDate(from.getDate() - Math.max(0, input.days - 1))\n return {\n from: from.getTime(),\n to,\n label: input.days === 0 || input.days === 1 ? \"today\" : `last ${input.days} days`,\n }\n }\n const year = input.year ?? now.getFullYear()\n return {\n from: new Date(year, 0, 1).getTime(),\n to: year === now.getFullYear() ? to : new Date(year + 1, 0, 1).getTime(),\n label: year === now.getFullYear() ? `${year} so far` : year.toString(),\n }\n}\n\nfunction renderActivity(\n activity: SessionStatsInfo[\"activity\"],\n from: number,\n to: number,\n color: boolean,\n width: number,\n) {\n const values = new Map(activity.map((day) => [day.date, day.steps]))\n const rangeStart = dateOrdinal(new Date(from))\n const rangeEnd = dateOrdinal(new Date(to - 1))\n const end = new Date(to - 1)\n end.setHours(12, 0, 0, 0)\n end.setDate(end.getDate() + (7 - mondayIndex(end) - 1))\n const start = new Date(from)\n start.setHours(12, 0, 0, 0)\n start.setDate(start.getDate() - mondayIndex(start))\n const maxWeeks = Math.max(1, Math.min(53, width - 4))\n const totalWeeks = Math.floor((dateOrdinal(end) - dateOrdinal(start)) / 7) + 1\n const latest = new Date(end)\n latest.setDate(latest.getDate() - (maxWeeks - 1) * 7)\n if (start < latest) start.setTime(latest.getTime())\n\n const active = [...values.values()].filter((value) => value > 0)\n const levels = [...new Set(active)].sort((a, b) => a - b)\n const weekStarts = Array.from({ length: Math.floor((dateOrdinal(end) - dateOrdinal(start)) / 7) + 1 }, (_, week) => {\n const date = new Date(start)\n date.setDate(date.getDate() + week * 7)\n return date\n })\n const weeks = weekStarts.map((week) =>\n Array.from({ length: 7 }, (_, day) => {\n const date = new Date(week)\n date.setDate(date.getDate() + day)\n const ordinal = dateOrdinal(date)\n if (ordinal < rangeStart || ordinal > rangeEnd) return \" \"\n return activityGlyph(values.get(dateKey(date)) ?? 0, levels, color)\n }),\n )\n const weekdays = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"]\n return [\n style(totalWeeks > maxWeeks ? `activity · last ${maxWeeks} weeks` : \"activity\", `1;${colors.primary}`, color),\n ` ${style(monthLabels(weekStarts), \"2\", color)}`,\n ...weekdays.flatMap((label, day) => [\n `${style(label, \"2\", color)} ${weeks.map((week) => week[day]).join(\"\")}`,\n ...(day === weekdays.length - 1 ? [] : [\"\"]),\n ]),\n \"\",\n ` ${style(\"less\", \"2\", color)} ${[0, 1, 2, 3, 4].map((level) => paintActivity(level, color)).join(\"\")} ${style(\"more\", \"2\", color)}`,\n ]\n}\n\nfunction renderCost(stats: SessionStatsInfo) {\n const input = stats.tokens.input + stats.tokens.cache.read + stats.tokens.cache.write\n const cached = input === 0 ? 0 : (stats.tokens.cache.read / input) * 100\n return [\n \"COST & TOKENS\",\n row(\"cost\", `$${stats.cost.toFixed(2)}`),\n row(\"input\", formatNumber(stats.tokens.input)),\n row(\"output\", formatNumber(stats.tokens.output)),\n row(\"reasoning\", formatNumber(stats.tokens.reasoning)),\n row(\"cache read\", formatNumber(stats.tokens.cache.read)),\n row(\"cache write\", formatNumber(stats.tokens.cache.write)),\n row(\"cached input\", formatPercent(cached)),\n ]\n}\n\nfunction renderModels(stats: SessionStatsInfo, limit: number, width: number) {\n if (stats.models.length === 0) return [\"MODELS\", \" no model usage\"]\n const models = stats.models.slice(0, limit)\n const more = stats.models.length - models.length\n if (width < 68)\n return [\n \"MODELS\",\n ...models.flatMap((item) => [\n truncate(\n `${item.model.providerID}/${item.model.id}${item.model.variant ? `#${item.model.variant}` : \"\"}`,\n width,\n ),\n ` ${formatNumber(tokenTotal(item.tokens))} tokens · ${formatNumber(item.steps)} steps · $${item.cost.toFixed(2)}`,\n ]),\n ...(more > 0 ? [\"\", `+${more.toLocaleString(\"en-US\")} more model${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n return [\n \"MODELS\",\n tableHeader(\"model\", \"tokens\", \"steps\", \"cost\"),\n ...models.map((item) =>\n tableRow(\n `${item.model.providerID}/${item.model.id}${item.model.variant ? `#${item.model.variant}` : \"\"}`,\n formatNumber(tokenTotal(item.tokens)),\n formatNumber(item.steps),\n `$${item.cost.toFixed(2)}`,\n ),\n ),\n ...(more > 0 ? [\"\", `+${more.toLocaleString(\"en-US\")} more model${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n}\n\nfunction renderTools(stats: SessionStatsInfo, limit: number, width: number) {\n if (stats.tools.mode !== \"detail\") return [\"TOOL RELIABILITY\", \" tool details unavailable\"]\n if (stats.tools.usage.length === 0) return [\"TOOL RELIABILITY\", \" no tool calls\"]\n const tools = stats.tools.usage.slice(0, limit)\n const more = stats.tools.usage.length - tools.length\n if (width < 68)\n return [\n \"TOOL RELIABILITY\",\n ...tools.flatMap((tool) => {\n const terminal = tool.succeeded + tool.failed\n return [\n truncate(tool.name, width),\n ` ${formatNumber(tool.calls)} calls · ${terminal === 0 ? \"-\" : formatPercent((tool.failed / terminal) * 100)} error · ${tool.durationP50 === undefined ? \"-\" : formatDuration(tool.durationP50)} p50`,\n ]\n }),\n \"\",\n `${formatNumber(stats.tools.totals.succeeded + stats.tools.totals.failed)} finished calls · ${formatNumber(stats.tools.totals.unfinished)} unfinished`,\n ...(more > 0 ? [`+${more.toLocaleString(\"en-US\")} more tool${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n return [\n \"TOOL RELIABILITY\",\n tableHeader(\"tool\", \"calls\", \"error\", \"p50\"),\n ...tools.map((tool) => {\n const terminal = tool.succeeded + tool.failed\n return tableRow(\n tool.name,\n formatNumber(tool.calls),\n terminal === 0 ? \"-\" : formatPercent((tool.failed / terminal) * 100),\n tool.durationP50 === undefined ? \"-\" : formatDuration(tool.durationP50),\n )\n }),\n \"\",\n `${formatNumber(stats.tools.totals.succeeded + stats.tools.totals.failed)} finished calls · ${formatNumber(stats.tools.totals.unfinished)} unfinished`,\n ...(more > 0 ? [`+${more.toLocaleString(\"en-US\")} more tool${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n}\n\nfunction row(label: string, value: string) {\n return ` ${label.padEnd(20)}${value}`\n}\n\nfunction tableHeader(label: string, second: string, third: string, fourth: string) {\n return tableRow(label, second, third, fourth)\n}\n\nfunction tableRow(label: string, second: string, third: string, fourth: string) {\n return `${truncate(label, 34).padEnd(34)}${second.padStart(10)}${third.padStart(12)}${fourth.padStart(12)}`\n}\n\nfunction truncate(value: string, width: number) {\n return value.length <= width ? value : value.slice(0, width - 1) + \"…\"\n}\n\nfunction tokenTotal(tokens: SessionStatsInfo[\"tokens\"]) {\n return tokens.input + tokens.output + tokens.reasoning + tokens.cache.read + tokens.cache.write\n}\n\nfunction formatNumber(value: number) {\n if (value >= 1_000_000_000) return `${trimDecimal(value / 1_000_000_000)}b`\n if (value >= 1_000_000) return `${trimDecimal(value / 1_000_000)}m`\n if (value >= 1_000) return `${trimDecimal(value / 1_000)}k`\n return Math.round(value).toLocaleString(\"en-US\")\n}\n\nfunction trimDecimal(value: number) {\n return value.toFixed(1).replace(/\\.0$/, \"\")\n}\n\nfunction formatPercent(value: number) {\n return `${value.toFixed(value >= 10 ? 1 : 2)}%`\n}\n\nfunction formatDuration(value: number) {\n if (value < 1_000) return `${Math.round(value)}ms`\n return `${trimDecimal(value / 1_000)}s`\n}\n\nfunction metricCount(value: number, noun: string, color: boolean) {\n return `${style(formatNumber(value), `1;${colors.primary}`, color)} ${noun}${value === 1 ? \"\" : \"s\"}`\n}\n\nfunction style(value: string, code: string, color: boolean) {\n return color ? `\\x1b[${code}m${value}\\x1b[0m` : value\n}\n\nfunction activityGlyph(value: number, levels: number[], color: boolean) {\n if (value === 0) return paintActivity(0, color)\n const index = levels.indexOf(value)\n const level = Math.max(1, Math.ceil(((index + 1) / levels.length) * 4))\n return paintActivity(level, color)\n}\n\nfunction paintActivity(level: number, color: boolean) {\n const glyph = [\"·\", \"░\", \"▒\", \"▓\", \"█\"][level]\n if (!color) return glyph\n if (level === 0) return `\\x1b[2m${glyph}\\x1b[22m`\n return `\\x1b[${colors.activity[level - 1]}m${glyph}\\x1b[39m`\n}\n\nfunction terminalPalette() {\n const background = Number(process.env.COLORFGBG?.split(\";\").at(-1))\n if (Number.isFinite(background) && background >= 7)\n return {\n primary: \"38;2;59;125;216\",\n activity: [\"38;2;153;169;192\", \"38;2;122;155;200\", \"38;2;90;140;208\", \"38;2;59;125;216\"],\n }\n if (Number.isFinite(background))\n return {\n primary: \"38;2;250;178;131\",\n activity: [\"38;2;117;99;87\", \"38;2;161;125;102\", \"38;2;206;152;116\", \"38;2;250;178;131\"],\n }\n return { primary: \"36\", activity: [\"2;36\", \"36\", \"1;36\", \"1;96\"] }\n}\n\nfunction monthLabels(weeks: Date[]) {\n const line: string[] = []\n weeks.reduce((previous, week, index) => {\n const middle = new Date(week)\n middle.setDate(middle.getDate() + 3)\n const month = middle.getMonth()\n if (month === previous) return previous\n Intl.DateTimeFormat(\"en-US\", { month: \"short\" })\n .format(middle)\n .split(\"\")\n .forEach((character, offset) => {\n line[index + offset] = character\n })\n return month\n }, -1)\n return Array.from({ length: Math.max(weeks.length, line.length) }, (_, index) => line[index] ?? \" \")\n .join(\"\")\n .trimEnd()\n}\n\nfunction mondayIndex(date: Date) {\n return (date.getDay() + 6) % 7\n}\n\nfunction dateKey(date: Date) {\n return [\n date.getFullYear(),\n String(date.getMonth() + 1).padStart(2, \"0\"),\n String(date.getDate()).padStart(2, \"0\"),\n ].join(\"-\")\n}\n\nfunction dateOrdinal(date: Date) {\n return Math.floor(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86_400_000)\n}\n" | ||
| ], | ||
| "mappings": ";4lCAGA,cAAS,WAMT,IAAM,EAAU,EAAO,GAAG,WAAW,EAAE,SAAU,CAAC,EAAsD,CACtG,IAAM,EAAO,EAAO,eAAe,EAAM,IAAI,EACvC,EAAO,EAAO,eAAe,EAAM,IAAI,EACvC,EAAU,EAAO,eAAe,EAAM,OAAO,EACnD,GAAI,CAAC,IAAS,OAAW,IAAS,OAAW,EAAM,GAA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AGZ,SAAS,CAAW,CAAC,EAAY,CAC/B,OAAO,KAAK,MAAM,KAAK,IAAI,EAAK,YAAY,EAAG,EAAK,SAAS,EAAG,EAAK,QAAQ,CAAC,EAAI,QAAU", | ||
| "debugId": "5E3E3E3E9DD88A0664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/mcp.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Mcp from \"./mcp.js\"\n\nimport { Schema } from \"effect\"\nimport { optional, PositiveInt } from \"./schema.js\"\nimport { IntegrationID } from \"./integration-id.js\"\n\nexport class TimeoutConfig extends Schema.Class<TimeoutConfig>(\"Mcp.TimeoutConfig\")({\n startup: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to establish and initialize the MCP server.\",\n }),\n catalog: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to wait for MCP discovery requests such as tools/list and prompts/list.\",\n }),\n execution: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to wait for MCP tool and prompt execution.\",\n }),\n}) {}\n\nexport class LocalConfig extends Schema.Class<LocalConfig>(\"Mcp.LocalConfig\")({\n type: Schema.Literal(\"local\"),\n command: Schema.String.pipe(Schema.Array),\n cwd: Schema.String.pipe(optional).annotate({\n description: \"Working directory for the MCP server process. Relative paths resolve from the workspace directory.\",\n }),\n environment: Schema.Record(Schema.String, Schema.String).pipe(optional),\n disabled: Schema.Boolean.pipe(optional),\n codemode: Schema.Boolean.pipe(optional).annotate({\n description: \"Expose this server's tools through Code Mode. Defaults to true.\",\n }),\n timeout: TimeoutConfig.pipe(optional),\n}) {}\n\nexport class OAuthConfig extends Schema.Class<OAuthConfig>(\"Mcp.OAuthConfig\")({\n client_id: Schema.String.pipe(optional),\n client_secret: Schema.String.pipe(optional),\n scope: Schema.String.pipe(optional),\n callback_port: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })).pipe(optional),\n redirect_uri: Schema.String.pipe(optional),\n}) {}\n\nexport class RemoteConfig extends Schema.Class<RemoteConfig>(\"Mcp.RemoteConfig\")({\n type: Schema.Literal(\"remote\"),\n url: Schema.String,\n headers: Schema.Record(Schema.String, Schema.String).pipe(optional),\n oauth: Schema.Union([OAuthConfig, Schema.Literal(false)]).pipe(optional),\n disabled: Schema.Boolean.pipe(optional),\n codemode: Schema.Boolean.pipe(optional).annotate({\n description: \"Expose this server's tools through Code Mode. Defaults to true.\",\n }),\n timeout: TimeoutConfig.pipe(optional),\n}) {}\n\nexport const ServerConfig = Schema.Union([LocalConfig, RemoteConfig]).pipe(Schema.toTaggedUnion(\"type\"))\nexport type ServerConfig = typeof ServerConfig.Type\n\nconst Connected = Schema.Struct({ status: Schema.Literal(\"connected\") }).annotate({\n identifier: \"Mcp.Status.Connected\",\n})\nconst Pending = Schema.Struct({ status: Schema.Literal(\"pending\") }).annotate({\n identifier: \"Mcp.Status.Pending\",\n})\nconst Disabled = Schema.Struct({ status: Schema.Literal(\"disabled\") }).annotate({\n identifier: \"Mcp.Status.Disabled\",\n})\nconst Failed = Schema.Struct({ status: Schema.Literal(\"failed\"), error: Schema.String }).annotate({\n identifier: \"Mcp.Status.Failed\",\n})\nconst NeedsAuth = Schema.Struct({ status: Schema.Literal(\"needs_auth\") }).annotate({\n identifier: \"Mcp.Status.NeedsAuth\",\n})\n\nexport type Status = typeof Status.Type\nexport const Status = Schema.Union([Connected, Pending, Disabled, Failed, NeedsAuth]).pipe(\n Schema.toTaggedUnion(\"status\"),\n)\n\nexport interface Server extends Schema.Schema.Type<typeof Server> {}\nexport const Server = Schema.Struct({\n name: Schema.String,\n status: Status,\n // Set for remote servers registered as OAuth integrations; lets clients act on the right integration\n // without matching by name, which could collide with provider or plugin integrations.\n integrationID: optional(IntegrationID),\n}).annotate({ identifier: \"Mcp.Server\" })\n\nexport interface Resource extends Schema.Schema.Type<typeof Resource> {}\nexport const Resource = Schema.Struct({\n server: Schema.String,\n name: Schema.String,\n uri: Schema.String,\n description: optional(Schema.String),\n mimeType: optional(Schema.String),\n}).annotate({ identifier: \"Mcp.Resource\" })\n\nexport interface ResourceTemplate extends Schema.Schema.Type<typeof ResourceTemplate> {}\nexport const ResourceTemplate = Schema.Struct({\n server: Schema.String,\n name: Schema.String,\n uriTemplate: Schema.String,\n description: optional(Schema.String),\n mimeType: optional(Schema.String),\n}).annotate({ identifier: \"Mcp.ResourceTemplate\" })\n\nexport interface ResourceCatalog extends Schema.Schema.Type<typeof ResourceCatalog> {}\nexport const ResourceCatalog = Schema.Struct({\n resources: Schema.Array(Resource),\n templates: Schema.Array(ResourceTemplate),\n}).annotate({ identifier: \"Mcp.ResourceCatalog\" })\n\nexport const ResourceContentPart = Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"text\"),\n uri: Schema.String,\n text: Schema.String,\n mimeType: optional(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal(\"blob\"),\n uri: Schema.String,\n blob: Schema.String,\n mimeType: optional(Schema.String),\n }),\n]).pipe(Schema.toTaggedUnion(\"type\"), Schema.annotate({ identifier: \"Mcp.ResourceContentPart\" }))\nexport type ResourceContentPart = typeof ResourceContentPart.Type\n\nexport interface ResourceContent extends Schema.Schema.Type<typeof ResourceContent> {}\nexport const ResourceContent = Schema.Struct({\n server: Schema.String,\n uri: Schema.String,\n contents: Schema.Array(ResourceContentPart),\n}).annotate({ identifier: \"Mcp.ResourceContent\" })\n" | ||
| ], | ||
| "mappings": ";sdAMO,MAAM,UAAsB,EAAO,MAAqB,mBAAmB,EAAE,CAClF,QAAS,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC3C,YAAa,0EACf,CAAC,EACD,QAAS,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC3C,YAAa,sGACf,CAAC,EACD,UAAW,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC7C,YAAa,yEACf,CAAC,CACH,CAAC,CAAE,CAAC,CAEG,MAAM,UAAoB,EAAO,MAAmB,iBAAiB,EAAE,CAC5E,KAAM,E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AC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAEpC,EAAsB,EAAO,MAAM,CAC9C,EAAO,OAAO,CACZ,KAAM,EAAO,QAAQ,MAAM,EAC3B,IAAK,EAAO,OACZ,KAAM,EAAO,OACb,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,EACD,EAAO,OAAO,CACZ,KAAM,EAAO,QAAQ,MAAM,EAC3B,IAAK,EAAO,OACZ,KAAM,EAAO,OACb,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,CACH,CAAC,EAAE,KAAK,EAAO,cAAc,MAAM,EAAG,EAAO,SAAS,CAAE,WAAY,yBAA0B,CAAC,CAAC,EAInF,EAAkB,EAAO,OAAO,CAC3C,OAAQ,EAAO,OACf,IAAK,EAAO,OACZ,SAAU,EAAO,MAAM,CAAmB,CAC5C,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC", | ||
| "debugId": "0F0CCB1E511AE94264756E2164756E21", | ||
| "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": ["../schema/src/command.ts", "../schema/src/websearch.ts", "../schema/src/reference.ts"], | ||
| "sourcesContent": [ | ||
| "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 WebSearch from \"./websearch.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.js\"\n\nexport const ID = Schema.String.pipe(Schema.brand(\"WebSearch.ID\"))\nexport type ID = typeof ID.Type\n\nexport interface Provider extends Schema.Schema.Type<typeof Provider> {}\nexport const Provider = Schema.Struct({\n id: ID,\n name: Schema.String,\n}).annotate({ identifier: \"WebSearch.Provider\" })\n\nexport interface Input extends Schema.Schema.Type<typeof Input> {}\nexport const Input = Schema.Struct({\n query: Schema.String,\n providerID: ID.pipe(optional),\n}).annotate({ identifier: \"WebSearch.Input\" })\nexport type ProviderInput = Pick<Input, \"query\">\n\nexport interface Result extends Schema.Schema.Type<typeof Result> {}\nexport const Result = Schema.Struct({\n url: Schema.String,\n title: Schema.String.pipe(optional),\n content: Schema.String.pipe(optional),\n time: Schema.Struct({\n published: Schema.Finite.pipe(optional),\n }),\n}).annotate({ identifier: \"WebSearch.Result\" })\n\nexport class Response extends Schema.Class<Response>(\"WebSearch.Response\")({\n providerID: ID,\n results: Schema.Array(Result),\n}) {}\n\nconst Updated = ephemeral({\n type: \"websearch.updated\",\n schema: {},\n})\nexport const Event = { Updated, Definitions: inventory(Updated) }\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": ";6XAQA,IAAM,EAAU,EAAU,CAAE,KAAM,kBAAmB,OAAQ,CAAC,CAAE,CAAC,EAGpD,EAAO,EAAO,OAAO,CAChC,KAAM,EAAO,OACb,SAAU,EAAO,OACjB,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,MAAO,EAAM,GAAG,KAAK,CAAQ,EAC7B,MAAO,EAAM,IAAI,KAAK,CAAQ,EAC9B,QAAS,EAAO,QAAQ,KAAK,CAAQ,CACvC,CAAC,EAAE,SAAS,CAAE,WAAY,cAAe,CAAC,EAE7B,EAAQ,CACnB,UACA,YAAa,EAAU,CAAO,CAChC,8GCjBO,IAAM,EAAK,EAAO,OAAO,KAAK,EAAO,MAAM,cAAc,CAAC,EAIpD,EAAW,EAAO,OAAO,CACpC,GAAI,EACJ,KAAM,EAAO,MACf,CAAC,EAAE,SAAS,CAAE,WAAY,oBAAqB,CAAC,EAGnC,EAAQ,EAAO,OAAO,CACjC,MAAO,EAAO,OACd,WAAY,EAAG,KAAK,CAAQ,CAC9B,CAAC,EAAE,SAAS,CAAE,WAAY,iBAAkB,CAAC,EAIhC,EAAS,EAAO,OAAO,CAClC,IAAK,EAAO,OACZ,MAAO,EAAO,OAAO,KAAK,CAAQ,EAClC,QAAS,EAAO,OAAO,KAAK,CAAQ,EACpC,KAAM,EAAO,OAAO,CAClB,UAAW,EAAO,OAAO,KAAK,CAAQ,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