🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@opencode-ai/cli-linux-x64-musl

Package Overview
Dependencies
Maintainers
2
Versions
2705
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opencode-ai/cli-linux-x64-musl - npm Package Compare versions

Comparing version
0.0.0-next-15836
to
0.0.0-next-15837
+13
bin/chunk-0pqggxhx.js.map
{
"version": 3,
"sources": ["../simulation/src/backend/network.ts", "../simulation/src/backend/openai.ts", "../simulation/src/backend/simulated-provider.ts", "../simulation/src/backend/index.ts"],
"sourcesContent": [
"import { Clock, Effect, Layer, Ref } from \"effect\"\nimport { HttpClient, HttpClientResponse, type HttpMethod } from \"effect/unstable/http\"\nimport { HttpClientError, TransportError } from \"effect/unstable/http/HttpClientError\"\nimport type { HttpClientRequest } from \"effect/unstable/http\"\nimport { SimulationProtocol } from \"../protocol\"\n\n/**\n * Simulated network.\n *\n * Replaces the `HttpClient.HttpClient` platform node in simulation mode. All\n * outbound HTTP resolves against an in-memory route table; unknown\n * destinations fail loudly with a transport error so no simulation run can\n * silently reach the real network. The scripted LLM is one registered route,\n * not a separate mechanism.\n *\n * Each acquired run owns its routes and request log.\n */\n\nexport interface Route {\n /** Return a response effect to claim the request, undefined to pass. */\n readonly match: (\n request: HttpClientRequest.HttpClientRequest,\n url: URL,\n ) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError> | undefined\n}\n\nexport type LogEntry = SimulationProtocol.Backend.NetworkLogEntry\n\nconst LOG_LIMIT = 1000\n\n/** Static JSON route: exact method + origin/path match answered with a fixed body. */\nexport function json(method: HttpMethod.HttpMethod, url: string, body: unknown): Route {\n return {\n match: (request, requestUrl) => {\n if (request.method !== method) return undefined\n if (requestUrl.origin + requestUrl.pathname !== url) return undefined\n return Effect.sync(() =>\n HttpClientResponse.fromWeb(\n request,\n new Response(JSON.stringify(body), { status: 200, headers: { \"content-type\": \"application/json\" } }),\n ),\n )\n },\n }\n}\n\nexport interface Run {\n readonly client: HttpClient.HttpClient\n readonly log: () => Effect.Effect<readonly LogEntry[]>\n}\n\nexport const make = Effect.fn(\"SimulationNetwork.make\")(function* (routes: readonly Route[] = []) {\n const log = yield* Ref.make<readonly LogEntry[]>([])\n const client = HttpClient.make((request, url) =>\n Effect.gen(function* () {\n let matched: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError> | undefined\n for (const route of routes) {\n matched = route.match(request, url)\n if (matched) break\n }\n const entry = {\n time: yield* Clock.currentTimeMillis,\n method: request.method,\n url: url.toString(),\n matched: matched !== undefined,\n }\n yield* Ref.update(log, (entries) => [...entries, entry].slice(-LOG_LIMIT))\n if (matched) return yield* matched\n return yield* Effect.fail(\n new HttpClientError({\n reason: new TransportError({\n request,\n description: `Simulation denied unregistered network destination: ${request.method} ${url}`,\n }),\n }),\n )\n }),\n )\n return { client, log: () => Ref.get(log) } satisfies Run\n})\n\nexport const layer = (routes: readonly Route[] = []) =>\n Layer.effect(HttpClient.HttpClient, make(routes).pipe(Effect.map((run) => run.client)))\n\nexport * as SimulationNetwork from \"./network\"\n",
"import { Effect, Schema, Stream } from \"effect\"\nimport { HttpClientResponse } from \"effect/unstable/http\"\nimport { HttpClientError, TransportError } from \"effect/unstable/http/HttpClientError\"\nimport { OpenAIChatEvent, DEFAULT_BASE_URL, PATH } from \"@opencode-ai/ai/protocols/openai-chat\"\nimport { SimulationNetwork } from \"./network\"\nimport { SimulatedProvider } from \"./simulated-provider\"\n\n/**\n * Driver-answered OpenAI endpoint for the simulated network.\n *\n * Claims `POST {DEFAULT_BASE_URL}{PATH}` (the real openai-chat route\n * endpoint), invokes the simulated provider, and streams the driver's events back as\n * an OpenAI Chat SSE response terminated by `[DONE]`. Everything downstream\n * of the response bytes is the real pipeline: SSE framing, the OpenAIChat\n * event schema, the protocol state machine, and Lifecycle grammar.\n */\n\nconst encodeChunk = Schema.encodeUnknownSync(OpenAIChatEvent)\n\nconst encoder = new TextEncoder()\nconst decodeBody = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Json))\n\n// The simulated model id is echoed back only in non-schema fields; the\n// protocol event schema ignores unknown fields, so id/object/model are\n// decorative wire realism.\ntype ProviderItem = Exclude<SimulatedProvider.ProviderResponseEvent, { readonly type: \"finish\" }>\ntype FinishReason = Extract<SimulatedProvider.ProviderResponseEvent, { readonly type: \"finish\" }>[\"reason\"]\n\nfunction chunkOf(item: ProviderItem): OpenAIChatEvent | unknown {\n if (item.type === \"textDelta\") return { choices: [{ delta: { content: item.text } }] }\n if (item.type === \"reasoningDelta\") return { choices: [{ delta: { reasoning_content: item.text } }] }\n if (item.type === \"toolCall\")\n return {\n choices: [\n {\n delta: {\n tool_calls: [\n {\n index: item.index,\n id: item.id,\n function: { name: item.name, arguments: JSON.stringify(item.input) },\n },\n ],\n },\n },\n ],\n }\n return item.chunk\n}\n\nconst finishReasonWire: Record<FinishReason, string> = {\n stop: \"stop\",\n \"tool-calls\": \"tool_calls\",\n length: \"length\",\n \"content-filter\": \"content_filter\",\n}\n\nfunction frame(payload: unknown): Uint8Array {\n return encoder.encode(`data: ${JSON.stringify(payload)}\\n\\n`)\n}\n\nfunction sseBody(\n events: Stream.Stream<SimulatedProvider.ProviderResponseEvent, SimulatedProvider.ProviderDisconnectedError>,\n): Stream.Stream<Uint8Array, SimulatedProvider.ProviderDisconnectedError> {\n return events.pipe(\n Stream.map((event) => {\n if (event.type === \"finish\")\n return frame(encodeChunk({ choices: [{ delta: {}, finish_reason: finishReasonWire[event.reason] }] }))\n if (event.type === \"raw\") return frame(event.chunk)\n return frame(encodeChunk(chunkOf(event)))\n }),\n Stream.concat(Stream.make(encoder.encode(\"data: [DONE]\\n\\n\"))),\n )\n}\n\nexport const route = (provider: SimulatedProvider.Interface): SimulationNetwork.Route => ({\n match: (request, url) => {\n if (request.method !== \"POST\") return undefined\n if (url.origin + url.pathname !== DEFAULT_BASE_URL + PATH) return undefined\n return Effect.gen(function* () {\n const body =\n request.body._tag === \"Uint8Array\"\n ? yield* decodeBody(new TextDecoder().decode(request.body.body)).pipe(\n Effect.mapError(\n (cause) =>\n new HttpClientError({\n reason: new TransportError({\n request,\n cause,\n description: \"Simulation received an invalid OpenAI request body\",\n }),\n }),\n ),\n )\n : {}\n return HttpClientResponse.fromWeb(\n request,\n new Response(Stream.toReadableStream(sseBody(provider.stream({ url: url.toString(), body }))), {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n }),\n )\n })\n },\n})\n\nexport * as SimulationOpenAI from \"./openai\"\n",
"import { InstallationVersion } from \"@opencode-ai/core/installation/version\"\nimport { Cause, Context, Effect, Fiber, FiberSet, Layer, PubSub, Queue, Ref, Schema, Semaphore, Stream } from \"effect\"\nimport { SimulationControlServer } from \"../control-server\"\nimport { SimulationProtocol } from \"../protocol\"\n\nexport interface ProviderRequest {\n readonly url: string\n readonly body: unknown\n}\n\nexport type ProviderResponseEvent =\n | SimulationProtocol.Backend.Item\n | { readonly type: \"finish\"; readonly reason: SimulationProtocol.Backend.FinishReason }\n\nexport class ProviderDisconnectedError extends Schema.TaggedErrorClass<ProviderDisconnectedError>()(\n \"SimulatedProvider.ProviderDisconnectedError\",\n { message: Schema.String },\n) {}\n\nexport interface Interface {\n readonly stream: (request: ProviderRequest) => Stream.Stream<ProviderResponseEvent, ProviderDisconnectedError>\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/simulation/SimulatedProvider\") {}\n\ninterface ProviderInvocation extends ProviderRequest {\n readonly id: string\n}\n\ninterface PendingInvocation extends ProviderInvocation {\n readonly responses: Queue.Queue<ProviderResponseEvent, ProviderDisconnectedError | Cause.Done>\n}\n\ninterface State {\n readonly counter: number\n readonly pending: ReadonlyMap<string, PendingInvocation>\n}\n\ninterface Driver {\n readonly requests: Stream.Stream<ProviderInvocation>\n readonly push: (\n id: string,\n items: readonly SimulationProtocol.Backend.Item[],\n ) => Effect.Effect<void, InvocationNotFoundError>\n readonly finish: (\n id: string,\n reason: SimulationProtocol.Backend.FinishReason,\n ) => Effect.Effect<void, InvocationNotFoundError>\n readonly disconnect: (id: string) => Effect.Effect<void, InvocationNotFoundError>\n readonly pending: () => Effect.Effect<readonly ProviderInvocation[]>\n}\n\nclass InvocationNotFoundError extends Schema.TaggedErrorClass<InvocationNotFoundError>()(\n \"SimulatedProvider.InvocationNotFoundError\",\n { id: Schema.String, message: Schema.String },\n) {}\n\nclass ControllerDisconnectedError extends Schema.TaggedErrorClass<ControllerDisconnectedError>()(\n \"SimulatedProvider.ControllerDisconnectedError\",\n { message: Schema.String },\n) {}\n\ntype ControlSocket = SimulationControlServer.Socket\n\nexport const layerDrive = (options: { readonly endpoint: string }) =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const state = yield* Ref.make<State>({ counter: 0, pending: new Map() })\n const opened = yield* PubSub.unbounded<ProviderInvocation>()\n const lock = yield* Semaphore.make(1)\n\n const close = (invocation: PendingInvocation) =>\n Effect.gen(function* () {\n yield* Queue.shutdown(invocation.responses)\n yield* lock.withPermit(\n Ref.update(state, (current) =>\n current.pending.get(invocation.id) === invocation ? remove(current, invocation.id) : current,\n ),\n )\n })\n\n yield* Effect.addFinalizer(() =>\n Effect.gen(function* () {\n const current = yield* Ref.get(state)\n yield* Effect.forEach(current.pending.values(), (invocation) => Queue.shutdown(invocation.responses), {\n discard: true,\n })\n yield* PubSub.shutdown(opened)\n }),\n )\n\n const open = (request: ProviderRequest) =>\n lock.withPermit(\n Effect.gen(function* () {\n const current = yield* Ref.get(state)\n const id = `inv_${current.counter + 1}`\n const responses = yield* Queue.bounded<ProviderResponseEvent, ProviderDisconnectedError | Cause.Done>(256)\n const invocation: PendingInvocation = { id, ...request, responses }\n yield* Ref.set(state, {\n counter: current.counter + 1,\n pending: new Map(current.pending).set(id, invocation),\n })\n yield* PubSub.publish(opened, { id, ...request })\n return invocation\n }),\n )\n\n const requireInvocation = (id: string) =>\n Effect.gen(function* () {\n const current = yield* Ref.get(state)\n const invocation = current.pending.get(id)\n if (invocation) return invocation\n return yield* Effect.fail(\n new InvocationNotFoundError({\n id,\n message: `Simulated provider invocation not found or already finished: ${id}`,\n }),\n )\n })\n\n const remove = (current: State, id: string) => {\n const pending = new Map(current.pending)\n pending.delete(id)\n return { ...current, pending }\n }\n\n const driver: Driver = {\n requests: Stream.unwrap(\n lock.withPermit(\n Effect.gen(function* () {\n const subscription = yield* PubSub.subscribe(opened)\n const current = yield* Ref.get(state)\n const pending = Array.from(current.pending.values(), ({ id, url, body }) => ({ id, url, body }))\n return Stream.concat(Stream.fromIterable(pending), Stream.fromEffectRepeat(PubSub.take(subscription)))\n }),\n ),\n ),\n push: (id, items) =>\n Effect.gen(function* () {\n const invocation = yield* lock.withPermit(requireInvocation(id))\n yield* Queue.offerAll(invocation.responses, items)\n }),\n finish: (id, reason) =>\n Effect.gen(function* () {\n const invocation = yield* lock.withPermit(\n Effect.gen(function* () {\n const invocation = yield* requireInvocation(id)\n const current = yield* Ref.get(state)\n yield* Ref.set(state, remove(current, id))\n return invocation\n }),\n )\n yield* Queue.offer(invocation.responses, { type: \"finish\", reason })\n yield* Queue.end(invocation.responses)\n }),\n disconnect: (id) =>\n Effect.gen(function* () {\n const invocation = yield* lock.withPermit(\n Effect.gen(function* () {\n const invocation = yield* requireInvocation(id)\n const current = yield* Ref.get(state)\n yield* Ref.set(state, remove(current, id))\n return invocation\n }),\n )\n yield* Queue.fail(\n invocation.responses,\n new ProviderDisconnectedError({ message: \"Simulated model provider disconnected\" }),\n )\n }),\n pending: () =>\n lock.withPermit(\n Ref.get(state).pipe(\n Effect.map((current) => Array.from(current.pending.values(), ({ id, url, body }) => ({ id, url, body }))),\n ),\n ),\n }\n\n const fibers = yield* FiberSet.make<void, unknown>()\n const activeController = yield* Ref.make<Fiber.Fiber<void> | undefined>(undefined)\n const controllerLock = yield* Semaphore.make(1)\n yield* SimulationControlServer.start({\n endpoint: options.endpoint,\n label: \"opencode drive backend websocket\",\n data: () => ({}),\n decode: SimulationProtocol.Backend.decodeRequestEffect,\n handle: (socket, request) => handle(driver, fibers, activeController, controllerLock, socket, request),\n close: (socket) => releaseController(activeController, controllerLock, socket),\n })\n yield* Effect.sync(() => process.stderr.write(`opencode drive backend websocket: ${options.endpoint}\\n`))\n\n return Service.of({\n stream: (request) =>\n Stream.unwrap(\n Effect.acquireRelease(open(request), close).pipe(\n Effect.map((invocation) =>\n Stream.fromQueue(invocation.responses).pipe(Stream.takeUntil((event) => event.type === \"finish\")),\n ),\n ),\n ),\n })\n }),\n )\n\nfunction handle(\n driver: Driver,\n fibers: FiberSet.FiberSet<void, unknown>,\n activeController: Ref.Ref<Fiber.Fiber<void> | undefined>,\n controllerLock: Semaphore.Semaphore,\n socket: ControlSocket,\n request: SimulationProtocol.Backend.Request,\n) {\n switch (request.method) {\n case \"simulation.handshake\":\n return SimulationProtocol.Handshake.dispatch(\n {\n role: \"backend\",\n server: { name: \"opencode\", version: InstallationVersion },\n capabilities: SimulationProtocol.Backend.Capabilities,\n },\n request.params,\n )\n case \"llm.attach\":\n return controllerLock.withPermit(\n Effect.gen(function* () {\n if (socket.data.closed)\n return yield* Effect.fail(\n new ControllerDisconnectedError({ message: \"Drive controller disconnected before attachment\" }),\n )\n const previous = yield* Ref.get(activeController)\n if (previous) yield* Fiber.interrupt(previous)\n const attachment = yield* FiberSet.run(\n fibers,\n driver.requests.pipe(\n Stream.runForEach((invocation) =>\n Effect.sync(() => {\n socket.send(JSON.stringify({ jsonrpc: \"2.0\", method: \"llm.request\", params: invocation }))\n }),\n ),\n ),\n )\n if (socket.data.closed) {\n yield* Fiber.interrupt(attachment)\n return yield* Effect.fail(\n new ControllerDisconnectedError({ message: \"Drive controller disconnected during attachment\" }),\n )\n }\n socket.data.attachment = attachment\n yield* Ref.set(activeController, attachment)\n return { attached: true }\n }),\n )\n case \"llm.chunk\":\n return driver.push(request.params.id, request.params.items).pipe(Effect.as({ ok: true }))\n case \"llm.finish\":\n return driver.finish(request.params.id, request.params.reason).pipe(Effect.as({ ok: true }))\n case \"llm.disconnect\":\n return driver.disconnect(request.params.id).pipe(Effect.as({ ok: true }))\n case \"llm.pending\":\n return driver.pending().pipe(Effect.map((invocations) => ({ invocations })))\n }\n}\n\nfunction releaseController(\n activeController: Ref.Ref<Fiber.Fiber<void> | undefined>,\n controllerLock: Semaphore.Semaphore,\n socket: ControlSocket,\n) {\n return controllerLock.withPermit(\n Effect.gen(function* () {\n const attachment = socket.data.attachment\n if (!attachment) return\n yield* Fiber.interrupt(attachment)\n yield* Ref.update(activeController, (active) => (active === attachment ? undefined : active))\n }),\n )\n}\n\nexport * as SimulatedProvider from \"./simulated-provider\"\n",
"import { LayerNode } from \"@opencode-ai/core/effect/layer-node\"\nimport { httpClient } from \"@opencode-ai/core/effect/app-node-platform\"\nimport { Config, Effect, Layer } from \"effect\"\nimport { HttpClient } from \"effect/unstable/http\"\nimport { DriveManifest } from \"../manifest\"\nimport { SimulationNetwork } from \"./network\"\nimport { SimulationOpenAI } from \"./openai\"\nimport { SimulatedProvider } from \"./simulated-provider\"\n\n/**\n * Layer replacements applied when the server is built in simulation mode.\n *\n * The server merges these into the app node build when `OPENCODE_SIMULATE`\n * is enabled, via a dynamic import so this module is never loaded eagerly.\n *\n * - Network: all outbound HTTP resolves against the simulated route table;\n * unknown destinations are denied. The driver-answered OpenAI endpoint is\n * registered here as the first route.\n *\n */\n\nexport const simulationReplacements = Effect.fn(\"Simulation.replacements\")(function* () {\n // ModelsDev dies when its catalog fetch fails, so simulation answers it with\n // an empty catalog; providers come from seeded config instead.\n const models = SimulationNetwork.json(\"GET\", \"https://models.dev/api.json\", {})\n const drive = yield* Config.string(\"OPENCODE_DRIVE\").pipe(Config.withDefault(undefined))\n if (!drive) return [[httpClient, SimulationNetwork.layer([models])]] satisfies LayerNode.Replacements\n\n const manifest = yield* DriveManifest.resolve()\n const networkLayer = Layer.effect(\n HttpClient.HttpClient,\n Effect.gen(function* () {\n const provider = yield* SimulatedProvider.Service\n const network = yield* SimulationNetwork.make([SimulationOpenAI.route(provider), models])\n return network.client\n }),\n ).pipe(\n Layer.provide(\n SimulatedProvider.layerDrive({\n endpoint: manifest.endpoints.backend,\n }),\n ),\n )\n return [[httpClient, networkLayer]] satisfies LayerNode.Replacements\n})\n\nexport * as Simulation from \"./index\"\n"
],
"mappings": ";s4BA4BA,SAAM,QAAY,UAGX,cAAS,OAAI,MAAC,OAA+B,OAAa,OAAsB,MACrF,WAAO,MACL,WAAO,MAAC,EAAS,IAAe,CAC9B,GAAI,EAAQ,SAAW,EAAQ,OAC/B,GAAI,EAAW,OAAS,EAAW,WAAa,EAAK,OACrD,OAAO,EAAO,KAAK,IACjB,EAAmB,QACjB,EACA,IAAI,SAAS,KAAK,UAAU,CAAI,EAAG,CAAE,OAAQ,IAAK,QAAS,CAAE,eAAgB,kBAAmB,CAAE,CAAC,CACrG,CACF,EAEJ,EAQK,IAAM,EAAO,EAAO,GAAG,wBAAwB,EAAE,SAAU,CAAC,EAA2B,CAAC,EAAG,CAChG,IAAM,EAAM,MAAO,EAAI,KAA0B,CAAC,CAAC,EA0BnD,MAAO,CAAE,OAzBM,EAAW,KAAK,CAAC,EAAS,IACvC,EAAO,IAAI,SAAU,EAAG,CACtB,IAAI,EACJ,QAAW,KAAS,EAElB,GADA,EAAU,EAAM,MAAM,EAAS,CAAG,EAC9B,EAAS,MAEf,IAAM,EAAQ,CACZ,KAAM,MAAO,EAAM,kBACnB,OAAQ,EAAQ,OAChB,IAAK,EAAI,SAAS,EAClB,QAAS,IAAY,MACvB,EAEA,GADA,MAAO,EAAI,OAAO,EAAK,CAAC,IAAY,CAAC,GAAG,EAAS,CAAK,EAAE,MAAM,CAAC,EAAS,CAAC,EACrE,EAAS,OAAO,MAAO,EAC3B,OAAO,MAAO,EAAO,KACnB,IAAI,EAAgB,CAClB,OAAQ,IAAI,EAAe,CACzB,UACA,YAAa,uDAAuD,EAAQ,UAAU,GACxF,CAAC,CACH,CAAC,CACH,EACD,CACH,EACiB,IAAK,IAAM,EAAI,IAAI,CAAG,CAAE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I,CAAC,EAAY,OACjB,MAAO,EAAM,UAAU,CAAU,EACjC,MAAO,EAAI,OAAO,EAAkB,CAAC,IAAY,IAAW,EAAa,OAAY,CAAO,EAC7F,CACH,EC/PK,IAAM,GAAyB,EAAO,GAAG,yBAAyB,EAAE,SAAU,EAAG,CAGtF,IAAM,EAAS,EAAkB,KAAK,MAAO,8BAA+B,CAAC,CAAC,EAE9E,GAAI,EADU,MAAO,EAAO,OAAO,gBAAgB,EAAE,KAAK,EAAO,YAAY,MAAS,CAAC,GAC3E,MAAO,CAAC,CAAC,EAAY,EAAkB,MAAM,CAAC,CAAM,CAAC,CAAC,CAAC,EAEnE,IAAM,EAAW,MAAO,EAAc,QAAQ,EACxC,EAAe,EAAM,OACzB,EAAW,WACX,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAW,MAAO,EAAkB,QAE1C,OADgB,MAAO,EAAkB,KAAK,CAAC,EAAiB,MAAM,CAAQ,EAAG,CAAM,CAAC,GACzE,OAChB,CACH,EAAE,KACA,EAAM,QACJ,EAAkB,WAAW,CAC3B,SAAU,EAAS,UAAU,OAC/B,CAAC,CACH,CACF,EACA,MAAO,CAAC,CAAC,EAAY,CAAY,CAAC,EACnC",
"debugId": "FF6DE6618E856DAD64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["../core/src/installation/version.ts"],
"sourcesContent": [
"declare global {\n const OPENCODE_VERSION: string\n const OPENCODE_CHANNEL: string\n}\n\nexport const InstallationVersion = typeof OPENCODE_VERSION === \"string\" ? OPENCODE_VERSION : \"local\"\nexport const InstallationChannel = typeof OPENCODE_CHANNEL === \"string\" ? OPENCODE_CHANNEL : \"local\"\nexport const InstallationLocal = InstallationChannel === \"local\"\n"
],
"mappings": ";AAKO,IAAM,EAA6D,mBAC7D,EAA6D,OAC7D,EAAoB",
"debugId": "B323C13C4ED37E9964756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["../simulation/src/manifest.ts", "../simulation/src/protocol/index.ts", "../simulation/src/control-server.ts"],
"sourcesContent": [
"import { homedir } from \"node:os\"\nimport { isAbsolute, join } from \"node:path\"\nimport { Config, Effect, FileSystem, Schema } from \"effect\"\nimport { PositiveInt } from \"@opencode-ai/core/schema\"\n\nconst InstanceName = Schema.String.check(\n Schema.makeFilter((value) =>\n /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(value) ? undefined : \"a valid Drive instance name\",\n ),\n)\n\nconst Endpoint = Schema.String.check(\n Schema.makeFilter((value) => {\n if (!URL.canParse(value)) return \"a loopback WebSocket endpoint with an explicit port\"\n const endpoint = new URL(value)\n const port = Number(endpoint.port)\n return endpoint.protocol === \"ws:\" && endpoint.hostname === \"127.0.0.1\" && Number.isInteger(port) && port >= 1\n ? undefined\n : \"a loopback WebSocket endpoint with an explicit port\"\n }),\n)\n\nconst AbsolutePath = Schema.String.check(\n Schema.makeFilter((value) => (isAbsolute(value) ? undefined : \"an absolute path\")),\n)\n\nexport const Manifest = Schema.Struct({\n endpoints: Schema.Struct({\n ui: Endpoint,\n backend: Endpoint,\n }),\n viewport: Schema.optionalKey(\n Schema.Struct({\n cols: PositiveInt,\n rows: PositiveInt,\n }),\n ),\n recording: Schema.optionalKey(\n Schema.Struct({\n timeline: AbsolutePath,\n }),\n ),\n})\nexport interface Manifest extends Schema.Schema.Type<typeof Manifest> {}\n\nexport class ResolveError extends Schema.TaggedErrorClass<ResolveError>()(\"DriveManifest.ResolveError\", {\n reason: Schema.Literals([\"config\", \"not-found\", \"read\", \"decode\"]),\n path: Schema.optionalKey(Schema.String),\n message: Schema.String,\n cause: Schema.Defect(),\n}) {}\n\nexport const defaults: Manifest = {\n endpoints: {\n ui: \"ws://127.0.0.1:40900\",\n backend: \"ws://127.0.0.1:40950\",\n },\n}\n\nconst decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Manifest))\n\nconst configError = (cause: unknown) =>\n new ResolveError({\n reason: \"config\",\n message: `Invalid Drive configuration: ${String(cause)}`,\n cause,\n })\n\nexport const resolve = Effect.fn(\"DriveManifest.resolve\")(function* () {\n const name = yield* Config.schema(InstanceName, \"OPENCODE_DRIVE\").pipe(Effect.mapError(configError))\n if (name === \"1\") return defaults\n\n const state = yield* Config.string(\"XDG_STATE_HOME\").pipe(\n Config.withDefault(join(homedir(), \".local\", \"state\")),\n Effect.mapError(configError),\n )\n const directory = yield* Config.string(\"DRIVE_REGISTRY_DIR\").pipe(\n Config.withDefault(join(state, \"opencode-drive\", \"instances\")),\n Effect.mapError(configError),\n )\n const file = join(directory, `${name}.json`)\n const fs = yield* FileSystem.FileSystem\n const contents = yield* fs.readFileString(file).pipe(\n Effect.mapError(\n (cause) =>\n new ResolveError({\n reason: cause.reason._tag === \"NotFound\" ? \"not-found\" : \"read\",\n path: file,\n message:\n cause.reason._tag === \"NotFound\"\n ? `Drive manifest not found: ${file}`\n : `Failed to read Drive manifest: ${file}: ${cause.message}`,\n cause,\n }),\n ),\n )\n return yield* decode(contents).pipe(\n Effect.mapError(\n (cause) =>\n new ResolveError({\n reason: \"decode\",\n path: file,\n message: `Invalid Drive manifest: ${file}: ${cause.message}`,\n cause,\n }),\n ),\n )\n})\n\nexport * as DriveManifest from \"./manifest\"\n",
"import { Effect, Schema } from \"effect\"\n\nconst JsonRpcID = Schema.Union([Schema.String, Schema.Number, Schema.Null])\ntype Json = Schema.Schema.Type<typeof Schema.Json>\n\nexport namespace JsonRpc {\n export const RequestFields = {\n jsonrpc: Schema.Literal(\"2.0\"),\n id: Schema.optional(JsonRpcID),\n }\n export const Request = Schema.Struct({\n ...RequestFields,\n method: Schema.String,\n params: Schema.optional(Schema.Json),\n })\n export interface Request extends Schema.Schema.Type<typeof Request> {}\n\n export const ErrorObject = Schema.Struct({\n code: Schema.Number,\n message: Schema.String,\n data: Schema.optional(Schema.Json),\n })\n\n export const Response = Schema.Struct({\n jsonrpc: Schema.Literal(\"2.0\"),\n id: JsonRpcID,\n result: Schema.optional(Schema.Json),\n error: Schema.optional(ErrorObject),\n })\n export interface Response extends Schema.Schema.Type<typeof Response> {}\n\n export const decodeRequest = Schema.decodeUnknownSync(Request)\n\n export function success(id: Request[\"id\"], result: unknown): Response | undefined {\n if (id === undefined) return undefined\n return { jsonrpc: \"2.0\", id, result: result as Json }\n }\n\n export function failure(id: Request[\"id\"], error: unknown): Response {\n return {\n jsonrpc: \"2.0\",\n id: id ?? null,\n error: {\n code: -32000,\n message: error instanceof Error ? error.message : String(error),\n },\n }\n }\n}\n\nexport namespace Handshake {\n export const ProtocolVersion = Schema.Literal(1)\n export type ProtocolVersion = Schema.Schema.Type<typeof ProtocolVersion>\n\n export const Capability = Schema.NonEmptyString\n export type Capability = Schema.Schema.Type<typeof Capability>\n\n export const EndpointRole = Schema.Literals([\"ui\", \"backend\"])\n export type EndpointRole = Schema.Schema.Type<typeof EndpointRole>\n\n export const Identity = Schema.Struct({\n name: Schema.NonEmptyString,\n version: Schema.NonEmptyString,\n })\n export interface Identity extends Schema.Schema.Type<typeof Identity> {}\n\n export const Params = Schema.Struct({\n client: Identity,\n expectedRole: EndpointRole,\n offeredVersions: Schema.Array(Schema.Int.check(Schema.isGreaterThan(0))).check(\n Schema.isMinLength(1),\n Schema.isUnique(),\n ),\n requiredCapabilities: Schema.Array(Capability).check(Schema.isUnique()),\n optionalCapabilities: Schema.Array(Capability).check(Schema.isUnique()),\n })\n export interface Params extends Schema.Schema.Type<typeof Params> {}\n\n export const Response = Schema.Struct({\n protocolVersion: ProtocolVersion,\n role: EndpointRole,\n server: Identity,\n capabilities: Schema.Array(Capability),\n })\n export interface Response extends Schema.Schema.Type<typeof Response> {}\n\n export const Request = Schema.Struct({\n ...JsonRpc.RequestFields,\n method: Schema.Literal(\"simulation.handshake\"),\n params: Params,\n })\n export interface Request extends Schema.Schema.Type<typeof Request> {}\n\n export interface DispatchAction {\n readonly role: EndpointRole\n readonly server: Identity\n readonly capabilities: ReadonlyArray<Capability>\n }\n\n export class RoleMismatchError extends Schema.TaggedErrorClass<RoleMismatchError>()(\n \"SimulationHandshake.RoleMismatchError\",\n {\n expected: EndpointRole,\n actual: EndpointRole,\n message: Schema.String,\n },\n ) {}\n\n export class UnsupportedProtocolError extends Schema.TaggedErrorClass<UnsupportedProtocolError>()(\n \"SimulationHandshake.UnsupportedProtocolError\",\n {\n offered: Schema.Array(Schema.Number),\n supported: Schema.Array(ProtocolVersion),\n message: Schema.String,\n },\n ) {}\n\n export class MissingCapabilityError extends Schema.TaggedErrorClass<MissingCapabilityError>()(\n \"SimulationHandshake.MissingCapabilityError\",\n {\n missing: Schema.Array(Capability),\n message: Schema.String,\n },\n ) {}\n\n export function dispatch(action: DispatchAction, params: Params) {\n return Effect.gen(function* () {\n if (params.expectedRole !== action.role) {\n return yield* Effect.fail(\n new RoleMismatchError({\n expected: params.expectedRole,\n actual: action.role,\n message: `Expected simulation endpoint role ${params.expectedRole}, received ${action.role}`,\n }),\n )\n }\n if (!params.offeredVersions.includes(1)) {\n return yield* Effect.fail(\n new UnsupportedProtocolError({\n offered: params.offeredVersions,\n supported: [1],\n message: \"No mutually supported simulation protocol version\",\n }),\n )\n }\n const installed = new Set(action.capabilities)\n const missing = params.requiredCapabilities.filter((capability) => !installed.has(capability))\n if (missing.length > 0) {\n return yield* Effect.fail(\n new MissingCapabilityError({\n missing,\n message: `Simulation endpoint is missing required capabilities: ${missing.join(\", \")}`,\n }),\n )\n }\n return {\n protocolVersion: 1,\n role: action.role,\n server: action.server,\n capabilities: Array.from(installed),\n } satisfies Response\n })\n }\n}\n\nexport namespace Frontend {\n export const Capabilities = [\n \"ui.type\",\n \"ui.press\",\n \"ui.enter\",\n \"ui.arrow\",\n \"ui.focus\",\n \"ui.click\",\n \"ui.click.semantic\",\n \"ui.resize\",\n \"ui.matches\",\n \"ui.screenshot\",\n \"ui.state\",\n \"ui.snapshot\",\n \"ui.capture\",\n \"ui.recording.finish\",\n ] as const satisfies ReadonlyArray<Handshake.Capability>\n\n export const KeyModifiers = Schema.Struct({\n ctrl: Schema.optional(Schema.Boolean),\n shift: Schema.optional(Schema.Boolean),\n meta: Schema.optional(Schema.Boolean),\n super: Schema.optional(Schema.Boolean),\n hyper: Schema.optional(Schema.Boolean),\n })\n export interface KeyModifiers extends Schema.Schema.Type<typeof KeyModifiers> {}\n\n export const SemanticClickTarget = Schema.Struct({\n id: Schema.NonEmptyString,\n instance: Schema.optionalKey(Schema.NonEmptyString),\n element: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),\n })\n export interface SemanticClickTarget extends Schema.Schema.Type<typeof SemanticClickTarget> {}\n\n export const Action = Schema.Union([\n Schema.Struct({ type: Schema.Literal(\"ui.type\"), text: Schema.String }),\n Schema.Struct({ type: Schema.Literal(\"ui.press\"), key: Schema.String, modifiers: Schema.optional(KeyModifiers) }),\n Schema.Struct({ type: Schema.Literal(\"ui.enter\") }),\n Schema.Struct({ type: Schema.Literal(\"ui.arrow\"), direction: Schema.Literals([\"up\", \"down\", \"left\", \"right\"]) }),\n Schema.Struct({ type: Schema.Literal(\"ui.focus\"), target: Schema.Number }),\n Schema.Struct({\n type: Schema.Literal(\"ui.click\"),\n target: Schema.Number,\n x: Schema.Number,\n y: Schema.Number,\n semantic: Schema.optionalKey(SemanticClickTarget),\n }),\n Schema.Struct({ type: Schema.Literal(\"ui.resize\"), cols: Schema.Number, rows: Schema.Number }),\n ])\n export type Action = Schema.Schema.Type<typeof Action>\n\n export const Element = Schema.Struct({\n id: Schema.String,\n num: Schema.Number,\n x: Schema.Number,\n y: Schema.Number,\n width: Schema.Number,\n height: Schema.Number,\n focusable: Schema.Boolean,\n focused: Schema.Boolean,\n clickable: Schema.Boolean,\n editor: Schema.Boolean,\n })\n export interface Element extends Schema.Schema.Type<typeof Element> {}\n\n export const State = Schema.Struct({\n focused: Schema.Struct({\n renderable: Schema.optional(Schema.Number),\n editor: Schema.Boolean,\n }),\n elements: Schema.Array(Element),\n })\n export interface State extends Schema.Schema.Type<typeof State> {}\n\n export const SemanticNode = Schema.Struct({\n id: Schema.NonEmptyString,\n instance: Schema.optionalKey(Schema.NonEmptyString),\n parent: Schema.optionalKey(Schema.NonEmptyString),\n role: Schema.NonEmptyString,\n label: Schema.optionalKey(Schema.NonEmptyString),\n element: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),\n focused: Schema.optionalKey(Schema.Boolean),\n selected: Schema.optionalKey(Schema.Boolean),\n expanded: Schema.optionalKey(Schema.Boolean),\n disabled: Schema.optionalKey(Schema.Boolean),\n })\n export interface SemanticNode extends Schema.Schema.Type<typeof SemanticNode> {}\n\n export const SemanticSnapshot = Schema.Struct({\n format: Schema.Literal(\"opencode-ui-snapshot-v1\"),\n nodes: Schema.Array(SemanticNode).check(\n Schema.makeFilter((nodes) => {\n const ids = new Set(nodes.map((node) => node.id))\n if (ids.size !== nodes.length) return \"semantic node ids must be unique\"\n if (new Set(nodes.map((node) => node.element)).size !== nodes.length)\n return \"semantic node elements must be unique\"\n if (nodes.some((node) => node.parent !== undefined && !ids.has(node.parent)))\n return \"semantic node parents must reference another node\"\n const parents = new Map(nodes.map((node) => [node.id, node.parent]))\n for (const node of nodes) {\n const visited = new Set<string>()\n let current: string | undefined = node.id\n while (current !== undefined) {\n if (visited.has(current)) return \"semantic node hierarchy must be acyclic\"\n visited.add(current)\n current = parents.get(current)\n }\n }\n return undefined\n }),\n ),\n })\n export interface SemanticSnapshot extends Schema.Schema.Type<typeof SemanticSnapshot> {}\n\n export const Screenshot = Schema.String\n export type Screenshot = Schema.Schema.Type<typeof Screenshot>\n\n export const Color = Schema.Tuple([Schema.Number, Schema.Number, Schema.Number, Schema.Number])\n export type Color = Schema.Schema.Type<typeof Color>\n\n export const CapturedFrame = Schema.Struct({\n cols: Schema.Number,\n rows: Schema.Number,\n cursor: Schema.Tuple([Schema.Number, Schema.Number]),\n lines: Schema.Array(\n Schema.Struct({\n spans: Schema.Array(\n Schema.Struct({\n text: Schema.String,\n fg: Color,\n bg: Color,\n attributes: Schema.Number,\n width: Schema.Number,\n }),\n ),\n }),\n ),\n })\n export interface CapturedFrame extends Schema.Schema.Type<typeof CapturedFrame> {}\n\n export const RecordingFinish = Schema.String\n export type RecordingFinish = Schema.Schema.Type<typeof RecordingFinish>\n\n export const Matches = Schema.Boolean\n export type Matches = Schema.Schema.Type<typeof Matches>\n\n export const ScreenshotParams = Schema.Struct({ name: Schema.optional(Schema.String) })\n export interface ScreenshotParams extends Schema.Schema.Type<typeof ScreenshotParams> {}\n\n export const TypeParams = Schema.Struct({ text: Schema.String })\n export interface TypeParams extends Schema.Schema.Type<typeof TypeParams> {}\n\n export const MatchesParams = Schema.Struct({ text: Schema.String })\n export interface MatchesParams extends Schema.Schema.Type<typeof MatchesParams> {}\n\n export const PressParams = Schema.Struct({ key: Schema.String, modifiers: Schema.optional(KeyModifiers) })\n export interface PressParams extends Schema.Schema.Type<typeof PressParams> {}\n\n export const ArrowParams = Schema.Struct({ direction: Schema.Literals([\"up\", \"down\", \"left\", \"right\"]) })\n export interface ArrowParams extends Schema.Schema.Type<typeof ArrowParams> {}\n\n export const FocusParams = Schema.Struct({ target: Schema.Number })\n export interface FocusParams extends Schema.Schema.Type<typeof FocusParams> {}\n\n export const ClickParams = Schema.Struct({\n target: Schema.Number,\n x: Schema.Number,\n y: Schema.Number,\n semantic: Schema.optionalKey(SemanticClickTarget),\n })\n export interface ClickParams extends Schema.Schema.Type<typeof ClickParams> {}\n\n export const ResizeParams = Schema.Struct({ cols: Schema.Number, rows: Schema.Number })\n export interface ResizeParams extends Schema.Schema.Type<typeof ResizeParams> {}\n\n export const Request = Schema.Union([\n Handshake.Request,\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.type\"), params: TypeParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.press\"), params: PressParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.arrow\"), params: ArrowParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.focus\"), params: FocusParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.click\"), params: ClickParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.resize\"), params: ResizeParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.matches\"), params: MatchesParams }),\n Schema.Struct({\n ...JsonRpc.RequestFields,\n method: Schema.Literal(\"ui.screenshot\"),\n params: Schema.optional(ScreenshotParams),\n }),\n Schema.Struct({\n ...JsonRpc.RequestFields,\n method: Schema.Literals([\"ui.enter\", \"ui.state\", \"ui.snapshot\", \"ui.recording.finish\"]),\n }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.capture\") }),\n ])\n export type Request = Schema.Schema.Type<typeof Request>\n export const decodeRequest = Schema.decodeUnknownSync(Request)\n export const decodeRequestEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Request))\n}\n\nexport namespace Backend {\n export const Capabilities = [\n \"llm.attach\",\n \"llm.chunk\",\n \"llm.finish\",\n \"llm.disconnect\",\n \"llm.pending\",\n \"llm.request\",\n ] as const satisfies ReadonlyArray<Handshake.Capability>\n\n export const Item = Schema.Union([\n Schema.Struct({ type: Schema.Literal(\"textDelta\"), text: Schema.String }),\n Schema.Struct({ type: Schema.Literal(\"reasoningDelta\"), text: Schema.String }),\n Schema.Struct({\n type: Schema.Literal(\"toolCall\"),\n index: Schema.Number,\n id: Schema.String,\n name: Schema.String,\n input: Schema.Json,\n }),\n Schema.Struct({ type: Schema.Literal(\"raw\"), chunk: Schema.Json }),\n ])\n export type Item = Schema.Schema.Type<typeof Item>\n\n export const FinishReason = Schema.Literals([\"stop\", \"tool-calls\", \"length\", \"content-filter\"])\n export type FinishReason = Schema.Schema.Type<typeof FinishReason>\n\n export const ChunkParams = Schema.Struct({ id: Schema.String, items: Schema.Array(Item) })\n export interface ChunkParams extends Schema.Schema.Type<typeof ChunkParams> {}\n\n export const FinishParams = Schema.Struct({\n id: Schema.String,\n reason: FinishReason.pipe(Schema.withDecodingDefault(Effect.succeed(\"stop\" as const))),\n })\n export interface FinishParams extends Schema.Schema.Type<typeof FinishParams> {}\n\n export const DisconnectParams = Schema.Struct({ id: Schema.String })\n export interface DisconnectParams extends Schema.Schema.Type<typeof DisconnectParams> {}\n\n export const Request = Schema.Union([\n Handshake.Request,\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"llm.chunk\"), params: ChunkParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"llm.finish\"), params: FinishParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"llm.disconnect\"), params: DisconnectParams }),\n Schema.Struct({\n ...JsonRpc.RequestFields,\n method: Schema.Literals([\"llm.attach\", \"llm.pending\"]),\n }),\n ])\n export type Request = Schema.Schema.Type<typeof Request>\n export const decodeRequest = Schema.decodeUnknownSync(Request)\n export const decodeRequestEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Request))\n\n export const ProviderInvocation = Schema.Struct({ id: Schema.String, url: Schema.String, body: Schema.Json })\n export interface ProviderInvocation extends Schema.Schema.Type<typeof ProviderInvocation> {}\n\n export const NetworkLogEntry = Schema.Struct({\n time: Schema.Number,\n method: Schema.String,\n url: Schema.String,\n matched: Schema.Boolean,\n })\n export interface NetworkLogEntry extends Schema.Schema.Type<typeof NetworkLogEntry> {}\n}\n\nexport * as SimulationProtocol from \"./index\"\n",
"import { Effect, Fiber, Queue, Stream } from \"effect\"\nimport { SimulationProtocol } from \"./protocol\"\n\nexport interface Server {\n readonly url: string\n}\n\ninterface Request {\n readonly id?: string | number | null\n}\n\nexport interface SocketData {\n readonly drive?: true\n attachment?: Fiber.Fiber<void>\n closed?: true\n}\n\nexport type Socket = Bun.ServerWebSocket<SocketData>\n\nexport function start<RequestType extends Request, Error, Services>(options: {\n readonly endpoint: string\n readonly label: string\n readonly data: () => SocketData\n readonly decode: (input: string) => Effect.Effect<RequestType, Error>\n readonly handle: (socket: Socket, request: RequestType) => Effect.Effect<unknown, unknown, Services>\n readonly close?: (socket: Socket) => Effect.Effect<void, never, Services>\n}) {\n return Effect.gen(function* () {\n const messages = yield* Queue.bounded<{ readonly socket: Socket; readonly input: string }>(256)\n const closures = yield* Queue.unbounded<Socket>()\n yield* Stream.fromQueue(messages).pipe(\n Stream.runForEach((message) =>\n options.decode(message.input).pipe(\n Effect.flatMap((request) =>\n options.handle(message.socket, request).pipe(\n Effect.matchEffect({\n onFailure: (error) => send(message.socket, SimulationProtocol.JsonRpc.failure(request.id, error)),\n onSuccess: (result) => send(message.socket, SimulationProtocol.JsonRpc.success(request.id, result)),\n }),\n ),\n ),\n Effect.catch((error) => send(message.socket, SimulationProtocol.JsonRpc.failure(undefined, error))),\n ),\n ),\n Effect.forkScoped,\n )\n yield* Stream.fromQueue(closures).pipe(\n Stream.runForEach((socket) => options.close?.(socket) ?? Effect.void),\n Effect.forkScoped,\n )\n const url = yield* Effect.try({ try: () => new URL(options.endpoint), catch: (cause) => cause })\n yield* Effect.acquireRelease(\n Effect.sync(() =>\n Bun.serve<SocketData>({\n hostname: url.hostname,\n port: Number(url.port),\n fetch(request, server) {\n if (server.upgrade(request, { data: options.data() })) return undefined\n return new Response(options.label, { status: 426 })\n },\n websocket: {\n close(socket) {\n socket.data.closed = true\n Queue.offerUnsafe(closures, socket)\n },\n message(socket, message) {\n const input = typeof message === \"string\" ? message : message.toString()\n if (Queue.offerUnsafe(messages, { socket, input })) return\n socket.send(\n JSON.stringify(\n SimulationProtocol.JsonRpc.failure(undefined, new Error(\"Simulation control queue is full\")),\n ),\n )\n },\n },\n }),\n ),\n (server) => Effect.promise(() => server.stop(true)),\n )\n return { url: options.endpoint } satisfies Server\n })\n}\n\nfunction send(socket: Socket, response: SimulationProtocol.JsonRpc.Response | undefined) {\n if (!response) return Effect.void\n return Effect.sync(() => {\n socket.send(JSON.stringify(response))\n })\n}\n\nexport * as SimulationControlServer from \"./control-server\"\n"
],
"mappings": ";8RAAA,uBAAS,iBACT,qBAAS,WAAY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KAAM,EAAQ,KAAK,CAAE,CAAC,EAAG,OACvD,OAAO,IAAI,SAAS,EAAQ,MAAO,CAAE,OAAQ,GAAI,CAAC,GAEpD,UAAW,CACT,KAAK,CAAC,EAAQ,CACZ,EAAO,KAAK,OAAS,GACrB,EAAM,YAAY,EAAU,CAAM,GAEpC,OAAO,CAAC,EAAQ,EAAS,CACvB,IAAM,EAAQ,OAAO,IAAY,SAAW,EAAU,EAAQ,SAAS,EACvE,GAAI,EAAM,YAAY,EAAU,CAAE,SAAQ,OAAM,CAAC,EAAG,OACpD,EAAO,KACL,KAAK,UACH,EAAmB,QAAQ,QAAQ,OAAe,MAAM,kCAAkC,CAAC,CAC7F,CACF,EAEJ,CACF,CAAC,CACH,EACA,CAAC,IAAW,EAAO,QAAQ,IAAM,EAAO,KAAK,EAAI,CAAC,CACpD,EACO,CAAE,IAAK,EAAQ,QAAS,EAChC,EAGH,SAAS,CAAI,CAAC,EAAgB,EAA2D,CACvF,GAAI,CAAC,EAAU,OAAO,EAAO,KAC7B,OAAO,EAAO,KAAK,IAAM,CACvB,EAAO,KAAK,KAAK,UAAU,CAAQ,CAAC,EACrC",
"debugId": "2A0BB6887639795864756E2164756E21",
"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": ["../client/src/effect/service.ts", "src/services/service-config.ts", "src/util/process.ts"],
"sourcesContent": [
"import { ServiceStatus } from \"@opencode-ai/protocol/groups/health\"\nimport { Effect, FileSystem, Option, Schedule, Schema } from \"effect\"\nimport { spawn, type ChildProcess } from \"node:child_process\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\nimport type { DiscoverOptions, Endpoint, EnsureOptions, StopOptions } from \"../service.js\"\n\nexport * from \"../service.js\"\n/** Contents of the local service registration file. */\nexport type Info = import(\"../service.js\").Info\n\n// Find, start, and stop the local opencode background service.\n//\n// The service daemon advertises itself through a registration file in the\n// user's state directory: url, pid, version, and the private password, with\n// 0600 permissions. That file is the complete discovery contract — reading it\n// is all a client needs to connect. The daemon's own configuration (port,\n// persisted password) is CLI-owned and never read here.\n\ntype Contender = {\n readonly child: ChildProcess\n readonly error: () => Error | undefined\n}\n\n// Read-only lookup: registration file plus health check and version gate.\n// Never spawns; escalation to ensure() is the caller's policy.\n/** Discover a healthy, compatible local service without starting one. */\nexport const discover = Effect.fn(\"service.discover\")(function* (options: DiscoverOptions = {}) {\n return (yield* discoverLocal(options))?.endpoint\n})\n\n/** Recognize an authenticated compatible service bound to an expected URL, including while it starts or fails. */\nexport const incumbent = Effect.fn(\"service.incumbent\")(function* (\n options: DiscoverOptions & { readonly url: string },\n) {\n const info = yield* read(options.file)\n const found = info === undefined ? undefined : yield* probe({ ...info, url: options.url })\n if (found === undefined || found.legacy) return undefined\n if (options.version !== undefined && found.version !== options.version) return undefined\n return { endpoint: found.endpoint, state: found.state }\n})\n\nconst discoverLocal = Effect.fnUntraced(function* (options: DiscoverOptions) {\n const found = (yield* registered(options.file)).service\n if (found?.state !== \"ready\") return undefined\n if (options.version !== undefined && found.version !== options.version) return undefined\n return found\n})\n\n// Idempotent ensure-running: reuses a healthy compatible server, replaces a\n// version-mismatched one, and otherwise spawns small contenders until a server\n// becomes discoverable. A contender is never killed merely for slow startup.\n/** Ensure a healthy, compatible local service is running. */\nexport const ensure = Effect.fn(\"service.ensure\")(function* (options: EnsureOptions = {}) {\n const contenders = new Set<Contender>()\n let announced = false\n let lastSpawn = 0\n let spawnDelay = 5_000\n let ownerHeld = false\n const announce = (reason: \"missing\" | \"version-mismatch\", previousVersion?: string) =>\n Effect.sync(() => {\n if (announced) return\n announced = true\n options.onStart?.(reason, previousVersion)\n })\n const spawnContender = Effect.gen(function* () {\n const [command, ...args] = options.command ?? [\"opencode\", \"serve\", \"--service\"]\n if (command === undefined) return yield* Effect.fail(new Error(\"Missing service command\"))\n return yield* Effect.try({\n try: () => {\n const child = spawn(command, args, { detached: true, stdio: \"ignore\" })\n let error: Error | undefined\n child.once(\"error\", (cause) => {\n error = new Error(\"Failed to start server\", { cause })\n })\n child.unref()\n return { child, error: () => error }\n },\n catch: (cause) => new Error(\"Failed to start server\", { cause }),\n })\n })\n const found = yield* Effect.gen(function* () {\n const registration = yield* registered(options.file, true)\n const info = registration.info\n const service = registration.service\n if (service !== undefined) {\n ownerHeld = false\n spawnDelay = 5_000\n const compatible = !service.legacy && (options.version === undefined || service.version === options.version)\n if (compatible && service.state === \"ready\") return Option.some(service)\n if (compatible && service.state === \"failed\")\n return yield* Effect.fail(new Error(\"Background service failed to start\"))\n if (compatible) return Option.none<LocalService>()\n yield* announce(\"version-mismatch\", service.version)\n yield* kill(service, options).pipe(Effect.ignore)\n lastSpawn = 0\n return Option.none<LocalService>()\n } else if (lastSpawn === 0 && info !== undefined) lastSpawn = Date.now()\n\n const failure = [...contenders].map(contenderFailure).find((error): error is Error => error !== undefined)\n if (failure !== undefined) return yield* Effect.fail(failure)\n const finished = [...contenders].filter(contenderFinished)\n if (finished.some((item) => item.child.exitCode === 0)) {\n ownerHeld = true\n spawnDelay = Math.min(spawnDelay * 2, 30_000)\n }\n finished.forEach((item) => contenders.delete(item))\n // Keep one candidate plus one lock probe so a pre-lock stall cannot block recovery.\n if (contenders.size < 2 && Date.now() - lastSpawn >= spawnDelay) {\n yield* announce(\"missing\")\n contenders.add(yield* spawnContender)\n lastSpawn = Date.now()\n }\n return Option.none<LocalService>()\n }).pipe(\n Effect.repeat({\n until: Option.isSome,\n schedule: Schedule.max([Schedule.spaced(\"1 second\"), Schedule.recurs(120)]),\n }),\n )\n if (Option.isNone(found))\n return yield* Effect.fail(new Error(\"Timed out waiting for the background service to start\"))\n return found.value.endpoint\n})\n\nfunction contenderFailure(contender: Contender) {\n const error = contender.error()\n if (error !== undefined) return error\n if (contender.child.exitCode !== null && contender.child.exitCode !== 0)\n return new Error(`Server process exited with code ${contender.child.exitCode}`)\n if (contender.child.signalCode !== null)\n return new Error(`Server process terminated by ${contender.child.signalCode}`)\n return undefined\n}\n\nfunction contenderFinished(contender: Contender) {\n return contender.error() !== undefined || contender.child.exitCode !== null || contender.child.signalCode !== null\n}\n\n/** Stop the registered local service. */\nexport const stop = Effect.fn(\"service.stop\")(function* (options: StopOptions = {}) {\n const existing = yield* find(options)\n if (existing !== undefined) yield* kill(existing, options)\n})\n\nfunction fallback() {\n const state = process.env[\"XDG_STATE_HOME\"] ?? join(homedir(), \".local\", \"state\")\n return join(state, \"opencode\", \"service.json\")\n}\n\n/** Create HTTP authentication headers for a service endpoint. */\nexport function headers(endpoint: Endpoint) {\n if (endpoint.auth === undefined) return undefined\n return { authorization: \"Basic \" + btoa(endpoint.auth.username + \":\" + endpoint.auth.password) }\n}\n\n/** Schema for the local service registration file. */\nexport const Info = Schema.Struct({\n id: Schema.optional(Schema.String),\n version: Schema.optional(Schema.String),\n url: Schema.String,\n pid: Schema.Int.check(Schema.isGreaterThan(0)),\n password: Schema.optional(Schema.String),\n})\n\nconst decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))\nconst decodeHealth = Schema.decodeUnknownOption(ServiceStatus.Health)\nconst decodeLegacyHealth = Schema.decodeUnknownOption(Schema.Struct({ healthy: Schema.Literal(true) }))\n\n// A missing or corrupt file means no valid info; callers treat both\n// the same (the registering server self-evicts, clients rediscover).\nconst read = Effect.fnUntraced(function* (file?: string) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(file ?? fallback()).pipe(Effect.option)\n if (Option.isNone(text)) return undefined\n return yield* decode(text.value).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n})\n\ntype LocalService = {\n readonly info: Info\n readonly endpoint: Endpoint\n readonly version?: string\n readonly state: \"ready\" | \"waiting\" | \"failed\"\n readonly legacy: boolean\n}\n\nconst probe = Effect.fnUntraced(function* (info: Info, allowLegacy = false) {\n const endpoint = {\n url: info.url,\n auth:\n info.password === undefined\n ? undefined\n : { type: \"basic\" as const, username: \"opencode\", password: info.password },\n } satisfies Endpoint\n const response = yield* Effect.tryPromise(() =>\n fetch(new URL(\"/api/health\", info.url), {\n headers: headers(endpoint),\n signal: AbortSignal.timeout(2_000),\n }),\n ).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n if (response === undefined) return undefined\n const body = yield* Effect.tryPromise(() => response.json()).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n const health = decodeHealth(body)\n if (Option.isSome(health)) {\n if (health.value.pid !== info.pid) return undefined\n if (info.version !== undefined && health.value.version !== info.version) return undefined\n return {\n info,\n endpoint,\n version: health.value.version,\n state: response.ok ? \"ready\" : response.status === 500 ? \"failed\" : \"waiting\",\n legacy: false,\n } satisfies LocalService\n }\n if (\n !allowLegacy ||\n Option.isNone(decodeLegacyHealth(body)) ||\n (typeof body === \"object\" && body !== null && (\"version\" in body || \"pid\" in body))\n )\n return undefined\n return { info, endpoint, state: \"ready\", legacy: true } satisfies LocalService\n})\n\nconst registered = Effect.fnUntraced(function* (file?: string, allowLegacy = false) {\n const info = yield* read(file)\n if (info === undefined) return { info: undefined, service: undefined }\n return { info, service: yield* probe(info, allowLegacy) }\n})\n\n// Health-checked lookup without the version gate: lifecycle operations must be\n// able to see (and replace or stop) a server from a different version.\nconst find = Effect.fnUntraced(function* (options: { readonly file?: string }) {\n return (yield* registered(options.file, true)).service\n})\n\n// 50ms cadence bounded at ~5s, shared by stop escalation and each ensure\n// discovery window.\nconst poll = Schedule.max([Schedule.spaced(\"50 millis\"), Schedule.recurs(100)])\n\nconst signal = (pid: number, name: NodeJS.Signals) =>\n Effect.try({ try: () => process.kill(pid, name), catch: (cause) => cause }).pipe(Effect.ignore)\n\nconst stopped = Effect.fnUntraced(function* (pid: number) {\n const running = yield* Effect.try({ try: () => process.kill(pid, 0), catch: () => false }).pipe(\n Effect.orElseSucceed(() => false),\n )\n if (!running) return true\n return yield* Effect.fail(new Error(`Server process ${pid} is still running`))\n})\n\nfunction same(left: Info, right: Info) {\n return left.id === right.id && left.version === right.version && left.url === right.url && left.pid === right.pid\n}\n\nconst kill = Effect.fnUntraced(function* (service: LocalService, options: { readonly file?: string }) {\n const requested = yield* requestStop(service)\n if (requested === \"rejected\") return\n if (requested === \"unsupported\") {\n // A stale registration may point at a reused PID. Authenticate again\n // immediately before the legacy signal fallback.\n const current = yield* find(options)\n if (current === undefined || !same(current.info, service.info)) return\n yield* signal(service.info.pid, \"SIGTERM\")\n }\n const done = yield* stopped(service.info.pid).pipe(Effect.retry(poll), Effect.option)\n if (Option.isSome(done)) return\n\n const latest = yield* find(options)\n if (latest === undefined || !same(latest.info, service.info)) return\n yield* signal(service.info.pid, \"SIGKILL\")\n yield* stopped(service.info.pid).pipe(Effect.retry(poll))\n})\n\nconst decodeStopResponse = Schema.decodeUnknownOption(ServiceStatus.StopResponse)\n\nconst requestStop = Effect.fnUntraced(function* (service: LocalService) {\n if (service.info.id === undefined || service.legacy) return \"unsupported\" as const\n const response = yield* Effect.tryPromise(() =>\n fetch(new URL(\"/api/service/stop\", service.info.url), {\n method: \"POST\",\n headers: { ...headers(service.endpoint), \"content-type\": \"application/json\" },\n body: JSON.stringify({ instanceID: service.info.id }),\n signal: AbortSignal.timeout(2_000),\n }),\n ).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n if (response === undefined || response.status === 404 || response.status === 405) return \"unsupported\" as const\n const body = yield* Effect.tryPromise(() => response.json()).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n const decoded = decodeStopResponse(body)\n if (!response.ok || Option.isNone(decoded) || !decoded.value.accepted) return \"rejected\" as const\n return \"accepted\" as const\n})\n\n/** Effect-based local service lifecycle operations. */\nexport const Service = { discover, incumbent, ensure, stop, headers, Info }\n",
"import { Global } from \"@opencode-ai/core/global\"\nimport { InstallationChannel, InstallationVersion } from \"@opencode-ai/core/installation/version\"\nimport { Hash } from \"@opencode-ai/core/util/hash\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, FileSystem, Option, Schema } from \"effect\"\nimport { randomBytes } from \"crypto\"\nimport path from \"path\"\nimport { selfCommand } from \"../util/process\"\n\n// The CLI's service configuration file, plus the Service.EnsureOptions binding that\n// points the client package's service operations at this CLI: which\n// registration file (by channel), which version, and how to spawn opencode.\n\nexport const Info = Schema.Struct({\n hostname: Schema.optional(Schema.String),\n port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),\n password: Schema.optional(Schema.String),\n})\nexport type Info = typeof Info.Type\n\nconst keys = [\"hostname\", \"port\", \"password\"] as const\ntype Key = (typeof keys)[number]\n\nconst decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))\nconst decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info))\n\nexport function filename(channel = InstallationChannel) {\n if (channel === \"latest\") return \"service.json\"\n if (channel === \"local\") return \"service-local.json\"\n return `service-${Hash.fast(channel)}.json`\n}\n\nexport function defaultPort(channel = InstallationChannel) {\n if (channel === \"latest\") 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 versionBelongsToChannel(\n version: string | undefined,\n channel = InstallationChannel,\n installedVersion = InstallationVersion,\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 = InstallationChannel,\n installedVersion = InstallationVersion,\n) {\n if (channel === \"latest\" || channel === \"local\") return\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\nfunction configKey(key: string): Key {\n if (key === \"hostname\" || key === \"port\" || key === \"password\") return key\n throw new Error(`Unknown service config key: ${key}`)\n}\n\nconst paths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem\n const global = yield* Global.Service\n const name = filename()\n const file = path.join(global.state, name)\n return {\n fs,\n file,\n legacyFile: path.join(global.state, \"service.json\"),\n configFile: path.join(global.config, name),\n }\n})\n\nexport const options = Effect.fnUntraced(function* () {\n const { file, legacyFile } = yield* paths\n yield* migrateRegistration(legacyFile, file)\n return {\n file,\n version: InstallationVersion,\n command: [...selfCommand(), \"serve\", \"--service\"],\n }\n})\n\nexport const read = Effect.fn(\"cli.service-config.read\")(function* () {\n const { fs, configFile } = yield* paths\n return yield* fs.readFileString(configFile).pipe(\n Effect.flatMap(decodeInfo),\n Effect.catch(() => Effect.succeed({} as Info)),\n )\n})\n\nconst write = Effect.fn(\"cli.service-config.write\")(function* (value: Info) {\n const { fs, configFile } = yield* paths\n const temp = configFile + \".tmp\"\n yield* fs.makeDirectory(path.dirname(configFile), { recursive: true })\n yield* fs.writeFileString(temp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n yield* fs.rename(temp, configFile)\n})\n\nexport const password = Effect.fn(\"cli.service-config.password\")(function* (value?: string) {\n const existing = yield* read()\n if (value === undefined && existing.password) return existing.password\n const next = value ?? randomBytes(32).toString(\"base64url\")\n\n // Keep one private credential across server restarts so discovered clients\n // can reconnect without exposing a password flag or environment variable.\n yield* write({ ...existing, password: next })\n return next\n})\n\nexport const get = Effect.fn(\"cli.service-config.get\")(function* (key?: string) {\n if (key === undefined) {\n const { password: _password, ...safe } = yield* read()\n return JSON.stringify(safe, null, 2)\n }\n switch (configKey(key)) {\n case \"hostname\": {\n return (yield* read()).hostname ?? \"\"\n }\n case \"port\": {\n const port = (yield* read()).port\n return port === undefined ? \"\" : String(port)\n }\n case \"password\": {\n return yield* password()\n }\n }\n throw new Error(`Unknown service config key: ${key}`)\n})\n\nexport const set = Effect.fn(\"cli.service-config.set\")(function* (key: string, value: string) {\n switch (configKey(key)) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), hostname: value })\n return\n }\n case \"port\": {\n const port = Number(value)\n if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error(\"Port must be between 1 and 65535\")\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), port })\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n yield* password(value)\n return\n }\n }\n})\n\nexport const unset = Effect.fn(\"cli.service-config.unset\")(function* (key: string) {\n switch (configKey(key)) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n const { hostname: _hostname, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"port\": {\n yield* Service.stop(yield* options())\n const { port: _port, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n const { password: _password, ...next } = yield* read()\n yield* write(next)\n return\n }\n }\n})\n\nexport * as ServiceConfig from \"./service-config\"\n",
"import path from \"node:path\"\n\nexport function selfCommand() {\n const runtime = path.basename(process.execPath, path.extname(process.execPath)).toLowerCase()\n if (runtime !== \"bun\" && runtime !== \"node\" && runtime !== \"nodejs\") return [process.execPath]\n if (!process.argv[1]) throw new Error(\"Failed to resolve CLI entrypoint\")\n if (runtime === \"node\" || runtime === \"nodejs\") return [process.execPath, ...nodeFlags(), process.argv[1]]\n return [process.execPath, process.argv[1]]\n}\n\nfunction nodeFlags() {\n return process.execArgv.flatMap((arg, index, args) => {\n if (index > 0 && args[index - 1] === \"--conditions\") return []\n if (arg === \"--conditions\") return args[index + 1] ? [arg, args[index + 1]] : []\n if (arg.startsWith(\"--conditions=\")) return [arg]\n if (\n arg === \"--experimental-ffi\" ||\n arg === \"--use-system-ca\" ||\n arg === \"--enable-source-maps\" ||\n arg === \"--no-addons\"\n )\n return [arg]\n if (arg === \"--no-warnings\" || arg.startsWith(\"--disable-warning=\")) return [arg]\n return []\n })\n}\n"
],
"mappings": ";iSAEA,qBAAS,2BACT,uBA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AAC,EACpC,MAAO,EAAM,IAAM,MAAO,EAAK,EAAI,MAAK,CAAC,EACzC,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,MAAO,EAAS,CAAK,EACrB,MACF,GAEH,EAEY,GAAQ,EAAO,GAAG,0BAA0B,EAAE,SAAU,CAAC,EAAa,CACjF,OAAQ,EAAU,CAAG,OACd,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,KACK,OAAQ,CACX,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,KAAM,KAAU,GAAS,MAAO,EAAK,EAC7C,MAAO,EAAM,CAAI,EACjB,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,GAEH",
"debugId": "1EA5A8538896805C64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/migrate.ts"],
"sourcesContent": [
"import { Effect } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\n\nexport default Runtime.handler(Commands.commands.migrate, (_input) => Effect.log(\"No migrations to run.\"))\n"
],
"mappings": ";u1BAIA,SAAe,SAAQ,aAAQ,OAAS,cAAS,aAAS,MAAC,SAAW,OAAO,SAAI,4BAAuB,MAAC",
"debugId": "42FEF986B5725A5564756E2164756E21",
"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(\n ` Run \\`opencode service set hostname 0.0.0.0\\` to access the service remotely.${EOL}${EOL}`,\n )\n }),\n)\n"
],
"mappings": ";8gCAAA,mBAAS,gBAST,SAAe,SAAQ,aACrB,OAAS,cAAS,UAClB,OAAO,QAAG,eAAU,OAAE,cAAU,OAAG,MACjC,SAAM,OAAW,WAAO,OAAQ,YAAO,WAAO,OAAc,aAAQ,MAAC,OAC/D,OAAW,WAAO,EAAc,SAAS,EAIzC,EAAO,CAAE,MAHA,MAAO,EAAO,WAAW,IACtC,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAAE,OAAO,IAAI,CAC1F,GAC4B,KAAM,SAAU,WAAY,UAAS,EACjE,QAAQ,OAAO,MACb,CACE,GACA,eAAe,EAAK,KAAK,IAAM,WAC/B,GAAG,EAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,IAAQ,eAAe,GAAK,EACvD,eAAe,EAAK,WACpB,eAAe,EAAK,WACpB,GACA,iBACA,GACA,EAAqB,KAAK,UAAU,CAAI,EAAG,CAAE,OAAQ,CAAE,CAAC,EACrD,MAAM,CAAG,EACT,IAAI,CAAC,IAAS,KAAO,CAAI,EACzB,KAAK,CAAG,EACX,EACF,EAAE,KAAK,CAAG,EAAI,CAChB,EAEA,IAAM,EAAW,IAAI,IAAI,EAAS,GAAG,EAAE,SACvC,GAAI,CAAC,CAAC,YAAa,YAAa,OAAO,EAAE,SAAS,CAAQ,EAAG,OAC7D,QAAQ,OAAO,MACb,kFAAkF,IAAM,GAC1F,EACD,CACH",
"debugId": "E546215023E7EA1064756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/ui/timeline.tsx", "src/commands/handlers/console/login.ts"],
"sourcesContent": [
"import { createComponent as _$createComponent } from \"@opentui/solid\";\nimport { effect as _$effect } from \"@opentui/solid\";\nimport { createTextNode as _$createTextNode } from \"@opentui/solid\";\nimport { insertNode as _$insertNode } from \"@opentui/solid\";\nimport { insert as _$insert } from \"@opentui/solid\";\nimport { setProp as _$setProp } from \"@opentui/solid\";\nimport { createElement as _$createElement } from \"@opentui/solid\";\n/** @jsxImportSource @opentui/solid */\nimport { createCliRenderer, RGBA } from \"@opentui/core\";\nimport { createScrollbackWriter, render, useKeyboard } from \"@opentui/solid\";\nimport { registerOpencodeSpinner } from \"@opencode-ai/tui/component/register-spinner\";\nimport { Show, createSignal } from \"solid-js\";\nregisterOpencodeSpinner();\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst IDLE_TIMEOUT = 1_000;\nconst COLORS = {\n accent: RGBA.fromIndex(6),\n error: RGBA.fromIndex(1),\n foreground: RGBA.defaultForeground(),\n muted: RGBA.fromIndex(8),\n success: RGBA.fromIndex(2)\n};\nconst ROWS = {\n intro: {\n marker: \"┌\",\n color: COLORS.muted,\n connector: true\n },\n item: {\n marker: \"●\",\n color: COLORS.accent,\n connector: true\n },\n success: {\n marker: \"◇\",\n color: COLORS.success,\n connector: true\n },\n failure: {\n marker: \"■\",\n color: COLORS.error,\n connector: false\n },\n outro: {\n marker: \"└\",\n color: COLORS.muted,\n connector: false\n }\n};\nfunction row(kind, value) {\n const style = ROWS[kind];\n return createScrollbackWriter(() => (() => {\n var _el$ = _$createElement(\"box\"),\n _el$2 = _$createElement(\"box\"),\n _el$3 = _$createElement(\"text\"),\n _el$4 = _$createElement(\"text\");\n _$insertNode(_el$, _el$2);\n _$setProp(_el$, \"width\", \"100%\");\n _$setProp(_el$, \"minHeight\", 1);\n _$setProp(_el$, \"flexDirection\", \"column\");\n _$insertNode(_el$2, _el$3);\n _$insertNode(_el$2, _el$4);\n _$setProp(_el$2, \"width\", \"100%\");\n _$setProp(_el$2, \"minHeight\", 1);\n _$setProp(_el$2, \"flexDirection\", \"row\");\n _$setProp(_el$2, \"gap\", 1);\n _$setProp(_el$3, \"flexShrink\", 0);\n _$insert(_el$3, () => style.marker);\n _$setProp(_el$4, \"wrapMode\", \"word\");\n _$insert(_el$4, value);\n _$insert(_el$, _$createComponent(Show, {\n get when() {\n return style.connector;\n },\n get children() {\n var _el$5 = _$createElement(\"text\");\n _$insertNode(_el$5, _$createTextNode(`│`));\n _$effect(_$p => _$setProp(_el$5, \"fg\", COLORS.muted, _$p));\n return _el$5;\n }\n }), null);\n _$effect(_p$ => {\n var _v$ = style.color,\n _v$2 = COLORS.foreground;\n _v$ !== _p$.e && (_p$.e = _$setProp(_el$3, \"fg\", _v$, _p$.e));\n _v$2 !== _p$.t && (_p$.t = _$setProp(_el$4, \"fg\", _v$2, _p$.t));\n return _p$;\n }, {\n e: undefined,\n t: undefined\n });\n return _el$;\n })(), {\n startOnNewLine: true,\n trailingNewline: !style.connector\n });\n}\nfunction TimelineFooter(props) {\n useKeyboard(event => {\n if (event.name !== \"escape\" && !(event.ctrl && event.name === \"c\")) return;\n event.preventDefault();\n props.cancel();\n });\n return (() => {\n var _el$7 = _$createElement(\"box\");\n _$setProp(_el$7, \"width\", \"100%\");\n _$setProp(_el$7, \"height\", 1);\n _$setProp(_el$7, \"flexDirection\", \"row\");\n _$setProp(_el$7, \"gap\", 1);\n _$insert(_el$7, _$createComponent(Show, {\n get when() {\n return props.pending();\n },\n children: text => [(() => {\n var _el$8 = _$createElement(\"spinner\");\n _$setProp(_el$8, \"frames\", SPINNER_FRAMES);\n _$setProp(_el$8, \"interval\", 80);\n _$effect(_$p => _$setProp(_el$8, \"color\", COLORS.accent, _$p));\n return _el$8;\n })(), (() => {\n var _el$9 = _$createElement(\"text\");\n _$setProp(_el$9, \"wrapMode\", \"none\");\n _$setProp(_el$9, \"truncate\", true);\n _$insert(_el$9, text);\n _$effect(_$p => _$setProp(_el$9, \"fg\", COLORS.foreground, _$p));\n return _el$9;\n })()]\n }));\n return _el$7;\n })();\n}\nfunction bounded(task) {\n return new Promise(resolve => {\n const timer = setTimeout(resolve, IDLE_TIMEOUT);\n timer.unref();\n const finish = () => {\n clearTimeout(timer);\n resolve();\n };\n void task.then(finish, finish);\n });\n}\nasync function shutdown(renderer) {\n await bounded(renderer.idle());\n try {\n renderer.externalOutputMode = \"passthrough\";\n } finally {\n try {\n renderer.screenMode = \"main-screen\";\n } finally {\n if (!renderer.isDestroyed) renderer.destroy();\n }\n }\n}\nexport async function createTimelineHost() {\n const stdout = process.stdout;\n const controller = new AbortController();\n const signals = [\"SIGINT\", \"SIGHUP\", \"SIGQUIT\"];\n const cancel = () => {\n if (!controller.signal.aborted) controller.abort();\n };\n signals.forEach(signal => process.on(signal, cancel));\n if (!stdout.isTTY || !process.stdin.isTTY) {\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = async (kind, text) => {\n if (closed) throw new Error(\"timeline closed\");\n if (writing) throw new Error(\"timeline write already in progress\");\n writing = true;\n try {\n const style = kind === \"pending\" ? undefined : ROWS[kind];\n const marker = kind === \"pending\" ? \".\" : ROWS[kind].marker;\n const connector = style?.connector ? \"│\\n\" : \"\";\n active = new Promise((resolve, reject) => {\n stdout.write(`${marker} ${text}\\n${connector}`, error => error ? reject(error) : resolve());\n });\n await active;\n } finally {\n writing = false;\n active = undefined;\n }\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n signals.forEach(signal => process.off(signal, cancel));\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n }\n let renderer;\n try {\n // Start on a fresh row so delayed SSH cursor reports cannot make\n // split-footer overwrite the shell command.\n process.stdout.write(\"\\n\");\n renderer = await createCliRenderer({\n stdin: process.stdin,\n useMouse: false,\n autoFocus: false,\n openConsoleOnError: false,\n exitOnCtrlC: false,\n exitSignals: [],\n screenMode: \"split-footer\",\n footerHeight: 1,\n externalOutputMode: \"capture-stdout\",\n consoleMode: \"disabled\",\n clearOnShutdown: false\n });\n const activeRenderer = renderer;\n const [pending, setPending] = createSignal();\n const renderTask = render(() => _$createComponent(TimelineFooter, {\n pending: pending,\n cancel: cancel\n }), activeRenderer);\n void renderTask.catch(cancel);\n await bounded(activeRenderer.idle());\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = (kind, text) => {\n if (closed) return Promise.reject(new Error(\"timeline closed\"));\n if (writing) return Promise.reject(new Error(\"timeline write already in progress\"));\n writing = true;\n active = (async () => {\n if (kind === \"pending\") {\n setPending(text);\n activeRenderer.requestRender();\n } else {\n if (kind === \"success\" || kind === \"failure\" || kind === \"outro\") setPending(undefined);\n activeRenderer.writeToScrollback(row(kind, text));\n activeRenderer.requestRender();\n }\n await bounded(activeRenderer.idle());\n })().finally(() => {\n writing = false;\n active = undefined;\n });\n return active;\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n try {\n await shutdown(activeRenderer);\n await bounded(renderTask);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n } catch (error) {\n try {\n if (renderer) await shutdown(renderer);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n throw error;\n }\n}",
"import { Cause, Effect, Exit, Option } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { AppProcess } from \"@opencode-ai/core/process\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { createTimelineHost, type TimelineHost } from \"../../../ui/timeline\"\n\nconst integrationID = \"opencode\"\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.console.commands.login,\n Effect.fn(\"cli.console.login\")(function* (input) {\n const timeline = yield* Effect.acquireRelease(\n Effect.promise(() => createTimelineHost()),\n (value) => request(() => value.close()).pipe(Effect.ignore),\n )\n const exit = yield* login(timeline, Option.getOrUndefined(input.url)).pipe(\n Effect.raceFirst(AppProcess.waitForAbort(timeline.signal)),\n Effect.exit,\n )\n if (Exit.isSuccess(exit)) return\n\n const cancelled = timeline.signal.aborted\n yield* request(() => timeline.failure(cancelled ? \"Authorization cancelled\" : errorMessage(exit.cause))).pipe(\n Effect.ignore,\n )\n process.exitCode = cancelled ? 130 : 1\n }),\n)\n\nconst login = Effect.fn(\"cli.console.login.run\")(function* (timeline: TimelineHost, server?: string) {\n yield* request(() => timeline.intro(\"Log in\"))\n yield* request(() => timeline.pending(\"Connecting to OpenCode...\"))\n\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const found = yield* request((signal) => client.integration.get({ integrationID, location }, { signal }))\n const integration = yield* required(found.data, \"OpenCode Console integration is unavailable\")\n const method = yield* required(\n integration.methods.find((candidate) => candidate.type === \"oauth\"),\n \"OpenCode Console login is unavailable\",\n )\n\n yield* request(() => timeline.pending(\"Starting authorization...\"))\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n {\n integrationID,\n methodID: method.id,\n inputs: server ? { server } : {},\n location,\n },\n { signal },\n ),\n )\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n if (attempt.mode !== \"auto\") yield* Effect.fail(new Error(\"OpenCode Console requires a device login\"))\n\n yield* request(() => timeline.item(`Go to: ${attempt.url}`))\n yield* request(() => timeline.item(attempt.instructions))\n yield* request(async () => {\n const { default: open } = await import(\"open\")\n await open(attempt.url)\n }).pipe(Effect.ignore)\n yield* request(() => timeline.pending(\"Waiting for authorization...\"))\n\n const status = yield* waitForConsoleLogin(client, integrationID, attempt.attemptID)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") yield* Effect.fail(new Error(\"Device code expired\"))\n\n yield* request(() => timeline.success(\"Connected to OpenCode Console\"))\n yield* request(() => timeline.outro(\"Done\"))\n})\n\nconst waitForConsoleLogin = Effect.fn(\"cli.console.login.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.oauth.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n yield* Effect.sleep(500)\n }\n})\n\nfunction request<A>(task: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: task,\n catch: (cause) => cause,\n })\n}\n\nfunction required<A>(value: A | null | undefined, message: string) {\n return value === null || value === undefined ? Effect.fail(new Error(message)) : Effect.succeed(value)\n}\n\nfunction errorMessage(cause: Cause.Cause<unknown>) {\n const error = Cause.squash(cause)\n if (error instanceof Error) return error.message\n if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\") {\n return error.message\n }\n return String(error)\n}\n"
],
"mappings": ";2rCAYA,OAAwB,OACxB,SAAM,OAAiB,MAAC,cAAI,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,aAAG,OACjE,QAAe,UACf,OAAS,MACb,YAAQ,OAAK,eAAU,MAAC,OACxB,WAAO,OAAK,UAAU,CAAC,EACvB,WAAY,EAAK,kBAAkB,EACnC,MAAO,EAAK,UAAU,CAAC,EACvB,QAAS,EAAK,UAAU,CAAC,CAC3B,EACM,EAAO,CACX,MAAO,CACL,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,EACA,KAAM,CACJ,OAAQ,SACR,MAAO,EAAO,OACd,UAAW,EACb,EACA,QAAS,CACP,OAAQ,SACR,MAAO,EAAO,QACd,UAAW,EACb,EACA,QAAS,CACP,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,EACA,MAAO,CACL,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,CACF,EACA,SAAS,EAAG,CAAC,EAAM,EAAO,CACxB,IAAM,EAAQ,EAAK,GACnB,OAAO,EAAuB,KAAO,IAAM,CACzC,IAAI,EAAO,EAAgB,KAAK,EAC9B,EAAQ,EAAgB,KAAK,EAC7B,EAAQ,EAAgB,MAAM,EAC9B,EAAQ,EAAgB,MAAM,EAoChC,OAnCA,EAAa,EAAM,CAAK,EACxB,EAAU,EAAM,QAAS,MAAM,EAC/B,EAAU,EAAM,YAAa,CAAC,EAC9B,EAAU,EAAM,gBAAiB,QAAQ,EACzC,EAAa,EAAO,CAAK,EACzB,EAAa,EAAO,CAAK,EACzB,EAAU,EAAO,QAAS,MAAM,EAChC,EAAU,EAAO,YAAa,CAAC,EAC/B,EAAU,EAAO,g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,GAE1B,EAED,SAAS,CAAU,CAAC,EAA2C,CAC7D,OAAO,EAAO,WAAW,CACvB,IAAK,EACL,MAAO,CAAC,IAAU,CACpB,CAAC,EAGH,SAAS,CAAW,CAAC,EAA6B,EAAiB,CACjE,OAAO,IAAU,MAAQ,IAAU,OAAY,EAAO,KAAS,MAAM,CAAO,CAAC,EAAI,EAAO,QAAQ,CAAK,EAGvG,SAAS,EAAY,CAAC,EAA6B,CACjD,IAAM,EAAQ,EAAM,OAAO,CAAK,EAChC,GAAI,aAAiB,MAAO,OAAO,EAAM,QACzC,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,OAAO,EAAM,UAAY,SAChG,OAAO,EAAM,QAEf,OAAO,OAAO,CAAK",
"debugId": "BDAE1D3EB89C5DE364756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/mcp/logout.ts"],
"sourcesContent": [
"import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.logout,\n Effect.fn(\"cli.mcp.logout\")(function* (input) {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n yield* Effect.forEach(\n credentials,\n (connection) => Effect.promise(() => client.credential.remove({ credentialID: connection.id, location })),\n { discard: true },\n )\n process.stdout.write(`Removed OAuth credentials for ${input.name}` + EOL)\n }),\n)\n"
],
"mappings": ";8gCAAA,mBAAS,gBAST,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,YAC/B,OAAO,QAAG,qBAAgB,OAAE,cAAU,MAAC,OAAO,MAC5C,SAAM,OAAU,MAAO,EAAc,QAAQ,EAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EAAa,CAChB,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,IAAM,EAAc,EAAY,YAAY,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACnG,GAAI,EAAY,SAAW,EAAG,CAC5B,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,MAAO,EAAO,QACZ,EACA,CAAC,IAAe,EAAO,QAAQ,IAAM,EAAO,WAAW,OAAO,CAAE,aAAc,EAAW,GAAI,UAAS,CAAC,CAAC,EACxG,CAAE,QAAS,EAAK,CAClB,EACA,QAAQ,OAAO,MAAM,iCAAiC,EAAM,OAAS,CAAG,EACzE,CACH",
"debugId": "F3DF66FB4D13928064756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/mcp/auth.ts"],
"sourcesContent": [
"import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport {\n OpenCode,\n type IntegrationAttemptStatus,\n type IntegrationOAuthMethod,\n type OpenCodeClient,\n} from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.auth,\n Effect.fn(\"cli.mcp.auth\")(function* (input) {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n const method = integration.methods.find(\n (candidate): candidate is IntegrationOAuthMethod => candidate.type === \"oauth\",\n )\n if (!method)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n\n const started = yield* Effect.promise(() =>\n client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),\n )\n const attempt = started.data\n if (attempt.mode === \"code\")\n return yield* Effect.fail(new Error(\"This server requires manual code entry, which the CLI does not support\"))\n\n process.stdout.write(attempt.instructions + EOL + attempt.url + EOL)\n\n const result = yield* poll(client, integration.id, attempt.attemptID)\n if (result.status === \"complete\") {\n process.stdout.write(`Authenticated with ${input.name}` + EOL)\n return\n }\n const reason = result.status === \"failed\" ? `: ${result.message}` : \"\"\n return yield* Effect.fail(new Error(`Authentication ${result.status}${reason}`))\n }),\n)\n\nconst poll = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n): Effect.Effect<Exclude<IntegrationAttemptStatus, { status: \"pending\" }>> =>\n Effect.gen(function* () {\n const status = yield* Effect.promise(() =>\n client.integration.oauth.status({ integrationID, attemptID, location }),\n ).pipe(Effect.map((result) => result.data))\n if (status.status === \"pending\") {\n yield* Effect.sleep(\"1 second\")\n return yield* poll(client, integrationID, attemptID)\n }\n return status\n })\n"
],
"mappings": ";8gCAAA,mBAAS,gBAcT,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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": "98B2ADC2690405E664756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/service/unset.ts"],
"sourcesContent": [
"import { Effect } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.unset,\n Effect.fn(\"cli.service.unset\")(function* (input) {\n yield* ServiceConfig.unset(input.key)\n }),\n)\n"
],
"mappings": ";w6BAKA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,WACnC,OAAO,QAAG,wBAAmB,OAAE,cAAU,MAAC,OAAO,MAC/C,WAAO,OAAc,WAAM,OAAM,QAAG,OACrC,MACH",
"debugId": "94B2509EE2AB03B864756E2164756E21",
"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 } from \"@opencode-ai/client/promise\"\nimport { FSUtil } from \"@opencode-ai/core/fs-util\"\nimport { Model } from \"@opencode-ai/schema/model\"\nimport { open } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { readStdin } from \"../util/io\"\nimport { ServerConnection } from \"../services/server-connection\"\nimport { waitForCatalogReady } from \"../services/catalog\"\nimport { toolInlineInfo, type MiniToolPart } from \"@opencode-ai/tui/mini/tool\"\nimport { runNonInteractivePrompt } from \"./noninteractive\"\nimport { UI } from \"./ui\"\n\nexport type RunCommandInput = {\n server: ServerConnection.Resolved\n message: string[]\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n format: \"default\" | \"json\"\n file: string[]\n title?: string\n thinking?: boolean\n auto?: boolean\n}\n\ntype FilePart = {\n url: string\n filename: string\n mime: string\n}\n\ntype Prepared = {\n directory?: string\n message: string\n files: FilePart[]\n}\n\ntype ExecutionOptions = {\n root?: string\n directory?: string\n useServerDirectory?: boolean\n variant?: string\n attached?: boolean\n compatibility?: \"v1\"\n}\n\nconst ATTACH_FILE_MAX_BYTES = 10 * 1024 * 1024\n\nexport function runNonInteractive(input: RunCommandInput) {\n return runNonInteractiveWithOptions(input, {})\n}\n\n/** @internal Used only by the V1 command boundary. */\nexport function runNonInteractiveWithOptions(input: RunCommandInput, options: ExecutionOptions) {\n return run(input, options).catch((error) => reportRunError(input, errorMessage(error)))\n}\n\nasync function run(input: RunCommandInput, options: ExecutionOptions) {\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n const root = options.root ?? process.env.PWD ?? process.cwd()\n const local = localDirectory(root)\n const directory = options.useServerDirectory ? undefined : (options.directory ?? local)\n const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin())\n if (!message?.trim()) fail(\"You must provide a message\")\n const files = await Promise.all(input.file.map((file) => prepareFile(file, root, options)))\n const prepared = { directory, message, files }\n return execute(input, prepared, input.server.endpoint, options)\n}\n\nasync function execute(input: RunCommandInput, prepared: Prepared, endpoint: Endpoint, options: ExecutionOptions) {\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const requestedDirectory = prepared.directory ?? (await client.location.get()).directory\n if (!requestedDirectory) fail(\"Failed to resolve server directory\")\n const session = await selectSession(client, requestedDirectory, input)\n const cwd = session?.location.directory ?? requestedDirectory\n const workspace = session?.location.workspaceID\n const explicit = parseRunModel(input.model)\n const explicitModel = explicit?.model\n const variant = options.variant ?? explicit?.variant\n const sessionModel = session?.model ? { providerID: session.model.providerID, modelID: session.model.id } : undefined\n const defaultModel =\n !explicitModel && !sessionModel\n ? await client.model\n .default({ location: { directory: cwd, workspace } })\n .then((result) => (result.data ? { providerID: result.data.providerID, modelID: result.data.id } : undefined))\n : undefined\n const model = pickRunModel(explicitModel, variant, sessionModel, defaultModel)\n if (variant && !model) return reportRunError(input, \"Cannot select a variant before selecting a model\", session?.id)\n if (model) {\n await waitForCatalogReady({ sdk: client, directory: cwd, workspace, model })\n const available = await client.model.list({ location: { directory: cwd, workspace } })\n if (!available.data.some((item) => item.providerID === model.providerID && item.id === model.modelID))\n return reportRunError(input, `Model unavailable: ${model.providerID}/${model.modelID}`, session?.id)\n }\n const agent = await validateAgent(client, cwd, input.agent)\n const selected =\n session ??\n (await client.session.create({\n agent,\n model: model ? { providerID: model.providerID, id: model.modelID, variant } : undefined,\n location: { directory: cwd },\n }))\n if (!session && input.title !== undefined) {\n await client.session.rename({\n sessionID: selected.id,\n title: input.title || prepared.message.slice(0, 50) + (prepared.message.length > 50 ? \"...\" : \"\"),\n })\n }\n\n await runNonInteractivePrompt({\n client,\n sessionID: selected.id,\n message: prepared.message,\n files: prepared.files,\n 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,\n renderToolError,\n }).catch((error) => reportRunError(input, errorMessage(error), selected.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\nexport function pickRunModel(\n explicit: { providerID: string; modelID: string } | undefined,\n variant: string | undefined,\n session: { providerID: string; modelID: string } | undefined,\n fallback: { providerID: string; modelID: string } | undefined,\n) {\n if (explicit) return explicit\n if (!variant) return\n return session ?? fallback\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 if (!value) return\n const ref = Model.Ref.parse(value)\n return {\n model: { providerID: ref.providerID, modelID: ref.id },\n variant: ref.variant,\n }\n}\n\nasync function validateAgent(client: OpenCodeClient, directory: string, name?: string) {\n if (!name) return\n const agents = await client.agent\n .list({ location: { directory } })\n .then((result) => result.data)\n .catch(() => undefined)\n if (!agents) {\n warning(\"failed to list agents. Falling back to default agent\")\n return\n }\n const agent = agents.find((item) => item.id === name)\n if (!agent) {\n warning(`agent \"${name}\" not found. Falling back to default agent`)\n return\n }\n if (agent.mode === \"subagent\") {\n warning(`agent \"${name}\" is a subagent, not a primary agent. Falling back to default agent`)\n return\n }\n return name\n}\n\nasync function selectSession(client: OpenCodeClient, directory: string, input: RunCommandInput) {\n const selected = input.session\n ? await client.session.get({ sessionID: input.session }).catch(() => undefined)\n : input.continue\n ? await client.session\n .list({ directory, parentID: null, limit: 1, order: \"desc\" })\n .then((result) => result.data[0])\n : undefined\n if (input.session && !selected) fail(\"Session not found\")\n if (!selected || !input.fork) return selected\n return client.session.fork({ sessionID: selected.id })\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: MiniToolPart) {\n const info = toolInlineInfo(part)\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: MiniToolPart) {\n const info = toolInlineInfo(part)\n UI.println(UI.Style.TEXT_NORMAL + \"✗\", UI.Style.TEXT_NORMAL + `${info.title} failed`)\n}\n\nfunction warning(message: string) {\n UI.println(UI.Style.TEXT_WARNING_BOLD + \"!\", UI.Style.TEXT_NORMAL, message)\n}\n\nfunction errorMessage(error: unknown) {\n if (error instanceof Error) return error.message\n if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\")\n return error.message\n return String(error)\n}\n\n/** @internal Used by the V1 command boundary before a Session exists. */\nexport function reportRunError(input: Pick<RunCommandInput, \"format\">, message: string, sessionID?: string) {\n process.exitCode = 1\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify({\n type: \"error\",\n timestamp: Date.now(),\n sessionID: sessionID ?? \"\",\n error: { type: \"unknown\", message },\n }) + \"\\n\",\n )\n return\n }\n UI.error(message)\n}\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n",
"import type { EventSubscribeOutput, OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { SessionMessage } from \"@opencode-ai/schema/session-message\"\nimport { EOL } from \"node:os\"\nimport { readFile } from \"node:fs/promises\"\nimport { toolOutputText, type MiniToolPart } from \"@opencode-ai/tui/mini/tool\"\nimport { UI } from \"./ui\"\n\ntype Model = {\n providerID: string\n modelID: string\n}\n\ntype File = {\n url: string\n filename: string\n mime: string\n}\n\ntype Input = {\n client: OpenCodeClient\n sessionID: string\n 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: MiniToolPart) => Promise<void>\n renderToolError: (part: MiniToolPart) => 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, unknown>\n raw?: string\n provider?: unknown\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 let submitted = false\n let promoted = false\n let emittedError = false\n let questionRejected = false\n let permissionRejected = false\n let formCancelled = false\n let interrupted = false\n let v1InvalidOutput = 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 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 rejectQuestion = async (request: { id: string }) => {\n questionRejected = true\n await input.client.question.reject({ sessionID: input.sessionID, requestID: request.id }).catch(() => {})\n }\n\n const cancelForm = async (request: Pick<FormRequest, \"id\" | \"sessionID\">) => {\n formCancelled = true\n await input.client.form.cancel({ sessionID: request.sessionID, formID: request.id }).catch(() => {})\n }\n\n const consume = async () => {\n while (!controller.signal.aborted) {\n const next = await stream.next().catch((error) => {\n if (!emittedError) throw error\n return { done: true as const, value: undefined }\n })\n if (next.done) {\n if (emittedError) return\n throw new Error(\"Event stream disconnected during prompt execution\")\n }\n const event = next.value\n\n if (event.type === \"permission.v2.asked\" && submitted && event.data.sessionID === input.sessionID) {\n await replyPermission(event.data)\n continue\n }\n if (event.type === \"question.v2.asked\" && submitted && event.data.sessionID === input.sessionID) {\n await rejectQuestion(event.data)\n continue\n }\n if (\n event.type === \"form.created\" &&\n submitted &&\n (event.data.form.sessionID === input.sessionID ||\n (!input.attached && event.data.form.sessionID === GLOBAL_FORM_SESSION_ID))\n ) {\n await cancelForm(event.data.form)\n continue\n }\n if (!(\"sessionID\" in event.data) || event.data.sessionID !== input.sessionID) continue\n const time = toMillis(\"created\" in event ? event.created : undefined)\n\n if (event.type === \"session.input.promoted\") {\n if (event.data.inputID === messageID) {\n promoted = true\n continue\n }\n }\n if (\n event.type === \"session.execution.interrupted\" &&\n event.data.reason === \"user\" &&\n (interrupted || permissionRejected || questionRejected || formCancelled)\n ) {\n return\n }\n if (!promoted) 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\", { id: partID(event.id), timestamp: time })\n continue\n }\n if (event.type === \"session.text.ended\") {\n const started = starts.get(\"text\")\n starts.delete(\"text\")\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 writeText(part, time)\n continue\n }\n\n if (event.type === \"session.reasoning.started\") {\n flushStep()\n starts.set(\"reasoning\", { id: partID(event.id), timestamp: time })\n continue\n }\n if (event.type === \"session.reasoning.ended\" && input.thinking) {\n const started = starts.get(\"reasoning\")\n starts.delete(\"reasoning\")\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 if (emit(\"reasoning\", time, { part })) continue\n const text = part.text.trim()\n if (!text) continue\n const line = `Thinking: ${text}`\n if (!process.stdout.isTTY) {\n process.stdout.write(line + EOL)\n continue\n }\n UI.empty()\n UI.println(`${UI.Style.TEXT_DIM}\\u001b[3m${line}\\u001b[0m${UI.Style.TEXT_NORMAL}`)\n UI.empty()\n continue\n }\n\n if (event.type === \"session.tool.input.started\") {\n flushStep()\n tools.set(event.data.callID, {\n id: partID(event.id),\n timestamp: time,\n assistantMessageID: event.data.assistantMessageID,\n tool: event.data.name,\n input: {},\n })\n continue\n }\n if (event.type === \"session.tool.input.ended\") {\n const current = tools.get(event.data.callID)\n if (current) current.raw = event.data.text\n continue\n }\n if (event.type === \"session.tool.called\") {\n flushStep()\n const current = tools.get(event.data.callID)\n tools.set(event.data.callID, {\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 })\n continue\n }\n if (event.type === \"session.tool.success\") {\n const current = tools.get(event.data.callID) ?? fallbackTool(event)\n const part: MiniToolPart = {\n id: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n callID: event.data.callID,\n tool: current.tool,\n state: {\n status: \"completed\",\n input: current.input,\n output: toolOutputText(current.tool, event.data.content),\n title: current.tool,\n metadata: {\n structured: event.data.structured,\n content: event.data.content,\n result: event.data.result,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(event.data.callID)\n if (!emit(\"tool_use\", time, { part })) await input.renderTool(part)\n continue\n }\n if (event.type === \"session.tool.failed\") {\n const current = tools.get(event.data.callID) ?? fallbackTool(event)\n const error = event.data.error.message\n const part: MiniToolPart = {\n id: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n callID: event.data.callID,\n tool: current.tool,\n state: {\n status: \"error\",\n input: current.input,\n error,\n metadata: {\n result: event.data.result,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(event.data.callID)\n if (input.compatibility === \"v1\" && (permissionRejected || questionRejected || formCancelled)) continue\n if (!emit(\"tool_use\", time, { part })) {\n await input.renderToolError(part)\n UI.error(error)\n }\n continue\n }\n\n if (event.type === \"session.step.ended\") {\n flushStep()\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-finish\",\n reason: event.data.finish,\n snapshot: event.data.snapshot,\n cost: event.data.cost,\n tokens: event.data.tokens,\n }\n emit(\"step_finish\", time, { part })\n continue\n }\n if (event.type === \"session.step.failed\") {\n if (\n input.compatibility === \"v1\" &&\n event.data.error.message === \"Provider stream ended without a terminal finish event\"\n ) {\n pendingStep = undefined\n v1InvalidOutput = true\n continue\n }\n if (interrupted || permissionRejected || questionRejected || 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 (\n input.compatibility === \"v1\" &&\n (v1InvalidOutput || permissionRejected || questionRejected || formCancelled)\n )\n return\n flushStep()\n if (!emittedError && !questionRejected && !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 || questionRejected || 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 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, questions, forms] = await Promise.all([\n input.client.permission.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.client.question.list({ sessionID: input.sessionID }).catch(() => undefined),\n Promise.all(\n (input.attached ? [input.sessionID] : [input.sessionID, GLOBAL_FORM_SESSION_ID]).map((sessionID) =>\n input.client.form.list({ sessionID }).catch(() => undefined),\n ),\n ),\n ])\n await Promise.all([\n ...(permissions ?? []).map(replyPermission),\n ...(questions ?? []).map(rejectQuestion),\n ...forms.flatMap((response) => response ?? []).map(cancelForm),\n ])\n await completed\n } finally {\n process.off(\"SIGINT\", interrupt)\n controller.abort()\n await stream.return?.(undefined).catch(() => {})\n }\n}\n\nfunction partID(eventID: string) {\n return `prt_${eventID.replace(/^evt_/, \"\")}`\n}\n\nfunction fallbackTool(event: {\n id: string\n created: number\n data: { assistantMessageID: string; callID: string }\n}): ToolState {\n return {\n id: partID(event.id),\n timestamp: toMillis(event.created),\n assistantMessageID: event.data.assistantMessageID,\n tool: \"tool\",\n input: {},\n }\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": ";88BAIA,oBAAS,0BACT,yBCHA,mBAAS,gBACT,wBAAS,uGCHT,mBAAS,iBAEF,SAAM,OAAQ,MACnB,cAAU,gBACV,iBAAa,eACb,uBAAmB,uBACnB,sBAAkB,sBACpB,OAEO,cAAS,MAAO,SAAI,EAAmB,CAC5C,QAAQ,OAAO,MAAM,EAAQ,KAAK,GAAG,EAAI,EAAG,EAG9C,IAAI,EAAQ,GAEL,SAAS,EAAK,EAAG,CACtB,GAAI,EAAO,OACX,EAAQ,EAAM,WAAW,EACzB,EAAQ,GAGH,SAAS,EAAK,CAAC,EAAiB,CACrC,GAAI,EAAQ,WAAW,SAAS,EAAG,EAAU,EAAQ,MAAM,CAAgB,EAC3E,EAAQ,EAAM,iBAAmB,UAAY,EAAM,YAAc,CAAO,EDgC1E,IAAM,EAAyB,SAE/B,eAAsB,CAAuB,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,EAAe,GAAG,OAAO,EACrC,EAAS,IAAI,IACb,EAAQ,IAAI,IACd,EAAY,GACZ,EAAW,GACX,EAAe,GACf,EAAmB,GACnB,EAAqB,GACrB,EAAgB,GAChB,EAAc,GACd,EAAkB,GAClB,EACA,EAEE,EAAO,CAAC,EAAc,EAAmB,IAAkC,CAC/E,GAAI,E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EAG5E,SAAS,EAAY,CAAC,EAAgB,CACpC,GAAI,aAAiB,MAAO,OAAO,EAAM,QACzC,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,OAAO,EAAM,UAAY,SAChG,OAAO,EAAM,QACf,OAAO,OAAO,CAAK,EAId,SAAS,CAAc,CAAC,EAAwC,EAAiB,EAAoB,CAE1G,GADA,QAAQ,SAAW,EACf,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UAAU,CACb,KAAM,QACN,UAAW,KAAK,IAAI,EACpB,UAAW,GAAa,GACxB,MAAO,CAAE,KAAM,UAAW,SAAQ,CACpC,CAAC,EAAI;AAAA,CACP,EACA,OAEF,EAAG,MAAM,CAAO,EAGlB,SAAS,CAAI,CAAC,EAAwB,CACpC,MAAU,MAAM,CAAO",
"debugId": "FFE7DD4410529A5064756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/debug/agents.ts"],
"sourcesContent": [
"import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.agents,\n Effect.fn(\"cli.debug.agents\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.agent.list({ location: { directory: process.cwd() } }))\n process.stdout.write(\n JSON.stringify(\n response.data.toSorted((a, b) => a.id.localeCompare(b.id)),\n null,\n 2,\n ) + EOL,\n )\n }),\n)\n"
],
"mappings": ";+9BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,WAAM,cAAS,YACjC,OAAO,QAAG,uBAAkB,OAAE,cAAU,OAAG,MACzC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,QADQ,WAAO,OAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EAC1G,QAAQ,OAAO,MACb,KAAK,UACH,EAAS,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzD,KACA,CACF,EAAI,CACN,EACD,CACH",
"debugId": "413785FD0A3C538964756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/services/standalone.ts", "src/services/server-connection.ts"],
"sourcesContent": [
"import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { CrossSpawnSpawner } from \"@opencode-ai/core/cross-spawn-spawner\"\nimport { LayerNode } from \"@opencode-ai/core/effect/layer-node\"\nimport { Deferred, Effect, Schema, Stream } from \"effect\"\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\"\nimport { randomBytes } from \"node:crypto\"\nimport { selfCommand } from \"../util/process\"\n\nconst Ready = Schema.Struct({ url: Schema.String })\nconst decodeReady = Schema.decodeUnknownPromise(Schema.fromJsonString(Ready))\n\ntype Options = {\n readonly command?: ReadonlyArray<string>\n}\n\nfunction command(password: string, options: Options) {\n const [executable, ...args] = options.command ?? [...selfCommand(), \"serve\"]\n if (!executable) throw new Error(\"Failed to resolve standalone server command\")\n return ChildProcess.make(executable, [...args, \"--stdio\", \"--port\", \"0\"], {\n cwd: process.cwd(),\n // Explicit entry wins over anything inherited, so a user-exported\n // OPENCODE_PASSWORD cannot shadow the child's lease credential.\n env: { OPENCODE_PASSWORD: password },\n extendEnv: true,\n // The server treats EOF on this pipe as the end of its ownership lease.\n // The OS closes it even when the TUI is killed before Effect finalizers run.\n stdin: \"pipe\",\n stderr: \"ignore\",\n killSignal: \"SIGTERM\",\n forceKillAfter: \"3 seconds\",\n })\n}\n\nconst makeEndpoint = Effect.fn(\"cli.standalone.endpoint\")(\n function* (options: Options) {\n const password = randomBytes(32).toString(\"base64url\")\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner\n const proc = yield* spawner.spawn(command(password, options))\n const readyLine = yield* Deferred.make<string, Error>()\n // Keep draining stdout after readiness so later server writes cannot hit EPIPE.\n yield* proc.stdout.pipe(\n Stream.decodeText(),\n Stream.splitLines,\n Stream.runForEach((line) => Deferred.succeed(readyLine, line)),\n Effect.ensuring(Deferred.fail(readyLine, new Error(\"Standalone server exited before reporting readiness\"))),\n Effect.forkScoped,\n )\n const output = yield* Deferred.await(readyLine)\n const ready = yield* Effect.tryPromise(() => decodeReady(output))\n return {\n url: ready.url,\n auth: { type: \"basic\" as const, username: \"opencode\", password },\n pid: proc.pid,\n } satisfies Endpoint & { readonly pid: number }\n },\n Effect.provide(LayerNode.compile(CrossSpawnSpawner.node)),\n)\n\nexport function start(options: Options = {}) {\n return makeEndpoint(options)\n}\n\nexport * as Standalone from \"./standalone\"\n",
"import { Service, type Endpoint, type EnsureOptions } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, isUnauthorizedError, OpenCode } from \"@opencode-ai/client/promise\"\nimport { InstallationVersion } from \"@opencode-ai/core/installation/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 !== InstallationVersion)\n process.stderr.write(\n `Warning: Server at ${endpoint.url} has version ${health.version}; this client is ${InstallationVersion}. Continuing anyway.\\n`,\n )\n return { endpoint } satisfies Resolved\n }\n if (args.standalone) {\n return { endpoint: yield* Standalone.start() } satisfies Resolved\n }\n\n const options = yield* ServiceConfig.options()\n return {\n endpoint: yield* resolveManaged({ ...options, onStart: args.onStart }, args.mismatch ?? \"replace\"),\n service: managedService(options),\n } satisfies Resolved\n})\n\nfunction managedService(options: EnsureOptions) {\n const reconnectOptions = { ...options, version: undefined }\n return {\n reconnect: () => Service.ensure(reconnectOptions),\n restart: () =>\n Effect.gen(function* () {\n yield* Service.stop(options)\n yield* Service.ensure(options)\n }),\n }\n}\n\nconst resolveManaged = Effect.fnUntraced(function* (\n options: EnsureOptions,\n mismatch: NonNullable<Args[\"mismatch\"]>,\n) {\n if (mismatch === \"replace\") return yield* Service.ensure(options)\n if (mismatch === \"ignore\") return yield* Service.ensure({ ...options, version: undefined })\n\n const compatible = yield* Service.discover(options)\n if (compatible !== undefined) return compatible\n const existing = yield* Service.discover({ ...options, version: undefined })\n if (existing !== undefined)\n return yield* Effect.fail(new Error(\"Background server version does not match this client\"))\n return yield* Service.ensure(options)\n})\n\nfunction connectError(endpoint: Endpoint, cause: unknown) {\n if (isUnauthorizedError(cause)) {\n return new Error(\n endpoint.auth === undefined\n ? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`\n : `Server at ${endpoint.url} rejected the password`,\n { cause },\n )\n }\n if (cause instanceof ClientError && cause.reason === \"Transport\")\n return new Error(`Could not reach server at ${endpoint.url}`, { cause })\n return new Error(`Server at ${endpoint.url} did not provide a compatible V2 health response`, { cause })\n}\n\nexport * as ServerConnection from \"./server-connection\"\n"
],
"mappings": ";slBAKA,2BAAS,oBAGT,SAAM,OAAQ,OAAO,YAAO,MAAE,SAAK,EAAO,MAAO,CAAC,EAC5C,EAAc,EAAO,qBAAqB,EAAO,eAAe,CAAK,CAAC,EAM5E,SAAS,CAAO,CAAC,EAAkB,EAAkB,CACnD,IAAO,KAAe,GAAQ,EAAQ,SAAW,CAAC,GAAG,EAAY,EAAG,OAAO,EAC3E,GAAI,CAAC,EAAY,MAAU,MAAM,6CAA6C,EAC9E,OAAO,EAAa,KAAK,EAAY,CAAC,GAAG,EAAM,UAAW,SAAU,GAAG,EAAG,CACxE,IAAK,QAAQ,IAAI,EAGjB,IAAK,CAAE,kBAAmB,CAAS,EACnC,UAAW,GAGX,MAAO,OACP,OAAQ,SACR,WAAY,UACZ,eAAgB,WAClB,CAAC,EAGH,IAAM,EAAe,EAAO,GAAG,yBAAyB,EACtD,SAAU,CAAC,EAAkB,CAC3B,IAAM,EAAW,EAAY,EAAE,EAAE,SAAS,WAAW,EAE/C,EAAO,OADG,MAAO,EAAoB,qBACf,MAAM,EAAQ,EAAU,CAAO,CAAC,EACtD,EAAY,MAAO,EAAS,KAAoB,EAEtD,MAAO,EAAK,OAAO,KACjB,EAAO,WAAW,EAClB,EAAO,WACP,EAAO,WAAW,CAAC,IAAS,EAAS,QAAQ,EAAW,CAAI,CAAC,EAC7D,EAAO,SAAS,EAAS,KAAK,EAAe,MAAM,qDAAqD,CAAC,CAAC,EAC1G,EAAO,UACT,EACA,IAAM,EAAS,MAAO,EAAS,MAAM,CAAS,EAE9C,MAAO,CACL,KAFY,MAAO,EAAO,WAAW,IAAM,EAAY,CAAM,CAAC,GAEnD,IACX,KAAM,CAAE,KAA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O,CAAgB,EAChD,QAAS,IACP,EAAO,IAAI,SAAU,EAAG,CACtB,MAAO,EAAQ,KAAK,CAAO,EAC3B,MAAO,EAAQ,OAAO,CAAO,EAC9B,CACL,EAGF,IAAM,EAAiB,EAAO,WAAW,SAAU,CACjD,EACA,EACA,CACA,GAAI,IAAa,UAAW,OAAO,MAAO,EAAQ,OAAO,CAAO,EAChE,GAAI,IAAa,SAAU,OAAO,MAAO,EAAQ,OAAO,IAAK,EAAS,QAAS,MAAU,CAAC,EAE1F,IAAM,EAAa,MAAO,EAAQ,SAAS,CAAO,EAClD,GAAI,IAAe,OAAW,OAAO,EAErC,IADiB,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,KAC1D,OACf,OAAO,MAAO,EAAO,KAAS,MAAM,sDAAsD,CAAC,EAC7F,OAAO,MAAO,EAAQ,OAAO,CAAO,EACrC,EAED,SAAS,CAAY,CAAC,EAAoB,EAAgB,CACxD,GAAI,EAAoB,CAAK,EAC3B,OAAW,MACT,EAAS,OAAS,OACd,aAAa,EAAS,iDACtB,aAAa,EAAS,4BAC1B,CAAE,OAAM,CACV,EAEF,GAAI,aAAiB,GAAe,EAAM,SAAW,YACnD,OAAW,MAAM,6BAA6B,EAAS,MAAO,CAAE,OAAM,CAAC,EACzE,OAAW,MAAM,aAAa,EAAS,sDAAuD,CAAE,OAAM,CAAC",
"debugId": "F8441F0966F6DBED64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/server-process.ts", "src/commands/handlers/serve.ts"],
"sourcesContent": [
"export * as ServerProcess from \"./server-process\"\n\nimport { NodeServices } from \"@effect/platform-node\"\nimport { Service, type DiscoverOptions, type Info } from \"@opencode-ai/client/effect/service\"\nimport { LayerNode } from \"@opencode-ai/core/effect/layer-node\"\nimport { Global } from \"@opencode-ai/core/global\"\nimport { InstallationVersion } from \"@opencode-ai/core/installation/version\"\nimport { AppProcess } from \"@opencode-ai/core/process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport path from \"node:path\"\nimport { Effect, FileSystem, Logger, Option, Redacted, Schedule, Schema } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { Env } from \"./env\"\nimport { ServiceConfig } from \"./services/service-config\"\nimport { Updater } from \"./services/updater\"\n\nexport type Mode = \"default\" | \"service\" | \"stdio\"\n\nexport type Options = {\n readonly mode: Mode\n readonly hostname?: string\n readonly port?: number\n}\n\n// The process effect lives until server shutdown; tracing it would parent every request to one process-lifetime trace.\nexport const run = Effect.fnUntraced(function* (options: Options) {\n return yield* processEffect(options).pipe(\n Effect.provide(Updater.layer),\n Effect.provide(LayerNode.compile(LayerNode.group([Global.node, AppProcess.node]))),\n Effect.provide(NodeServices.layer),\n )\n})\n\nconst processEffect = Effect.fnUntraced(function* (options: Options) {\n if (options.mode === \"service\") yield* Effect.sync(() => process.chdir(Global.Path.home))\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const serviceOptions = options.mode === \"service\" ? yield* ServiceConfig.options() : undefined\n const config = options.mode === \"service\" ? yield* ServiceConfig.read() : {}\n const hostname = options.hostname ?? config.hostname ?? \"127.0.0.1\"\n const port = options.port ?? config.port ?? (options.mode === \"service\" ? ServiceConfig.defaultPort() : undefined)\n if (\n serviceOptions !== undefined &&\n port !== undefined &&\n (yield* Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })) !== undefined\n )\n return\n const { start } = yield* Effect.promise(() => import(\"@opencode-ai/server/process\"))\n const environmentPassword = yield* Env.password\n // Keep the lease credential out of the environment inherited by tools.\n if (options.mode === \"stdio\") {\n delete process.env.OPENCODE_PASSWORD\n delete process.env.OPENCODE_SERVER_PASSWORD\n }\n const password =\n options.mode === \"service\"\n ? config.password || randomBytes(32).toString(\"base64url\")\n : environmentPassword\n ? Redacted.value(environmentPassword)\n : randomBytes(32).toString(\"base64url\")\n if (!password) return yield* Effect.fail(new Error(\"Missing server password\"))\n const instanceID = randomUUID()\n const server = yield* start({\n hostname,\n port: Option.fromNullishOr(port),\n password,\n instanceID,\n service:\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* register(address, password, instanceID, serviceOptions.file, shutdown)\n }),\n },\n }).pipe(\n Effect.provide(Logger.layer([], { mergeWithExisting: false })),\n Effect.catch((error) => {\n if (serviceOptions === undefined || port === undefined || !addressInUse(error)) return Effect.fail(error)\n return recognizeIncumbent(serviceOptions, hostname, port).pipe(\n Effect.flatMap((found) =>\n found\n ? Effect.void\n : Effect.fail(\n new Error(\n `Managed service port ${port} on ${hostname} is already in use by another process. ` +\n \"Configure another port with `opencode service set port <port>` and start the service again.\",\n { cause: error },\n ),\n ),\n ),\n )\n }),\n )\n if (server === undefined) return\n const url = HttpServer.formatAddress(server.address)\n console.log(options.mode === \"stdio\" ? JSON.stringify({ url }) : `server listening on ${url}`)\n if (options.mode === \"default\" && !environmentPassword) console.log(`server password ${password}`)\n const updater = yield* Updater.Service\n yield* updater.check().pipe(Effect.schedule(Schedule.spaced(\"10 minutes\")), Effect.forkScoped)\n return yield* options.mode === \"service\"\n ? server.shutdown\n : options.mode === \"stdio\"\n ? waitForStdinClose()\n : Effect.never\n }).pipe(Effect.annotateLogs({ role: \"server\" })),\n )\n})\n\nconst infoJson = Schema.fromJsonString(Service.Info)\nconst encodeInfo = Schema.encodeEffect(infoJson)\nconst decodeInfo = Schema.decodeUnknownEffect(infoJson)\n\nconst register = Effect.fnUntraced(function* (\n address: HttpServer.Address,\n password: string,\n id: string,\n file: string,\n shutdown: Effect.Effect<void>,\n) {\n const fs = yield* FileSystem.FileSystem\n const temp = file + \".\" + id + \".tmp\"\n yield* fs.makeDirectory(path.dirname(file), { recursive: true })\n const info = {\n id,\n version: InstallationVersion,\n url: HttpServer.formatAddress(address),\n pid: process.pid,\n password,\n }\n const encoded = yield* encodeInfo(info)\n const current = fs.readFileString(file).pipe(\n Effect.flatMap(decodeInfo),\n Effect.orElseSucceed(() => undefined),\n )\n const owns = (found: Info | undefined) =>\n found?.id === info.id &&\n found.version === info.version &&\n found.url === info.url &&\n found.pid === info.pid &&\n found.password === info.password\n yield* fs.writeFileString(temp, encoded, { mode: 0o600 }).pipe(Effect.andThen(fs.rename(temp, file)))\n yield* current.pipe(\n Effect.filterOrFail(owns),\n Effect.repeat(Schedule.spaced(\"5 seconds\")),\n Effect.ignore,\n Effect.andThen(shutdown),\n Effect.forkScoped,\n )\n return current.pipe(\n Effect.flatMap((found) => (owns(found) ? fs.remove(file) : Effect.void)),\n Effect.ignore,\n )\n})\n\nconst recognizeIncumbent = Effect.fnUntraced(function* (options: DiscoverOptions, hostname: string, port: number) {\n const found = yield* Service.incumbent({ ...options, url: serviceURL(hostname, port) }).pipe(\n Effect.filterOrFail((value) => value !== undefined),\n Effect.retry(Schedule.spaced(\"100 millis\")),\n Effect.timeoutOption(\"15 seconds\"),\n )\n return Option.isSome(found)\n})\n\nfunction serviceURL(hostname: string, port: number) {\n return `http://${hostname.includes(\":\") ? `[${hostname}]` : hostname}:${port}`\n}\n\nfunction addressInUse(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false\n if (\"code\" in error && error.code === \"EADDRINUSE\") return true\n return \"cause\" in error && addressInUse(error.cause)\n}\n\nfunction waitForStdinClose() {\n return Effect.callback<void>((resume) => {\n const close = () => resume(Effect.void)\n process.stdin.once(\"end\", close)\n process.stdin.once(\"close\", close)\n process.stdin.resume()\n if (process.stdin.readableEnded || process.stdin.destroyed) close()\n return Effect.sync(() => {\n process.stdin.off(\"end\", close)\n process.stdin.off(\"close\", close)\n process.stdin.pause()\n })\n })\n}\n",
"import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerProcess } from \"../../server-process\"\n\nexport default Runtime.handler(\n Commands.commands.serve,\n Effect.fnUntraced(function* (input) {\n if (input.service && input.stdio) return yield* Effect.fail(new Error(\"--service and --stdio cannot be combined\"))\n return yield* ServerProcess.run({\n mode: input.service ? \"service\" : input.stdio ? \"stdio\" : \"default\",\n hostname: Option.getOrUndefined(input.hostname),\n port: Option.getOrUndefined(input.port),\n })\n }),\n)\n"
],
"mappings": ";wqCAQA,2BAAS,qBAAa,oBACtB,yBAgBO,SAAM,OAAM,OAAO,gBAAW,cAAU,MAAC,OAAkB,MAChE,YAAO,WAAO,OAAc,MAAO,OAAE,UACnC,OAAO,aAAQ,OAAQ,UAAK,OAC5B,OAAO,aAAQ,OAAU,QAAQ,EAAU,MAAM,CAAC,EAAO,KAAM,EAAW,IAAI,CAAC,CAAC,CAAC,EACjF,EAAO,QAAQ,EAAa,KAAK,CACnC,EACD,EAEK,EAAgB,EAAO,WAAW,SAAU,CAAC,EAAkB,CACnE,GAAI,EAAQ,OAAS,UAAW,MAAO,EAAO,KAAK,IAAM,QAAQ,MAAM,EAAO,KAAK,IAAI,CAAC,EACxF,OAAO,MAAO,EAAO,OACnB,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAiB,EAAQ,OAAS,UAAY,MAAO,EAAc,QAAQ,EAAI,OAC/E,EAAS,EAAQ,OAAS,UAAY,MAAO,EAAc,KAAK,EAAI,CAAC,EACrE,EAAW,EAAQ,UAAY,EAAO,UAAY,YAClD,EAAO,EAAQ,MAAQ,EAAO,OAAS,EAAQ,OAAS,UAAY,EAAc,YAAY,EAAI,QACxG,GACE,IAAmB,QACnB,IAAS,SACR,MAAO,EAAQ,UAAU,IAAK,EAAgB,IAAK,EAAW,EAAU,CAAI,CAAE,CAAC,KAAO,OAEvF,OACF,IAAQ,SAAU,MAAO,EAAO,QAAQ,IAAa,wCAA8B,EAC7E,EAAsB,MAAO,EAAI,SAEvC,GAAI,EAAQ,OAAS,QACnB,OAAO,QAAQ,IAAI,kBACnB,OAAO,QAAQ,IAAI,yBAErB,IAAM,EACJ,EAAQ,OAAS,UACb,EAAO,UAAY,EAAY,EAAE,EAAE,SAAS,WAAW,EACvD,EACE,EAAS,MAAM,CAAmB,EAClC,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too big to display

{
"version": 3,
"sources": ["src/commands/handlers/service/set.ts"],
"sourcesContent": [
"import { Effect } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.set,\n Effect.fn(\"cli.service.set\")(function* (input) {\n yield* ServiceConfig.set(input.key, input.value)\n }),\n)\n"
],
"mappings": ";w6BAKA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,SACnC,OAAO,QAAG,sBAAiB,OAAE,cAAU,MAAC,OAAO,MAC7C,WAAO,OAAc,SAAI,OAAM,SAAK,OAAM,UAAK,OAChD,MACH",
"debugId": "FE13179BA904170764756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/service/status.ts"],
"sourcesContent": [
"import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.status,\n Effect.fn(\"cli.service.status\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover({ ...options, version: undefined })\n process.stdout.write((found?.url ?? \"stopped\") + EOL)\n }),\n)\n"
],
"mappings": ";g7BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,YACnC,OAAO,QAAG,yBAAoB,OAAE,cAAU,OAAG,MAC3C,SAAM,OAAU,WAAO,OAAc,aAAQ,OACvC,OAAQ,WAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,EACxE,QAAQ,OAAO,OAAO,GAAO,KAAO,WAAa,CAAG,EACrD,CACH",
"debugId": "CC277D17C559491464756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/auth/connect.ts"],
"sourcesContent": [
"import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type IntegrationCommandStatusOutput, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.connect,\n Effect.fn(\"cli.auth.connect\")(function* (input) {\n process.stdout.write(\"Connecting...\" + EOL + EOL)\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n yield* request(() => client.integration.wellknown.add({ url: input.url, location }))\n const integrationID = input.url.replace(/\\/+$/, \"\")\n const started = yield* request(() =>\n client.integration.command.connect({ integrationID, methodID: \"login\", location }),\n )\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.command.cancel({ integrationID, attemptID: started.data.attemptID, location }),\n ).pipe(Effect.ignore),\n )\n\n const status = yield* wait(client, integrationID, started.data.attemptID)\n if (status.status === \"failed\") return yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") return yield* Effect.fail(new Error(\"Authentication expired\"))\n process.stdout.write(\"Connected\" + EOL)\n }),\n)\n\nconst wait = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n shown = false,\n): Effect.Effect<Exclude<IntegrationCommandStatusOutput[\"data\"], { status: \"pending\" }>, unknown> =>\n Effect.gen(function* () {\n const response = yield* request(() => client.integration.command.status({ integrationID, attemptID, location }))\n if (response.data.status !== \"pending\") return response.data\n const output = response.data.message?.trim()\n if (!shown && output) process.stdout.write(output + EOL + EOL)\n yield* Effect.sleep(500)\n return yield* wait(client, integrationID, attemptID, shown || !!output)\n })\n\nfunction request<A>(task: () => Promise<A>) {\n return Effect.tryPromise({ try: task, catch: (cause) => cause })\n}\n"
],
"mappings": ";+9BAAA,mBAAS,gBAQT,SAAM,O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AS,KAAK,SAAS,KAAK,EAC3C,GAAI,CAAC,GAAS,EAAQ,QAAQ,OAAO,MAAM,EAAS,EAAM,CAAG,EAE7D,OADA,MAAO,EAAO,MAAM,GAAG,EAChB,MAAO,EAAK,EAAQ,EAAe,EAAW,GAAS,CAAC,CAAC,CAAM,EACvE,EAEH,SAAS,CAAU,CAAC,EAAwB,CAC1C,OAAO,EAAO,WAAW,CAAE,IAAK,EAAM,MAAO,CAAC,IAAU,CAAM,CAAC",
"debugId": "947D10DAB8650A7E64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/service/start.ts"],
"sourcesContent": [
"import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.start,\n Effect.fn(\"cli.service.start\")(function* () {\n const transport = yield* Service.ensure(yield* ServiceConfig.options())\n process.stdout.write(transport.url + EOL)\n }),\n)\n"
],
"mappings": ";g7BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,WACnC,OAAO,QAAG,wBAAmB,OAAE,cAAU,OAAG,MAC1C,SAAM,OAAY,WAAO,OAAQ,YAAO,WAAO,OAAc,aAAQ,CAAC,EACtE,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH",
"debugId": "00A04A3CEA35C11664756E2164756E21",
"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": ";g7BAMA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,UACnC,OAAO,QAAG,uBAAkB,OAAE,cAAU,OAAG,MACzC,WAAO,OAAQ,UAAK,WAAO,OAAc,aAAQ,MAAC,OACnD,MACH",
"debugId": "9975D56AADE8458964756E2164756E21",
"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": ";g7BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,aACnC,OAAO,QAAG,0BAAqB,OAAE,cAAU,OAAG,MAC5C,SAAM,OAAU,WAAO,OAAc,aAAQ,OAC7C,WAAO,OAAQ,KAAK,CAAO,EAC3B,IAAM,EAAY,MAAO,EAAQ,OAAO,CAAO,EAC/C,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH",
"debugId": "9F5C836C765FC37764756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["../simulation/src/frontend/actions.ts", "../simulation/src/recording.ts", "../simulation/src/frontend/renderer.ts", "../simulation/src/frontend/semantics.ts", "../simulation/src/frontend/server.ts", "../simulation/src/frontend/simulation.ts"],
"sourcesContent": [
"import { tmpdir } from \"node:os\"\nimport { extname, join, resolve } from \"node:path\"\nimport type { CliRenderer, Renderable } from \"@opentui/core\"\nimport {\n createMockKeys,\n createMockMouse,\n KeyCodes,\n type KeyInput,\n type MockInput,\n type MockMouse,\n} from \"@opentui/core/testing\"\nimport { Config, Effect, FileSystem, Schema } from \"effect\"\nimport { SimulationProtocol } from \"../protocol\"\nimport { SimulationRenderer } from \"./renderer\"\nimport { SimulationSemantics } from \"./semantics\"\n\nexport type Action = SimulationProtocol.Frontend.Action\nexport type Element = SimulationProtocol.Frontend.Element\n\nexport interface Harness {\n readonly renderer: CliRenderer\n readonly mockInput: MockInput\n readonly mockMouse: MockMouse\n readonly resize: (cols: number, rows: number) => void\n readonly renderOnce: () => Promise<void>\n readonly screen: () => string\n}\n\ntype RenderBuffer = {\n readonly width: number\n readonly height: number\n getRealCharBytes(includeAnsi?: boolean): Uint8Array\n}\n\nconst decoder = new TextDecoder()\n\nfunction isKeyCode(key: string): key is keyof typeof KeyCodes {\n return Object.hasOwn(KeyCodes, key)\n}\n\nfunction keyInput(key: string): KeyInput {\n const named = key.toUpperCase()\n return isKeyCode(named) ? named : key\n}\n\nfunction children(renderable: Renderable) {\n return renderable.getChildren().filter((child): child is Renderable => \"num\" in child)\n}\n\nfunction all(renderable: Renderable): Renderable[] {\n return [renderable, ...children(renderable).flatMap(all)]\n}\n\nfunction mouseListeners(renderable: Renderable) {\n const general = Reflect.get(renderable, \"_mouseListener\")\n const specific = Reflect.get(renderable, \"_mouseListeners\")\n return Boolean(general) || (specific && typeof specific === \"object\" && Object.keys(specific).length > 0)\n}\n\nfunction hit(renderer: CliRenderer, renderable: Renderable) {\n if (renderable.width <= 0 || renderable.height <= 0) return false\n const x = Math.floor(renderable.screenX + renderable.width / 2)\n const y = Math.floor(renderable.screenY + renderable.height / 2)\n const target = renderer.hitTest(x, y)\n return all(renderable).some((item) => item.num === target)\n}\n\n/**\n * Builds the harness the simulation server drives.\n *\n * When the renderer is the headless simulation renderer, its TestRendererSetup\n * provides the supported testing APIs. For the visible terminal renderer the\n * harness falls back to `requestRender` + `idle` and reading the private\n * `currentRenderBuffer`.\n */\nexport function createHarness(renderer: CliRenderer): Harness {\n const setup = SimulationRenderer.setupFor(renderer)\n return {\n renderer,\n mockInput: setup?.mockInput ?? createMockKeys(renderer),\n mockMouse: setup?.mockMouse ?? createMockMouse(renderer),\n resize: setup?.resize ?? ((cols, rows) => renderer.resize(cols, rows)),\n renderOnce:\n setup?.renderOnce ??\n (async () => {\n renderer.requestRender()\n await renderer.idle()\n }),\n // captureCharFrame follows the test renderer's output sink. Recording\n // redirects that sink to the timeline, so read the live render buffer\n // instead; it is also the source used by screenshots.\n screen: () => decoder.decode((Reflect.get(renderer, \"currentRenderBuffer\") as RenderBuffer).getRealCharBytes()),\n }\n}\n\nexport function elements(renderer: CliRenderer): Element[] {\n return all(renderer.root)\n .filter((renderable) => renderable.visible && !renderable.isDestroyed)\n .map((renderable) => {\n const clickable = mouseListeners(renderable) && hit(renderer, renderable)\n return {\n id: renderable.id,\n num: renderable.num,\n x: renderable.screenX,\n y: renderable.screenY,\n width: renderable.width,\n height: renderable.height,\n focusable: renderable.focusable,\n focused: renderable.focused,\n clickable,\n editor: renderer.currentFocusedEditor === renderable,\n } satisfies Element\n })\n .filter((element) => element.focusable || element.clickable || element.editor)\n}\n\nexport function state(harness: Harness) {\n return {\n focused: {\n renderable: harness.renderer.currentFocusedRenderable?.num,\n editor: Boolean(harness.renderer.currentFocusedEditor),\n },\n elements: elements(harness.renderer),\n }\n}\n\nexport function snapshot(harness: Harness): SimulationProtocol.Frontend.SemanticSnapshot {\n const ids = new Set<string>()\n const visit = (renderable: Renderable, parent?: string): SimulationProtocol.Frontend.SemanticNode[] => {\n if (!renderable.visible || renderable.isDestroyed) return []\n const definition = SimulationSemantics.read(renderable)?.()\n if (definition && ids.has(renderable.id)) throw new Error(`duplicate semantic UI id: ${renderable.id}`)\n if (definition) ids.add(renderable.id)\n const node = definition\n ? [{ id: renderable.id, ...definition, ...(parent === undefined ? {} : { parent }), element: renderable.num }]\n : []\n const ancestor = definition ? renderable.id : parent\n return [...node, ...children(renderable).flatMap((child) => visit(child, ancestor))]\n }\n return Schema.decodeUnknownSync(SimulationProtocol.Frontend.SemanticSnapshot)({\n format: \"opencode-ui-snapshot-v1\",\n nodes: visit(harness.renderer.root),\n })\n}\n\nexport function matches(harness: Pick<Harness, \"screen\">, text: string) {\n return harness.screen().includes(text)\n}\n\nexport const capture = Effect.fn(\"SimulationActions.capture\")(function* (harness: Harness) {\n yield* Effect.tryPromise(() => harness.renderOnce())\n const buffer = harness.renderer.currentRenderBuffer\n return {\n cols: buffer.width,\n rows: buffer.height,\n cursor: [0, 0] as const,\n lines: buffer.getSpanLines().map((line) => ({\n spans: line.spans.map((span) => ({\n text: span.text,\n fg: span.fg.toInts(),\n bg: span.bg.toInts(),\n attributes: span.attributes,\n width: span.width,\n })),\n })),\n } satisfies SimulationProtocol.Frontend.CapturedFrame\n})\n\nexport const screenshot = Effect.fn(\"SimulationActions.screenshot\")(function* (harness: Harness, name?: string) {\n const filename = name ?? `screenshot-${crypto.randomUUID()}`\n if (!filename || filename.includes(\"/\") || filename.includes(\"\\\\\") || extname(filename))\n return yield* Effect.fail(new Error(\"screenshot name must not contain a path or extension\"))\n yield* Effect.tryPromise(() => harness.renderOnce())\n const { SimulationPng } = yield* Effect.promise(() => import(\"./png\"))\n const image = SimulationPng.screenshot(harness.renderer)\n const directory = resolve(\n yield* Config.string(\"OPENCODE_DRIVE_MEDIA_DIR\").pipe(\n Config.withDefault(join(tmpdir(), \"opencode-drive\", \"output\")),\n ),\n )\n const fs = yield* FileSystem.FileSystem\n yield* fs.makeDirectory(directory, { recursive: true })\n const path = join(directory, `${filename}.png`)\n yield* fs.writeFile(path, image.data)\n return path\n})\n\nexport const execute = Effect.fn(\"SimulationActions.execute\")(function* (harness: Harness, action: Action) {\n switch (action.type) {\n case \"ui.type\":\n yield* Effect.tryPromise(() => harness.mockInput.typeText(action.text))\n break\n case \"ui.press\":\n harness.mockInput.pressKey(keyInput(action.key), action.modifiers)\n break\n case \"ui.enter\":\n harness.mockInput.pressEnter()\n break\n case \"ui.arrow\":\n harness.mockInput.pressArrow(action.direction)\n break\n case \"ui.focus\":\n all(harness.renderer.root)\n .find((item) => item.num === action.target)\n ?.focus()\n break\n case \"ui.click\": {\n const target = all(harness.renderer.root).find((item) => item.num === action.target)\n if (!target || !target.visible || target.isDestroyed)\n return yield* Effect.fail(new Error(`click target is stale or unavailable: ${action.target}`))\n if (action.semantic) {\n const current = snapshot(harness).nodes.find((node) => node.element === action.target)\n if (\n current?.id !== action.semantic.id ||\n current.instance !== action.semantic.instance ||\n current.element !== action.semantic.element\n )\n return yield* Effect.fail(new Error(`semantic click target is stale or unavailable: ${action.semantic.id}`))\n }\n if (\n !Number.isFinite(action.x) ||\n action.x < 0 ||\n action.x >= target.width ||\n !Number.isFinite(action.y) ||\n action.y < 0 ||\n action.y >= target.height\n )\n return yield* Effect.fail(new Error(\"click position must be within the target element\"))\n yield* Effect.tryPromise(() => harness.mockMouse.click(target.screenX + action.x, target.screenY + action.y))\n break\n }\n case \"ui.resize\":\n if (\n !Number.isSafeInteger(action.cols) ||\n action.cols <= 0 ||\n !Number.isSafeInteger(action.rows) ||\n action.rows <= 0\n ) {\n return yield* Effect.fail(new Error(\"resize cols and rows must be positive integers\"))\n }\n harness.resize(action.cols, action.rows)\n SimulationRenderer.recordResize(harness.renderer, action.cols, action.rows)\n break\n }\n yield* Effect.tryPromise(() => harness.renderOnce())\n return state(harness)\n})\n\nexport * as SimulationActions from \"./actions\"\n",
"import { createWriteStream, type WriteStream } from \"node:fs\"\nimport { mkdir } from \"node:fs/promises\"\nimport { dirname } from \"node:path\"\nimport { Writable } from \"node:stream\"\nimport { finished } from \"node:stream/promises\"\nimport { Schema } from \"effect\"\n\nexport const Header = Schema.Struct({\n type: Schema.Literal(\"header\"),\n version: Schema.Literal(1),\n cols: Schema.Number,\n rows: Schema.Number,\n encoding: Schema.Literal(\"base64\"),\n})\nexport interface Header extends Schema.Schema.Type<typeof Header> {}\n\nexport const Output = Schema.Struct({\n type: Schema.Literal(\"output\"),\n at_ms: Schema.Number,\n data: Schema.String,\n})\nexport interface Output extends Schema.Schema.Type<typeof Output> {}\n\nexport const Resize = Schema.Struct({\n type: Schema.Literal(\"resize\"),\n at_ms: Schema.Number,\n cols: Schema.Number,\n rows: Schema.Number,\n})\nexport interface Resize extends Schema.Schema.Type<typeof Resize> {}\n\nexport const Event = Schema.Union([Header, Output, Resize])\nexport type Event = Schema.Schema.Type<typeof Event>\n\nexport class Timeline extends Writable {\n readonly isTTY = true\n readonly path: string\n readonly columns: number\n readonly rows: number\n private readonly output: WriteStream\n private readonly started = performance.now()\n private readonly timestamps: number[] = []\n private done?: Promise<string>\n\n private constructor(path: string, cols: number, rows: number, output: WriteStream) {\n super()\n this.path = path\n this.columns = cols\n this.rows = rows\n this.output = output\n // finish() reports stream failures; keep Writable from also throwing them process-wide.\n this.on(\"error\", () => {})\n output.on(\"error\", (error) => this.destroy(error))\n }\n\n static async create(path: string, cols: number, rows: number) {\n await mkdir(dirname(path), { recursive: true })\n const output = createWriteStream(path)\n const timeline = new Timeline(path, cols, rows, output)\n await new Promise<void>((resolve, reject) => {\n output.write(\n `${JSON.stringify({ type: \"header\", version: 1, cols, rows, encoding: \"base64\" } satisfies Header)}\\n`,\n (error) => (error ? reject(error) : resolve()),\n )\n })\n return timeline\n }\n\n getColorDepth() {\n return 24\n }\n\n override write(chunk: unknown, callback?: (error?: Error | null) => void): boolean\n override write(chunk: unknown, encoding: BufferEncoding, callback?: (error?: Error | null) => void): boolean\n override write(\n chunk: unknown,\n encoding?: BufferEncoding | ((error?: Error | null) => void),\n callback?: (error?: Error | null) => void,\n ) {\n if (!this.writableEnded) {\n this.timestamps.push(this.elapsed())\n if (typeof encoding === \"function\") return super.write(chunk, encoding)\n if (encoding === undefined) return super.write(chunk, callback)\n return super.write(chunk, encoding, callback)\n }\n const done = typeof encoding === \"function\" ? encoding : callback\n queueMicrotask(() => done?.(null))\n return true\n }\n\n override _write(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null) => void) {\n this.writeOutput(chunk, this.timestamps.shift() ?? this.elapsed(), callback)\n }\n\n override _final(callback: (error?: Error | null) => void) {\n this.writeOutput(Buffer.alloc(0), this.elapsed(), (error) => {\n if (error) return callback(error)\n this.output.end(callback)\n })\n }\n\n finish() {\n if (this.done) return this.done\n this.end()\n this.done = finished(this).then(() => this.path)\n return this.done\n }\n\n resize(cols: number, rows: number) {\n if (this.writableEnded) return\n const event = { type: \"resize\", at_ms: this.elapsed(), cols, rows } satisfies Resize\n this.output.write(`${JSON.stringify(event)}\\n`)\n }\n\n private elapsed() {\n return Math.max(0, Math.round(performance.now() - this.started))\n }\n\n private writeOutput(data: Buffer, at_ms: number, callback: (error?: Error | null) => void) {\n const event = {\n type: \"output\",\n at_ms,\n data: data.toString(\"base64\"),\n } satisfies Output\n this.output.write(`${JSON.stringify(event)}\\n`, callback)\n }\n}\n\nexport * as SimulationRecording from \"./recording\"\n",
"import type { CliRenderer, CliRendererConfig } from \"@opentui/core\"\nimport { createTestRenderer, type TestRendererSetup } from \"@opentui/core/testing\"\nimport { Effect } from \"effect\"\nimport { Timeline } from \"../recording\"\n\nconst setups = new WeakMap<CliRenderer, TestRendererSetup>()\nconst recordings = new WeakMap<CliRenderer, Timeline>()\n\n/**\n * Creates a headless renderer with optional recording: a real CliRenderer\n * backed by an in-memory screen buffer. The TestRendererSetup is kept\n * module-side so the harness can use supported testing APIs without app\n * code carrying it around.\n */\nexport interface Viewport {\n readonly cols: number\n readonly rows: number\n}\n\nexport const create = Effect.fn(\"SimulationRenderer.create\")(function* (\n options: CliRendererConfig,\n path?: string,\n viewport?: Viewport,\n) {\n const cols = viewport?.cols ?? 100\n const rows = viewport?.rows ?? 40\n const recording = path\n ? yield* Effect.acquireRelease(\n Effect.tryPromise(() => Timeline.create(path, cols, rows)),\n (recording) =>\n Effect.tryPromise(() => recording.finish()).pipe(\n Effect.catch((error) =>\n Effect.sync(() => process.stderr.write(`Failed to finish UI recording: ${error}\\n`)),\n ),\n ),\n )\n : undefined\n const setup = yield* Effect.acquireRelease(\n Effect.tryPromise(() =>\n createTestRenderer({\n ...options,\n width: cols,\n height: rows,\n ...(recording\n ? {\n stdout: recording as unknown as NodeJS.WriteStream,\n bufferedOutput: \"stdout\" as const,\n }\n : {}),\n }),\n ),\n (setup) =>\n Effect.sync(() => {\n if (!setup.renderer.isDestroyed) setup.renderer.destroy()\n }),\n )\n setups.set(setup.renderer, setup)\n if (recording) recordings.set(setup.renderer, recording)\n return setup.renderer\n})\n\nexport function recordResize(renderer: CliRenderer, cols: number, rows: number) {\n recordings.get(renderer)?.resize(cols, rows)\n}\n\nexport function setupFor(renderer: CliRenderer): TestRendererSetup | undefined {\n return setups.get(renderer)\n}\n\nexport function finish(renderer: CliRenderer) {\n const recording = recordings.get(renderer)\n if (!recording) return Effect.fail(new Error(\"UI recording is not available\"))\n return Effect.tryPromise(() => recording.finish())\n}\n\nexport * as SimulationRenderer from \"./renderer\"\n",
"import type { Renderable } from \"@opentui/core\"\nimport type { SimulationProtocol } from \"../protocol\"\n\n// Semantic renderables set an explicit stable OpenTUI id so ui.state and\n// ui.snapshot expose the same identity. Hierarchy and element handles come\n// from the live render tree.\nexport type Definition = Omit<SimulationProtocol.Frontend.SemanticNode, \"id\" | \"element\" | \"parent\">\n\nconst key = Symbol.for(\"opencode.simulation.semantics\")\n\nconst bind = (definition: () => Definition) => (renderable: Renderable) => {\n Object.defineProperty(renderable, key, { value: definition, configurable: true })\n}\n\nexport const read = (renderable: Renderable) => {\n const definition: unknown = Reflect.get(renderable, key)\n return typeof definition === \"function\" ? (definition as () => Definition) : undefined\n}\n\nexport const SimulationSemantics = { bind, read }\n",
"import { InstallationVersion } from \"@opencode-ai/core/installation/version\"\nimport { Effect } from \"effect\"\nimport { SimulationControlServer } from \"../control-server\"\nimport { SimulationProtocol } from \"../protocol\"\nimport { SimulationActions, type Harness } from \"./actions\"\nimport { SimulationRenderer } from \"./renderer\"\n\nfunction handle(harness: Harness, request: SimulationProtocol.Frontend.Request) {\n switch (request.method) {\n case \"simulation.handshake\":\n return SimulationProtocol.Handshake.dispatch(\n {\n role: \"ui\",\n server: { name: \"opencode\", version: InstallationVersion },\n capabilities: SimulationProtocol.Frontend.Capabilities,\n },\n request.params,\n )\n case \"ui.capture\":\n return SimulationActions.capture(harness)\n case \"ui.screenshot\":\n return SimulationActions.screenshot(harness, request.params?.name)\n case \"ui.state\":\n return Effect.sync(() => SimulationActions.state(harness))\n case \"ui.snapshot\":\n return Effect.sync(() => SimulationActions.snapshot(harness))\n case \"ui.matches\":\n return Effect.sync(() => SimulationActions.matches(harness, request.params.text))\n case \"ui.recording.finish\":\n return SimulationRenderer.finish(harness.renderer)\n case \"ui.type\":\n return SimulationActions.execute(harness, { type: \"ui.type\", text: request.params.text })\n case \"ui.enter\":\n return SimulationActions.execute(harness, { type: \"ui.enter\" })\n case \"ui.press\":\n return SimulationActions.execute(harness, {\n type: \"ui.press\",\n key: request.params.key,\n modifiers: request.params.modifiers,\n })\n case \"ui.arrow\":\n return SimulationActions.execute(harness, { type: \"ui.arrow\", direction: request.params.direction })\n case \"ui.focus\":\n return SimulationActions.execute(harness, { type: \"ui.focus\", target: request.params.target })\n case \"ui.click\":\n return SimulationActions.execute(harness, {\n type: \"ui.click\",\n target: request.params.target,\n x: request.params.x,\n y: request.params.y,\n semantic: request.params.semantic,\n })\n case \"ui.resize\":\n return SimulationActions.execute(harness, {\n type: \"ui.resize\",\n cols: request.params.cols,\n rows: request.params.rows,\n })\n }\n}\n\nexport const start = Effect.fn(\"SimulationServer.start\")(function* (harness: Harness, endpoint: string) {\n return yield* SimulationControlServer.start({\n endpoint,\n label: \"opencode drive ui websocket\",\n data: () => ({ drive: true as const }),\n decode: SimulationProtocol.Frontend.decodeRequestEffect,\n handle: (_socket, request) => handle(harness, request),\n })\n})\n\nexport * as SimulationServer from \"./server\"\n",
"import { createCliRenderer, type CliRendererConfig } from \"@opentui/core\"\nimport { Config, Effect } from \"effect\"\nimport { DriveManifest } from \"../manifest\"\nimport { SimulationActions } from \"./actions\"\nimport { SimulationRenderer } from \"./renderer\"\nimport { SimulationServer } from \"./server\"\n\n/** Drive-mode renderer and control-server acquisition. */\nexport const create = Effect.fn(\"Drive.create\")(function* (options: CliRendererConfig) {\n const headless = (yield* Config.string(\"OPENCODE_DRIVE_RENDERER\").pipe(Config.withDefault(\"visible\"))) === \"headless\"\n const manifest = yield* DriveManifest.resolve()\n const renderer = headless\n ? yield* SimulationRenderer.create(options, manifest.recording?.timeline, manifest.viewport)\n : yield* Effect.acquireRelease(\n Effect.tryPromise(() => createCliRenderer(options)),\n (renderer) =>\n Effect.sync(() => {\n if (!renderer.isDestroyed) renderer.destroy()\n }),\n )\n if (!headless && manifest.viewport) renderer.resize(manifest.viewport.cols, manifest.viewport.rows)\n const server = yield* SimulationServer.start(SimulationActions.createHarness(renderer), manifest.endpoints.ui)\n yield* Effect.sync(() => process.stderr.write(`opencode drive ui websocket: ${server.url}\\n`))\n return renderer\n})\n\nexport * as Drive from \"./simulation\"\n"
],
"mappings": ";6pBAAA,sBAAS,iBACT,uBAAS,gBAAS,kBAAM,wHCDxB,iCAAS,gBACT,gBAAS,oBACT,kBAAS,aACT,mBAAS,eACT,mBAAS,wBAGF,IAAM,EAAS,EAAO,OAAO,CAClC,KAAM,EAAO,QAAQ,QAAQ,EAC7B,QAAS,EAAO,QAAQ,CAAC,EACzB,KAAM,EAAO,OACb,KAAM,EAAO,OACb,SAAU,EAAO,QAAQ,QAAQ,CACnC,CAAC,EAGY,EAAS,EAAO,OAAO,CAClC,KAAM,EAAO,QAAQ,QAAQ,EAC7B,MAAO,EAAO,OACd,KAAM,EAAO,MACf,CAAC,EAGY,EAAS,EAAO,OAAO,CAClC,KAAM,EAAO,QAAQ,QAAQ,EAC7B,MAAO,EAAO,OACd,KAAM,EAAO,OACb,KAAM,EAAO,MACf,CAAC,EAGY,GAAQ,EAAO,MAAM,CAAC,EAAQ,EAAQ,CAAM,CAAC,EAGnD,MAAM,UAAiB,CAAS,CAC5B,MAAQ,GACR,KACA,QACA,K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ources": ["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": ";miCAAA,mBAAS,gBAOT,SAAM,OAAU,SAAI,SAAI,MAAC,cAAU,WAAO,YAAQ,eAAW,aAAS,YAAQ,UAAK,MAAC,OAUrE,SAAQ,aACrB,OAAS,cAAS,SAClB,OAAO,QAAG,cAAS,OAAE,cAAU,MAAC,OAAO,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,wCAAwC,GA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AO,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": "48DC36782F40907D64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/mini.ts", "src/mini-host.ts"],
"sourcesContent": [
"import { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { setTimeout } from \"node:timers/promises\"\nimport { ServerConnection } from \"./services/server-connection\"\nimport { waitForCatalogReady } from \"./services/catalog\"\nimport { readStdin } from \"./util/io\"\nimport { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from \"./mini-host\"\n\nexport type MiniCommandInput = {\n server: ServerConnection.Resolved\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}\n\ntype Session = Awaited<ReturnType<OpenCodeClient[\"session\"][\"get\"]>>\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 sdk = OpenCode.make({\n baseUrl: input.server.endpoint.url,\n headers: Service.headers(input.server.endpoint),\n })\n const model = parseModel(input.model)\n let agentTask: Promise<string | undefined> | undefined\n const resolveAgent = () => {\n agentTask ??= validateAgent(sdk, directory, input.agent)\n return agentTask\n }\n const resolveSession = async () => {\n const [agent, selected] = await Promise.all([resolveAgent(), selectSession(sdk, directory, input)])\n const readyModel =\n model ?? (selected?.model ? { providerID: selected.model.providerID, modelID: selected.model.id } : undefined)\n if (readyModel) await waitForCatalogReady({ sdk, directory, model: readyModel })\n const session = selected ?? (await createSession(sdk, directory, agent, model))\n return { id: session.id, title: session.title, resume: selected !== undefined }\n }\n const create = (\n _sdk: OpenCodeClient,\n next: { agent: string | undefined; model: Model; variant: string | undefined },\n ) => createSession(sdk, directory, next.agent, next.model, next.variant)\n const frontend = await frontendTask\n return frontend.runMiniFrontend({\n host: createMiniHost({ terminal, directory }),\n sdk,\n directory,\n resolveAgent,\n session: resolveSession,\n createSession: create,\n agent: input.agent,\n model,\n variant: undefined,\n files: [],\n initialInput,\n thinking: true,\n replay: input.replay ?? true,\n replayLimit: input.replayLimit,\n demo: input.demo,\n tuiConfig: input.tuiConfig,\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\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): Model {\n if (!value) return\n const [providerID, ...rest] = value.split(\"/\")\n const modelID = rest.join(\"/\")\n if (!providerID || !modelID) throw new MiniInputError(\"--model must use the format provider/model\")\n return { providerID, modelID }\n}\n\nasync function validateAgent(sdk: OpenCodeClient, directory: string, name?: string) {\n if (!name) return\n const deadline = Date.now() + 5_000\n let agents: Awaited<ReturnType<OpenCodeClient[\"agent\"][\"list\"]>> | undefined\n while (Date.now() < deadline) {\n agents = await sdk.agent.list({ location: { directory } }).catch(() => undefined)\n const agent = agents?.data.find((item) => item.id === name)\n if (agent?.mode === \"subagent\") {\n warning(`agent \"${name}\" is a subagent, not a primary agent. Falling back to default agent`)\n return\n }\n if (agent) return name\n await setTimeout(25)\n }\n if (!agents) {\n warning(\"failed to list agents. Falling back to default agent\")\n return\n }\n warning(`agent \"${name}\" not found. Falling back to default agent`)\n}\n\nasync function selectSession(sdk: OpenCodeClient, directory: string, input: MiniCommandInput, preselected?: Session) {\n const selected =\n preselected ??\n (input.session\n ? await sdk.session.get({ sessionID: input.session }).catch(() => undefined)\n : input.continue\n ? await sdk.session\n .list({ directory, parentID: null, limit: 1, order: \"desc\" })\n .then((result) => result.data[0])\n : undefined)\n if (input.session && !selected) throw new MiniInputError(\"Session not found\")\n if (!selected) return\n if (!input.fork) return selected\n return sdk.session.fork({ sessionID: selected.id })\n}\n\nasync function createSession(\n sdk: OpenCodeClient,\n directory: string,\n agent: string | undefined,\n model: Model,\n variant?: string,\n): Promise<Session> {\n if (model) await waitForCatalogReady({ sdk, directory, model })\n return sdk.session.create({\n agent,\n model: model ? { providerID: model.providerID, id: model.modelID, variant } : undefined,\n location: { directory },\n })\n}\n\nfunction warning(message: string) {\n process.stderr.write(`\\x1b[93m\\x1b[1m!\\x1b[0m ${message}\\n`)\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 { Flag } from \"@opencode-ai/core/flag/flag\"\nimport { Global } from \"@opencode-ai/core/global\"\nimport fs from \"node:fs\"\nimport { mkdir, readFile, writeFile } 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\"]\ntype ModelState = Record<string, unknown> & {\n variant?: Record<string, string | undefined>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value)\n}\n\nfunction state(value: unknown): ModelState {\n if (!isRecord(value)) return {}\n const variant = isRecord(value.variant)\n ? Object.fromEntries(\n Object.entries(value.variant).flatMap(([key, item]) =>\n typeof item === \"string\" ? ([[key, item]] as const) : [],\n ),\n )\n : undefined\n return { ...value, variant }\n}\n\nfunction variantKey(model: NonNullable<MiniFrontendInput[\"model\"]>) {\n return `${model.providerID}/${model.modelID}`\n}\n\nfunction preferences(statePath: string): MiniHost[\"preferences\"] {\n const file = path.join(statePath, \"model.json\")\n const read = () =>\n readFile(file, \"utf8\")\n .then((value) => state(JSON.parse(value)))\n .catch(() => state(undefined))\n return {\n async resolveVariant(model) {\n if (!model) return\n return (await read()).variant?.[variantKey(model)]\n },\n async saveVariant(model, variant) {\n if (!model) return\n const current = await read()\n const next = { ...current.variant }\n if (variant) next[variantKey(model)] = variant\n if (!variant) delete next[variantKey(model)]\n await mkdir(path.dirname(file), { recursive: true })\n .then(() => writeFile(file, JSON.stringify({ ...current, variant: next }, null, 2)))\n .catch(() => {})\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: Pick<MiniHost[\"diagnostics\"], \"pid\" | \"cwd\" | \"argv\">,\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?: MiniHost[\"paths\"]\n}): MiniHost {\n const paths = input.paths ?? {\n home: Global.Path.home,\n state: Global.Path.state,\n log: Global.Path.log,\n }\n const diagnostics = {\n pid: process.pid,\n cwd: input.directory,\n argv: process.argv.slice(2),\n }\n return {\n terminal: input.terminal,\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,\n signals: {\n sigint: signal(\"SIGINT\"),\n sigusr2: signal(\"SIGUSR2\"),\n },\n startup: {\n showTiming: Flag.OPENCODE_SHOW_TTFD,\n now: () => performance.now(),\n },\n diagnostics: {\n ...diagnostics,\n trace: createTrace(paths.log, diagnostics),\n },\n preferences: preferences(paths.state),\n }\n}\n"
],
"mappings": ";4tBAGA,0BAAS,6BCAT,uBACA,qBAAS,mBAAO,oBAAU,yBAC1B,yBACA,0BAAS,iBAEF,SAAM,OAA0B,+DAYvC,cAAS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ts-ignore Bun embeds static file imports when compiling the CLI.\nimport photonWasm from \"@silvia-odwyer/photon-node/photon_rs_bg.wasm\" with { type: \"file\" }\n\nexport default photonWasm\n",
"import photonWasm from \"#photon-wasm\"\nimport { Effect } from \"effect\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { FileSystem } from \"../filesystem\"\nimport { DecodeError, ResizerUnavailableError, SizeError } from \"../image\"\n\nconst JPEG_QUALITIES = [80, 85, 70, 55, 40]\n\nexport const make = Effect.gen(function* () {\n ;(globalThis as typeof globalThis & { __OPENCODE_PHOTON_WASM_PATH?: string }).__OPENCODE_PHOTON_WASM_PATH =\n path.isAbsolute(photonWasm) ? photonWasm : fileURLToPath(new URL(photonWasm, import.meta.url))\n const loadPhoton = yield* Effect.cached(\n Effect.tryPromise({\n try: () => import(\"@silvia-odwyer/photon-node\"),\n catch: () => new ResizerUnavailableError(),\n }),\n )\n return Effect.fn(\"Image.Photon.normalize\")(function* (\n resource: string,\n content: FileSystem.Content & { readonly encoding: \"base64\" },\n limits: {\n readonly autoResize: boolean\n readonly maxWidth: number\n readonly maxHeight: number\n readonly maxBase64Bytes: number\n },\n ) {\n const photon = yield* loadPhoton\n const decoded = yield* Effect.try({\n try: () => photon.PhotonImage.new_from_byteslice(Buffer.from(content.content, \"base64\")),\n catch: () => new DecodeError({ resource }),\n })\n try {\n const width = decoded.get_width()\n const height = decoded.get_height()\n const bytes = Buffer.byteLength(content.content, \"utf-8\")\n if (width <= limits.maxWidth && height <= limits.maxHeight && bytes <= limits.maxBase64Bytes) return content\n if (!limits.autoResize)\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n const scale = Math.min(1, limits.maxWidth / width, limits.maxHeight / height)\n const sizes = Array.from({ length: 32 }).reduce<Array<{ width: number; height: number }>>((acc) => {\n const previous = acc.at(-1) ?? {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n const next =\n acc.length === 0\n ? previous\n : {\n width: previous.width === 1 ? 1 : Math.max(1, Math.floor(previous.width * 0.75)),\n height: previous.height === 1 ? 1 : Math.max(1, Math.floor(previous.height * 0.75)),\n }\n return acc.some((item) => item.width === next.width && item.height === next.height) ? acc : [...acc, next]\n }, [])\n for (const size of sizes) {\n const resized = photon.resize(decoded, size.width, size.height, photon.SamplingFilter.Lanczos3)\n try {\n const encoders: Array<readonly [mime: string, encode: () => Uint8Array]> = [\n [\"image/png\", () => resized.get_bytes()],\n ...JPEG_QUALITIES.map((quality) => [\"image/jpeg\", () => resized.get_bytes_jpeg(quality)] as const),\n ]\n for (const [mime, encode] of encoders) {\n const candidate = Buffer.from(encode()).toString(\"base64\")\n if (Buffer.byteLength(candidate, \"utf-8\") <= limits.maxBase64Bytes)\n return { ...content, content: candidate, encoding: \"base64\" as const, mime }\n }\n } finally {\n resized.free()\n }\n }\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n } finally {\n decoded.free()\n }\n })\n})\n"
],
"mappings": ";i4BAGA,SAAe,SCDf,yBACA,6BAAS,iBAIT,SAAM,OAAiB,MAAC,QAAI,QAAI,QAAI,QAAI,OAAE,OAE7B,OAAO,OAAO,SAAI,cAAU,OAAG,MACxC,gBAA4E,iCAC5E,OAAK,yBAAW,CAAU,EAAI,EAAa,EAAc,IAAI,IAAI,EAAY,YAAY,GAAG,CAAC,EAC/F,IAAM,EAAa,MAAO,EAAO,OAC/B,EAAO,WAAW,CAChB,IAAK,IAAa,yCAClB,MAAO,IAAM,IAAI,CACnB,CAAC,CACH,EACA,OAAO,EAAO,GAAG,wBAAwB,EAAE,SAAU,CACnD,EACA,EACA,EAMA,CACA,IAAM,EAAS,MAAO,EAChB,EAAU,MAAO,EAAO,IAAI,CAChC,IAAK,IAAM,EAAO,YAAY,mBA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ACF,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": "E3341830881B8A9D64756E2164756E21",
"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/core/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 configPath = yield* Effect.promise(() => resolveConfigPath(input.global ? Global.Path.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": ";i4BAAA,mBAAS,gBACT,yBACA,wBAAS,eAAU,oBAAM,yBAOzB,SAAe,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,SAC/B,OAAO,QAAG,kBAAa,OAAE,cAAU,MAAC,OAAO,MACzC,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,EAA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,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": "F68950AA96805D4C64756E2164756E21",
"names": []
}

Sorry, the diff of this file is too big to display

{
"version": 3,
"sources": ["src/commands/handlers/run.ts"],
"sourcesContent": [
"import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(Commands.commands.run, (input) =>\n Effect.gen(function* () {\n const { runNonInteractive } = yield* Effect.promise(() => import(\"../../run/run\"))\n const separator = process.argv.indexOf(\"--\", 2)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n yield* Effect.promise(() =>\n runNonInteractive({\n server,\n message: [...input.message, ...(separator === -1 ? [] : process.argv.slice(separator + 1))],\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n format: input.format,\n file: [...input.file],\n title: Option.getOrUndefined(input.title),\n thinking: input.thinking,\n auto: input.auto || input.yolo,\n }),\n )\n }),\n)\n"
],
"mappings": ";miCAKA,SAAe,SAAQ,aAAQ,OAAS,cAAS,SAAK,MAAC,SACrD,OAAO,SAAI,cAAU,OAAG,MACtB,SAAQ,0BAAsB,WAAO,OAAO,aAAQ,SAAa,wCAAgB,OAC3E,OAAY,aAAQ,UAAK,aAAQ,UAAM,MAAC,OACxC,OAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACD,MAAO,EAAO,QAAQ,IACpB,EAAkB,CAChB,SACA,QAAS,CAAC,GAAG,EAAM,QAAS,GAAI,IAAc,GAAK,CAAC,EAAI,QAAQ,KAAK,MAAM,EAAY,CAAC,CAAE,EAC1F,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAM,OACd,KAAM,CAAC,GAAG,EAAM,IAAI,EACpB,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,SAAU,EAAM,SAChB,KAAM,EAAM,MAAQ,EAAM,IAC5B,CAAC,CACH,EACD,CACH",
"debugId": "FAE95A7B71F833B564756E2164756E21",
"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 options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.mcp.list({ location: { directory: process.cwd() } }))\n const servers = response.data.toSorted((a, b) => a.name.localeCompare(b.name))\n if (servers.length === 0) {\n process.stdout.write(\"No MCP servers configured\" + EOL)\n return\n }\n const width = Math.max(...servers.map((server) => server.name.length))\n const lines = servers.map(\n (server) => `${icon(server.status)} ${server.name.padEnd(width)} ${describe(server.status)}`,\n )\n process.stdout.write(lines.join(EOL) + EOL)\n }),\n)\n\nfunction icon(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"connected\":\n return \"✓\"\n case \"needs_auth\":\n return \"⚠\"\n case \"failed\":\n case \"needs_client_registration\":\n return \"✗\"\n default:\n return \"○\"\n }\n}\n\nfunction describe(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"needs_auth\":\n return \"needs authentication\"\n case \"needs_client_registration\":\n return `needs client registration: ${status.error}`\n case \"failed\":\n return `failed: ${status.error}`\n default:\n return status.status\n }\n}\n"
],
"mappings": ";+9BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,UAC/B,OAAO,QAAG,mBAAc,OAAE,cAAU,OAAG,MACrC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,QADQ,WAAO,OAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,IAAI,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAC/E,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC,EAC7E,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,4BAA8B,CAAG,EACtD,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAQ,IAAI,CAAC,IAAW,EAAO,KAAK,MAAM,CAAC,EAC/D,EAAQ,EAAQ,IACpB,CAAC,IAAW,GAAG,EAAK,EAAO,MAAM,KAAK,EAAO,KAAK,OAAO,CAAK,MAAM,EAAS,EAAO,MAAM,GAC5F,EACA,QAAQ,OAAO,MAAM,EAAM,KAAK,CAAG,EAAI,CAAG,EAC3C,CACH,EAEA,SAAS,CAAI,CAAC,EAA6B,CACzC,OAAQ,EAAO,YACR,YACH,MAAO,aACJ,aACH,MAAO,aACJ,aACA,4BACH,MAAO,iBAEP,MAAO,UAIb,SAAS,CAAQ,CAAC,EAA6B,CAC7C,OAAQ,EAAO,YACR,aACH,MAAO,2BACJ,4BACH,MAAO,8BAA8B,EAAO,YACzC,SACH,MAAO,WAAW,EAAO,gBAEzB,OAAO,EAAO",
"debugId": "089E3393F50D1E5C64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/mini.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.mini, (input) =>\n Effect.gen(function* () {\n const { runMini, validateMiniTerminal } = yield* Effect.promise(() => import(\"../../mini\"))\n yield* Effect.promise(async () => validateMiniTerminal())\n const serverURL = Option.getOrUndefined(input.server)\n const server = yield* ServerConnection.resolve({ server: serverURL, standalone: input.standalone })\n yield* Effect.promise(() =>\n runMini({\n server,\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n prompt: Option.getOrUndefined(input.prompt),\n replay: input.replay,\n replayLimit: Option.getOrUndefined(input.replayLimit),\n demo: input.demo,\n }),\n )\n }),\n)\n"
],
"mappings": ";miCAKA,SAAe,SAAQ,aAAQ,OAAS,cAAS,UAAM,MAAC,SACtD,OAAO,SAAI,cAAU,OAAG,MACtB,SAAQ,eAAS,6BAAyB,WAAO,OAAO,aAAQ,SAAa,wCAAa,OAC1F,WAAO,OAAO,aAAQ,cAAY,OAAqB,MAAC,OACxD,IAAM,EAAY,EAAO,eAAe,EAAM,MAAM,EAC9C,EAAS,MAAO,EAAiB,QAAQ,CAAE,OAAQ,EAAW,WAAY,EAAM,UAAW,CAAC,EAClG,MAAO,EAAO,QAAQ,IACpB,EAAQ,CACN,SACA,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,OAAQ,EAAM,OACd,YAAa,EAAO,eAAe,EAAM,WAAW,EACpD,KAAM,EAAM,IACd,CAAC,CACH,EACD,CACH",
"debugId": "D60299196D163B3E64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/plugin/list.ts"],
"sourcesContent": [
"import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.list,\n Effect.fn(\"cli.plugin.list\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.plugin.list({ location: { directory: process.cwd() } }))\n const plugins = response.data.toSorted((a, b) => a.id.localeCompare(b.id))\n if (plugins.length === 0) {\n process.stdout.write(\"No plugins loaded\" + EOL)\n return\n }\n process.stdout.write(plugins.map((plugin) => plugin.id).join(EOL) + EOL)\n }),\n)\n"
],
"mappings": ";+9BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,YAAO,cAAS,UAClC,OAAO,QAAG,sBAAiB,OAAE,cAAU,OAAG,MACxC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,QADQ,WAAO,OAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAClF,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzE,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,oBAAsB,CAAG,EAC9C,OAEF,QAAQ,OAAO,MAAM,EAAQ,IAAI,CAAC,IAAW,EAAO,EAAE,EAAE,KAAK,CAAG,EAAI,CAAG,EACxE,CACH",
"debugId": "021ED190AF18FD5864756E2164756E21",
"names": []
}

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((yield* ServiceConfig.get(Option.getOrUndefined(input.key))) + EOL)\n }),\n)\n"
],
"mappings": ";g7BAAA,mBAAS,gBAMT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,SACnC,OAAO,QAAG,sBAAiB,OAAE,cAAU,MAAC,OAAO,MAC7C,aAAQ,YAAO,YAAO,WAAO,OAAc,SAAI,OAAO,eAAe,EAAM,GAAG,CAAC,GAAK,CAAG,EACxF,CACH",
"debugId": "3B5C015829597F8264756E2164756E21",
"names": []
}
+1
-1
{
"name": "@opencode-ai/cli-linux-x64-musl",
"version": "0.0.0-next-15836",
"version": "0.0.0-next-15837",
"license": "MIT",

@@ -5,0 +5,0 @@ "repository": {

{
"version": 3,
"sources": ["../simulation/src/frontend/actions.ts", "../simulation/src/recording.ts", "../simulation/src/frontend/renderer.ts", "../simulation/src/frontend/semantics.ts", "../simulation/src/frontend/server.ts", "../simulation/src/frontend/simulation.ts"],
"sourcesContent": [
"import { tmpdir } from \"node:os\"\nimport { extname, join, resolve } from \"node:path\"\nimport type { CliRenderer, Renderable } from \"@opentui/core\"\nimport {\n createMockKeys,\n createMockMouse,\n KeyCodes,\n type KeyInput,\n type MockInput,\n type MockMouse,\n} from \"@opentui/core/testing\"\nimport { Config, Effect, FileSystem, Schema } from \"effect\"\nimport { SimulationProtocol } from \"../protocol\"\nimport { SimulationRenderer } from \"./renderer\"\nimport { SimulationSemantics } from \"./semantics\"\n\nexport type Action = SimulationProtocol.Frontend.Action\nexport type Element = SimulationProtocol.Frontend.Element\n\nexport interface Harness {\n readonly renderer: CliRenderer\n readonly mockInput: MockInput\n readonly mockMouse: MockMouse\n readonly resize: (cols: number, rows: number) => void\n readonly renderOnce: () => Promise<void>\n readonly screen: () => string\n}\n\ntype RenderBuffer = {\n readonly width: number\n readonly height: number\n getRealCharBytes(includeAnsi?: boolean): Uint8Array\n}\n\nconst decoder = new TextDecoder()\n\nfunction isKeyCode(key: string): key is keyof typeof KeyCodes {\n return Object.hasOwn(KeyCodes, key)\n}\n\nfunction keyInput(key: string): KeyInput {\n const named = key.toUpperCase()\n return isKeyCode(named) ? named : key\n}\n\nfunction children(renderable: Renderable) {\n return renderable.getChildren().filter((child): child is Renderable => \"num\" in child)\n}\n\nfunction all(renderable: Renderable): Renderable[] {\n return [renderable, ...children(renderable).flatMap(all)]\n}\n\nfunction mouseListeners(renderable: Renderable) {\n const general = Reflect.get(renderable, \"_mouseListener\")\n const specific = Reflect.get(renderable, \"_mouseListeners\")\n return Boolean(general) || (specific && typeof specific === \"object\" && Object.keys(specific).length > 0)\n}\n\nfunction hit(renderer: CliRenderer, renderable: Renderable) {\n if (renderable.width <= 0 || renderable.height <= 0) return false\n const x = Math.floor(renderable.screenX + renderable.width / 2)\n const y = Math.floor(renderable.screenY + renderable.height / 2)\n const target = renderer.hitTest(x, y)\n return all(renderable).some((item) => item.num === target)\n}\n\n/**\n * Builds the harness the simulation server drives.\n *\n * When the renderer is the headless simulation renderer, its TestRendererSetup\n * provides the supported testing APIs. For the visible terminal renderer the\n * harness falls back to `requestRender` + `idle` and reading the private\n * `currentRenderBuffer`.\n */\nexport function createHarness(renderer: CliRenderer): Harness {\n const setup = SimulationRenderer.setupFor(renderer)\n return {\n renderer,\n mockInput: setup?.mockInput ?? createMockKeys(renderer),\n mockMouse: setup?.mockMouse ?? createMockMouse(renderer),\n resize: setup?.resize ?? ((cols, rows) => renderer.resize(cols, rows)),\n renderOnce:\n setup?.renderOnce ??\n (async () => {\n renderer.requestRender()\n await renderer.idle()\n }),\n // captureCharFrame follows the test renderer's output sink. Recording\n // redirects that sink to the timeline, so read the live render buffer\n // instead; it is also the source used by screenshots.\n screen: () => decoder.decode((Reflect.get(renderer, \"currentRenderBuffer\") as RenderBuffer).getRealCharBytes()),\n }\n}\n\nexport function elements(renderer: CliRenderer): Element[] {\n return all(renderer.root)\n .filter((renderable) => renderable.visible && !renderable.isDestroyed)\n .map((renderable) => {\n const clickable = mouseListeners(renderable) && hit(renderer, renderable)\n return {\n id: renderable.id,\n num: renderable.num,\n x: renderable.screenX,\n y: renderable.screenY,\n width: renderable.width,\n height: renderable.height,\n focusable: renderable.focusable,\n focused: renderable.focused,\n clickable,\n editor: renderer.currentFocusedEditor === renderable,\n } satisfies Element\n })\n .filter((element) => element.focusable || element.clickable || element.editor)\n}\n\nexport function state(harness: Harness) {\n return {\n focused: {\n renderable: harness.renderer.currentFocusedRenderable?.num,\n editor: Boolean(harness.renderer.currentFocusedEditor),\n },\n elements: elements(harness.renderer),\n }\n}\n\nexport function snapshot(harness: Harness): SimulationProtocol.Frontend.SemanticSnapshot {\n const ids = new Set<string>()\n const visit = (renderable: Renderable, parent?: string): SimulationProtocol.Frontend.SemanticNode[] => {\n if (!renderable.visible || renderable.isDestroyed) return []\n const definition = SimulationSemantics.read(renderable)?.()\n if (definition && ids.has(renderable.id)) throw new Error(`duplicate semantic UI id: ${renderable.id}`)\n if (definition) ids.add(renderable.id)\n const node = definition\n ? [{ id: renderable.id, ...definition, ...(parent === undefined ? {} : { parent }), element: renderable.num }]\n : []\n const ancestor = definition ? renderable.id : parent\n return [...node, ...children(renderable).flatMap((child) => visit(child, ancestor))]\n }\n return Schema.decodeUnknownSync(SimulationProtocol.Frontend.SemanticSnapshot)({\n format: \"opencode-ui-snapshot-v1\",\n nodes: visit(harness.renderer.root),\n })\n}\n\nexport function matches(harness: Pick<Harness, \"screen\">, text: string) {\n return harness.screen().includes(text)\n}\n\nexport const capture = Effect.fn(\"SimulationActions.capture\")(function* (harness: Harness) {\n yield* Effect.tryPromise(() => harness.renderOnce())\n const buffer = harness.renderer.currentRenderBuffer\n return {\n cols: buffer.width,\n rows: buffer.height,\n cursor: [0, 0] as const,\n lines: buffer.getSpanLines().map((line) => ({\n spans: line.spans.map((span) => ({\n text: span.text,\n fg: span.fg.toInts(),\n bg: span.bg.toInts(),\n attributes: span.attributes,\n width: span.width,\n })),\n })),\n } satisfies SimulationProtocol.Frontend.CapturedFrame\n})\n\nexport const screenshot = Effect.fn(\"SimulationActions.screenshot\")(function* (harness: Harness, name?: string) {\n const filename = name ?? `screenshot-${crypto.randomUUID()}`\n if (!filename || filename.includes(\"/\") || filename.includes(\"\\\\\") || extname(filename))\n return yield* Effect.fail(new Error(\"screenshot name must not contain a path or extension\"))\n yield* Effect.tryPromise(() => harness.renderOnce())\n const { SimulationPng } = yield* Effect.promise(() => import(\"./png\"))\n const image = SimulationPng.screenshot(harness.renderer)\n const directory = resolve(\n yield* Config.string(\"OPENCODE_DRIVE_MEDIA_DIR\").pipe(\n Config.withDefault(join(tmpdir(), \"opencode-drive\", \"output\")),\n ),\n )\n const fs = yield* FileSystem.FileSystem\n yield* fs.makeDirectory(directory, { recursive: true })\n const path = join(directory, `${filename}.png`)\n yield* fs.writeFile(path, image.data)\n return path\n})\n\nexport const execute = Effect.fn(\"SimulationActions.execute\")(function* (harness: Harness, action: Action) {\n switch (action.type) {\n case \"ui.type\":\n yield* Effect.tryPromise(() => harness.mockInput.typeText(action.text))\n break\n case \"ui.press\":\n harness.mockInput.pressKey(keyInput(action.key), action.modifiers)\n break\n case \"ui.enter\":\n harness.mockInput.pressEnter()\n break\n case \"ui.arrow\":\n harness.mockInput.pressArrow(action.direction)\n break\n case \"ui.focus\":\n all(harness.renderer.root)\n .find((item) => item.num === action.target)\n ?.focus()\n break\n case \"ui.click\": {\n const target = all(harness.renderer.root).find((item) => item.num === action.target)\n if (!target || !target.visible || target.isDestroyed)\n return yield* Effect.fail(new Error(`click target is stale or unavailable: ${action.target}`))\n if (\n !Number.isFinite(action.x) ||\n action.x < 0 ||\n action.x >= target.width ||\n !Number.isFinite(action.y) ||\n action.y < 0 ||\n action.y >= target.height\n )\n return yield* Effect.fail(new Error(\"click position must be within the target element\"))\n yield* Effect.tryPromise(() => harness.mockMouse.click(target.screenX + action.x, target.screenY + action.y))\n break\n }\n case \"ui.resize\":\n if (\n !Number.isSafeInteger(action.cols) ||\n action.cols <= 0 ||\n !Number.isSafeInteger(action.rows) ||\n action.rows <= 0\n ) {\n return yield* Effect.fail(new Error(\"resize cols and rows must be positive integers\"))\n }\n harness.resize(action.cols, action.rows)\n SimulationRenderer.recordResize(harness.renderer, action.cols, action.rows)\n break\n }\n yield* Effect.tryPromise(() => harness.renderOnce())\n return state(harness)\n})\n\nexport * as SimulationActions from \"./actions\"\n",
"import { createWriteStream, type WriteStream } from \"node:fs\"\nimport { mkdir } from \"node:fs/promises\"\nimport { dirname } from \"node:path\"\nimport { Writable } from \"node:stream\"\nimport { finished } from \"node:stream/promises\"\nimport { Schema } from \"effect\"\n\nexport const Header = Schema.Struct({\n type: Schema.Literal(\"header\"),\n version: Schema.Literal(1),\n cols: Schema.Number,\n rows: Schema.Number,\n encoding: Schema.Literal(\"base64\"),\n})\nexport interface Header extends Schema.Schema.Type<typeof Header> {}\n\nexport const Output = Schema.Struct({\n type: Schema.Literal(\"output\"),\n at_ms: Schema.Number,\n data: Schema.String,\n})\nexport interface Output extends Schema.Schema.Type<typeof Output> {}\n\nexport const Resize = Schema.Struct({\n type: Schema.Literal(\"resize\"),\n at_ms: Schema.Number,\n cols: Schema.Number,\n rows: Schema.Number,\n})\nexport interface Resize extends Schema.Schema.Type<typeof Resize> {}\n\nexport const Event = Schema.Union([Header, Output, Resize])\nexport type Event = Schema.Schema.Type<typeof Event>\n\nexport class Timeline extends Writable {\n readonly isTTY = true\n readonly path: string\n readonly columns: number\n readonly rows: number\n private readonly output: WriteStream\n private readonly started = performance.now()\n private readonly timestamps: number[] = []\n private done?: Promise<string>\n\n private constructor(path: string, cols: number, rows: number, output: WriteStream) {\n super()\n this.path = path\n this.columns = cols\n this.rows = rows\n this.output = output\n // finish() reports stream failures; keep Writable from also throwing them process-wide.\n this.on(\"error\", () => {})\n output.on(\"error\", (error) => this.destroy(error))\n }\n\n static async create(path: string, cols: number, rows: number) {\n await mkdir(dirname(path), { recursive: true })\n const output = createWriteStream(path)\n const timeline = new Timeline(path, cols, rows, output)\n await new Promise<void>((resolve, reject) => {\n output.write(\n `${JSON.stringify({ type: \"header\", version: 1, cols, rows, encoding: \"base64\" } satisfies Header)}\\n`,\n (error) => (error ? reject(error) : resolve()),\n )\n })\n return timeline\n }\n\n getColorDepth() {\n return 24\n }\n\n override write(chunk: unknown, callback?: (error?: Error | null) => void): boolean\n override write(chunk: unknown, encoding: BufferEncoding, callback?: (error?: Error | null) => void): boolean\n override write(\n chunk: unknown,\n encoding?: BufferEncoding | ((error?: Error | null) => void),\n callback?: (error?: Error | null) => void,\n ) {\n if (!this.writableEnded) {\n this.timestamps.push(this.elapsed())\n if (typeof encoding === \"function\") return super.write(chunk, encoding)\n if (encoding === undefined) return super.write(chunk, callback)\n return super.write(chunk, encoding, callback)\n }\n const done = typeof encoding === \"function\" ? encoding : callback\n queueMicrotask(() => done?.(null))\n return true\n }\n\n override _write(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null) => void) {\n this.writeOutput(chunk, this.timestamps.shift() ?? this.elapsed(), callback)\n }\n\n override _final(callback: (error?: Error | null) => void) {\n this.writeOutput(Buffer.alloc(0), this.elapsed(), (error) => {\n if (error) return callback(error)\n this.output.end(callback)\n })\n }\n\n finish() {\n if (this.done) return this.done\n this.end()\n this.done = finished(this).then(() => this.path)\n return this.done\n }\n\n resize(cols: number, rows: number) {\n if (this.writableEnded) return\n const event = { type: \"resize\", at_ms: this.elapsed(), cols, rows } satisfies Resize\n this.output.write(`${JSON.stringify(event)}\\n`)\n }\n\n private elapsed() {\n return Math.max(0, Math.round(performance.now() - this.started))\n }\n\n private writeOutput(data: Buffer, at_ms: number, callback: (error?: Error | null) => void) {\n const event = {\n type: \"output\",\n at_ms,\n data: data.toString(\"base64\"),\n } satisfies Output\n this.output.write(`${JSON.stringify(event)}\\n`, callback)\n }\n}\n\nexport * as SimulationRecording from \"./recording\"\n",
"import type { CliRenderer, CliRendererConfig } from \"@opentui/core\"\nimport { createTestRenderer, type TestRendererSetup } from \"@opentui/core/testing\"\nimport { Effect } from \"effect\"\nimport { Timeline } from \"../recording\"\n\nconst setups = new WeakMap<CliRenderer, TestRendererSetup>()\nconst recordings = new WeakMap<CliRenderer, Timeline>()\n\n/**\n * Creates a headless renderer with optional recording: a real CliRenderer\n * backed by an in-memory screen buffer. The TestRendererSetup is kept\n * module-side so the harness can use supported testing APIs without app\n * code carrying it around.\n */\nexport interface Viewport {\n readonly cols: number\n readonly rows: number\n}\n\nexport const create = Effect.fn(\"SimulationRenderer.create\")(function* (\n options: CliRendererConfig,\n path?: string,\n viewport?: Viewport,\n) {\n const cols = viewport?.cols ?? 100\n const rows = viewport?.rows ?? 40\n const recording = path\n ? yield* Effect.acquireRelease(\n Effect.tryPromise(() => Timeline.create(path, cols, rows)),\n (recording) =>\n Effect.tryPromise(() => recording.finish()).pipe(\n Effect.catch((error) =>\n Effect.sync(() => process.stderr.write(`Failed to finish UI recording: ${error}\\n`)),\n ),\n ),\n )\n : undefined\n const setup = yield* Effect.acquireRelease(\n Effect.tryPromise(() =>\n createTestRenderer({\n ...options,\n width: cols,\n height: rows,\n ...(recording\n ? {\n stdout: recording as unknown as NodeJS.WriteStream,\n bufferedOutput: \"stdout\" as const,\n }\n : {}),\n }),\n ),\n (setup) =>\n Effect.sync(() => {\n if (!setup.renderer.isDestroyed) setup.renderer.destroy()\n }),\n )\n setups.set(setup.renderer, setup)\n if (recording) recordings.set(setup.renderer, recording)\n return setup.renderer\n})\n\nexport function recordResize(renderer: CliRenderer, cols: number, rows: number) {\n recordings.get(renderer)?.resize(cols, rows)\n}\n\nexport function setupFor(renderer: CliRenderer): TestRendererSetup | undefined {\n return setups.get(renderer)\n}\n\nexport function finish(renderer: CliRenderer) {\n const recording = recordings.get(renderer)\n if (!recording) return Effect.fail(new Error(\"UI recording is not available\"))\n return Effect.tryPromise(() => recording.finish())\n}\n\nexport * as SimulationRenderer from \"./renderer\"\n",
"import type { Renderable } from \"@opentui/core\"\nimport type { SimulationProtocol } from \"../protocol\"\n\n// Semantic renderables set an explicit stable OpenTUI id so ui.state and\n// ui.snapshot expose the same identity. Hierarchy and element handles come\n// from the live render tree.\nexport type Definition = Omit<SimulationProtocol.Frontend.SemanticNode, \"id\" | \"element\" | \"parent\">\n\nconst key = Symbol.for(\"opencode.simulation.semantics\")\n\nconst bind = (definition: () => Definition) => (renderable: Renderable) => {\n Object.defineProperty(renderable, key, { value: definition, configurable: true })\n}\n\nexport const read = (renderable: Renderable) => {\n const definition: unknown = Reflect.get(renderable, key)\n return typeof definition === \"function\" ? (definition as () => Definition) : undefined\n}\n\nexport const SimulationSemantics = { bind, read }\n",
"import { InstallationVersion } from \"@opencode-ai/core/installation/version\"\nimport { Effect } from \"effect\"\nimport { SimulationControlServer } from \"../control-server\"\nimport { SimulationProtocol } from \"../protocol\"\nimport { SimulationActions, type Harness } from \"./actions\"\nimport { SimulationRenderer } from \"./renderer\"\n\nfunction handle(harness: Harness, request: SimulationProtocol.Frontend.Request) {\n switch (request.method) {\n case \"simulation.handshake\":\n return SimulationProtocol.Handshake.dispatch(\n {\n role: \"ui\",\n server: { name: \"opencode\", version: InstallationVersion },\n capabilities: SimulationProtocol.Frontend.Capabilities,\n },\n request.params,\n )\n case \"ui.capture\":\n return SimulationActions.capture(harness)\n case \"ui.screenshot\":\n return SimulationActions.screenshot(harness, request.params?.name)\n case \"ui.state\":\n return Effect.sync(() => SimulationActions.state(harness))\n case \"ui.snapshot\":\n return Effect.sync(() => SimulationActions.snapshot(harness))\n case \"ui.matches\":\n return Effect.sync(() => SimulationActions.matches(harness, request.params.text))\n case \"ui.recording.finish\":\n return SimulationRenderer.finish(harness.renderer)\n case \"ui.type\":\n return SimulationActions.execute(harness, { type: \"ui.type\", text: request.params.text })\n case \"ui.enter\":\n return SimulationActions.execute(harness, { type: \"ui.enter\" })\n case \"ui.press\":\n return SimulationActions.execute(harness, {\n type: \"ui.press\",\n key: request.params.key,\n modifiers: request.params.modifiers,\n })\n case \"ui.arrow\":\n return SimulationActions.execute(harness, { type: \"ui.arrow\", direction: request.params.direction })\n case \"ui.focus\":\n return SimulationActions.execute(harness, { type: \"ui.focus\", target: request.params.target })\n case \"ui.click\":\n return SimulationActions.execute(harness, {\n type: \"ui.click\",\n target: request.params.target,\n x: request.params.x,\n y: request.params.y,\n })\n case \"ui.resize\":\n return SimulationActions.execute(harness, {\n type: \"ui.resize\",\n cols: request.params.cols,\n rows: request.params.rows,\n })\n }\n}\n\nexport const start = Effect.fn(\"SimulationServer.start\")(function* (harness: Harness, endpoint: string) {\n return yield* SimulationControlServer.start({\n endpoint,\n label: \"opencode drive ui websocket\",\n data: () => ({ drive: true as const }),\n decode: SimulationProtocol.Frontend.decodeRequestEffect,\n handle: (_socket, request) => handle(harness, request),\n })\n})\n\nexport * as SimulationServer from \"./server\"\n",
"import { createCliRenderer, type CliRendererConfig } from \"@opentui/core\"\nimport { Config, Effect } from \"effect\"\nimport { DriveManifest } from \"../manifest\"\nimport { SimulationActions } from \"./actions\"\nimport { SimulationRenderer } from \"./renderer\"\nimport { SimulationServer } from \"./server\"\n\n/** Drive-mode renderer and control-server acquisition. */\nexport const create = Effect.fn(\"Drive.create\")(function* (options: CliRendererConfig) {\n const headless = (yield* Config.string(\"OPENCODE_DRIVE_RENDERER\").pipe(Config.withDefault(\"visible\"))) === \"headless\"\n const manifest = yield* DriveManifest.resolve()\n const renderer = headless\n ? yield* SimulationRenderer.create(options, manifest.recording?.timeline, manifest.viewport)\n : yield* Effect.acquireRelease(\n Effect.tryPromise(() => createCliRenderer(options)),\n (renderer) =>\n Effect.sync(() => {\n if (!renderer.isDestroyed) renderer.destroy()\n }),\n )\n if (!headless && manifest.viewport) renderer.resize(manifest.viewport.cols, manifest.viewport.rows)\n const server = yield* SimulationServer.start(SimulationActions.createHarness(renderer), manifest.endpoints.ui)\n yield* Effect.sync(() => process.stderr.write(`opencode drive ui websocket: ${server.url}\\n`))\n return renderer\n})\n\nexport * as Drive from \"./simulation\"\n"
],
"mappings": ";8pBAAA,sBAAS,gBACT,uBAAS,gBAAS,kBAAM,wHCDxB,iCAAS,gBACT,gBAAS,oBACT,kBAAS,aACT,mBAAS,eACT,mBAAS,wBAGF,IAAM,EAAS,EAAO,OAAO,CAClC,KAAM,EAAO,QAAQ,QAAQ,EAC7B,QAAS,EAAO,QAAQ,CAAC,EACzB,KAAM,EAAO,OACb,KAAM,EAAO,OACb,SAAU,EAAO,QAAQ,QAAQ,CACnC,CAAC,EAGY,EAAS,EAAO,OAAO,CAClC,KAAM,EAAO,QAAQ,QAAQ,EAC7B,MAAO,EAAO,OACd,KAAM,EAAO,MACf,CAAC,EAGY,EAAS,EAAO,OAAO,CAClC,KAAM,EAAO,QAAQ,QAAQ,EAC7B,MAAO,EAAO,OACd,KAAM,EAAO,OACb,KAAM,EAAO,MACf,CAAC,EAGY,GAAQ,EAAO,MAAM,CAAC,EAAQ,EAAQ,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,OAAO,IACvB,CAAC,GAIA,IAAM,GAAQ,EAAO,GAAG,wBAAwB,EAAE,SAAU,CAAC,EAAkB,EAAkB,CACtG,OAAO,MAAO,EAAwB,MAAM,CAC1C,WACA,MAAO,8BACP,KAAM,KAAO,CAAE,MAAO,EAAc,GACpC,OAAQ,EAAmB,SAAS,oBACpC,OAAQ,CAAC,EAAS,IAAY,GAAO,EAAS,CAAO,CACvD,CAAC,EACF,EC5DM,IAAM,GAAS,EAAO,GAAG,cAAc,EAAE,SAAU,CAAC,EAA4B,CACrF,IAAM,GAAY,MAAO,EAAO,OAAO,yBAAyB,EAAE,KAAK,EAAO,YAAY,SAAS,CAAC,KAAO,WACrG,EAAW,MAAO,EAAc,QAAQ,EACxC,EAAW,EACb,MAAO,EAAmB,OAAO,EAAS,EAAS,WAAW,SAAU,EAAS,QAAQ,EACzF,MAAO,EAAO,eACZ,EAAO,WAAW,IAAM,EAAkB,CAAO,CAAC,EAClD,CAAC,IACC,EAAO,KAAK,IAAM,CAChB,GAAI,CAAC,EAAS,YAAa,EAAS,QAAQ,EAC7C,CACL,EACJ,GAAI,CAAC,GAAY,EAAS,SAAU,EAAS,OAAO,EAAS,SAAS,KAAM,EAAS,SAAS,IAAI,EAClG,IAAM,EAAS,MAAO,EAAiB,MAAM,EAAkB,cAAc,CAAQ,EAAG,EAAS,UAAU,EAAE,EAE7G,OADA,MAAO,EAAO,KAAK,IAAM,QAAQ,OAAO,MAAM,gCAAgC,EAAO;AAAA,CAAO,CAAC,EACtF,EACR",
"debugId": "F14B8F350BDF4C1364756E2164756E21",
"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": ";g7BAMA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,UACnC,OAAO,QAAG,uBAAkB,OAAE,cAAU,OAAG,MACzC,WAAO,OAAQ,UAAK,WAAO,OAAc,aAAQ,MAAC,OACnD,MACH",
"debugId": "9975D56AADE8458964756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/service/unset.ts"],
"sourcesContent": [
"import { Effect } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.unset,\n Effect.fn(\"cli.service.unset\")(function* (input) {\n yield* ServiceConfig.unset(input.key)\n }),\n)\n"
],
"mappings": ";w6BAKA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,WACnC,OAAO,QAAG,wBAAmB,OAAE,cAAU,MAAC,OAAO,MAC/C,WAAO,OAAc,WAAM,OAAM,QAAG,OACrC,MACH",
"debugId": "94B2509EE2AB03B864756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/mcp/auth.ts"],
"sourcesContent": [
"import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport {\n OpenCode,\n type IntegrationAttemptStatus,\n type IntegrationOAuthMethod,\n type OpenCodeClient,\n} from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.auth,\n Effect.fn(\"cli.mcp.auth\")(function* (input) {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n const method = integration.methods.find(\n (candidate): candidate is IntegrationOAuthMethod => candidate.type === \"oauth\",\n )\n if (!method)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n\n const started = yield* Effect.promise(() =>\n client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),\n )\n const attempt = started.data\n if (attempt.mode === \"code\")\n return yield* Effect.fail(new Error(\"This server requires manual code entry, which the CLI does not support\"))\n\n process.stdout.write(attempt.instructions + EOL + attempt.url + EOL)\n\n const result = yield* poll(client, integration.id, attempt.attemptID)\n if (result.status === \"complete\") {\n process.stdout.write(`Authenticated with ${input.name}` + EOL)\n return\n }\n const reason = result.status === \"failed\" ? `: ${result.message}` : \"\"\n return yield* Effect.fail(new Error(`Authentication ${result.status}${reason}`))\n }),\n)\n\nconst poll = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n): Effect.Effect<Exclude<IntegrationAttemptStatus, { status: \"pending\" }>> =>\n Effect.gen(function* () {\n const status = yield* Effect.promise(() =>\n client.integration.oauth.status({ integrationID, attemptID, location }),\n ).pipe(Effect.map((result) => result.data))\n if (status.status === \"pending\") {\n yield* Effect.sleep(\"1 second\")\n return yield* poll(client, integrationID, attemptID)\n }\n return status\n })\n"
],
"mappings": ";8gCAAA,mBAAS,gBAcT,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,UAC/B,OAAO,QAAG,mBAAc,OAAE,cAAU,MAAC,OAAO,MAC1C,SAAM,OAAU,MAAO,EAAc,QAAQ,EAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS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AAK,EAAQ,EAAe,CAAS,EAErD,OAAO,EACR",
"debugId": "98B2ADC2690405E664756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/server-process.ts", "src/commands/handlers/serve.ts"],
"sourcesContent": [
"export * as ServerProcess from \"./server-process\"\n\nimport { NodeServices } from \"@effect/platform-node\"\nimport { Service, type DiscoverOptions, type Info } from \"@opencode-ai/client/effect/service\"\nimport { LayerNode } from \"@opencode-ai/core/effect/layer-node\"\nimport { Global } from \"@opencode-ai/core/global\"\nimport { InstallationVersion } from \"@opencode-ai/core/installation/version\"\nimport { AppProcess } from \"@opencode-ai/core/process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport path from \"node:path\"\nimport { Effect, FileSystem, Logger, Option, Redacted, Schedule, Schema } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { Env } from \"./env\"\nimport { ServiceConfig } from \"./services/service-config\"\nimport { Updater } from \"./services/updater\"\n\nexport type Mode = \"default\" | \"service\" | \"stdio\"\n\nexport type Options = {\n readonly mode: Mode\n readonly hostname?: string\n readonly port?: number\n}\n\n// The process effect lives until server shutdown; tracing it would parent every request to one process-lifetime trace.\nexport const run = Effect.fnUntraced(function* (options: Options) {\n return yield* processEffect(options).pipe(\n Effect.provide(Updater.layer),\n Effect.provide(LayerNode.compile(LayerNode.group([Global.node, AppProcess.node]))),\n Effect.provide(NodeServices.layer),\n )\n})\n\nconst processEffect = Effect.fnUntraced(function* (options: Options) {\n if (options.mode === \"service\") yield* Effect.sync(() => process.chdir(Global.Path.home))\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const serviceOptions = options.mode === \"service\" ? yield* ServiceConfig.options() : undefined\n const config = options.mode === \"service\" ? yield* ServiceConfig.read() : {}\n const hostname = options.hostname ?? config.hostname ?? \"127.0.0.1\"\n const port = options.port ?? config.port ?? (options.mode === \"service\" ? ServiceConfig.defaultPort() : undefined)\n if (\n serviceOptions !== undefined &&\n port !== undefined &&\n (yield* Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })) !== undefined\n )\n return\n const { start } = yield* Effect.promise(() => import(\"@opencode-ai/server/process\"))\n const environmentPassword = yield* Env.password\n // Keep the lease credential out of the environment inherited by tools.\n if (options.mode === \"stdio\") {\n delete process.env.OPENCODE_PASSWORD\n delete process.env.OPENCODE_SERVER_PASSWORD\n }\n const password =\n options.mode === \"service\"\n ? config.password || randomBytes(32).toString(\"base64url\")\n : environmentPassword\n ? Redacted.value(environmentPassword)\n : randomBytes(32).toString(\"base64url\")\n if (!password) return yield* Effect.fail(new Error(\"Missing server password\"))\n const instanceID = randomUUID()\n const server = yield* start({\n hostname,\n port: Option.fromNullishOr(port),\n password,\n instanceID,\n service:\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* register(address, password, instanceID, serviceOptions.file, shutdown)\n }),\n },\n }).pipe(\n Effect.provide(Logger.layer([], { mergeWithExisting: false })),\n Effect.catch((error) => {\n if (serviceOptions === undefined || port === undefined || !addressInUse(error)) return Effect.fail(error)\n return recognizeIncumbent(serviceOptions, hostname, port).pipe(\n Effect.flatMap((found) =>\n found\n ? Effect.void\n : Effect.fail(\n new Error(\n `Managed service port ${port} on ${hostname} is already in use by another process. ` +\n \"Configure another port with `opencode service set port <port>` and start the service again.\",\n { cause: error },\n ),\n ),\n ),\n )\n }),\n )\n if (server === undefined) return\n const url = HttpServer.formatAddress(server.address)\n console.log(options.mode === \"stdio\" ? JSON.stringify({ url }) : `server listening on ${url}`)\n if (options.mode === \"default\" && !environmentPassword) console.log(`server password ${password}`)\n const updater = yield* Updater.Service\n yield* updater.check().pipe(Effect.schedule(Schedule.spaced(\"10 minutes\")), Effect.forkScoped)\n return yield* options.mode === \"service\"\n ? server.shutdown\n : options.mode === \"stdio\"\n ? waitForStdinClose()\n : Effect.never\n }).pipe(Effect.annotateLogs({ role: \"server\" })),\n )\n})\n\nconst infoJson = Schema.fromJsonString(Service.Info)\nconst encodeInfo = Schema.encodeEffect(infoJson)\nconst decodeInfo = Schema.decodeUnknownEffect(infoJson)\n\nconst register = Effect.fnUntraced(function* (\n address: HttpServer.Address,\n password: string,\n id: string,\n file: string,\n shutdown: Effect.Effect<void>,\n) {\n const fs = yield* FileSystem.FileSystem\n const temp = file + \".\" + id + \".tmp\"\n yield* fs.makeDirectory(path.dirname(file), { recursive: true })\n const info = {\n id,\n version: InstallationVersion,\n url: HttpServer.formatAddress(address),\n pid: process.pid,\n password,\n }\n const encoded = yield* encodeInfo(info)\n const current = fs.readFileString(file).pipe(\n Effect.flatMap(decodeInfo),\n Effect.orElseSucceed(() => undefined),\n )\n const owns = (found: Info | undefined) =>\n found?.id === info.id &&\n found.version === info.version &&\n found.url === info.url &&\n found.pid === info.pid &&\n found.password === info.password\n yield* fs.writeFileString(temp, encoded, { mode: 0o600 }).pipe(Effect.andThen(fs.rename(temp, file)))\n yield* current.pipe(\n Effect.filterOrFail(owns),\n Effect.repeat(Schedule.spaced(\"5 seconds\")),\n Effect.ignore,\n Effect.andThen(shutdown),\n Effect.forkScoped,\n )\n return current.pipe(\n Effect.flatMap((found) => (owns(found) ? fs.remove(file) : Effect.void)),\n Effect.ignore,\n )\n})\n\nconst recognizeIncumbent = Effect.fnUntraced(function* (options: DiscoverOptions, hostname: string, port: number) {\n const found = yield* Service.incumbent({ ...options, url: serviceURL(hostname, port) }).pipe(\n Effect.filterOrFail((value) => value !== undefined),\n Effect.retry(Schedule.spaced(\"100 millis\")),\n Effect.timeoutOption(\"15 seconds\"),\n )\n return Option.isSome(found)\n})\n\nfunction serviceURL(hostname: string, port: number) {\n return `http://${hostname.includes(\":\") ? `[${hostname}]` : hostname}:${port}`\n}\n\nfunction addressInUse(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false\n if (\"code\" in error && error.code === \"EADDRINUSE\") return true\n return \"cause\" in error && addressInUse(error.cause)\n}\n\nfunction waitForStdinClose() {\n return Effect.callback<void>((resume) => {\n const close = () => resume(Effect.void)\n process.stdin.once(\"end\", close)\n process.stdin.once(\"close\", close)\n process.stdin.resume()\n if (process.stdin.readableEnded || process.stdin.destroyed) close()\n return Effect.sync(() => {\n process.stdin.off(\"end\", close)\n process.stdin.off(\"close\", close)\n process.stdin.pause()\n })\n })\n}\n",
"import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerProcess } from \"../../server-process\"\n\nexport default Runtime.handler(\n Commands.commands.serve,\n Effect.fnUntraced(function* (input) {\n if (input.service && input.stdio) return yield* Effect.fail(new Error(\"--service and --stdio cannot be combined\"))\n return yield* ServerProcess.run({\n mode: input.service ? \"service\" : input.stdio ? \"stdio\" : \"default\",\n hostname: Option.getOrUndefined(input.hostname),\n port: Option.getOrUndefined(input.port),\n })\n }),\n)\n"
],
"mappings": ";wqCAQA,2BAAS,qBAAa,oBACtB,yBAgBO,SAAM,OAAM,OAAO,gBAAW,cAAU,MAAC,OAAkB,MAChE,YAAO,WAAO,OAAc,MAAO,OAAE,UACnC,OAAO,aAAQ,OAAQ,UAAK,OAC5B,OAAO,aAAQ,OAAU,QAAQ,EAAU,MAAM,CAAC,EAAO,KAAM,EAAW,IAAI,CAAC,CAAC,CAAC,EACjF,EAAO,QAAQ,EAAa,KAAK,CACnC,EACD,EAEK,EAAgB,EAAO,WAAW,SAAU,CAAC,EAAkB,CACnE,GAAI,EAAQ,OAAS,UAAW,MAAO,EAAO,KAAK,IAAM,QAAQ,MAAM,EAAO,KAAK,IAAI,CAAC,EACxF,OAAO,MAAO,EAAO,OACnB,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAiB,EAAQ,OAAS,UAAY,MAAO,EAAc,QAAQ,EAAI,OAC/E,EAAS,EAAQ,OAAS,UAAY,MAAO,EAAc,KAAK,EAAI,CAAC,EACrE,EAAW,EAAQ,UAAY,EAAO,UAAY,YAClD,EAAO,EAAQ,MAAQ,EAAO,OAAS,EAAQ,O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QAAQ,MAAM,MAAM,EACrB,EACF,ECvLH,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": "3910EEF5437353A564756E2164756E21",
"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": ";miCAAA,mBAAS,gBAOT,SAAM,OAAU,SAAI,SAAI,MAAC,cAAU,WAAO,YAAQ,eAAW,aAAS,YAAQ,UAAK,MAAC,OAUrE,SAAQ,aACrB,OAAS,cAAS,SAClB,OAAO,QAAG,cAAS,OAAE,cAAU,MAAC,OAAO,CA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} from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.logout,\n Effect.fn(\"cli.mcp.logout\")(function* (input) {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n yield* Effect.forEach(\n credentials,\n (connection) => Effect.promise(() => client.credential.remove({ credentialID: connection.id, location })),\n { discard: true },\n )\n process.stdout.write(`Removed OAuth credentials for ${input.name}` + EOL)\n }),\n)\n"
],
"mappings": ";8gCAAA,mBAAS,gBAST,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,YAC/B,OAAO,QAAG,qBAAgB,OAAE,cAAU,MAAC,OAAO,MAC5C,SAAM,OAAU,MAAO,EAAc,QAAQ,EAEvC,GADQ,MAAO,EAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EAAa,CAChB,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,IAAM,EAAc,EAAY,YAAY,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACnG,GAAI,EAAY,SAAW,EAAG,CAC5B,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,MAAO,EAAO,QACZ,EACA,CAAC,IAAe,EAAO,QAAQ,IAAM,EAAO,WAAW,OAAO,CAAE,aAAc,EAAW,GAAI,UAAS,CAAC,CAAC,EACxG,CAAE,QAAS,EAAK,CAClB,EACA,QAAQ,OAAO,MAAM,iCAAiC,EAAM,OAAS,CAAG,EACzE,CACH",
"debugId": "F3DF66FB4D13928064756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/auth/connect.ts"],
"sourcesContent": [
"import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type IntegrationCommandStatusOutput, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.connect,\n Effect.fn(\"cli.auth.connect\")(function* (input) {\n process.stdout.write(\"Connecting...\" + EOL + EOL)\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n yield* request(() => client.integration.wellknown.add({ url: input.url, location }))\n const integrationID = input.url.replace(/\\/+$/, \"\")\n const started = yield* request(() =>\n client.integration.command.connect({ integrationID, methodID: \"login\", location }),\n )\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.command.cancel({ integrationID, attemptID: started.data.attemptID, location }),\n ).pipe(Effect.ignore),\n )\n\n const status = yield* wait(client, integrationID, started.data.attemptID)\n if (status.status === \"failed\") return yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") return yield* Effect.fail(new Error(\"Authentication expired\"))\n process.stdout.write(\"Connected\" + EOL)\n }),\n)\n\nconst wait = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n shown = false,\n): Effect.Effect<Exclude<IntegrationCommandStatusOutput[\"data\"], { status: \"pending\" }>, unknown> =>\n Effect.gen(function* () {\n const response = yield* request(() => client.integration.command.status({ integrationID, attemptID, location }))\n if (response.data.status !== \"pending\") return response.data\n const output = response.data.message?.trim()\n if (!shown && output) process.stdout.write(output + EOL + EOL)\n yield* Effect.sleep(500)\n return yield* wait(client, integrationID, attemptID, shown || !!output)\n })\n\nfunction request<A>(task: () => Promise<A>) {\n return Effect.tryPromise({ try: task, catch: (cause) => cause })\n}\n"
],
"mappings": ";+9BAAA,mBAAS,gBAQT,SAAM,OAAW,MAAE,eAAW,aAAQ,SAAI,MAAE,OAE7B,SAAQ,aACrB,OAAS,cAAS,UAAK,cAAS,aAChC,OAAO,QAAG,uBAAkB,OAAE,cAAU,MAAC,OAAO,MAC9C,aAAQ,OAAO,MAAM,gBAAkB,EAAM,CAAG,EAChD,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAC1F,MAAO,EAAQ,IAAM,EAAO,YAAY,UAAU,IAAI,CAAE,IAAK,EAAM,IAAK,UAAS,CAAC,CAAC,EACnF,IAAM,EAAgB,EAAM,IAAI,QAAQ,OAAQ,EAAE,EAC5C,EAAU,MAAO,EAAQ,IAC7B,EAAO,YAAY,QAAQ,QAAQ,CAAE,gBAAe,SAAU,QAAS,UAAS,CAAC,CACnF,EACA,MAAO,EAAO,aAAa,IACzB,EAAQ,IACN,EAAO,YAAY,QAAQ,OAAO,CAAE,gBAAe,UAAW,EAAQ,KAAK,UAAW,UAAS,CAAC,CAClG,EAAE,KAAK,EAAO,MAAM,CACtB,EAEA,IAAM,EAAS,MAAO,EAAK,EAAQ,EAAe,EAAQ,KAAK,SAAS,EACxE,GAAI,EAAO,SAAW,SAAU,OAAO,MAAO,EAAO,KAAS,MAAM,EAAO,OAAO,CAAC,EACnF,GAAI,EAAO,SAAW,UAAW,OAAO,MAAO,EAAO,KAAS,MAAM,wBAAwB,CAAC,EAC9F,QAAQ,OAAO,MAAM,YAAc,CAAG,EACvC,CACH,EAEM,EAAO,CACX,EACA,EACA,EACA,EAAQ,KAER,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAW,MAAO,EAAQ,IAAM,EAAO,YAAY,QAAQ,OAAO,CAAE,gBAAe,YAAW,UAAS,CAAC,CAAC,EAC/G,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,IAAM,EAAS,EAAS,KAAK,SAAS,KAAK,EAC3C,GAAI,CAAC,GAAS,EAAQ,QAAQ,OAAO,MAAM,EAAS,EAAM,CAAG,EAE7D,OADA,MAAO,EAAO,MAAM,GAAG,EAChB,MAAO,EAAK,EAAQ,EAAe,EAAW,GAAS,CAAC,CAAC,CAAM,EACvE,EAEH,SAAS,CAAU,CAAC,EAAwB,CAC1C,OAAO,EAAO,WAAW,CAAE,IAAK,EAAM,MAAO,CAAC,IAAU,CAAM,CAAC",
"debugId": "947D10DAB8650A7E64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/run.ts"],
"sourcesContent": [
"import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(Commands.commands.run, (input) =>\n Effect.gen(function* () {\n const { runNonInteractive } = yield* Effect.promise(() => import(\"../../run/run\"))\n const separator = process.argv.indexOf(\"--\", 2)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n yield* Effect.promise(() =>\n runNonInteractive({\n server,\n message: [...input.message, ...(separator === -1 ? [] : process.argv.slice(separator + 1))],\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n format: input.format,\n file: [...input.file],\n title: Option.getOrUndefined(input.title),\n thinking: input.thinking,\n auto: input.auto || input.yolo,\n }),\n )\n }),\n)\n"
],
"mappings": ";miCAKA,SAAe,SAAQ,aAAQ,OAAS,cAAS,SAAK,MAAC,SACrD,OAAO,SAAI,cAAU,OAAG,MACtB,SAAQ,0BAAsB,WAAO,OAAO,aAAQ,SAAa,wCAAgB,OAC3E,OAAY,aAAQ,UAAK,aAAQ,UAAM,MAAC,OACxC,OAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACD,MAAO,EAAO,QAAQ,IACpB,EAAkB,CAChB,SACA,QAAS,CAAC,GAAG,EAAM,QAAS,GAAI,IAAc,GAAK,CAAC,EAAI,QAAQ,KAAK,MAAM,EAAY,CAAC,CAAE,EAC1F,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAM,OACd,KAAM,CAAC,GAAG,EAAM,IAAI,EACpB,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,SAAU,EAAM,SAChB,KAAM,EAAM,MAAQ,EAAM,IAC5B,CAAC,CACH,EACD,CACH",
"debugId": "FAE95A7B71F833B564756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/mini.ts", "src/mini-host.ts"],
"sourcesContent": [
"import { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { setTimeout } from \"node:timers/promises\"\nimport { ServerConnection } from \"./services/server-connection\"\nimport { waitForCatalogReady } from \"./services/catalog\"\nimport { readStdin } from \"./util/io\"\nimport { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from \"./mini-host\"\n\nexport type MiniCommandInput = {\n server: ServerConnection.Resolved\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}\n\ntype Session = Awaited<ReturnType<OpenCodeClient[\"session\"][\"get\"]>>\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 sdk = OpenCode.make({\n baseUrl: input.server.endpoint.url,\n headers: Service.headers(input.server.endpoint),\n })\n const model = parseModel(input.model)\n let agentTask: Promise<string | undefined> | undefined\n const resolveAgent = () => {\n agentTask ??= validateAgent(sdk, directory, input.agent)\n return agentTask\n }\n const resolveSession = async () => {\n const [agent, selected] = await Promise.all([resolveAgent(), selectSession(sdk, directory, input)])\n const readyModel =\n model ?? (selected?.model ? { providerID: selected.model.providerID, modelID: selected.model.id } : undefined)\n if (readyModel) await waitForCatalogReady({ sdk, directory, model: readyModel })\n const session = selected ?? (await createSession(sdk, directory, agent, model))\n return { id: session.id, title: session.title, resume: selected !== undefined }\n }\n const create = (\n _sdk: OpenCodeClient,\n next: { agent: string | undefined; model: Model; variant: string | undefined },\n ) => createSession(sdk, directory, next.agent, next.model, next.variant)\n const frontend = await frontendTask\n return frontend.runMiniFrontend({\n host: createMiniHost({ terminal, directory }),\n sdk,\n directory,\n resolveAgent,\n session: resolveSession,\n createSession: create,\n agent: input.agent,\n model,\n variant: undefined,\n files: [],\n initialInput,\n thinking: true,\n replay: input.replay ?? true,\n replayLimit: input.replayLimit,\n demo: input.demo,\n tuiConfig: input.tuiConfig,\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\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): Model {\n if (!value) return\n const [providerID, ...rest] = value.split(\"/\")\n const modelID = rest.join(\"/\")\n if (!providerID || !modelID) throw new MiniInputError(\"--model must use the format provider/model\")\n return { providerID, modelID }\n}\n\nasync function validateAgent(sdk: OpenCodeClient, directory: string, name?: string) {\n if (!name) return\n const deadline = Date.now() + 5_000\n let agents: Awaited<ReturnType<OpenCodeClient[\"agent\"][\"list\"]>> | undefined\n while (Date.now() < deadline) {\n agents = await sdk.agent.list({ location: { directory } }).catch(() => undefined)\n const agent = agents?.data.find((item) => item.id === name)\n if (agent?.mode === \"subagent\") {\n warning(`agent \"${name}\" is a subagent, not a primary agent. Falling back to default agent`)\n return\n }\n if (agent) return name\n await setTimeout(25)\n }\n if (!agents) {\n warning(\"failed to list agents. Falling back to default agent\")\n return\n }\n warning(`agent \"${name}\" not found. Falling back to default agent`)\n}\n\nasync function selectSession(sdk: OpenCodeClient, directory: string, input: MiniCommandInput, preselected?: Session) {\n const selected =\n preselected ??\n (input.session\n ? await sdk.session.get({ sessionID: input.session }).catch(() => undefined)\n : input.continue\n ? await sdk.session\n .list({ directory, parentID: null, limit: 1, order: \"desc\" })\n .then((result) => result.data[0])\n : undefined)\n if (input.session && !selected) throw new MiniInputError(\"Session not found\")\n if (!selected) return\n if (!input.fork) return selected\n return sdk.session.fork({ sessionID: selected.id })\n}\n\nasync function createSession(\n sdk: OpenCodeClient,\n directory: string,\n agent: string | undefined,\n model: Model,\n variant?: string,\n): Promise<Session> {\n if (model) await waitForCatalogReady({ sdk, directory, model })\n return sdk.session.create({\n agent,\n model: model ? { providerID: model.providerID, id: model.modelID, variant } : undefined,\n location: { directory },\n })\n}\n\nfunction warning(message: string) {\n process.stderr.write(`\\x1b[93m\\x1b[1m!\\x1b[0m ${message}\\n`)\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 { Flag } from \"@opencode-ai/core/flag/flag\"\nimport { Global } from \"@opencode-ai/core/global\"\nimport fs from \"node:fs\"\nimport { mkdir, readFile, writeFile } 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\"]\ntype ModelState = Record<string, unknown> & {\n variant?: Record<string, string | undefined>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value)\n}\n\nfunction state(value: unknown): ModelState {\n if (!isRecord(value)) return {}\n const variant = isRecord(value.variant)\n ? Object.fromEntries(\n Object.entries(value.variant).flatMap(([key, item]) =>\n typeof item === \"string\" ? ([[key, item]] as const) : [],\n ),\n )\n : undefined\n return { ...value, variant }\n}\n\nfunction variantKey(model: NonNullable<MiniFrontendInput[\"model\"]>) {\n return `${model.providerID}/${model.modelID}`\n}\n\nfunction preferences(statePath: string): MiniHost[\"preferences\"] {\n const file = path.join(statePath, \"model.json\")\n const read = () =>\n readFile(file, \"utf8\")\n .then((value) => state(JSON.parse(value)))\n .catch(() => state(undefined))\n return {\n async resolveVariant(model) {\n if (!model) return\n return (await read()).variant?.[variantKey(model)]\n },\n async saveVariant(model, variant) {\n if (!model) return\n const current = await read()\n const next = { ...current.variant }\n if (variant) next[variantKey(model)] = variant\n if (!variant) delete next[variantKey(model)]\n await mkdir(path.dirname(file), { recursive: true })\n .then(() => writeFile(file, JSON.stringify({ ...current, variant: next }, null, 2)))\n .catch(() => {})\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: Pick<MiniHost[\"diagnostics\"], \"pid\" | \"cwd\" | \"argv\">,\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?: MiniHost[\"paths\"]\n}): MiniHost {\n const paths = input.paths ?? {\n home: Global.Path.home,\n state: Global.Path.state,\n log: Global.Path.log,\n }\n const diagnostics = {\n pid: process.pid,\n cwd: input.directory,\n argv: process.argv.slice(2),\n }\n return {\n terminal: input.terminal,\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,\n signals: {\n sigint: signal(\"SIGINT\"),\n sigusr2: signal(\"SIGUSR2\"),\n },\n startup: {\n showTiming: Flag.OPENCODE_SHOW_TTFD,\n now: () => performance.now(),\n },\n diagnostics: {\n ...diagnostics,\n trace: createTrace(paths.log, diagnostics),\n },\n preferences: preferences(paths.state),\n }\n}\n"
],
"mappings": ";4tBAGA,0BAAS,6BCAT,uBACA,qBAAS,mBAAO,oBAAU,yBAC1B,yBACA,0BAAS,iBAEF,SAAM,OAA0B,+DAYvC,cAAS,MAAQ,MAAC,OAAkD,MAClE,MAAO,CAAC,CAAC,GAAS,OAAO,IAAU,UAAY,CAAC,MAAM,QAAQ,CAAK,EAGrE,SAAS,CAAK,CAAC,EAA4B,CACzC,GAAI,CAAC,EAAS,CAAK,EAAG,MAAO,CAAC,EAC9B,IAAM,EAAU,EAAS,EAAM,OAAO,EAClC,OAAO,YACL,OAAO,QAAQ,EAAM,OAAO,EAAE,QAAQ,EAAE,EAAK,KAC3C,OAAO,IAAS,SAAY,CAAC,CAAC,EAAK,CAAI,CAAC,EAAc,CAAC,CACzD,CACF,EACA,OACJ,MAAO,IAAK,EAAO,SAAQ,EAG7B,SAAS,CAAU,CAAC,EAAgD,CAClE,MAAO,GAAG,EAAM,cAAc,EAAM,UAGtC,SAAS,CAAW,CAAC,EAA4C,CAC/D,IAAM,EAAO,EAAK,KAAK,EAAW,YAAY,EACxC,EAAO,IACX,EAAS,EAAM,MAAM,EAClB,KAAK,CAAC,IAAU,EAAM,KAAK,MAAM,CAAK,CAAC,CAAC,EACxC,MAAM,IAAM,EAAM,MAAS,CAAC,EACjC,MAAO,MACC,eAAc,CAAC,EAAO,CAC1B,GAAI,CAAC,EAAO,OACZ,OAAQ,MAAM,EAAK,GAAG,UAAU,EAAW,CAAK,SAE5C,YAAW,CAAC,EAAO,EAAS,CAChC,GAAI,CAAC,EAAO,OACZ,IAAM,EAAU,MAAM,EAAK,EACrB,EAAO,IAAK,EAAQ,OAAQ,EAClC,GAAI,EAAS,EAAK,EAAW,CAAK,GAAK,EACvC,GAAI,CAAC,EAAS,OAAO,EAAK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Q,OAAO,MAAM,2BAA2B;AAAA,CAAW,EAG7D,SAAS,CAAI,CAAC,EAAwB,CACpC,QAAQ,OAAO,MAAM,gCAAgC;AAAA,CAAW,EAChE,QAAQ,KAAK,CAAC",
"debugId": "63AD734A5128C90664756E2164756E21",
"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/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": ";g7BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,aACnC,OAAO,QAAG,0BAAqB,OAAE,cAAU,OAAG,MAC5C,SAAM,OAAU,WAAO,OAAc,aAAQ,OAC7C,WAAO,OAAQ,KAAK,CAAO,EAC3B,IAAM,EAAY,MAAO,EAAQ,OAAO,CAAO,EAC/C,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH",
"debugId": "9F5C836C765FC37764756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/services/standalone.ts", "src/services/server-connection.ts"],
"sourcesContent": [
"import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { CrossSpawnSpawner } from \"@opencode-ai/core/cross-spawn-spawner\"\nimport { LayerNode } from \"@opencode-ai/core/effect/layer-node\"\nimport { Deferred, Effect, Schema, Stream } from \"effect\"\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\"\nimport { randomBytes } from \"node:crypto\"\nimport { selfCommand } from \"../util/process\"\n\nconst Ready = Schema.Struct({ url: Schema.String })\nconst decodeReady = Schema.decodeUnknownPromise(Schema.fromJsonString(Ready))\n\ntype Options = {\n readonly command?: ReadonlyArray<string>\n}\n\nfunction command(password: string, options: Options) {\n const [executable, ...args] = options.command ?? [...selfCommand(), \"serve\"]\n if (!executable) throw new Error(\"Failed to resolve standalone server command\")\n return ChildProcess.make(executable, [...args, \"--stdio\", \"--port\", \"0\"], {\n cwd: process.cwd(),\n // Explicit entry wins over anything inherited, so a user-exported\n // OPENCODE_PASSWORD cannot shadow the child's lease credential.\n env: { OPENCODE_PASSWORD: password },\n extendEnv: true,\n // The server treats EOF on this pipe as the end of its ownership lease.\n // The OS closes it even when the TUI is killed before Effect finalizers run.\n stdin: \"pipe\",\n stderr: \"ignore\",\n killSignal: \"SIGTERM\",\n forceKillAfter: \"3 seconds\",\n })\n}\n\nconst makeEndpoint = Effect.fn(\"cli.standalone.endpoint\")(\n function* (options: Options) {\n const password = randomBytes(32).toString(\"base64url\")\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner\n const proc = yield* spawner.spawn(command(password, options))\n const readyLine = yield* Deferred.make<string, Error>()\n // Keep draining stdout after readiness so later server writes cannot hit EPIPE.\n yield* proc.stdout.pipe(\n Stream.decodeText(),\n Stream.splitLines,\n Stream.runForEach((line) => Deferred.succeed(readyLine, line)),\n Effect.ensuring(Deferred.fail(readyLine, new Error(\"Standalone server exited before reporting readiness\"))),\n Effect.forkScoped,\n )\n const output = yield* Deferred.await(readyLine)\n const ready = yield* Effect.tryPromise(() => decodeReady(output))\n return {\n url: ready.url,\n auth: { type: \"basic\" as const, username: \"opencode\", password },\n pid: proc.pid,\n } satisfies Endpoint & { readonly pid: number }\n },\n Effect.provide(LayerNode.compile(CrossSpawnSpawner.node)),\n)\n\nexport function start(options: Options = {}) {\n return makeEndpoint(options)\n}\n\nexport * as Standalone from \"./standalone\"\n",
"import { Service, type Endpoint, type EnsureOptions } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, isUnauthorizedError, OpenCode } from \"@opencode-ai/client/promise\"\nimport { InstallationVersion } from \"@opencode-ai/core/installation/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 !== InstallationVersion)\n process.stderr.write(\n `Warning: Server at ${endpoint.url} has version ${health.version}; this client is ${InstallationVersion}. Continuing anyway.\\n`,\n )\n return { endpoint } satisfies Resolved\n }\n if (args.standalone) {\n return { endpoint: yield* Standalone.start() } satisfies Resolved\n }\n\n const options = yield* ServiceConfig.options()\n return {\n endpoint: yield* resolveManaged({ ...options, onStart: args.onStart }, args.mismatch ?? \"replace\"),\n service: managedService(options),\n } satisfies Resolved\n})\n\nfunction managedService(options: EnsureOptions) {\n const reconnectOptions = { ...options, version: undefined }\n return {\n reconnect: () => Service.ensure(reconnectOptions),\n restart: () =>\n Effect.gen(function* () {\n yield* Service.stop(options)\n yield* Service.ensure(options)\n }),\n }\n}\n\nconst resolveManaged = Effect.fnUntraced(function* (\n options: EnsureOptions,\n mismatch: NonNullable<Args[\"mismatch\"]>,\n) {\n if (mismatch === \"replace\") return yield* Service.ensure(options)\n if (mismatch === \"ignore\") return yield* Service.ensure({ ...options, version: undefined })\n\n const compatible = yield* Service.discover(options)\n if (compatible !== undefined) return compatible\n const existing = yield* Service.discover({ ...options, version: undefined })\n if (existing !== undefined)\n return yield* Effect.fail(new Error(\"Background server version does not match this client\"))\n return yield* Service.ensure(options)\n})\n\nfunction connectError(endpoint: Endpoint, cause: unknown) {\n if (isUnauthorizedError(cause)) {\n return new Error(\n endpoint.auth === undefined\n ? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`\n : `Server at ${endpoint.url} rejected the password`,\n { cause },\n )\n }\n if (cause instanceof ClientError && cause.reason === \"Transport\")\n return new Error(`Could not reach server at ${endpoint.url}`, { cause })\n return new Error(`Server at ${endpoint.url} did not provide a compatible V2 health response`, { cause })\n}\n\nexport * as ServerConnection from \"./server-connection\"\n"
],
"mappings": ";slBAKA,2BAAS,oBAGT,SAAM,OAAQ,OAAO,YAAO,MAAE,SAAK,EAAO,MAAO,CAAC,EAC5C,EAAc,EAAO,qBAAqB,EAAO,eAAe,CAAK,CAAC,EAM5E,SAAS,CAAO,CAAC,EAAkB,EAAkB,CACnD,IAAO,KAAe,GAAQ,EAAQ,SAAW,CAAC,GAAG,EAAY,EAAG,OAAO,EAC3E,GAAI,CAAC,EAAY,MAAU,MAAM,6CAA6C,EAC9E,OAAO,EAAa,KAAK,EAAY,CAAC,GAAG,EAAM,UAAW,SAAU,GAAG,EAAG,CACxE,IAAK,QAAQ,IAAI,EAGjB,IAAK,CAAE,kBAAmB,CAAS,EACnC,UAAW,GAGX,MAAO,OACP,OAAQ,SACR,WAAY,UACZ,eAAgB,WAClB,CAAC,EAGH,IAAM,EAAe,EAAO,GAAG,yBAAyB,EACtD,SAAU,CAAC,EAAkB,CAC3B,IAAM,EAAW,EAAY,EAAE,EAAE,SAAS,WAAW,EAE/C,EAAO,OADG,MAAO,EAAoB,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AuD,CAAE,OAAM,CAAC",
"debugId": "F8441F0966F6DBED64756E2164756E21",
"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 } from \"@opencode-ai/client/promise\"\nimport { FSUtil } from \"@opencode-ai/core/fs-util\"\nimport { Model } from \"@opencode-ai/schema/model\"\nimport { open } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { readStdin } from \"../util/io\"\nimport { ServerConnection } from \"../services/server-connection\"\nimport { waitForCatalogReady } from \"../services/catalog\"\nimport { toolInlineInfo, type MiniToolPart } from \"@opencode-ai/tui/mini/tool\"\nimport { runNonInteractivePrompt } from \"./noninteractive\"\nimport { UI } from \"./ui\"\n\nexport type RunCommandInput = {\n server: ServerConnection.Resolved\n message: string[]\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n format: \"default\" | \"json\"\n file: string[]\n title?: string\n thinking?: boolean\n auto?: boolean\n}\n\ntype FilePart = {\n url: string\n filename: string\n mime: string\n}\n\ntype Prepared = {\n directory?: string\n message: string\n files: FilePart[]\n}\n\ntype ExecutionOptions = {\n root?: string\n directory?: string\n useServerDirectory?: boolean\n variant?: string\n attached?: boolean\n compatibility?: \"v1\"\n}\n\nconst ATTACH_FILE_MAX_BYTES = 10 * 1024 * 1024\n\nexport function runNonInteractive(input: RunCommandInput) {\n return runNonInteractiveWithOptions(input, {})\n}\n\n/** @internal Used only by the V1 command boundary. */\nexport function runNonInteractiveWithOptions(input: RunCommandInput, options: ExecutionOptions) {\n return run(input, options).catch((error) => reportRunError(input, errorMessage(error)))\n}\n\nasync function run(input: RunCommandInput, options: ExecutionOptions) {\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n const root = options.root ?? process.env.PWD ?? process.cwd()\n const local = localDirectory(root)\n const directory = options.useServerDirectory ? undefined : (options.directory ?? local)\n const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin())\n if (!message?.trim()) fail(\"You must provide a message\")\n const files = await Promise.all(input.file.map((file) => prepareFile(file, root, options)))\n const prepared = { directory, message, files }\n return execute(input, prepared, input.server.endpoint, options)\n}\n\nasync function execute(input: RunCommandInput, prepared: Prepared, endpoint: Endpoint, options: ExecutionOptions) {\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const requestedDirectory = prepared.directory ?? (await client.location.get()).directory\n if (!requestedDirectory) fail(\"Failed to resolve server directory\")\n const session = await selectSession(client, requestedDirectory, input)\n const cwd = session?.location.directory ?? requestedDirectory\n const workspace = session?.location.workspaceID\n const explicit = parseRunModel(input.model)\n const explicitModel = explicit?.model\n const variant = options.variant ?? explicit?.variant\n const sessionModel = session?.model ? { providerID: session.model.providerID, modelID: session.model.id } : undefined\n const defaultModel =\n !explicitModel && !sessionModel\n ? await client.model\n .default({ location: { directory: cwd, workspace } })\n .then((result) => (result.data ? { providerID: result.data.providerID, modelID: result.data.id } : undefined))\n : undefined\n const model = pickRunModel(explicitModel, variant, sessionModel, defaultModel)\n if (variant && !model) return reportRunError(input, \"Cannot select a variant before selecting a model\", session?.id)\n if (model) {\n await waitForCatalogReady({ sdk: client, directory: cwd, workspace, model })\n const available = await client.model.list({ location: { directory: cwd, workspace } })\n if (!available.data.some((item) => item.providerID === model.providerID && item.id === model.modelID))\n return reportRunError(input, `Model unavailable: ${model.providerID}/${model.modelID}`, session?.id)\n }\n const agent = await validateAgent(client, cwd, input.agent)\n const selected =\n session ??\n (await client.session.create({\n agent,\n model: model ? { providerID: model.providerID, id: model.modelID, variant } : undefined,\n location: { directory: cwd },\n }))\n if (!session && input.title !== undefined) {\n await client.session.rename({\n sessionID: selected.id,\n title: input.title || prepared.message.slice(0, 50) + (prepared.message.length > 50 ? \"...\" : \"\"),\n })\n }\n\n await runNonInteractivePrompt({\n client,\n sessionID: selected.id,\n message: prepared.message,\n files: prepared.files,\n 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,\n renderToolError,\n }).catch((error) => reportRunError(input, errorMessage(error), selected.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\nexport function pickRunModel(\n explicit: { providerID: string; modelID: string } | undefined,\n variant: string | undefined,\n session: { providerID: string; modelID: string } | undefined,\n fallback: { providerID: string; modelID: string } | undefined,\n) {\n if (explicit) return explicit\n if (!variant) return\n return session ?? fallback\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 if (!value) return\n const ref = Model.Ref.parse(value)\n return {\n model: { providerID: ref.providerID, modelID: ref.id },\n variant: ref.variant,\n }\n}\n\nasync function validateAgent(client: OpenCodeClient, directory: string, name?: string) {\n if (!name) return\n const agents = await client.agent\n .list({ location: { directory } })\n .then((result) => result.data)\n .catch(() => undefined)\n if (!agents) {\n warning(\"failed to list agents. Falling back to default agent\")\n return\n }\n const agent = agents.find((item) => item.id === name)\n if (!agent) {\n warning(`agent \"${name}\" not found. Falling back to default agent`)\n return\n }\n if (agent.mode === \"subagent\") {\n warning(`agent \"${name}\" is a subagent, not a primary agent. Falling back to default agent`)\n return\n }\n return name\n}\n\nasync function selectSession(client: OpenCodeClient, directory: string, input: RunCommandInput) {\n const selected = input.session\n ? await client.session.get({ sessionID: input.session }).catch(() => undefined)\n : input.continue\n ? await client.session\n .list({ directory, parentID: null, limit: 1, order: \"desc\" })\n .then((result) => result.data[0])\n : undefined\n if (input.session && !selected) fail(\"Session not found\")\n if (!selected || !input.fork) return selected\n return client.session.fork({ sessionID: selected.id })\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: MiniToolPart) {\n const info = toolInlineInfo(part)\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: MiniToolPart) {\n const info = toolInlineInfo(part)\n UI.println(UI.Style.TEXT_NORMAL + \"✗\", UI.Style.TEXT_NORMAL + `${info.title} failed`)\n}\n\nfunction warning(message: string) {\n UI.println(UI.Style.TEXT_WARNING_BOLD + \"!\", UI.Style.TEXT_NORMAL, message)\n}\n\nfunction errorMessage(error: unknown) {\n if (error instanceof Error) return error.message\n if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\")\n return error.message\n return String(error)\n}\n\n/** @internal Used by the V1 command boundary before a Session exists. */\nexport function reportRunError(input: Pick<RunCommandInput, \"format\">, message: string, sessionID?: string) {\n process.exitCode = 1\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify({\n type: \"error\",\n timestamp: Date.now(),\n sessionID: sessionID ?? \"\",\n error: { type: \"unknown\", message },\n }) + \"\\n\",\n )\n return\n }\n UI.error(message)\n}\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n",
"import type { EventSubscribeOutput, OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { SessionMessage } from \"@opencode-ai/schema/session-message\"\nimport { EOL } from \"node:os\"\nimport { readFile } from \"node:fs/promises\"\nimport { toolOutputText, type MiniToolPart } from \"@opencode-ai/tui/mini/tool\"\nimport { UI } from \"./ui\"\n\ntype Model = {\n providerID: string\n modelID: string\n}\n\ntype File = {\n url: string\n filename: string\n mime: string\n}\n\ntype Input = {\n client: OpenCodeClient\n sessionID: string\n 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: MiniToolPart) => Promise<void>\n renderToolError: (part: MiniToolPart) => 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, unknown>\n raw?: string\n provider?: unknown\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 let submitted = false\n let promoted = false\n let emittedError = false\n let questionRejected = false\n let permissionRejected = false\n let formCancelled = false\n let interrupted = false\n let v1InvalidOutput = 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 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 rejectQuestion = async (request: { id: string }) => {\n questionRejected = true\n await input.client.question.reject({ sessionID: input.sessionID, requestID: request.id }).catch(() => {})\n }\n\n const cancelForm = async (request: Pick<FormRequest, \"id\" | \"sessionID\">) => {\n formCancelled = true\n await input.client.form.cancel({ sessionID: request.sessionID, formID: request.id }).catch(() => {})\n }\n\n const consume = async () => {\n while (!controller.signal.aborted) {\n const next = await stream.next().catch((error) => {\n if (!emittedError) throw error\n return { done: true as const, value: undefined }\n })\n if (next.done) {\n if (emittedError) return\n throw new Error(\"Event stream disconnected during prompt execution\")\n }\n const event = next.value\n\n if (event.type === \"permission.v2.asked\" && submitted && event.data.sessionID === input.sessionID) {\n await replyPermission(event.data)\n continue\n }\n if (event.type === \"question.v2.asked\" && submitted && event.data.sessionID === input.sessionID) {\n await rejectQuestion(event.data)\n continue\n }\n if (\n event.type === \"form.created\" &&\n submitted &&\n (event.data.form.sessionID === input.sessionID ||\n (!input.attached && event.data.form.sessionID === GLOBAL_FORM_SESSION_ID))\n ) {\n await cancelForm(event.data.form)\n continue\n }\n if (!(\"sessionID\" in event.data) || event.data.sessionID !== input.sessionID) continue\n const time = toMillis(\"created\" in event ? event.created : undefined)\n\n if (event.type === \"session.input.promoted\") {\n if (event.data.inputID === messageID) {\n promoted = true\n continue\n }\n }\n if (\n event.type === \"session.execution.interrupted\" &&\n event.data.reason === \"user\" &&\n (interrupted || permissionRejected || questionRejected || formCancelled)\n ) {\n return\n }\n if (!promoted) 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\", { id: partID(event.id), timestamp: time })\n continue\n }\n if (event.type === \"session.text.ended\") {\n const started = starts.get(\"text\")\n starts.delete(\"text\")\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 writeText(part, time)\n continue\n }\n\n if (event.type === \"session.reasoning.started\") {\n flushStep()\n starts.set(\"reasoning\", { id: partID(event.id), timestamp: time })\n continue\n }\n if (event.type === \"session.reasoning.ended\" && input.thinking) {\n const started = starts.get(\"reasoning\")\n starts.delete(\"reasoning\")\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 if (emit(\"reasoning\", time, { part })) continue\n const text = part.text.trim()\n if (!text) continue\n const line = `Thinking: ${text}`\n if (!process.stdout.isTTY) {\n process.stdout.write(line + EOL)\n continue\n }\n UI.empty()\n UI.println(`${UI.Style.TEXT_DIM}\\u001b[3m${line}\\u001b[0m${UI.Style.TEXT_NORMAL}`)\n UI.empty()\n continue\n }\n\n if (event.type === \"session.tool.input.started\") {\n flushStep()\n tools.set(event.data.callID, {\n id: partID(event.id),\n timestamp: time,\n assistantMessageID: event.data.assistantMessageID,\n tool: event.data.name,\n input: {},\n })\n continue\n }\n if (event.type === \"session.tool.input.ended\") {\n const current = tools.get(event.data.callID)\n if (current) current.raw = event.data.text\n continue\n }\n if (event.type === \"session.tool.called\") {\n flushStep()\n const current = tools.get(event.data.callID)\n tools.set(event.data.callID, {\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 })\n continue\n }\n if (event.type === \"session.tool.success\") {\n const current = tools.get(event.data.callID) ?? fallbackTool(event)\n const part: MiniToolPart = {\n id: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n callID: event.data.callID,\n tool: current.tool,\n state: {\n status: \"completed\",\n input: current.input,\n output: toolOutputText(current.tool, event.data.content),\n title: current.tool,\n metadata: {\n structured: event.data.structured,\n content: event.data.content,\n result: event.data.result,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(event.data.callID)\n if (!emit(\"tool_use\", time, { part })) await input.renderTool(part)\n continue\n }\n if (event.type === \"session.tool.failed\") {\n const current = tools.get(event.data.callID) ?? fallbackTool(event)\n const error = event.data.error.message\n const part: MiniToolPart = {\n id: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n callID: event.data.callID,\n tool: current.tool,\n state: {\n status: \"error\",\n input: current.input,\n error,\n metadata: {\n result: event.data.result,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(event.data.callID)\n if (input.compatibility === \"v1\" && (permissionRejected || questionRejected || formCancelled)) continue\n if (!emit(\"tool_use\", time, { part })) {\n await input.renderToolError(part)\n UI.error(error)\n }\n continue\n }\n\n if (event.type === \"session.step.ended\") {\n flushStep()\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-finish\",\n reason: event.data.finish,\n snapshot: event.data.snapshot,\n cost: event.data.cost,\n tokens: event.data.tokens,\n }\n emit(\"step_finish\", time, { part })\n continue\n }\n if (event.type === \"session.step.failed\") {\n if (\n input.compatibility === \"v1\" &&\n event.data.error.message === \"Provider stream ended without a terminal finish event\"\n ) {\n pendingStep = undefined\n v1InvalidOutput = true\n continue\n }\n if (interrupted || permissionRejected || questionRejected || 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 (\n input.compatibility === \"v1\" &&\n (v1InvalidOutput || permissionRejected || questionRejected || formCancelled)\n )\n return\n flushStep()\n if (!emittedError && !questionRejected && !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 || questionRejected || 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 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, questions, forms] = await Promise.all([\n input.client.permission.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.client.question.list({ sessionID: input.sessionID }).catch(() => undefined),\n Promise.all(\n (input.attached ? [input.sessionID] : [input.sessionID, GLOBAL_FORM_SESSION_ID]).map((sessionID) =>\n input.client.form.list({ sessionID }).catch(() => undefined),\n ),\n ),\n ])\n await Promise.all([\n ...(permissions ?? []).map(replyPermission),\n ...(questions ?? []).map(rejectQuestion),\n ...forms.flatMap((response) => response ?? []).map(cancelForm),\n ])\n await completed\n } finally {\n process.off(\"SIGINT\", interrupt)\n controller.abort()\n await stream.return?.(undefined).catch(() => {})\n }\n}\n\nfunction partID(eventID: string) {\n return `prt_${eventID.replace(/^evt_/, \"\")}`\n}\n\nfunction fallbackTool(event: {\n id: string\n created: number\n data: { assistantMessageID: string; callID: string }\n}): ToolState {\n return {\n id: partID(event.id),\n timestamp: toMillis(event.created),\n assistantMessageID: event.data.assistantMessageID,\n tool: \"tool\",\n input: {},\n }\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": ";88BAIA,oBAAS,0BACT,yBCHA,mBAAS,gBACT,wBAAS,uGCHT,mBAAS,iBAEF,SAAM,OAAQ,MACnB,cAAU,gBACV,iBAAa,eACb,uBAAmB,uBACnB,sBAAkB,sBACpB,OAEO,cAAS,MAAO,SAAI,EAAmB,CAC5C,QAAQ,OAAO,MAAM,EAAQ,KAAK,GAAG,EAAI,EAAG,EAG9C,IAAI,EAAQ,GAEL,SAAS,EAAK,EAAG,CACtB,GAAI,EAAO,OACX,EAAQ,EAAM,WAAW,EACzB,EAAQ,GAGH,SAAS,EAAK,CAAC,EAAiB,CACrC,GAAI,EAAQ,WAAW,SAAS,EAAG,EAAU,EAAQ,MAAM,CAAgB,EAC3E,EAAQ,EAAM,iBA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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,EAAoB,CACjD,IAAM,EAAO,EAAe,CAAI,EAChC,EAAG,QAAQ,EAAG,MAAM,YAAc,SAAI,EAAG,MAAM,YAAc,GAAG,EAAK,cAAc,EAGrF,SAAS,CAAO,CAAC,EAAiB,CAChC,EAAG,QAAQ,EAAG,MAAM,kBAAoB,IAAK,EAAG,MAAM,YAAa,CAAO,EAG5E,SAAS,EAAY,CAAC,EAAgB,CACpC,GAAI,aAAiB,MAAO,OAAO,EAAM,QACzC,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,OAAO,EAAM,UAAY,SAChG,OAAO,EAAM,QACf,OAAO,OAAO,CAAK,EAId,SAAS,CAAc,CAAC,EAAwC,EAAiB,EAAoB,CAE1G,GADA,QAAQ,SAAW,EACf,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UAAU,CACb,KAAM,QACN,UAAW,KAAK,IAAI,EACpB,UAAW,GAAa,GACxB,MAAO,CAAE,KAAM,UAAW,SAAQ,CACpC,CAAC,EAAI;AAAA,CACP,EACA,OAEF,EAAG,MAAM,CAAO,EAGlB,SAAS,CAAI,CAAC,EAAwB,CACpC,MAAU,MAAM,CAAO",
"debugId": "FFE7DD4410529A5064756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["../core/src/installation/version.ts"],
"sourcesContent": [
"declare global {\n const OPENCODE_VERSION: string\n const OPENCODE_CHANNEL: string\n}\n\nexport const InstallationVersion = typeof OPENCODE_VERSION === \"string\" ? OPENCODE_VERSION : \"local\"\nexport const InstallationChannel = typeof OPENCODE_CHANNEL === \"string\" ? OPENCODE_CHANNEL : \"local\"\nexport const InstallationLocal = InstallationChannel === \"local\"\n"
],
"mappings": ";AAKO,IAAM,EAA6D,mBAC7D,EAA6D,OAC7D,EAAoB",
"debugId": "E9953DAA1E76DE5464756E2164756E21",
"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 options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.mcp.list({ location: { directory: process.cwd() } }))\n const servers = response.data.toSorted((a, b) => a.name.localeCompare(b.name))\n if (servers.length === 0) {\n process.stdout.write(\"No MCP servers configured\" + EOL)\n return\n }\n const width = Math.max(...servers.map((server) => server.name.length))\n const lines = servers.map(\n (server) => `${icon(server.status)} ${server.name.padEnd(width)} ${describe(server.status)}`,\n )\n process.stdout.write(lines.join(EOL) + EOL)\n }),\n)\n\nfunction icon(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"connected\":\n return \"✓\"\n case \"needs_auth\":\n return \"⚠\"\n case \"failed\":\n case \"needs_client_registration\":\n return \"✗\"\n default:\n return \"○\"\n }\n}\n\nfunction describe(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"needs_auth\":\n return \"needs authentication\"\n case \"needs_client_registration\":\n return `needs client registration: ${status.error}`\n case \"failed\":\n return `failed: ${status.error}`\n default:\n return status.status\n }\n}\n"
],
"mappings": ";+9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\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.list,\n Effect.fn(\"cli.plugin.list\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.plugin.list({ location: { directory: process.cwd() } }))\n const plugins = response.data.toSorted((a, b) => a.id.localeCompare(b.id))\n if (plugins.length === 0) {\n process.stdout.write(\"No plugins loaded\" + EOL)\n return\n }\n process.stdout.write(plugins.map((plugin) => plugin.id).join(EOL) + EOL)\n }),\n)\n"
],
"mappings": ";+9BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,YAAO,cAAS,UAClC,OAAO,QAAG,sBAAiB,OAAE,cAAU,OAAG,MACxC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,QADQ,WAAO,OAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAClF,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzE,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,oBAAsB,CAAG,EAC9C,OAEF,QAAQ,OAAO,MAAM,EAAQ,IAAI,CAAC,IAAW,EAAO,EAAE,EAAE,KAAK,CAAG,EAAI,CAAG,EACxE,CACH",
"debugId": "021ED190AF18FD5864756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/service/start.ts"],
"sourcesContent": [
"import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.start,\n Effect.fn(\"cli.service.start\")(function* () {\n const transport = yield* Service.ensure(yield* ServiceConfig.options())\n process.stdout.write(transport.url + EOL)\n }),\n)\n"
],
"mappings": ";g7BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,WACnC,OAAO,QAAG,wBAAmB,OAAE,cAAU,OAAG,MAC1C,SAAM,OAAY,WAAO,OAAQ,YAAO,WAAO,OAAc,aAAQ,CAAC,EACtE,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH",
"debugId": "00A04A3CEA35C11664756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["../simulation/src/backend/network.ts", "../simulation/src/backend/openai.ts", "../simulation/src/backend/simulated-provider.ts", "../simulation/src/backend/index.ts"],
"sourcesContent": [
"import { Clock, Effect, Layer, Ref } from \"effect\"\nimport { HttpClient, HttpClientResponse, type HttpMethod } from \"effect/unstable/http\"\nimport { HttpClientError, TransportError } from \"effect/unstable/http/HttpClientError\"\nimport type { HttpClientRequest } from \"effect/unstable/http\"\nimport { SimulationProtocol } from \"../protocol\"\n\n/**\n * Simulated network.\n *\n * Replaces the `HttpClient.HttpClient` platform node in simulation mode. All\n * outbound HTTP resolves against an in-memory route table; unknown\n * destinations fail loudly with a transport error so no simulation run can\n * silently reach the real network. The scripted LLM is one registered route,\n * not a separate mechanism.\n *\n * Each acquired run owns its routes and request log.\n */\n\nexport interface Route {\n /** Return a response effect to claim the request, undefined to pass. */\n readonly match: (\n request: HttpClientRequest.HttpClientRequest,\n url: URL,\n ) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError> | undefined\n}\n\nexport type LogEntry = SimulationProtocol.Backend.NetworkLogEntry\n\nconst LOG_LIMIT = 1000\n\n/** Static JSON route: exact method + origin/path match answered with a fixed body. */\nexport function json(method: HttpMethod.HttpMethod, url: string, body: unknown): Route {\n return {\n match: (request, requestUrl) => {\n if (request.method !== method) return undefined\n if (requestUrl.origin + requestUrl.pathname !== url) return undefined\n return Effect.sync(() =>\n HttpClientResponse.fromWeb(\n request,\n new Response(JSON.stringify(body), { status: 200, headers: { \"content-type\": \"application/json\" } }),\n ),\n )\n },\n }\n}\n\nexport interface Run {\n readonly client: HttpClient.HttpClient\n readonly log: () => Effect.Effect<readonly LogEntry[]>\n}\n\nexport const make = Effect.fn(\"SimulationNetwork.make\")(function* (routes: readonly Route[] = []) {\n const log = yield* Ref.make<readonly LogEntry[]>([])\n const client = HttpClient.make((request, url) =>\n Effect.gen(function* () {\n let matched: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError> | undefined\n for (const route of routes) {\n matched = route.match(request, url)\n if (matched) break\n }\n const entry = {\n time: yield* Clock.currentTimeMillis,\n method: request.method,\n url: url.toString(),\n matched: matched !== undefined,\n }\n yield* Ref.update(log, (entries) => [...entries, entry].slice(-LOG_LIMIT))\n if (matched) return yield* matched\n return yield* Effect.fail(\n new HttpClientError({\n reason: new TransportError({\n request,\n description: `Simulation denied unregistered network destination: ${request.method} ${url}`,\n }),\n }),\n )\n }),\n )\n return { client, log: () => Ref.get(log) } satisfies Run\n})\n\nexport const layer = (routes: readonly Route[] = []) =>\n Layer.effect(HttpClient.HttpClient, make(routes).pipe(Effect.map((run) => run.client)))\n\nexport * as SimulationNetwork from \"./network\"\n",
"import { Effect, Schema, Stream } from \"effect\"\nimport { HttpClientResponse } from \"effect/unstable/http\"\nimport { HttpClientError, TransportError } from \"effect/unstable/http/HttpClientError\"\nimport { OpenAIChatEvent, DEFAULT_BASE_URL, PATH } from \"@opencode-ai/ai/protocols/openai-chat\"\nimport { SimulationNetwork } from \"./network\"\nimport { SimulatedProvider } from \"./simulated-provider\"\n\n/**\n * Driver-answered OpenAI endpoint for the simulated network.\n *\n * Claims `POST {DEFAULT_BASE_URL}{PATH}` (the real openai-chat route\n * endpoint), invokes the simulated provider, and streams the driver's events back as\n * an OpenAI Chat SSE response terminated by `[DONE]`. Everything downstream\n * of the response bytes is the real pipeline: SSE framing, the OpenAIChat\n * event schema, the protocol state machine, and Lifecycle grammar.\n */\n\nconst encodeChunk = Schema.encodeUnknownSync(OpenAIChatEvent)\n\nconst encoder = new TextEncoder()\nconst decodeBody = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Json))\n\n// The simulated model id is echoed back only in non-schema fields; the\n// protocol event schema ignores unknown fields, so id/object/model are\n// decorative wire realism.\ntype ProviderItem = Exclude<SimulatedProvider.ProviderResponseEvent, { readonly type: \"finish\" }>\ntype FinishReason = Extract<SimulatedProvider.ProviderResponseEvent, { readonly type: \"finish\" }>[\"reason\"]\n\nfunction chunkOf(item: ProviderItem): OpenAIChatEvent | unknown {\n if (item.type === \"textDelta\") return { choices: [{ delta: { content: item.text } }] }\n if (item.type === \"reasoningDelta\") return { choices: [{ delta: { reasoning_content: item.text } }] }\n if (item.type === \"toolCall\")\n return {\n choices: [\n {\n delta: {\n tool_calls: [\n {\n index: item.index,\n id: item.id,\n function: { name: item.name, arguments: JSON.stringify(item.input) },\n },\n ],\n },\n },\n ],\n }\n return item.chunk\n}\n\nconst finishReasonWire: Record<FinishReason, string> = {\n stop: \"stop\",\n \"tool-calls\": \"tool_calls\",\n length: \"length\",\n \"content-filter\": \"content_filter\",\n}\n\nfunction frame(payload: unknown): Uint8Array {\n return encoder.encode(`data: ${JSON.stringify(payload)}\\n\\n`)\n}\n\nfunction sseBody(\n events: Stream.Stream<SimulatedProvider.ProviderResponseEvent, SimulatedProvider.ProviderDisconnectedError>,\n): Stream.Stream<Uint8Array, SimulatedProvider.ProviderDisconnectedError> {\n return events.pipe(\n Stream.map((event) => {\n if (event.type === \"finish\")\n return frame(encodeChunk({ choices: [{ delta: {}, finish_reason: finishReasonWire[event.reason] }] }))\n if (event.type === \"raw\") return frame(event.chunk)\n return frame(encodeChunk(chunkOf(event)))\n }),\n Stream.concat(Stream.make(encoder.encode(\"data: [DONE]\\n\\n\"))),\n )\n}\n\nexport const route = (provider: SimulatedProvider.Interface): SimulationNetwork.Route => ({\n match: (request, url) => {\n if (request.method !== \"POST\") return undefined\n if (url.origin + url.pathname !== DEFAULT_BASE_URL + PATH) return undefined\n return Effect.gen(function* () {\n const body =\n request.body._tag === \"Uint8Array\"\n ? yield* decodeBody(new TextDecoder().decode(request.body.body)).pipe(\n Effect.mapError(\n (cause) =>\n new HttpClientError({\n reason: new TransportError({\n request,\n cause,\n description: \"Simulation received an invalid OpenAI request body\",\n }),\n }),\n ),\n )\n : {}\n return HttpClientResponse.fromWeb(\n request,\n new Response(Stream.toReadableStream(sseBody(provider.stream({ url: url.toString(), body }))), {\n status: 200,\n headers: { \"content-type\": \"text/event-stream\" },\n }),\n )\n })\n },\n})\n\nexport * as SimulationOpenAI from \"./openai\"\n",
"import { InstallationVersion } from \"@opencode-ai/core/installation/version\"\nimport { Cause, Context, Effect, Fiber, FiberSet, Layer, PubSub, Queue, Ref, Schema, Semaphore, Stream } from \"effect\"\nimport { SimulationControlServer } from \"../control-server\"\nimport { SimulationProtocol } from \"../protocol\"\n\nexport interface ProviderRequest {\n readonly url: string\n readonly body: unknown\n}\n\nexport type ProviderResponseEvent =\n | SimulationProtocol.Backend.Item\n | { readonly type: \"finish\"; readonly reason: SimulationProtocol.Backend.FinishReason }\n\nexport class ProviderDisconnectedError extends Schema.TaggedErrorClass<ProviderDisconnectedError>()(\n \"SimulatedProvider.ProviderDisconnectedError\",\n { message: Schema.String },\n) {}\n\nexport interface Interface {\n readonly stream: (request: ProviderRequest) => Stream.Stream<ProviderResponseEvent, ProviderDisconnectedError>\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/simulation/SimulatedProvider\") {}\n\ninterface ProviderInvocation extends ProviderRequest {\n readonly id: string\n}\n\ninterface PendingInvocation extends ProviderInvocation {\n readonly responses: Queue.Queue<ProviderResponseEvent, ProviderDisconnectedError | Cause.Done>\n}\n\ninterface State {\n readonly counter: number\n readonly pending: ReadonlyMap<string, PendingInvocation>\n}\n\ninterface Driver {\n readonly requests: Stream.Stream<ProviderInvocation>\n readonly push: (\n id: string,\n items: readonly SimulationProtocol.Backend.Item[],\n ) => Effect.Effect<void, InvocationNotFoundError>\n readonly finish: (\n id: string,\n reason: SimulationProtocol.Backend.FinishReason,\n ) => Effect.Effect<void, InvocationNotFoundError>\n readonly disconnect: (id: string) => Effect.Effect<void, InvocationNotFoundError>\n readonly pending: () => Effect.Effect<readonly ProviderInvocation[]>\n}\n\nclass InvocationNotFoundError extends Schema.TaggedErrorClass<InvocationNotFoundError>()(\n \"SimulatedProvider.InvocationNotFoundError\",\n { id: Schema.String, message: Schema.String },\n) {}\n\nclass ControllerDisconnectedError extends Schema.TaggedErrorClass<ControllerDisconnectedError>()(\n \"SimulatedProvider.ControllerDisconnectedError\",\n { message: Schema.String },\n) {}\n\ntype ControlSocket = SimulationControlServer.Socket\n\nexport const layerDrive = (options: { readonly endpoint: string }) =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const state = yield* Ref.make<State>({ counter: 0, pending: new Map() })\n const opened = yield* PubSub.unbounded<ProviderInvocation>()\n const lock = yield* Semaphore.make(1)\n\n const close = (invocation: PendingInvocation) =>\n Effect.gen(function* () {\n yield* Queue.shutdown(invocation.responses)\n yield* lock.withPermit(\n Ref.update(state, (current) =>\n current.pending.get(invocation.id) === invocation ? remove(current, invocation.id) : current,\n ),\n )\n })\n\n yield* Effect.addFinalizer(() =>\n Effect.gen(function* () {\n const current = yield* Ref.get(state)\n yield* Effect.forEach(current.pending.values(), (invocation) => Queue.shutdown(invocation.responses), {\n discard: true,\n })\n yield* PubSub.shutdown(opened)\n }),\n )\n\n const open = (request: ProviderRequest) =>\n lock.withPermit(\n Effect.gen(function* () {\n const current = yield* Ref.get(state)\n const id = `inv_${current.counter + 1}`\n const responses = yield* Queue.bounded<ProviderResponseEvent, ProviderDisconnectedError | Cause.Done>(256)\n const invocation: PendingInvocation = { id, ...request, responses }\n yield* Ref.set(state, {\n counter: current.counter + 1,\n pending: new Map(current.pending).set(id, invocation),\n })\n yield* PubSub.publish(opened, { id, ...request })\n return invocation\n }),\n )\n\n const requireInvocation = (id: string) =>\n Effect.gen(function* () {\n const current = yield* Ref.get(state)\n const invocation = current.pending.get(id)\n if (invocation) return invocation\n return yield* Effect.fail(\n new InvocationNotFoundError({\n id,\n message: `Simulated provider invocation not found or already finished: ${id}`,\n }),\n )\n })\n\n const remove = (current: State, id: string) => {\n const pending = new Map(current.pending)\n pending.delete(id)\n return { ...current, pending }\n }\n\n const driver: Driver = {\n requests: Stream.unwrap(\n lock.withPermit(\n Effect.gen(function* () {\n const subscription = yield* PubSub.subscribe(opened)\n const current = yield* Ref.get(state)\n const pending = Array.from(current.pending.values(), ({ id, url, body }) => ({ id, url, body }))\n return Stream.concat(Stream.fromIterable(pending), Stream.fromEffectRepeat(PubSub.take(subscription)))\n }),\n ),\n ),\n push: (id, items) =>\n Effect.gen(function* () {\n const invocation = yield* lock.withPermit(requireInvocation(id))\n yield* Queue.offerAll(invocation.responses, items)\n }),\n finish: (id, reason) =>\n Effect.gen(function* () {\n const invocation = yield* lock.withPermit(\n Effect.gen(function* () {\n const invocation = yield* requireInvocation(id)\n const current = yield* Ref.get(state)\n yield* Ref.set(state, remove(current, id))\n return invocation\n }),\n )\n yield* Queue.offer(invocation.responses, { type: \"finish\", reason })\n yield* Queue.end(invocation.responses)\n }),\n disconnect: (id) =>\n Effect.gen(function* () {\n const invocation = yield* lock.withPermit(\n Effect.gen(function* () {\n const invocation = yield* requireInvocation(id)\n const current = yield* Ref.get(state)\n yield* Ref.set(state, remove(current, id))\n return invocation\n }),\n )\n yield* Queue.fail(\n invocation.responses,\n new ProviderDisconnectedError({ message: \"Simulated model provider disconnected\" }),\n )\n }),\n pending: () =>\n lock.withPermit(\n Ref.get(state).pipe(\n Effect.map((current) => Array.from(current.pending.values(), ({ id, url, body }) => ({ id, url, body }))),\n ),\n ),\n }\n\n const fibers = yield* FiberSet.make<void, unknown>()\n const activeController = yield* Ref.make<Fiber.Fiber<void> | undefined>(undefined)\n const controllerLock = yield* Semaphore.make(1)\n yield* SimulationControlServer.start({\n endpoint: options.endpoint,\n label: \"opencode drive backend websocket\",\n data: () => ({}),\n decode: SimulationProtocol.Backend.decodeRequestEffect,\n handle: (socket, request) => handle(driver, fibers, activeController, controllerLock, socket, request),\n close: (socket) => releaseController(activeController, controllerLock, socket),\n })\n yield* Effect.sync(() => process.stderr.write(`opencode drive backend websocket: ${options.endpoint}\\n`))\n\n return Service.of({\n stream: (request) =>\n Stream.unwrap(\n Effect.acquireRelease(open(request), close).pipe(\n Effect.map((invocation) =>\n Stream.fromQueue(invocation.responses).pipe(Stream.takeUntil((event) => event.type === \"finish\")),\n ),\n ),\n ),\n })\n }),\n )\n\nfunction handle(\n driver: Driver,\n fibers: FiberSet.FiberSet<void, unknown>,\n activeController: Ref.Ref<Fiber.Fiber<void> | undefined>,\n controllerLock: Semaphore.Semaphore,\n socket: ControlSocket,\n request: SimulationProtocol.Backend.Request,\n) {\n switch (request.method) {\n case \"simulation.handshake\":\n return SimulationProtocol.Handshake.dispatch(\n {\n role: \"backend\",\n server: { name: \"opencode\", version: InstallationVersion },\n capabilities: SimulationProtocol.Backend.Capabilities,\n },\n request.params,\n )\n case \"llm.attach\":\n return controllerLock.withPermit(\n Effect.gen(function* () {\n if (socket.data.closed)\n return yield* Effect.fail(\n new ControllerDisconnectedError({ message: \"Drive controller disconnected before attachment\" }),\n )\n const previous = yield* Ref.get(activeController)\n if (previous) yield* Fiber.interrupt(previous)\n const attachment = yield* FiberSet.run(\n fibers,\n driver.requests.pipe(\n Stream.runForEach((invocation) =>\n Effect.sync(() => {\n socket.send(JSON.stringify({ jsonrpc: \"2.0\", method: \"llm.request\", params: invocation }))\n }),\n ),\n ),\n )\n if (socket.data.closed) {\n yield* Fiber.interrupt(attachment)\n return yield* Effect.fail(\n new ControllerDisconnectedError({ message: \"Drive controller disconnected during attachment\" }),\n )\n }\n socket.data.attachment = attachment\n yield* Ref.set(activeController, attachment)\n return { attached: true }\n }),\n )\n case \"llm.chunk\":\n return driver.push(request.params.id, request.params.items).pipe(Effect.as({ ok: true }))\n case \"llm.finish\":\n return driver.finish(request.params.id, request.params.reason).pipe(Effect.as({ ok: true }))\n case \"llm.disconnect\":\n return driver.disconnect(request.params.id).pipe(Effect.as({ ok: true }))\n case \"llm.pending\":\n return driver.pending().pipe(Effect.map((invocations) => ({ invocations })))\n }\n}\n\nfunction releaseController(\n activeController: Ref.Ref<Fiber.Fiber<void> | undefined>,\n controllerLock: Semaphore.Semaphore,\n socket: ControlSocket,\n) {\n return controllerLock.withPermit(\n Effect.gen(function* () {\n const attachment = socket.data.attachment\n if (!attachment) return\n yield* Fiber.interrupt(attachment)\n yield* Ref.update(activeController, (active) => (active === attachment ? undefined : active))\n }),\n )\n}\n\nexport * as SimulatedProvider from \"./simulated-provider\"\n",
"import { LayerNode } from \"@opencode-ai/core/effect/layer-node\"\nimport { httpClient } from \"@opencode-ai/core/effect/app-node-platform\"\nimport { Config, Effect, Layer } from \"effect\"\nimport { HttpClient } from \"effect/unstable/http\"\nimport { DriveManifest } from \"../manifest\"\nimport { SimulationNetwork } from \"./network\"\nimport { SimulationOpenAI } from \"./openai\"\nimport { SimulatedProvider } from \"./simulated-provider\"\n\n/**\n * Layer replacements applied when the server is built in simulation mode.\n *\n * The server merges these into the app node build when `OPENCODE_SIMULATE`\n * is enabled, via a dynamic import so this module is never loaded eagerly.\n *\n * - Network: all outbound HTTP resolves against the simulated route table;\n * unknown destinations are denied. The driver-answered OpenAI endpoint is\n * registered here as the first route.\n *\n */\n\nexport const simulationReplacements = Effect.fn(\"Simulation.replacements\")(function* () {\n // ModelsDev dies when its catalog fetch fails, so simulation answers it with\n // an empty catalog; providers come from seeded config instead.\n const models = SimulationNetwork.json(\"GET\", \"https://models.dev/api.json\", {})\n const drive = yield* Config.string(\"OPENCODE_DRIVE\").pipe(Config.withDefault(undefined))\n if (!drive) return [[httpClient, SimulationNetwork.layer([models])]] satisfies LayerNode.Replacements\n\n const manifest = yield* DriveManifest.resolve()\n const networkLayer = Layer.effect(\n HttpClient.HttpClient,\n Effect.gen(function* () {\n const provider = yield* SimulatedProvider.Service\n const network = yield* SimulationNetwork.make([SimulationOpenAI.route(provider), models])\n return network.client\n }),\n ).pipe(\n Layer.provide(\n SimulatedProvider.layerDrive({\n endpoint: manifest.endpoints.backend,\n }),\n ),\n )\n return [[httpClient, networkLayer]] satisfies LayerNode.Replacements\n})\n\nexport * as Simulation from \"./index\"\n"
],
"mappings": ";s4BA4BA,SAAM,QAAY,UAGX,cAAS,OAAI,MAAC,OAA+B,OAAa,OAAsB,MACrF,WAAO,MACL,WAAO,MAAC,EAAS,IAAe,CAC9B,GAAI,EAAQ,SAAW,EAAQ,OAC/B,GAAI,EAAW,OAAS,EAAW,WAAa,EAAK,OACrD,OAAO,EAAO,KAAK,IACjB,EAAmB,QACjB,EACA,IAAI,SAAS,KAAK,UAAU,CAAI,EAAG,CAAE,OAAQ,IAAK,QAAS,CAAE,eAAgB,kBAAmB,CAAE,CAAC,CACrG,CACF,EAEJ,EAQK,IAAM,EAAO,EAAO,GAAG,wBAAwB,EAAE,SAAU,CAAC,EAA2B,CAAC,EAAG,CAChG,IAAM,EAAM,MAAO,EAAI,KAA0B,CAAC,CAAC,EA0BnD,MAAO,CAAE,OAzBM,EAAW,KAAK,CAAC,EAAS,IACvC,EAAO,IAAI,SAAU,EAAG,CACtB,IAAI,EACJ,QAAW,KAAS,EAElB,GADA,EAAU,EAAM,MAAM,EAAS,CAAG,EAC9B,EAAS,MAEf,IAAM,EAAQ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ts", "src/services/service-config.ts", "src/util/process.ts"],
"sourcesContent": [
"import { ServiceStatus } from \"@opencode-ai/protocol/groups/health\"\nimport { Effect, FileSystem, Option, Schedule, Schema } from \"effect\"\nimport { spawn, type ChildProcess } from \"node:child_process\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\nimport type { DiscoverOptions, Endpoint, EnsureOptions, StopOptions } from \"../service.js\"\n\nexport * from \"../service.js\"\n/** Contents of the local service registration file. */\nexport type Info = import(\"../service.js\").Info\n\n// Find, start, and stop the local opencode background service.\n//\n// The service daemon advertises itself through a registration file in the\n// user's state directory: url, pid, version, and the private password, with\n// 0600 permissions. That file is the complete discovery contract — reading it\n// is all a client needs to connect. The daemon's own configuration (port,\n// persisted password) is CLI-owned and never read here.\n\ntype Contender = {\n readonly child: ChildProcess\n readonly error: () => Error | undefined\n}\n\n// Read-only lookup: registration file plus health check and version gate.\n// Never spawns; escalation to ensure() is the caller's policy.\n/** Discover a healthy, compatible local service without starting one. */\nexport const discover = Effect.fn(\"service.discover\")(function* (options: DiscoverOptions = {}) {\n return (yield* discoverLocal(options))?.endpoint\n})\n\n/** Recognize an authenticated compatible service bound to an expected URL, including while it starts or fails. */\nexport const incumbent = Effect.fn(\"service.incumbent\")(function* (\n options: DiscoverOptions & { readonly url: string },\n) {\n const info = yield* read(options.file)\n const found = info === undefined ? undefined : yield* probe({ ...info, url: options.url })\n if (found === undefined || found.legacy) return undefined\n if (options.version !== undefined && found.version !== options.version) return undefined\n return { endpoint: found.endpoint, state: found.state }\n})\n\nconst discoverLocal = Effect.fnUntraced(function* (options: DiscoverOptions) {\n const found = (yield* registered(options.file)).service\n if (found?.state !== \"ready\") return undefined\n if (options.version !== undefined && found.version !== options.version) return undefined\n return found\n})\n\n// Idempotent ensure-running: reuses a healthy compatible server, replaces a\n// version-mismatched one, and otherwise spawns small contenders until a server\n// becomes discoverable. A contender is never killed merely for slow startup.\n/** Ensure a healthy, compatible local service is running. */\nexport const ensure = Effect.fn(\"service.ensure\")(function* (options: EnsureOptions = {}) {\n const contenders = new Set<Contender>()\n let announced = false\n let lastSpawn = 0\n let spawnDelay = 5_000\n let ownerHeld = false\n const announce = (reason: \"missing\" | \"version-mismatch\", previousVersion?: string) =>\n Effect.sync(() => {\n if (announced) return\n announced = true\n options.onStart?.(reason, previousVersion)\n })\n const spawnContender = Effect.gen(function* () {\n const [command, ...args] = options.command ?? [\"opencode\", \"serve\", \"--service\"]\n if (command === undefined) return yield* Effect.fail(new Error(\"Missing service command\"))\n return yield* Effect.try({\n try: () => {\n const child = spawn(command, args, { detached: true, stdio: \"ignore\" })\n let error: Error | undefined\n child.once(\"error\", (cause) => {\n error = new Error(\"Failed to start server\", { cause })\n })\n child.unref()\n return { child, error: () => error }\n },\n catch: (cause) => new Error(\"Failed to start server\", { cause }),\n })\n })\n const found = yield* Effect.gen(function* () {\n const registration = yield* registered(options.file, true)\n const info = registration.info\n const service = registration.service\n if (service !== undefined) {\n ownerHeld = false\n spawnDelay = 5_000\n const compatible = !service.legacy && (options.version === undefined || service.version === options.version)\n if (compatible && service.state === \"ready\") return Option.some(service)\n if (compatible && service.state === \"failed\")\n return yield* Effect.fail(new Error(\"Background service failed to start\"))\n if (compatible) return Option.none<LocalService>()\n yield* announce(\"version-mismatch\", service.version)\n yield* kill(service, options).pipe(Effect.ignore)\n lastSpawn = 0\n return Option.none<LocalService>()\n } else if (lastSpawn === 0 && info !== undefined) lastSpawn = Date.now()\n\n const failure = [...contenders].map(contenderFailure).find((error): error is Error => error !== undefined)\n if (failure !== undefined) return yield* Effect.fail(failure)\n const finished = [...contenders].filter(contenderFinished)\n if (finished.some((item) => item.child.exitCode === 0)) {\n ownerHeld = true\n spawnDelay = Math.min(spawnDelay * 2, 30_000)\n }\n finished.forEach((item) => contenders.delete(item))\n // Keep one candidate plus one lock probe so a pre-lock stall cannot block recovery.\n if (contenders.size < 2 && Date.now() - lastSpawn >= spawnDelay) {\n yield* announce(\"missing\")\n contenders.add(yield* spawnContender)\n lastSpawn = Date.now()\n }\n return Option.none<LocalService>()\n }).pipe(\n Effect.repeat({\n until: Option.isSome,\n schedule: Schedule.max([Schedule.spaced(\"1 second\"), Schedule.recurs(120)]),\n }),\n )\n if (Option.isNone(found))\n return yield* Effect.fail(new Error(\"Timed out waiting for the background service to start\"))\n return found.value.endpoint\n})\n\nfunction contenderFailure(contender: Contender) {\n const error = contender.error()\n if (error !== undefined) return error\n if (contender.child.exitCode !== null && contender.child.exitCode !== 0)\n return new Error(`Server process exited with code ${contender.child.exitCode}`)\n if (contender.child.signalCode !== null)\n return new Error(`Server process terminated by ${contender.child.signalCode}`)\n return undefined\n}\n\nfunction contenderFinished(contender: Contender) {\n return contender.error() !== undefined || contender.child.exitCode !== null || contender.child.signalCode !== null\n}\n\n/** Stop the registered local service. */\nexport const stop = Effect.fn(\"service.stop\")(function* (options: StopOptions = {}) {\n const existing = yield* find(options)\n if (existing !== undefined) yield* kill(existing, options)\n})\n\nfunction fallback() {\n const state = process.env[\"XDG_STATE_HOME\"] ?? join(homedir(), \".local\", \"state\")\n return join(state, \"opencode\", \"service.json\")\n}\n\n/** Create HTTP authentication headers for a service endpoint. */\nexport function headers(endpoint: Endpoint) {\n if (endpoint.auth === undefined) return undefined\n return { authorization: \"Basic \" + btoa(endpoint.auth.username + \":\" + endpoint.auth.password) }\n}\n\n/** Schema for the local service registration file. */\nexport const Info = Schema.Struct({\n id: Schema.optional(Schema.String),\n version: Schema.optional(Schema.String),\n url: Schema.String,\n pid: Schema.Int.check(Schema.isGreaterThan(0)),\n password: Schema.optional(Schema.String),\n})\n\nconst decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))\nconst decodeHealth = Schema.decodeUnknownOption(ServiceStatus.Health)\nconst decodeLegacyHealth = Schema.decodeUnknownOption(Schema.Struct({ healthy: Schema.Literal(true) }))\n\n// A missing or corrupt file means no valid info; callers treat both\n// the same (the registering server self-evicts, clients rediscover).\nconst read = Effect.fnUntraced(function* (file?: string) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(file ?? fallback()).pipe(Effect.option)\n if (Option.isNone(text)) return undefined\n return yield* decode(text.value).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n})\n\ntype LocalService = {\n readonly info: Info\n readonly endpoint: Endpoint\n readonly version?: string\n readonly state: \"ready\" | \"waiting\" | \"failed\"\n readonly legacy: boolean\n}\n\nconst probe = Effect.fnUntraced(function* (info: Info, allowLegacy = false) {\n const endpoint = {\n url: info.url,\n auth:\n info.password === undefined\n ? undefined\n : { type: \"basic\" as const, username: \"opencode\", password: info.password },\n } satisfies Endpoint\n const response = yield* Effect.tryPromise(() =>\n fetch(new URL(\"/api/health\", info.url), {\n headers: headers(endpoint),\n signal: AbortSignal.timeout(2_000),\n }),\n ).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n if (response === undefined) return undefined\n const body = yield* Effect.tryPromise(() => response.json()).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n const health = decodeHealth(body)\n if (Option.isSome(health)) {\n if (health.value.pid !== info.pid) return undefined\n if (info.version !== undefined && health.value.version !== info.version) return undefined\n return {\n info,\n endpoint,\n version: health.value.version,\n state: response.ok ? \"ready\" : response.status === 500 ? \"failed\" : \"waiting\",\n legacy: false,\n } satisfies LocalService\n }\n if (\n !allowLegacy ||\n Option.isNone(decodeLegacyHealth(body)) ||\n (typeof body === \"object\" && body !== null && (\"version\" in body || \"pid\" in body))\n )\n return undefined\n return { info, endpoint, state: \"ready\", legacy: true } satisfies LocalService\n})\n\nconst registered = Effect.fnUntraced(function* (file?: string, allowLegacy = false) {\n const info = yield* read(file)\n if (info === undefined) return { info: undefined, service: undefined }\n return { info, service: yield* probe(info, allowLegacy) }\n})\n\n// Health-checked lookup without the version gate: lifecycle operations must be\n// able to see (and replace or stop) a server from a different version.\nconst find = Effect.fnUntraced(function* (options: { readonly file?: string }) {\n return (yield* registered(options.file, true)).service\n})\n\n// 50ms cadence bounded at ~5s, shared by stop escalation and each ensure\n// discovery window.\nconst poll = Schedule.max([Schedule.spaced(\"50 millis\"), Schedule.recurs(100)])\n\nconst signal = (pid: number, name: NodeJS.Signals) =>\n Effect.try({ try: () => process.kill(pid, name), catch: (cause) => cause }).pipe(Effect.ignore)\n\nconst stopped = Effect.fnUntraced(function* (pid: number) {\n const running = yield* Effect.try({ try: () => process.kill(pid, 0), catch: () => false }).pipe(\n Effect.orElseSucceed(() => false),\n )\n if (!running) return true\n return yield* Effect.fail(new Error(`Server process ${pid} is still running`))\n})\n\nfunction same(left: Info, right: Info) {\n return left.id === right.id && left.version === right.version && left.url === right.url && left.pid === right.pid\n}\n\nconst kill = Effect.fnUntraced(function* (service: LocalService, options: { readonly file?: string }) {\n const requested = yield* requestStop(service)\n if (requested === \"rejected\") return\n if (requested === \"unsupported\") {\n // A stale registration may point at a reused PID. Authenticate again\n // immediately before the legacy signal fallback.\n const current = yield* find(options)\n if (current === undefined || !same(current.info, service.info)) return\n yield* signal(service.info.pid, \"SIGTERM\")\n }\n const done = yield* stopped(service.info.pid).pipe(Effect.retry(poll), Effect.option)\n if (Option.isSome(done)) return\n\n const latest = yield* find(options)\n if (latest === undefined || !same(latest.info, service.info)) return\n yield* signal(service.info.pid, \"SIGKILL\")\n yield* stopped(service.info.pid).pipe(Effect.retry(poll))\n})\n\nconst decodeStopResponse = Schema.decodeUnknownOption(ServiceStatus.StopResponse)\n\nconst requestStop = Effect.fnUntraced(function* (service: LocalService) {\n if (service.info.id === undefined || service.legacy) return \"unsupported\" as const\n const response = yield* Effect.tryPromise(() =>\n fetch(new URL(\"/api/service/stop\", service.info.url), {\n method: \"POST\",\n headers: { ...headers(service.endpoint), \"content-type\": \"application/json\" },\n body: JSON.stringify({ instanceID: service.info.id }),\n signal: AbortSignal.timeout(2_000),\n }),\n ).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n if (response === undefined || response.status === 404 || response.status === 405) return \"unsupported\" as const\n const body = yield* Effect.tryPromise(() => response.json()).pipe(Effect.option, Effect.map(Option.getOrUndefined))\n const decoded = decodeStopResponse(body)\n if (!response.ok || Option.isNone(decoded) || !decoded.value.accepted) return \"rejected\" as const\n return \"accepted\" as const\n})\n\n/** Effect-based local service lifecycle operations. */\nexport const Service = { discover, incumbent, ensure, stop, headers, Info }\n",
"import { Global } from \"@opencode-ai/core/global\"\nimport { InstallationChannel, InstallationVersion } from \"@opencode-ai/core/installation/version\"\nimport { Hash } from \"@opencode-ai/core/util/hash\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, FileSystem, Option, Schema } from \"effect\"\nimport { randomBytes } from \"crypto\"\nimport path from \"path\"\nimport { selfCommand } from \"../util/process\"\n\n// The CLI's service configuration file, plus the Service.EnsureOptions binding that\n// points the client package's service operations at this CLI: which\n// registration file (by channel), which version, and how to spawn opencode.\n\nexport const Info = Schema.Struct({\n hostname: Schema.optional(Schema.String),\n port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),\n password: Schema.optional(Schema.String),\n})\nexport type Info = typeof Info.Type\n\nconst keys = [\"hostname\", \"port\", \"password\"] as const\ntype Key = (typeof keys)[number]\n\nconst decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))\nconst decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info))\n\nexport function filename(channel = InstallationChannel) {\n if (channel === \"latest\") return \"service.json\"\n if (channel === \"local\") return \"service-local.json\"\n return `service-${Hash.fast(channel)}.json`\n}\n\nexport function defaultPort(channel = InstallationChannel) {\n if (channel === \"latest\") 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 versionBelongsToChannel(\n version: string | undefined,\n channel = InstallationChannel,\n installedVersion = InstallationVersion,\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 = InstallationChannel,\n installedVersion = InstallationVersion,\n) {\n if (channel === \"latest\" || channel === \"local\") return\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\nfunction configKey(key: string): Key {\n if (key === \"hostname\" || key === \"port\" || key === \"password\") return key\n throw new Error(`Unknown service config key: ${key}`)\n}\n\nconst paths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem\n const global = yield* Global.Service\n const name = filename()\n const file = path.join(global.state, name)\n return {\n fs,\n file,\n legacyFile: path.join(global.state, \"service.json\"),\n configFile: path.join(global.config, name),\n }\n})\n\nexport const options = Effect.fnUntraced(function* () {\n const { file, legacyFile } = yield* paths\n yield* migrateRegistration(legacyFile, file)\n return {\n file,\n version: InstallationVersion,\n command: [...selfCommand(), \"serve\", \"--service\"],\n }\n})\n\nexport const read = Effect.fn(\"cli.service-config.read\")(function* () {\n const { fs, configFile } = yield* paths\n return yield* fs.readFileString(configFile).pipe(\n Effect.flatMap(decodeInfo),\n Effect.catch(() => Effect.succeed({} as Info)),\n )\n})\n\nconst write = Effect.fn(\"cli.service-config.write\")(function* (value: Info) {\n const { fs, configFile } = yield* paths\n const temp = configFile + \".tmp\"\n yield* fs.makeDirectory(path.dirname(configFile), { recursive: true })\n yield* fs.writeFileString(temp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n yield* fs.rename(temp, configFile)\n})\n\nexport const password = Effect.fn(\"cli.service-config.password\")(function* (value?: string) {\n const existing = yield* read()\n if (value === undefined && existing.password) return existing.password\n const next = value ?? randomBytes(32).toString(\"base64url\")\n\n // Keep one private credential across server restarts so discovered clients\n // can reconnect without exposing a password flag or environment variable.\n yield* write({ ...existing, password: next })\n return next\n})\n\nexport const get = Effect.fn(\"cli.service-config.get\")(function* (key?: string) {\n if (key === undefined) {\n const { password: _password, ...safe } = yield* read()\n return JSON.stringify(safe, null, 2)\n }\n switch (configKey(key)) {\n case \"hostname\": {\n return (yield* read()).hostname ?? \"\"\n }\n case \"port\": {\n const port = (yield* read()).port\n return port === undefined ? \"\" : String(port)\n }\n case \"password\": {\n return yield* password()\n }\n }\n throw new Error(`Unknown service config key: ${key}`)\n})\n\nexport const set = Effect.fn(\"cli.service-config.set\")(function* (key: string, value: string) {\n switch (configKey(key)) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), hostname: value })\n return\n }\n case \"port\": {\n const port = Number(value)\n if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error(\"Port must be between 1 and 65535\")\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), port })\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n yield* password(value)\n return\n }\n }\n})\n\nexport const unset = Effect.fn(\"cli.service-config.unset\")(function* (key: string) {\n switch (configKey(key)) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n const { hostname: _hostname, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"port\": {\n yield* Service.stop(yield* options())\n const { port: _port, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n const { password: _password, ...next } = yield* read()\n yield* write(next)\n return\n }\n }\n})\n\nexport * as ServiceConfig from \"./service-config\"\n",
"import path from \"node:path\"\n\nexport function selfCommand() {\n const runtime = path.basename(process.execPath, path.extname(process.execPath)).toLowerCase()\n if (runtime !== \"bun\" && runtime !== \"node\" && runtime !== \"nodejs\") return [process.execPath]\n if (!process.argv[1]) throw new Error(\"Failed to resolve CLI entrypoint\")\n if (runtime === \"node\" || runtime === \"nodejs\") return [process.execPath, ...nodeFlags(), process.argv[1]]\n return [process.execPath, process.argv[1]]\n}\n\nfunction nodeFlags() {\n return process.execArgv.flatMap((arg, index, args) => {\n if (index > 0 && args[index - 1] === \"--conditions\") return []\n if (arg === \"--conditions\") return args[index + 1] ? [arg, args[index + 1]] : []\n if (arg.startsWith(\"--conditions=\")) return [arg]\n if (\n arg === \"--experimental-ffi\" ||\n arg === \"--use-system-ca\" ||\n arg === \"--enable-source-maps\" ||\n arg === \"--no-addons\"\n )\n return [arg]\n if (arg === \"--no-warnings\" || arg.startsWith(\"--disable-warning=\")) return [arg]\n return []\n })\n}\n"
],
"mappings": ";iSAEA,qBAAS,2BACT,uBAAS,gBACT,eAAS,aAuBF,IAAM,GAAW,EAAO,GAAG,kBAAkB,EAAE,SAAU,CAAC,EAA2B,CAAC,EAAG,CAC9F,OAAQ,MAAO,GAAc,CAAO,IAAI,SACzC,EAGY,GAAY,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAChE,EACA,CACA,IAAM,EAAO,MAAO,EAAK,EAAQ,IAAI,EAC/B,EAAQ,IAAS,OAAY,OAAY,MAAO,EAAM,IAAK,EAAM,IAAK,EAAQ,GAAI,CAAC,EACzF,GAAI,IAAU,QAAa,EAAM,OAAQ,OACzC,GAAI,EAAQ,UAAY,QAAa,EAAM,UAAY,EAAQ,QAAS,OACxE,MAAO,CAAE,SAAU,EAAM,SAAU,MAAO,EAAM,KAAM,EACvD,EAEK,GAAgB,EAAO,WAAW,SAAU,CAAC,EAA0B,CAC3E,IAAM,GAAS,MAAO,EAAW,EAAQ,IAAI,GAAG,QAChD,GAAI,GAAO,QAAU,QAAS,OAC9B,GAAI,EAAQ,UAAY,QAAa,EAAM,UAAY,EAAQ,QAAS,OACxE,OAAO,EACR,EAMY,GAAS,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAyB,CAAC,EAAG,CACxF,IAAM,EAAa,IAAI,IACnB,EAAY,GACZ,EAAY,EACZ,EAAa,KACb,EAAY,GACV,EAAW,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MAAM,+BAA+B,GAAK,EACrD,EAEY,GAAM,EAAO,GAAG,wBAAwB,EAAE,SAAU,CAAC,EAAa,EAAe,CAC5F,OAAQ,EAAU,CAAG,OACd,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,MAAO,EAAM,IAAM,MAAO,EAAK,EAAI,SAAU,CAAM,CAAC,EACpD,MACF,KACK,OAAQ,CACX,IAAM,EAAO,OAAO,CAAK,EACzB,GAAI,CAAC,OAAO,UAAU,CAAI,GAAK,EAAO,GAAK,EAAO,MAAQ,MAAU,MAAM,kCAAkC,EAC5G,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,MAAO,EAAM,IAAM,MAAO,EAAK,EAAI,MAAK,CAAC,EACzC,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,MAAO,EAAS,CAAK,EACrB,MACF,GAEH,EAEY,GAAQ,EAAO,GAAG,0BAA0B,EAAE,SAAU,CAAC,EAAa,CACjF,OAAQ,EAAU,CAAG,OACd,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,KACK,OAAQ,CACX,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,KAAM,KAAU,GAAS,MAAO,EAAK,EAC7C,MAAO,EAAM,CAAI,EACjB,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,GAEH",
"debugId": "1EA5A8538896805C64756E2164756E21",
"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/core/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 configPath = yield* Effect.promise(() => resolveConfigPath(input.global ? Global.Path.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": ";i4BAAA,mBAAS,gBACT,yBACA,wBAAS,eAAU,oBAAM,yBAOzB,SAAe,SAAQ,aACrB,OAAS,cAAS,SAAI,cAAS,SAC/B,OAAO,QAAG,kBAAa,OAAE,cAAU,MAAC,OAAO,MACzC,IAAM,EAAM,EAAO,eAAe,EAAM,GAAG,EACrC,EAAU,EAAO,eAAe,EAAM,MAAM,EAC5C,EAAc,EAAO,eAAe,EAAM,GAAG,EAG7C,EAAO,QAAQ,KAAK,QAAQ,IAAI,EAChC,EAAU,IAAS,GAAK,CAAC,GAAG,EAAM,OAAO,EAAI,QAAQ,KAAK,MAAM,EAAO,CAAC,EAExE,EAAa,EAAQ,OAAS,EACpC,GAAI,GAAO,EACT,OAAO,MAAO,EAAO,KAAS,MAAM,4DAA4D,CAAC,EACnG,GAAI,CAAC,GAAO,CAAC,EAAY,OAAO,MAAO,EAAO,KAAS,MAAM,kDAAkD,CAAC,EAChH,GAAI,GAAO,CAAC,IAAI,SAAS,CAAG,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,gBAAgB,GAAK,CAAC,EACzF,GAAI,GAAO,EAAa,OAAO,MAAO,EAAO,KAAS,MAAM,2CAA2C,CAAC,EACxG,GAAI,GAAc,EAAS,OAAO,MAAO,EAAO,KAAS,MAAM,+CAA+C,CAAC,EAE/G,IAAM,EAAS,EACX,CAAE,KAAM,SAAmB,SAAS,EAAU,CAAE,SAAQ,EAAI,CAAC,CAAG,EAChE,CAAE,KAAM,QAAkB,aAAa,EAAc,CAAE,aAAY,EAAI,CAAC,CAAG,EAEzE,EAAa,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAM,OAAS,EAAO,KAAK,OAAS,QAAQ,IAAI,CAAC,CAAC,EACnH,MAAO,EAAO,QAAQ,IAAM,EAAM,EAAY,EAAM,KAAM,CAAM,CAAC,EACjE,QAAQ,OAAO,MAAM,eAAe,EAAM,kBAAkB,IAAe,CAAG,EAC/E,CACH,EAEA,eAAsB,CAAiB,CAAC,EAAmB,CACzD,IAAM,EAAa,CACjB,EAAK,KAAK,EAAW,eAAe,EACpC,EAAK,KAAK,EAAW,gBAAgB,EACrC,EAAK,KAAK,EAAW,YAAa,eAAe,EACjD,EAAK,KAAK,EAAW,YAAa,gBAAgB,CACpD,EACA,QAAW,KAAa,EACtB,GACE,MAAM,EAAK,CAAS,EAAE,KACpB,CAAC,IAAS,EAAK,OAAO,EACtB,IAAM,EACR,EAEA,OAAO,EAEX,OAAO,EAAW,GAGpB,eAAe,CAAK,CAAC,EAAoB,EAAc,EAAiB,CACtE,IAAM,EAAO,MAAM,EAAS,EAAY,MAAM,EAAE,MAAM,CAAC,IAAU,CAC/D,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,SAAU,GAAS,EAAM,OAAS,SAAU,MAAO,KACtG,MAAM,EACP,EACK,EAAQ,EAAO,EAAM,CAAC,MAAO,UAAW,CAAI,EAAG,EAAQ,CAC3D,kBAAmB,CAAE,QAAS,EAAG,aAAc,EAAK,CACtD,CAAC,EACD,MAAM,EAAU,EAAY,EAAW,EAAM,CAAK,CAAC",
"debugId": "F68950AA96805D4C64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/service/get.ts"],
"sourcesContent": [
"import { EOL } from \"os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.get,\n Effect.fn(\"cli.service.get\")(function* (input) {\n process.stdout.write((yield* ServiceConfig.get(Option.getOrUndefined(input.key))) + EOL)\n }),\n)\n"
],
"mappings": ";g7BAAA,mBAAS,gBAMT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,SACnC,OAAO,QAAG,sBAAiB,OAAE,cAAU,MAAC,OAAO,MAC7C,aAAQ,YAAO,YAAO,WAAO,OAAc,SAAI,OAAO,eAAe,EAAM,GAAG,CAAC,GAAK,CAAG,EACxF,CACH",
"debugId": "3B5C015829597F8264756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/migrate.ts"],
"sourcesContent": [
"import { Effect } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\n\nexport default Runtime.handler(Commands.commands.migrate, (_input) => Effect.log(\"No migrations to run.\"))\n"
],
"mappings": ";u1BAIA,SAAe,SAAQ,aAAQ,OAAS,cAAS,aAAS,MAAC,SAAW,OAAO,SAAI,4BAAuB,MAAC",
"debugId": "42FEF986B5725A5564756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/service/set.ts"],
"sourcesContent": [
"import { Effect } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.set,\n Effect.fn(\"cli.service.set\")(function* (input) {\n yield* ServiceConfig.set(input.key, input.value)\n }),\n)\n"
],
"mappings": ";w6BAKA,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,SACnC,OAAO,QAAG,sBAAiB,OAAE,cAAU,MAAC,OAAO,MAC7C,WAAO,OAAc,SAAI,OAAM,SAAK,OAAM,UAAK,OAChD,MACH",
"debugId": "FE13179BA904170764756E2164756E21",
"names": []
}

Sorry, the diff of this file is too big to display

{
"version": 3,
"sources": ["../simulation/src/manifest.ts", "../simulation/src/protocol/index.ts", "../simulation/src/control-server.ts"],
"sourcesContent": [
"import { homedir } from \"node:os\"\nimport { isAbsolute, join } from \"node:path\"\nimport { Config, Effect, FileSystem, Schema } from \"effect\"\nimport { PositiveInt } from \"@opencode-ai/core/schema\"\n\nconst InstanceName = Schema.String.check(\n Schema.makeFilter((value) =>\n /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(value) ? undefined : \"a valid Drive instance name\",\n ),\n)\n\nconst Endpoint = Schema.String.check(\n Schema.makeFilter((value) => {\n if (!URL.canParse(value)) return \"a loopback WebSocket endpoint with an explicit port\"\n const endpoint = new URL(value)\n const port = Number(endpoint.port)\n return endpoint.protocol === \"ws:\" && endpoint.hostname === \"127.0.0.1\" && Number.isInteger(port) && port >= 1\n ? undefined\n : \"a loopback WebSocket endpoint with an explicit port\"\n }),\n)\n\nconst AbsolutePath = Schema.String.check(\n Schema.makeFilter((value) => (isAbsolute(value) ? undefined : \"an absolute path\")),\n)\n\nexport const Manifest = Schema.Struct({\n endpoints: Schema.Struct({\n ui: Endpoint,\n backend: Endpoint,\n }),\n viewport: Schema.optionalKey(\n Schema.Struct({\n cols: PositiveInt,\n rows: PositiveInt,\n }),\n ),\n recording: Schema.optionalKey(\n Schema.Struct({\n timeline: AbsolutePath,\n }),\n ),\n})\nexport interface Manifest extends Schema.Schema.Type<typeof Manifest> {}\n\nexport class ResolveError extends Schema.TaggedErrorClass<ResolveError>()(\"DriveManifest.ResolveError\", {\n reason: Schema.Literals([\"config\", \"not-found\", \"read\", \"decode\"]),\n path: Schema.optionalKey(Schema.String),\n message: Schema.String,\n cause: Schema.Defect(),\n}) {}\n\nexport const defaults: Manifest = {\n endpoints: {\n ui: \"ws://127.0.0.1:40900\",\n backend: \"ws://127.0.0.1:40950\",\n },\n}\n\nconst decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Manifest))\n\nconst configError = (cause: unknown) =>\n new ResolveError({\n reason: \"config\",\n message: `Invalid Drive configuration: ${String(cause)}`,\n cause,\n })\n\nexport const resolve = Effect.fn(\"DriveManifest.resolve\")(function* () {\n const name = yield* Config.schema(InstanceName, \"OPENCODE_DRIVE\").pipe(Effect.mapError(configError))\n if (name === \"1\") return defaults\n\n const state = yield* Config.string(\"XDG_STATE_HOME\").pipe(\n Config.withDefault(join(homedir(), \".local\", \"state\")),\n Effect.mapError(configError),\n )\n const directory = yield* Config.string(\"DRIVE_REGISTRY_DIR\").pipe(\n Config.withDefault(join(state, \"opencode-drive\", \"instances\")),\n Effect.mapError(configError),\n )\n const file = join(directory, `${name}.json`)\n const fs = yield* FileSystem.FileSystem\n const contents = yield* fs.readFileString(file).pipe(\n Effect.mapError(\n (cause) =>\n new ResolveError({\n reason: cause.reason._tag === \"NotFound\" ? \"not-found\" : \"read\",\n path: file,\n message:\n cause.reason._tag === \"NotFound\"\n ? `Drive manifest not found: ${file}`\n : `Failed to read Drive manifest: ${file}: ${cause.message}`,\n cause,\n }),\n ),\n )\n return yield* decode(contents).pipe(\n Effect.mapError(\n (cause) =>\n new ResolveError({\n reason: \"decode\",\n path: file,\n message: `Invalid Drive manifest: ${file}: ${cause.message}`,\n cause,\n }),\n ),\n )\n})\n\nexport * as DriveManifest from \"./manifest\"\n",
"import { Effect, Schema } from \"effect\"\n\nconst JsonRpcID = Schema.Union([Schema.String, Schema.Number, Schema.Null])\ntype Json = Schema.Schema.Type<typeof Schema.Json>\n\nexport namespace JsonRpc {\n export const RequestFields = {\n jsonrpc: Schema.Literal(\"2.0\"),\n id: Schema.optional(JsonRpcID),\n }\n export const Request = Schema.Struct({\n ...RequestFields,\n method: Schema.String,\n params: Schema.optional(Schema.Json),\n })\n export interface Request extends Schema.Schema.Type<typeof Request> {}\n\n export const ErrorObject = Schema.Struct({\n code: Schema.Number,\n message: Schema.String,\n data: Schema.optional(Schema.Json),\n })\n\n export const Response = Schema.Struct({\n jsonrpc: Schema.Literal(\"2.0\"),\n id: JsonRpcID,\n result: Schema.optional(Schema.Json),\n error: Schema.optional(ErrorObject),\n })\n export interface Response extends Schema.Schema.Type<typeof Response> {}\n\n export const decodeRequest = Schema.decodeUnknownSync(Request)\n\n export function success(id: Request[\"id\"], result: unknown): Response | undefined {\n if (id === undefined) return undefined\n return { jsonrpc: \"2.0\", id, result: result as Json }\n }\n\n export function failure(id: Request[\"id\"], error: unknown): Response {\n return {\n jsonrpc: \"2.0\",\n id: id ?? null,\n error: {\n code: -32000,\n message: error instanceof Error ? error.message : String(error),\n },\n }\n }\n}\n\nexport namespace Handshake {\n export const ProtocolVersion = Schema.Literal(1)\n export type ProtocolVersion = Schema.Schema.Type<typeof ProtocolVersion>\n\n export const Capability = Schema.NonEmptyString\n export type Capability = Schema.Schema.Type<typeof Capability>\n\n export const EndpointRole = Schema.Literals([\"ui\", \"backend\"])\n export type EndpointRole = Schema.Schema.Type<typeof EndpointRole>\n\n export const Identity = Schema.Struct({\n name: Schema.NonEmptyString,\n version: Schema.NonEmptyString,\n })\n export interface Identity extends Schema.Schema.Type<typeof Identity> {}\n\n export const Params = Schema.Struct({\n client: Identity,\n expectedRole: EndpointRole,\n offeredVersions: Schema.Array(Schema.Int.check(Schema.isGreaterThan(0))).check(\n Schema.isMinLength(1),\n Schema.isUnique(),\n ),\n requiredCapabilities: Schema.Array(Capability).check(Schema.isUnique()),\n optionalCapabilities: Schema.Array(Capability).check(Schema.isUnique()),\n })\n export interface Params extends Schema.Schema.Type<typeof Params> {}\n\n export const Response = Schema.Struct({\n protocolVersion: ProtocolVersion,\n role: EndpointRole,\n server: Identity,\n capabilities: Schema.Array(Capability),\n })\n export interface Response extends Schema.Schema.Type<typeof Response> {}\n\n export const Request = Schema.Struct({\n ...JsonRpc.RequestFields,\n method: Schema.Literal(\"simulation.handshake\"),\n params: Params,\n })\n export interface Request extends Schema.Schema.Type<typeof Request> {}\n\n export interface DispatchAction {\n readonly role: EndpointRole\n readonly server: Identity\n readonly capabilities: ReadonlyArray<Capability>\n }\n\n export class RoleMismatchError extends Schema.TaggedErrorClass<RoleMismatchError>()(\n \"SimulationHandshake.RoleMismatchError\",\n {\n expected: EndpointRole,\n actual: EndpointRole,\n message: Schema.String,\n },\n ) {}\n\n export class UnsupportedProtocolError extends Schema.TaggedErrorClass<UnsupportedProtocolError>()(\n \"SimulationHandshake.UnsupportedProtocolError\",\n {\n offered: Schema.Array(Schema.Number),\n supported: Schema.Array(ProtocolVersion),\n message: Schema.String,\n },\n ) {}\n\n export class MissingCapabilityError extends Schema.TaggedErrorClass<MissingCapabilityError>()(\n \"SimulationHandshake.MissingCapabilityError\",\n {\n missing: Schema.Array(Capability),\n message: Schema.String,\n },\n ) {}\n\n export function dispatch(action: DispatchAction, params: Params) {\n return Effect.gen(function* () {\n if (params.expectedRole !== action.role) {\n return yield* Effect.fail(\n new RoleMismatchError({\n expected: params.expectedRole,\n actual: action.role,\n message: `Expected simulation endpoint role ${params.expectedRole}, received ${action.role}`,\n }),\n )\n }\n if (!params.offeredVersions.includes(1)) {\n return yield* Effect.fail(\n new UnsupportedProtocolError({\n offered: params.offeredVersions,\n supported: [1],\n message: \"No mutually supported simulation protocol version\",\n }),\n )\n }\n const installed = new Set(action.capabilities)\n const missing = params.requiredCapabilities.filter((capability) => !installed.has(capability))\n if (missing.length > 0) {\n return yield* Effect.fail(\n new MissingCapabilityError({\n missing,\n message: `Simulation endpoint is missing required capabilities: ${missing.join(\", \")}`,\n }),\n )\n }\n return {\n protocolVersion: 1,\n role: action.role,\n server: action.server,\n capabilities: Array.from(installed),\n } satisfies Response\n })\n }\n}\n\nexport namespace Frontend {\n export const Capabilities = [\n \"ui.type\",\n \"ui.press\",\n \"ui.enter\",\n \"ui.arrow\",\n \"ui.focus\",\n \"ui.click\",\n \"ui.resize\",\n \"ui.matches\",\n \"ui.screenshot\",\n \"ui.state\",\n \"ui.snapshot\",\n \"ui.capture\",\n \"ui.recording.finish\",\n ] as const satisfies ReadonlyArray<Handshake.Capability>\n\n export const KeyModifiers = Schema.Struct({\n ctrl: Schema.optional(Schema.Boolean),\n shift: Schema.optional(Schema.Boolean),\n meta: Schema.optional(Schema.Boolean),\n super: Schema.optional(Schema.Boolean),\n hyper: Schema.optional(Schema.Boolean),\n })\n export interface KeyModifiers extends Schema.Schema.Type<typeof KeyModifiers> {}\n\n export const Action = Schema.Union([\n Schema.Struct({ type: Schema.Literal(\"ui.type\"), text: Schema.String }),\n Schema.Struct({ type: Schema.Literal(\"ui.press\"), key: Schema.String, modifiers: Schema.optional(KeyModifiers) }),\n Schema.Struct({ type: Schema.Literal(\"ui.enter\") }),\n Schema.Struct({ type: Schema.Literal(\"ui.arrow\"), direction: Schema.Literals([\"up\", \"down\", \"left\", \"right\"]) }),\n Schema.Struct({ type: Schema.Literal(\"ui.focus\"), target: Schema.Number }),\n Schema.Struct({ type: Schema.Literal(\"ui.click\"), target: Schema.Number, x: Schema.Number, y: Schema.Number }),\n Schema.Struct({ type: Schema.Literal(\"ui.resize\"), cols: Schema.Number, rows: Schema.Number }),\n ])\n export type Action = Schema.Schema.Type<typeof Action>\n\n export const Element = Schema.Struct({\n id: Schema.String,\n num: Schema.Number,\n x: Schema.Number,\n y: Schema.Number,\n width: Schema.Number,\n height: Schema.Number,\n focusable: Schema.Boolean,\n focused: Schema.Boolean,\n clickable: Schema.Boolean,\n editor: Schema.Boolean,\n })\n export interface Element extends Schema.Schema.Type<typeof Element> {}\n\n export const State = Schema.Struct({\n focused: Schema.Struct({\n renderable: Schema.optional(Schema.Number),\n editor: Schema.Boolean,\n }),\n elements: Schema.Array(Element),\n })\n export interface State extends Schema.Schema.Type<typeof State> {}\n\n export const SemanticNode = Schema.Struct({\n id: Schema.NonEmptyString,\n instance: Schema.optionalKey(Schema.NonEmptyString),\n parent: Schema.optionalKey(Schema.NonEmptyString),\n role: Schema.NonEmptyString,\n label: Schema.optionalKey(Schema.NonEmptyString),\n element: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),\n focused: Schema.optionalKey(Schema.Boolean),\n selected: Schema.optionalKey(Schema.Boolean),\n expanded: Schema.optionalKey(Schema.Boolean),\n disabled: Schema.optionalKey(Schema.Boolean),\n })\n export interface SemanticNode extends Schema.Schema.Type<typeof SemanticNode> {}\n\n export const SemanticSnapshot = Schema.Struct({\n format: Schema.Literal(\"opencode-ui-snapshot-v1\"),\n nodes: Schema.Array(SemanticNode).check(\n Schema.makeFilter((nodes) => {\n const ids = new Set(nodes.map((node) => node.id))\n if (ids.size !== nodes.length) return \"semantic node ids must be unique\"\n if (new Set(nodes.map((node) => node.element)).size !== nodes.length)\n return \"semantic node elements must be unique\"\n if (nodes.some((node) => node.parent !== undefined && !ids.has(node.parent)))\n return \"semantic node parents must reference another node\"\n const parents = new Map(nodes.map((node) => [node.id, node.parent]))\n for (const node of nodes) {\n const visited = new Set<string>()\n let current: string | undefined = node.id\n while (current !== undefined) {\n if (visited.has(current)) return \"semantic node hierarchy must be acyclic\"\n visited.add(current)\n current = parents.get(current)\n }\n }\n return undefined\n }),\n ),\n })\n export interface SemanticSnapshot extends Schema.Schema.Type<typeof SemanticSnapshot> {}\n\n export const Screenshot = Schema.String\n export type Screenshot = Schema.Schema.Type<typeof Screenshot>\n\n export const Color = Schema.Tuple([Schema.Number, Schema.Number, Schema.Number, Schema.Number])\n export type Color = Schema.Schema.Type<typeof Color>\n\n export const CapturedFrame = Schema.Struct({\n cols: Schema.Number,\n rows: Schema.Number,\n cursor: Schema.Tuple([Schema.Number, Schema.Number]),\n lines: Schema.Array(\n Schema.Struct({\n spans: Schema.Array(\n Schema.Struct({\n text: Schema.String,\n fg: Color,\n bg: Color,\n attributes: Schema.Number,\n width: Schema.Number,\n }),\n ),\n }),\n ),\n })\n export interface CapturedFrame extends Schema.Schema.Type<typeof CapturedFrame> {}\n\n export const RecordingFinish = Schema.String\n export type RecordingFinish = Schema.Schema.Type<typeof RecordingFinish>\n\n export const Matches = Schema.Boolean\n export type Matches = Schema.Schema.Type<typeof Matches>\n\n export const ScreenshotParams = Schema.Struct({ name: Schema.optional(Schema.String) })\n export interface ScreenshotParams extends Schema.Schema.Type<typeof ScreenshotParams> {}\n\n export const TypeParams = Schema.Struct({ text: Schema.String })\n export interface TypeParams extends Schema.Schema.Type<typeof TypeParams> {}\n\n export const MatchesParams = Schema.Struct({ text: Schema.String })\n export interface MatchesParams extends Schema.Schema.Type<typeof MatchesParams> {}\n\n export const PressParams = Schema.Struct({ key: Schema.String, modifiers: Schema.optional(KeyModifiers) })\n export interface PressParams extends Schema.Schema.Type<typeof PressParams> {}\n\n export const ArrowParams = Schema.Struct({ direction: Schema.Literals([\"up\", \"down\", \"left\", \"right\"]) })\n export interface ArrowParams extends Schema.Schema.Type<typeof ArrowParams> {}\n\n export const FocusParams = Schema.Struct({ target: Schema.Number })\n export interface FocusParams extends Schema.Schema.Type<typeof FocusParams> {}\n\n export const ClickParams = Schema.Struct({ target: Schema.Number, x: Schema.Number, y: Schema.Number })\n export interface ClickParams extends Schema.Schema.Type<typeof ClickParams> {}\n\n export const ResizeParams = Schema.Struct({ cols: Schema.Number, rows: Schema.Number })\n export interface ResizeParams extends Schema.Schema.Type<typeof ResizeParams> {}\n\n export const Request = Schema.Union([\n Handshake.Request,\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.type\"), params: TypeParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.press\"), params: PressParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.arrow\"), params: ArrowParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.focus\"), params: FocusParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.click\"), params: ClickParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.resize\"), params: ResizeParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.matches\"), params: MatchesParams }),\n Schema.Struct({\n ...JsonRpc.RequestFields,\n method: Schema.Literal(\"ui.screenshot\"),\n params: Schema.optional(ScreenshotParams),\n }),\n Schema.Struct({\n ...JsonRpc.RequestFields,\n method: Schema.Literals([\"ui.enter\", \"ui.state\", \"ui.snapshot\", \"ui.recording.finish\"]),\n }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"ui.capture\") }),\n ])\n export type Request = Schema.Schema.Type<typeof Request>\n export const decodeRequest = Schema.decodeUnknownSync(Request)\n export const decodeRequestEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Request))\n}\n\nexport namespace Backend {\n export const Capabilities = [\n \"llm.attach\",\n \"llm.chunk\",\n \"llm.finish\",\n \"llm.disconnect\",\n \"llm.pending\",\n \"llm.request\",\n ] as const satisfies ReadonlyArray<Handshake.Capability>\n\n export const Item = Schema.Union([\n Schema.Struct({ type: Schema.Literal(\"textDelta\"), text: Schema.String }),\n Schema.Struct({ type: Schema.Literal(\"reasoningDelta\"), text: Schema.String }),\n Schema.Struct({\n type: Schema.Literal(\"toolCall\"),\n index: Schema.Number,\n id: Schema.String,\n name: Schema.String,\n input: Schema.Json,\n }),\n Schema.Struct({ type: Schema.Literal(\"raw\"), chunk: Schema.Json }),\n ])\n export type Item = Schema.Schema.Type<typeof Item>\n\n export const FinishReason = Schema.Literals([\"stop\", \"tool-calls\", \"length\", \"content-filter\"])\n export type FinishReason = Schema.Schema.Type<typeof FinishReason>\n\n export const ChunkParams = Schema.Struct({ id: Schema.String, items: Schema.Array(Item) })\n export interface ChunkParams extends Schema.Schema.Type<typeof ChunkParams> {}\n\n export const FinishParams = Schema.Struct({\n id: Schema.String,\n reason: FinishReason.pipe(Schema.withDecodingDefault(Effect.succeed(\"stop\" as const))),\n })\n export interface FinishParams extends Schema.Schema.Type<typeof FinishParams> {}\n\n export const DisconnectParams = Schema.Struct({ id: Schema.String })\n export interface DisconnectParams extends Schema.Schema.Type<typeof DisconnectParams> {}\n\n export const Request = Schema.Union([\n Handshake.Request,\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"llm.chunk\"), params: ChunkParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"llm.finish\"), params: FinishParams }),\n Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(\"llm.disconnect\"), params: DisconnectParams }),\n Schema.Struct({\n ...JsonRpc.RequestFields,\n method: Schema.Literals([\"llm.attach\", \"llm.pending\"]),\n }),\n ])\n export type Request = Schema.Schema.Type<typeof Request>\n export const decodeRequest = Schema.decodeUnknownSync(Request)\n export const decodeRequestEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Request))\n\n export const ProviderInvocation = Schema.Struct({ id: Schema.String, url: Schema.String, body: Schema.Json })\n export interface ProviderInvocation extends Schema.Schema.Type<typeof ProviderInvocation> {}\n\n export const NetworkLogEntry = Schema.Struct({\n time: Schema.Number,\n method: Schema.String,\n url: Schema.String,\n matched: Schema.Boolean,\n })\n export interface NetworkLogEntry extends Schema.Schema.Type<typeof NetworkLogEntry> {}\n}\n\nexport * as SimulationProtocol from \"./index\"\n",
"import { Effect, Fiber, Queue, Stream } from \"effect\"\nimport { SimulationProtocol } from \"./protocol\"\n\nexport interface Server {\n readonly url: string\n}\n\ninterface Request {\n readonly id?: string | number | null\n}\n\nexport interface SocketData {\n readonly drive?: true\n attachment?: Fiber.Fiber<void>\n closed?: true\n}\n\nexport type Socket = Bun.ServerWebSocket<SocketData>\n\nexport function start<RequestType extends Request, Error, Services>(options: {\n readonly endpoint: string\n readonly label: string\n readonly data: () => SocketData\n readonly decode: (input: string) => Effect.Effect<RequestType, Error>\n readonly handle: (socket: Socket, request: RequestType) => Effect.Effect<unknown, unknown, Services>\n readonly close?: (socket: Socket) => Effect.Effect<void, never, Services>\n}) {\n return Effect.gen(function* () {\n const messages = yield* Queue.bounded<{ readonly socket: Socket; readonly input: string }>(256)\n const closures = yield* Queue.unbounded<Socket>()\n yield* Stream.fromQueue(messages).pipe(\n Stream.runForEach((message) =>\n options.decode(message.input).pipe(\n Effect.flatMap((request) =>\n options.handle(message.socket, request).pipe(\n Effect.matchEffect({\n onFailure: (error) => send(message.socket, SimulationProtocol.JsonRpc.failure(request.id, error)),\n onSuccess: (result) => send(message.socket, SimulationProtocol.JsonRpc.success(request.id, result)),\n }),\n ),\n ),\n Effect.catch((error) => send(message.socket, SimulationProtocol.JsonRpc.failure(undefined, error))),\n ),\n ),\n Effect.forkScoped,\n )\n yield* Stream.fromQueue(closures).pipe(\n Stream.runForEach((socket) => options.close?.(socket) ?? Effect.void),\n Effect.forkScoped,\n )\n const url = yield* Effect.try({ try: () => new URL(options.endpoint), catch: (cause) => cause })\n yield* Effect.acquireRelease(\n Effect.sync(() =>\n Bun.serve<SocketData>({\n hostname: url.hostname,\n port: Number(url.port),\n fetch(request, server) {\n if (server.upgrade(request, { data: options.data() })) return undefined\n return new Response(options.label, { status: 426 })\n },\n websocket: {\n close(socket) {\n socket.data.closed = true\n Queue.offerUnsafe(closures, socket)\n },\n message(socket, message) {\n const input = typeof message === \"string\" ? message : message.toString()\n if (Queue.offerUnsafe(messages, { socket, input })) return\n socket.send(\n JSON.stringify(\n SimulationProtocol.JsonRpc.failure(undefined, new Error(\"Simulation control queue is full\")),\n ),\n )\n },\n },\n }),\n ),\n (server) => Effect.promise(() => server.stop(true)),\n )\n return { url: options.endpoint } satisfies Server\n })\n}\n\nfunction send(socket: Socket, response: SimulationProtocol.JsonRpc.Response | undefined) {\n if (!response) return Effect.void\n return Effect.sync(() => {\n socket.send(JSON.stringify(response))\n })\n}\n\nexport * as SimulationControlServer from \"./control-server\"\n"
],
"mappings": ";8RAAA,uBAAS,iBACT,qBAAS,WAAY,aAIrB,IAAM,GAAe,EAAO,OAAO,MACjC,EAAO,WAAW,CAAC,IACjB,oCAAoC,KAAK,CAAK,EAAI,OAAY,6BAChE,CACF,EAEM,EAAW,EAAO,OAAO,MAC7B,EAAO,WAAW,CAAC,IAAU,CAC3B,GAAI,CAAC,IAAI,SAAS,CAAK,EAAG,MAAO,sDACjC,IAAM,EAAW,IAAI,IAAI,CAAK,EACxB,EAAO,OAAO,EAAS,IAAI,EACjC,OAAO,EAAS,WAAa,OAAS,EAAS,WAAa,aAAe,OAAO,UAAU,CAAI,GAAK,GAAQ,EACzG,OAC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A2D,CACvF,GAAI,CAAC,EAAU,OAAO,EAAO,KAC7B,OAAO,EAAO,KAAK,IAAM,CACvB,EAAO,KAAK,KAAK,UAAU,CAAQ,CAAC,EACrC",
"debugId": "F9284AD94975331564756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/mini.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.mini, (input) =>\n Effect.gen(function* () {\n const { runMini, validateMiniTerminal } = yield* Effect.promise(() => import(\"../../mini\"))\n yield* Effect.promise(async () => validateMiniTerminal())\n const serverURL = Option.getOrUndefined(input.server)\n const server = yield* ServerConnection.resolve({ server: serverURL, standalone: input.standalone })\n yield* Effect.promise(() =>\n runMini({\n server,\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n prompt: Option.getOrUndefined(input.prompt),\n replay: input.replay,\n replayLimit: Option.getOrUndefined(input.replayLimit),\n demo: input.demo,\n }),\n )\n }),\n)\n"
],
"mappings": ";miCAKA,SAAe,SAAQ,aAAQ,OAAS,cAAS,UAAM,MAAC,SACtD,OAAO,SAAI,cAAU,OAAG,MACtB,SAAQ,eAAS,6BAAyB,WAAO,OAAO,aAAQ,SAAa,wCAAa,OAC1F,WAAO,OAAO,aAAQ,cAAY,OAAqB,MAAC,OACxD,IAAM,EAAY,EAAO,eAAe,EAAM,MAAM,EAC9C,EAAS,MAAO,EAAiB,QAAQ,CAAE,OAAQ,EAAW,WAAY,EAAM,UAAW,CAAC,EAClG,MAAO,EAAO,QAAQ,IACpB,EAAQ,CACN,SACA,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,OAAQ,EAAM,OACd,YAAa,EAAO,eAAe,EAAM,WAAW,EACpD,KAAM,EAAM,IACd,CAAC,CACH,EACD,CACH",
"debugId": "D60299196D163B3E64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/debug/agents.ts"],
"sourcesContent": [
"import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.agents,\n Effect.fn(\"cli.debug.agents\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover(options)\n const endpoint = found ?? (yield* Service.ensure(options))\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.agent.list({ location: { directory: process.cwd() } }))\n process.stdout.write(\n JSON.stringify(\n response.data.toSorted((a, b) => a.id.localeCompare(b.id)),\n null,\n 2,\n ) + EOL,\n )\n }),\n)\n"
],
"mappings": ";+9BAAA,mBAAS,gBAQT,SAAe,SAAQ,aACrB,OAAS,cAAS,WAAM,cAAS,YACjC,OAAO,QAAG,uBAAkB,OAAE,cAAU,OAAG,MACzC,SAAM,OAAU,WAAO,OAAc,aAAQ,OAEvC,QADQ,WAAO,OAAQ,SAAS,CAAO,KAClB,MAAO,EAAQ,OAAO,CAAO,GAClD,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EAC1G,QAAQ,OAAO,MACb,KAAK,UACH,EAAS,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzD,KACA,CACF,EAAI,CACN,EACD,CACH",
"debugId": "413785FD0A3C538964756E2164756E21",
"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(\n ` Run \\`opencode service set hostname 0.0.0.0\\` to access the service remotely.${EOL}${EOL}`,\n )\n }),\n)\n"
],
"mappings": ";8gCAAA,mBAAS,gBAST,SAAe,SAAQ,aACrB,OAAS,cAAS,UAClB,OAAO,QAAG,eAAU,OAAE,cAAU,OAAG,MACjC,SAAM,OAAW,WAAO,OAAQ,YAAO,WAAO,OAAc,aAAQ,MAAC,OAC/D,OAAW,WAAO,EAAc,SAAS,EAIzC,EAAO,CAAE,MAHA,MAAO,EAAO,WAAW,IACtC,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAAE,OAAO,IAAI,CAC1F,GAC4B,KAAM,SAAU,WAAY,UAAS,EACjE,QAAQ,OAAO,MACb,CACE,GACA,eAAe,EAAK,KAAK,IAAM,WAC/B,GAAG,EAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,IAAQ,eAAe,GAAK,EACvD,eAAe,EAAK,WACpB,eAAe,EAAK,WACpB,GACA,iBACA,GACA,EAAqB,KAAK,UAAU,CAAI,EAAG,CAAE,OAAQ,CAAE,CAAC,EACrD,MAAM,CAAG,EACT,IAAI,CAAC,IAAS,KAAO,CAAI,EACzB,KAAK,CAAG,EACX,EACF,EAAE,KAAK,CAAG,EAAI,CAChB,EAEA,IAAM,EAAW,IAAI,IAAI,EAAS,GAAG,EAAE,SACvC,GAAI,CAAC,CAAC,YAAa,YAAa,OAAO,EAAE,SAAS,CAAQ,EAAG,OAC7D,QAAQ,OAAO,MACb,kFAAkF,IAAM,GAC1F,EACD,CACH",
"debugId": "E546215023E7EA1064756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["../core/src/image/photon-wasm.bun.ts", "../core/src/image/photon.ts"],
"sourcesContent": [
"// @ts-ignore Bun embeds static file imports when compiling the CLI.\nimport photonWasm from \"@silvia-odwyer/photon-node/photon_rs_bg.wasm\" with { type: \"file\" }\n\nexport default photonWasm\n",
"import photonWasm from \"#photon-wasm\"\nimport { Effect } from \"effect\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { FileSystem } from \"../filesystem\"\nimport { DecodeError, ResizerUnavailableError, SizeError } from \"../image\"\n\nconst JPEG_QUALITIES = [80, 85, 70, 55, 40]\n\nexport const make = Effect.gen(function* () {\n ;(globalThis as typeof globalThis & { __OPENCODE_PHOTON_WASM_PATH?: string }).__OPENCODE_PHOTON_WASM_PATH =\n path.isAbsolute(photonWasm) ? photonWasm : fileURLToPath(new URL(photonWasm, import.meta.url))\n const loadPhoton = yield* Effect.cached(\n Effect.tryPromise({\n try: () => import(\"@silvia-odwyer/photon-node\"),\n catch: () => new ResizerUnavailableError(),\n }),\n )\n return Effect.fn(\"Image.Photon.normalize\")(function* (\n resource: string,\n content: FileSystem.Content & { readonly encoding: \"base64\" },\n limits: {\n readonly autoResize: boolean\n readonly maxWidth: number\n readonly maxHeight: number\n readonly maxBase64Bytes: number\n },\n ) {\n const photon = yield* loadPhoton\n const decoded = yield* Effect.try({\n try: () => photon.PhotonImage.new_from_byteslice(Buffer.from(content.content, \"base64\")),\n catch: () => new DecodeError({ resource }),\n })\n try {\n const width = decoded.get_width()\n const height = decoded.get_height()\n const bytes = Buffer.byteLength(content.content, \"utf-8\")\n if (width <= limits.maxWidth && height <= limits.maxHeight && bytes <= limits.maxBase64Bytes) return content\n if (!limits.autoResize)\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n const scale = Math.min(1, limits.maxWidth / width, limits.maxHeight / height)\n const sizes = Array.from({ length: 32 }).reduce<Array<{ width: number; height: number }>>((acc) => {\n const previous = acc.at(-1) ?? {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n const next =\n acc.length === 0\n ? previous\n : {\n width: previous.width === 1 ? 1 : Math.max(1, Math.floor(previous.width * 0.75)),\n height: previous.height === 1 ? 1 : Math.max(1, Math.floor(previous.height * 0.75)),\n }\n return acc.some((item) => item.width === next.width && item.height === next.height) ? acc : [...acc, next]\n }, [])\n for (const size of sizes) {\n const resized = photon.resize(decoded, size.width, size.height, photon.SamplingFilter.Lanczos3)\n try {\n const encoders: Array<readonly [mime: string, encode: () => Uint8Array]> = [\n [\"image/png\", () => resized.get_bytes()],\n ...JPEG_QUALITIES.map((quality) => [\"image/jpeg\", () => resized.get_bytes_jpeg(quality)] as const),\n ]\n for (const [mime, encode] of encoders) {\n const candidate = Buffer.from(encode()).toString(\"base64\")\n if (Buffer.byteLength(candidate, \"utf-8\") <= limits.maxBase64Bytes)\n return { ...content, content: candidate, encoding: \"base64\" as const, mime }\n }\n } finally {\n resized.free()\n }\n }\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n } finally {\n decoded.free()\n }\n })\n})\n"
],
"mappings": ";i4BAGA,SAAe,SCDf,yBACA,6BAAS,iBAIT,SAAM,OAAiB,MAAC,QAAI,QAAI,QAAI,QAAI,OAAE,OAE7B,OAAO,OAAO,SAAI,cAAU,OAAG,MACxC,gBAA4E,iCAC5E,OAAK,yBAAW,CAAU,EAAI,EAAa,EAAc,IAAI,IAAI,EAAY,YAAY,GAAG,CAAC,EAC/F,IAAM,EAAa,MAAO,EAAO,OAC/B,EAAO,WAAW,CAChB,IAAK,IAAa,yCAClB,MAAO,IAAM,IAAI,CACnB,CAAC,CACH,EACA,OAAO,EAAO,GAAG,wBAAwB,EAAE,SAAU,CACnD,EACA,EACA,EAMA,CACA,IAAM,EAAS,MAAO,EAChB,EAAU,MAAO,EAAO,IAAI,CAChC,IAAK,IAAM,EAAO,YAAY,mBAAmB,OAAO,KAAK,EAAQ,QAAS,QAAQ,CAAC,EACvF,MAAO,IAAM,IAAI,EAAY,CAAE,UAAS,CAAC,CAC3C,CAAC,EACD,GAAI,CACF,IAAM,EAAQ,EAAQ,UAAU,EAC1B,EAAS,EAAQ,WAAW,EAC5B,EAAQ,OAAO,WAAW,EAAQ,QAAS,OAAO,EACxD,GAAI,GAAS,EAAO,UAAY,GAAU,EAAO,WAAa,GAAS,EAAO,eAAgB,OAAO,EACrG,GAAI,CAAC,EAAO,WACV,OAAO,MAAO,IAAI,EAAU,CAC1B,WACA,QACA,SACA,QACA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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": "E3341830881B8A9D64756E2164756E21",
"names": []
}
{
"version": 3,
"sources": ["src/commands/handlers/service/status.ts"],
"sourcesContent": [
"import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.status,\n Effect.fn(\"cli.service.status\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover({ ...options, version: undefined })\n process.stdout.write((found?.url ?? \"stopped\") + EOL)\n }),\n)\n"
],
"mappings": ";g7BAAA,mBAAS,gBAOT,SAAe,SAAQ,aACrB,OAAS,cAAS,aAAQ,cAAS,YACnC,OAAO,QAAG,yBAAoB,OAAE,cAAU,OAAG,MAC3C,SAAM,OAAU,WAAO,OAAc,aAAQ,OACvC,OAAQ,WAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,EACxE,QAAQ,OAAO,OAAO,GAAO,KAAO,WAAa,CAAG,EACrD,CACH",
"debugId": "CC277D17C559491464756E2164756E21",
"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/core/process\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { createTimelineHost, type TimelineHost } from \"../../../ui/timeline\"\n\nconst integrationID = \"opencode\"\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.console.commands.login,\n Effect.fn(\"cli.console.login\")(function* (input) {\n const timeline = yield* Effect.acquireRelease(\n Effect.promise(() => createTimelineHost()),\n (value) => request(() => value.close()).pipe(Effect.ignore),\n )\n const exit = yield* login(timeline, Option.getOrUndefined(input.url)).pipe(\n Effect.raceFirst(AppProcess.waitForAbort(timeline.signal)),\n Effect.exit,\n )\n if (Exit.isSuccess(exit)) return\n\n const cancelled = timeline.signal.aborted\n yield* request(() => timeline.failure(cancelled ? \"Authorization cancelled\" : errorMessage(exit.cause))).pipe(\n Effect.ignore,\n )\n process.exitCode = cancelled ? 130 : 1\n }),\n)\n\nconst login = Effect.fn(\"cli.console.login.run\")(function* (timeline: TimelineHost, server?: string) {\n yield* request(() => timeline.intro(\"Log in\"))\n yield* request(() => timeline.pending(\"Connecting to OpenCode...\"))\n\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const found = yield* request((signal) => client.integration.get({ integrationID, location }, { signal }))\n const integration = yield* required(found.data, \"OpenCode Console integration is unavailable\")\n const method = yield* required(\n integration.methods.find((candidate) => candidate.type === \"oauth\"),\n \"OpenCode Console login is unavailable\",\n )\n\n yield* request(() => timeline.pending(\"Starting authorization...\"))\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n {\n integrationID,\n methodID: method.id,\n inputs: server ? { server } : {},\n location,\n },\n { signal },\n ),\n )\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n if (attempt.mode !== \"auto\") yield* Effect.fail(new Error(\"OpenCode Console requires a device login\"))\n\n yield* request(() => timeline.item(`Go to: ${attempt.url}`))\n yield* request(() => timeline.item(attempt.instructions))\n yield* request(async () => {\n const { default: open } = await import(\"open\")\n await open(attempt.url)\n }).pipe(Effect.ignore)\n yield* request(() => timeline.pending(\"Waiting for authorization...\"))\n\n const status = yield* waitForConsoleLogin(client, integrationID, attempt.attemptID)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") yield* Effect.fail(new Error(\"Device code expired\"))\n\n yield* request(() => timeline.success(\"Connected to OpenCode Console\"))\n yield* request(() => timeline.outro(\"Done\"))\n})\n\nconst waitForConsoleLogin = Effect.fn(\"cli.console.login.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.oauth.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n yield* Effect.sleep(500)\n }\n})\n\nfunction request<A>(task: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: task,\n catch: (cause) => cause,\n })\n}\n\nfunction required<A>(value: A | null | undefined, message: string) {\n return value === null || value === undefined ? Effect.fail(new Error(message)) : Effect.succeed(value)\n}\n\nfunction errorMessage(cause: Cause.Cause<unknown>) {\n const error = Cause.squash(cause)\n if (error instanceof Error) return error.message\n if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\") {\n return error.message\n }\n return String(error)\n}\n"
],
"mappings": ";2rCAYA,OAAwB,OACxB,SAAM,OAAiB,MAAC,cAAI,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,cAAK,aAAG,OACjE,QAAe,UACf,OAAS,MACb,YAAQ,OAAK,eAAU,MAAC,OACxB,WAAO,OAAK,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,MA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