diff --git a/packages/cli/src/commands/handlers/debug/heap-dump.ts b/packages/cli/src/commands/handlers/debug/heap-dump.ts index a1c3d461ff5..275737c3926 100644 --- a/packages/cli/src/commands/handlers/debug/heap-dump.ts +++ b/packages/cli/src/commands/handlers/debug/heap-dump.ts @@ -55,8 +55,7 @@ export default Runtime.handler(Commands.commands.debug.commands["heap-dump"], (i // replace, or restart the background service. const running = Effect.fnUntraced(function* (server: string | undefined) { if (server !== undefined) return (yield* ServerConnection.resolve({ server })).endpoint - const options = yield* ServiceConfig.options() - const endpoint = yield* Service.discover({ ...options, version: undefined }) + const endpoint = yield* Service.discover({ file: yield* ServiceConfig.registrationFile() }) if (endpoint) return endpoint return yield* Effect.fail( new Error("No background server is running. Pass --server to capture a server started another way."), diff --git a/packages/cli/src/commands/handlers/machine/common.ts b/packages/cli/src/commands/handlers/machine/common.ts index 190e4d74955..57330ff107d 100644 --- a/packages/cli/src/commands/handlers/machine/common.ts +++ b/packages/cli/src/commands/handlers/machine/common.ts @@ -24,8 +24,7 @@ export const ensureMachineClient = Effect.fn("cli.machine.client")(function* () new Error("--standalone starts a server for this command only; a machine needs one that keeps running."), ) const serverFlag = yield* Effect.serviceOption(Server).pipe(Effect.map(Option.flatten)) - const config = yield* ServiceConfig.read() - if (Option.isNone(serverFlag) && config.disabled === true) + if (Option.isNone(serverFlag) && (yield* ServiceConfig.read()).disabled === true) return yield* Effect.fail( new Error("Managing machines requires the background service; run `opencode service unset disabled` first."), ) diff --git a/packages/cli/src/commands/handlers/service/status.ts b/packages/cli/src/commands/handlers/service/status.ts index ade0a391993..35fc0efdd9a 100644 --- a/packages/cli/src/commands/handlers/service/status.ts +++ b/packages/cli/src/commands/handlers/service/status.ts @@ -8,8 +8,7 @@ import { ServiceConfig } from "../../../services/service-config" export default Runtime.handler( Commands.commands.service.commands.status, Effect.fn("cli.service.status")(function* () { - const options = yield* ServiceConfig.options() - const found = yield* Service.discover({ ...options, version: undefined }) + const found = yield* Service.discover({ file: yield* ServiceConfig.registrationFile() }) process.stdout.write((found?.url ?? "stopped") + EOL) }), ) diff --git a/packages/cli/src/commands/handlers/service/stop.ts b/packages/cli/src/commands/handlers/service/stop.ts index c0dd64ad418..481e2490890 100644 --- a/packages/cli/src/commands/handlers/service/stop.ts +++ b/packages/cli/src/commands/handlers/service/stop.ts @@ -7,8 +7,7 @@ import { ServiceConfig } from "../../../services/service-config" export default Runtime.handler( Commands.commands.service.commands.stop, Effect.fn("cli.service.stop")(function* () { - const options = yield* ServiceConfig.options() // No explicit daemon shutdown: stopping without a handoff drops the daemon's owner, which stops it with its processes. - yield* Service.stop(options) + yield* Service.stop({ file: yield* ServiceConfig.registrationFile() }) }), ) diff --git a/packages/cli/src/server-process.ts b/packages/cli/src/server-process.ts index 1c40512d272..131b23fd3c5 100644 --- a/packages/cli/src/server-process.ts +++ b/packages/cli/src/server-process.ts @@ -67,13 +67,13 @@ const processEffect = Effect.fnUntraced(function* (options: Options) { return yield* Effect.scoped( Effect.gen(function* () { const foreground = options.mode === "default" - const serviceOptions = options.mode === "service" ? yield* ServiceConfig.options() : undefined + const registrationFile = options.mode === "service" ? yield* ServiceConfig.registrationFile() : undefined const config = options.mode === "service" ? yield* ServiceConfig.read() : {} const hostname = options.hostname ?? config.hostname ?? "127.0.0.1" const port = options.port ?? config.port ?? (options.mode === "service" ? ServiceConfig.defaultPort() : undefined) const findIncumbent = - serviceOptions !== undefined && port !== undefined - ? Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) }) + registrationFile !== undefined && port !== undefined + ? Service.incumbent({ file: registrationFile, url: serviceURL(hostname, port) }) : undefined if (findIncumbent !== undefined && (yield* findIncumbent) !== undefined) return // Desktop can launch the service directly without injecting its saved environment. @@ -149,7 +149,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) { : !truthy(process.env.OPENCODE_DISABLE_FFF), }, }, - serviceOptions === undefined + registrationFile === undefined ? undefined : { onListen: (address, shutdown) => @@ -159,7 +159,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) { address, password, id: instanceID, - file: serviceOptions.file, + file: registrationFile, shutdown, }) }), @@ -193,7 +193,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) { }), ) if (server === undefined) return - if (serviceOptions !== undefined && config.remote !== undefined && NetAddress.isInetAddress(server.address)) { + if (registrationFile !== undefined && config.remote !== undefined && NetAddress.isInetAddress(server.address)) { const bound = NetAddress.formatIp(server.address.address) // A wildcard bind also listens on loopback, which is all the tunnel needs to reach. const target = diff --git a/packages/cli/src/services/service-config.ts b/packages/cli/src/services/service-config.ts index 483db314c40..a90ac2812d2 100644 --- a/packages/cli/src/services/service-config.ts +++ b/packages/cli/src/services/service-config.ts @@ -2,7 +2,7 @@ import { Global } from "@opencode/util/global" import { OPENCODE_CHANNEL, OPENCODE_VERSION } from "../version" import { Hash } from "@opencode/util/hash" import { Service } from "@opencode/client/effect/service" -import { Effect, FileSystem, Option, Schedule, Schema } from "effect" +import { Effect, FileSystem, Option, Result, Schedule, Schema } from "effect" import { randomBytes } from "crypto" import path from "path" import { selfCommand } from "../util/process" @@ -28,10 +28,19 @@ export const Info = Schema.Struct({ }) export type Info = typeof Info.Type +export class InvalidError extends Schema.TaggedError()("ServiceConfig.InvalidError", { + path: Schema.String, + issue: Schema.String, +}) { + override get message() { + return `Invalid service config at ${this.path}: ${this.issue}` + } +} + const keys = ["disabled", "remote", "hostname", "port", "password", "cors", "env"] as const type Key = (typeof keys)[number] -const decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info)) +const decodeInfo = Schema.decodeUnknownResult(Schema.fromJsonString(Info)) // Earlier builds stored remote access as a boolean. const decodeLegacy = Schema.decodeUnknownOption( Schema.fromJsonString(Schema.Struct({ ...Info.fields, remote: Schema.Boolean })), @@ -95,21 +104,13 @@ export const migrateConfig = Effect.fnUntraced(function* (legacy: string, file: const fs = yield* FileSystem.FileSystem const text = yield* fs.readFileString(legacy).pipe(Effect.option) if (Option.isNone(text)) return - if (Option.isNone(yield* decodeInfo(text.value).pipe(Effect.option))) return + if (Result.isFailure(decodeInfo(text.value))) return yield* fs.writeFileString(file, text.value, { flag: "wx", mode: 0o600 }).pipe(Effect.ignore) }) function configKey(key: string): Key { - if ( - key === "disabled" || - key === "remote" || - key === "hostname" || - key === "port" || - key === "password" || - key === "cors" || - key === "env" - ) - return key + const found = keys.find((candidate) => candidate === key) + if (found !== undefined) return found throw new Error(`Unknown service config key: ${key}`) } @@ -140,11 +141,15 @@ export function processEnv(env: Info["env"]) { return rest } -export const options = Effect.fnUntraced(function* (input: { readonly checkVersion?: boolean } = {}) { +export const registrationFile = Effect.fnUntraced(function* () { const { file, legacyRegistrationFiles } = yield* paths yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file)) + return file +}) + +export const options = Effect.fnUntraced(function* (input: { readonly checkVersion?: boolean } = {}) { return { - file, + file: yield* registrationFile(), version: input.checkVersion ? OPENCODE_VERSION : undefined, env: processEnv((yield* read()).env), command: [...selfCommand(), "serve", "--service"], @@ -154,12 +159,19 @@ export const options = Effect.fnUntraced(function* (input: { readonly checkVersi export const read = Effect.fn("cli.service-config.read")(function* () { const { fs, configFile, legacyConfigFile } = yield* paths if (legacyConfigFile) yield* migrateConfig(legacyConfigFile, configFile) - const text = yield* fs.readFileString(configFile).pipe(Effect.option) - if (Option.isNone(text)) return {} as Info - const info = yield* decodeInfo(text.value).pipe(Effect.option) - if (Option.isSome(info)) return info.value - const legacy = decodeLegacy(text.value) - if (Option.isNone(legacy)) return {} as Info + const text = yield* fs.readFileString(configFile).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.undefined, + ), + ) + if (text === undefined) return {} satisfies Info + const info = decodeInfo(text, { errors: "all" }) + if (Result.isSuccess(info)) return info.success + const legacy = decodeLegacy(text) + if (Option.isNone(legacy)) { + return yield* new InvalidError({ path: configFile, issue: info.failure.message }) + } // Repair the file in place so every reader sees the same route. const { remote: enabled, ...rest } = legacy.value const repaired: Info = enabled ? { ...rest, remote: { route: route() } } : rest @@ -244,7 +256,6 @@ export const get = Effect.fn("cli.service-config.get")(function* (key?: string, return name === undefined ? JSON.stringify(env, null, 2) : (env[name] ?? "") } } - throw new Error(`Unknown service config key: ${key}`) }) export const set = Effect.fn("cli.service-config.set")(function* (key: string, value: string, nestedValue?: string) { @@ -260,9 +271,10 @@ export const set = Effect.fn("cli.service-config.set")(function* (key: string, v } case "remote": { if (value !== "true" && value !== "false") throw new Error("Remote must be true or false") + const stopOptions = yield* options() // A tunnel that cannot be created leaves remote access off instead of a service that keeps retrying. if (value === "true") yield* RemoteTunnel.ensure() - yield* Service.stop(yield* options()) + yield* Service.stop(stopOptions) if (value === "true") { yield* remote() return diff --git a/packages/cli/test/service-config.test.ts b/packages/cli/test/service-config.test.ts new file mode 100644 index 00000000000..a7ee2064d29 --- /dev/null +++ b/packages/cli/test/service-config.test.ts @@ -0,0 +1,127 @@ +import { NodeServices } from "@effect/platform-node" +import { Global } from "@opencode/util/global" +import { expect, test } from "bun:test" +import { Effect, FileSystem } from "effect" +import fs from "node:fs/promises" +import path from "node:path" +import { ServiceConfig } from "../src/services/service-config" +import { OPENCODE_VERSION } from "../src/version" +import { it } from "../../core/test/lib/effect" +import { isolatedEnv } from "./fixture/environment" +import { tmpdir } from "./fixture/tmpdir" + +it.live("missing service.json returns an empty config and initializes cleanly on first write", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem + const root = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-service-config-missing-" }) + const config = path.join(root, "config") + const state = path.join(root, "state") + + yield* Effect.gen(function* () { + expect(yield* ServiceConfig.read()).toEqual({}) + const created = yield* ServiceConfig.password() + yield* ServiceConfig.set("port", "4321") + expect(yield* ServiceConfig.read()).toEqual({ password: created, port: 4321 }) + }).pipe(Effect.provideService(Global.Service, Global.make({ config, state }))) + }).pipe(Effect.provide(NodeServices.layer)), +) + +it.live("corrupt or unreadable service.json fails cleanly and is never overwritten", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem + const root = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-service-config-corrupt-" }) + const config = path.join(root, "config") + const state = path.join(root, "state") + const file = path.join(config, ServiceConfig.filename()) + const registration = path.join(state, ServiceConfig.filename()) + yield* fs.makeDirectory(config) + yield* fs.makeDirectory(state) + + const registered = JSON.stringify({ id: "keep-running", url: "http://127.0.0.1:9", pid: 2_147_483_647 }) + yield* fs.writeFileString(registration, registered) + + yield* Effect.gen(function* () { + const samples = [ + '{"hostname":"0.0.0.0","port":"4096","password":"keep-me","env":{"KEEP":"1"}}\n', + '{"port": 4096,', + '{"remote":true,"port":"4096","password":"keep-me"}', + ] + + yield* Effect.forEach(samples, (raw) => + Effect.gen(function* () { + yield* fs.writeFileString(file, raw) + const error = yield* ServiceConfig.read().pipe(Effect.flip) + expect(error).toBeInstanceOf(ServiceConfig.InvalidError) + expect(error.message).toContain(file) + + yield* Effect.forEach( + [ + ServiceConfig.password(), + ServiceConfig.set("port", "4097"), + ServiceConfig.set("remote", "true"), + ServiceConfig.unset("port"), + ], + (write) => + Effect.gen(function* () { + expect(yield* write.pipe(Effect.flip)).toBeInstanceOf(ServiceConfig.InvalidError) + expect(yield* fs.readFileString(file)).toBe(raw) + expect(yield* fs.readFileString(registration)).toBe(registered) + }), + ) + }), + ) + + yield* fs.remove(file) + yield* fs.makeDirectory(file) + expect(yield* ServiceConfig.set("port", "4097").pipe(Effect.flip)).toMatchObject({ _tag: "PlatformError" }) + expect((yield* fs.stat(file)).type).toBe("Directory") + }).pipe(Effect.provideService(Global.Service, Global.make({ config, state }))) + }).pipe(Effect.provide(NodeServices.layer)), +) + +test("CLI refuses to overwrite an invalid service.json on serve --service while status and stop still work", async () => { + await using root = await tmpdir() + const file = path.join(root.path, "config", ServiceConfig.filename()) + const registration = path.join(root.path, "state", "opencode", ServiceConfig.filename()) + const raw = '{"hostname":"127.0.0.1","port":"4096","password":"keep-me","env":{"KEEP":"1"}}\n' + await fs.mkdir(path.dirname(file), { recursive: true }) + await fs.mkdir(path.dirname(registration), { recursive: true }) + await fs.writeFile(file, raw) + + const cli = async (...args: string[]) => { + const child = Bun.spawn([process.execPath, path.join(import.meta.dir, "../src/index.ts"), ...args], { + env: isolatedEnv(root.path), + stdout: "pipe", + stderr: "pipe", + }) + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]) + return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode } + } + + const serve = await cli("serve", "--service") + expect(serve.exitCode).toBe(1) + expect(serve.stderr).toContain(`Invalid service config at ${file}`) + expect(serve.stderr).toContain('["port"]') + expect(await Bun.file(file).text()).toBe(raw) + expect(await Bun.file(registration).exists()).toBe(false) + + using server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch: () => Response.json({ version: OPENCODE_VERSION, pid: 2_147_483_647, urls: [] }), + }) + const url = server.url.origin + await fs.writeFile( + registration, + JSON.stringify({ id: "running", version: OPENCODE_VERSION, url, pid: 2_147_483_647 }), + ) + + expect(await cli("service", "status")).toEqual({ stdout: url, stderr: "", exitCode: 0 }) + expect(await cli("service", "stop")).toEqual({ stdout: "", stderr: "", exitCode: 0 }) + expect(await Bun.file(registration).exists()).toBe(false) + expect(await Bun.file(file).text()).toBe(raw) +})