refactor(client): split package into promise and effect entrypoints
This commit is contained in:
parent
0087dd56d9
commit
af5eabcb26
46 changed files with 5211 additions and 2332 deletions
1
bun.lock
1
bun.lock
|
|
@ -126,7 +126,6 @@
|
|||
"@opencode-ai/schema": "workspace:*",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@opencode-ai/core": "workspace:*",
|
||||
"@opencode-ai/httpapi-codegen": "workspace:*",
|
||||
"@opencode-ai/server": "workspace:*",
|
||||
|
|
|
|||
|
|
@ -2,8 +2,9 @@ import { EOL } from "node:os"
|
|||
import { Effect, Option } from "effect"
|
||||
import { Commands } from "../commands"
|
||||
import { Runtime } from "../../framework/runtime"
|
||||
import { Service } from "../../services/service"
|
||||
import type { Transport } from "@opencode-ai/client/service"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { ServiceConfig } from "../../services/service-config"
|
||||
import type { Transport } from "@opencode-ai/client/effect"
|
||||
|
||||
const methods = new Set(["delete", "get", "head", "options", "patch", "post", "put"])
|
||||
|
||||
|
|
@ -18,7 +19,9 @@ type OpenApi = {
|
|||
export default Runtime.handler(
|
||||
Commands.commands.api,
|
||||
Effect.fn("cli.api")(function* (input) {
|
||||
const transport = yield* Service.connect()
|
||||
const options = yield* ServiceConfig.options()
|
||||
const found = yield* Service.discover(options)
|
||||
const transport = found ?? (yield* Service.start(options))
|
||||
const params = Option.getOrElse(input.param, () => ({}))
|
||||
const request = yield* resolveRequest(transport, input.request, params)
|
||||
const headers = new Headers(transport.headers)
|
||||
|
|
|
|||
|
|
@ -3,12 +3,15 @@ import * as Effect from "effect/Effect"
|
|||
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.debug.commands.agents,
|
||||
Effect.fn("cli.debug.agents")(function* () {
|
||||
const transport = yield* Service.connect()
|
||||
const options = yield* ServiceConfig.options()
|
||||
const found = yield* Service.discover(options)
|
||||
const transport = found ?? (yield* Service.start(options))
|
||||
const client = createOpencodeClient({ baseUrl: transport.url, headers: transport.headers })
|
||||
const response = yield* Effect.promise(() => client.v2.agent.list({ location: { directory: process.cwd() } }))
|
||||
process.stdout.write(
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import { NodeFileSystem } from "@effect/platform-node"
|
||||
import { Commands } from "../commands"
|
||||
import { Runtime } from "../../framework/runtime"
|
||||
import { Global } from "@opencode-ai/core/global"
|
||||
import { Effect, FileSystem, Option } from "effect"
|
||||
import { Service } from "../../services/service"
|
||||
import { Effect, Option } from "effect"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import type { Transport } from "@opencode-ai/client/effect"
|
||||
import { ServiceConfig } from "../../services/service-config"
|
||||
import { Standalone } from "../../services/standalone"
|
||||
import { Updater } from "../../services/updater"
|
||||
import { basicAuth } from "@opencode-ai/client/service"
|
||||
import type { Transport } from "@opencode-ai/client/service"
|
||||
|
||||
export default Runtime.handler(Commands, (input) =>
|
||||
Effect.gen(function* () {
|
||||
|
|
@ -17,29 +17,34 @@ export default Runtime.handler(Commands, (input) =>
|
|||
const server = Option.getOrUndefined(input.server)
|
||||
if (server !== undefined && input.standalone)
|
||||
return yield* Effect.fail(new Error("--server and --standalone cannot be combined"))
|
||||
const transport = yield* resolveTransport(server, input.standalone)
|
||||
const transport = yield* Effect.gen(function* () {
|
||||
if (server !== undefined) {
|
||||
const password = process.env["OPENCODE_SERVER_PASSWORD"]
|
||||
return {
|
||||
url: server,
|
||||
headers: password ? { authorization: "Basic " + btoa("opencode:" + password) } : undefined,
|
||||
} satisfies Transport
|
||||
}
|
||||
if (input.standalone) return yield* Standalone.transport()
|
||||
const options = yield* ServiceConfig.options()
|
||||
const found = yield* Service.discover(options)
|
||||
return found ?? (yield* Service.start(options))
|
||||
})
|
||||
const { runTui } = yield* Effect.promise(() => import("../../tui"))
|
||||
// The TUI re-runs discover whenever its event stream drops. For an explicit
|
||||
// --server or a standalone child the transport is fixed, so reconnects
|
||||
// retry the same address; for the managed service discovery re-reads the
|
||||
// registration and may start a replacement.
|
||||
const context = yield* Effect.context<FileSystem.FileSystem | Global.Service>()
|
||||
const discover =
|
||||
server !== undefined || input.standalone
|
||||
? () => Promise.resolve(transport)
|
||||
: () => Effect.runPromise(Service.connect().pipe(Effect.provide(context)))
|
||||
const serviceOptions = server === undefined && !input.standalone ? yield* ServiceConfig.options() : undefined
|
||||
const discover = serviceOptions
|
||||
? () =>
|
||||
Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const found = yield* Service.discover(serviceOptions)
|
||||
return found ?? (yield* Service.start(serviceOptions))
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
)
|
||||
: () => Promise.resolve(transport)
|
||||
yield* runTui(transport, { continue: input.continue, sessionID: Option.getOrUndefined(input.session) }, discover)
|
||||
}),
|
||||
)
|
||||
|
||||
function resolveTransport(server: string | undefined, standalone: boolean) {
|
||||
if (server !== undefined) {
|
||||
const password = process.env["OPENCODE_SERVER_PASSWORD"]
|
||||
return Effect.succeed({
|
||||
url: server,
|
||||
headers: password ? basicAuth(password) : undefined,
|
||||
} satisfies Transport)
|
||||
}
|
||||
if (standalone) return Standalone.transport()
|
||||
return Service.connect()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ import {
|
|||
} from "@opencode-ai/sdk/v2/client"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
import { resolveIntegration } from "./resolve"
|
||||
|
||||
const location = { directory: process.cwd() }
|
||||
|
|
@ -16,7 +17,9 @@ const location = { directory: process.cwd() }
|
|||
export default Runtime.handler(
|
||||
Commands.commands.mcp.commands.auth,
|
||||
Effect.fn("cli.mcp.auth")(function* (input) {
|
||||
const transport = yield* Service.connect()
|
||||
const options = yield* ServiceConfig.options()
|
||||
const found = yield* Service.discover(options)
|
||||
const transport = found ?? (yield* Service.start(options))
|
||||
const client = createOpencodeClient({ baseUrl: transport.url, headers: transport.headers })
|
||||
|
||||
const integration = yield* resolveIntegration(client, input.name, location)
|
||||
|
|
|
|||
|
|
@ -3,12 +3,15 @@ import * as Effect from "effect/Effect"
|
|||
import { createOpencodeClient, type McpServer } from "@opencode-ai/sdk/v2/client"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.mcp.commands.list,
|
||||
Effect.fn("cli.mcp.list")(function* () {
|
||||
const transport = yield* Service.connect()
|
||||
const options = yield* ServiceConfig.options()
|
||||
const found = yield* Service.discover(options)
|
||||
const transport = found ?? (yield* Service.start(options))
|
||||
const client = createOpencodeClient({ baseUrl: transport.url, headers: transport.headers })
|
||||
const response = yield* Effect.promise(() => client.v2.mcp.list({ location: { directory: process.cwd() } }))
|
||||
const servers = (response.data?.data ?? []).toSorted((a, b) => a.name.localeCompare(b.name))
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ import { Effect } from "effect"
|
|||
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
import { resolveIntegration } from "./resolve"
|
||||
|
||||
const location = { directory: process.cwd() }
|
||||
|
|
@ -11,7 +12,9 @@ const location = { directory: process.cwd() }
|
|||
export default Runtime.handler(
|
||||
Commands.commands.mcp.commands.logout,
|
||||
Effect.fn("cli.mcp.logout")(function* (input) {
|
||||
const transport = yield* Service.connect()
|
||||
const options = yield* ServiceConfig.options()
|
||||
const found = yield* Service.discover(options)
|
||||
const transport = found ?? (yield* Service.start(options))
|
||||
const client = createOpencodeClient({ baseUrl: transport.url, headers: transport.headers })
|
||||
|
||||
const integration = yield* resolveIntegration(client, input.name, location)
|
||||
|
|
|
|||
|
|
@ -4,18 +4,20 @@ import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
|||
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
|
||||
import { PermissionSaved } from "@opencode-ai/core/permission/saved"
|
||||
import { Global } from "@opencode-ai/core/global"
|
||||
import { Context, Layer, Option, Schedule } from "effect"
|
||||
import { Context, FileSystem, Layer, Option, Schedule, Schema } from "effect"
|
||||
import * as Effect from "effect/Effect"
|
||||
import { HttpRouter, HttpServer } from "effect/unstable/http"
|
||||
import { createServer } from "node:http"
|
||||
import { createRoutes } from "@opencode-ai/server/routes"
|
||||
import { ServerAuth } from "@opencode-ai/server/auth"
|
||||
import { InstallationVersion } from "@opencode-ai/core/installation/version"
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
|
||||
import { Commands } from "../commands"
|
||||
import { Runtime } from "../../framework/runtime"
|
||||
import { Service } from "../../services/service"
|
||||
import { ServiceConfig } from "../../services/service-config"
|
||||
import { Updater } from "../../services/updater"
|
||||
import { randomBytes } from "crypto"
|
||||
import { randomBytes, randomUUID } from "crypto"
|
||||
import path from "path"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.serve,
|
||||
|
|
@ -25,9 +27,9 @@ export default Runtime.handler(
|
|||
Effect.gen(function* () {
|
||||
const standalonePassword = process.env.OPENCODE_SERVER_PASSWORD
|
||||
if (input.stdio) delete process.env.OPENCODE_SERVER_PASSWORD
|
||||
const config = input.service ? yield* Service.config() : {}
|
||||
const config = input.service ? yield* ServiceConfig.read() : {}
|
||||
const password = input.service
|
||||
? yield* Service.password()
|
||||
? yield* ServiceConfig.password()
|
||||
: standalonePassword || randomBytes(32).toString("base64url")
|
||||
if (!password) return yield* Effect.fail(new Error("Missing server password"))
|
||||
const hostname = Option.getOrUndefined(input.hostname) ?? config.hostname ?? "127.0.0.1"
|
||||
|
|
@ -43,7 +45,7 @@ export default Runtime.handler(
|
|||
headers: ServerAuth.headers({ password }),
|
||||
}).v2.health.get({}),
|
||||
)
|
||||
if (input.service) yield* Service.register(address)
|
||||
if (input.service) yield* register(address)
|
||||
const url = HttpServer.formatAddress(address)
|
||||
console.log(input.stdio ? JSON.stringify({ url }) : `server listening on ${url}`)
|
||||
if (!input.service && !input.stdio && !standalonePassword) console.log(`server password ${password}`)
|
||||
|
|
@ -55,6 +57,56 @@ export default Runtime.handler(
|
|||
}),
|
||||
)
|
||||
|
||||
// Server-side half of the registration protocol. The registration embeds the
|
||||
// password so the file alone is enough for any client to discover and
|
||||
// authenticate. The file arbitrates ownership after concurrent starts; it is
|
||||
// not a startup lock: the atomic rename elects the latest writer, the watcher
|
||||
// self-evicts losers, and the finalizer id-guard keeps an exiting server from
|
||||
// deleting its successor's registration.
|
||||
const RegistrationId = Schema.Struct({ id: Schema.optional(Schema.String) })
|
||||
const decodeRegistrationId = Schema.decodeUnknownEffect(Schema.fromJsonString(RegistrationId))
|
||||
|
||||
const register = Effect.fnUntraced(function* (address: HttpServer.Address) {
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
const { file } = yield* ServiceConfig.options()
|
||||
const id = randomUUID()
|
||||
const secret = yield* ServiceConfig.password()
|
||||
const temp = file + "." + id + ".tmp"
|
||||
yield* fs.makeDirectory(path.dirname(file), { recursive: true })
|
||||
yield* fs.writeFileString(
|
||||
temp,
|
||||
JSON.stringify({
|
||||
id,
|
||||
version: InstallationVersion,
|
||||
url: HttpServer.formatAddress(address),
|
||||
pid: process.pid,
|
||||
password: secret,
|
||||
}),
|
||||
{ mode: 0o600 },
|
||||
)
|
||||
yield* fs.rename(temp, file)
|
||||
const currentID = fs.readFileString(file).pipe(
|
||||
Effect.flatMap(decodeRegistrationId),
|
||||
Effect.map((info) => info.id),
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
)
|
||||
yield* currentID.pipe(
|
||||
Effect.flatMap((current) =>
|
||||
current === id
|
||||
? Effect.void
|
||||
: Effect.try({ try: () => process.kill(process.pid, "SIGTERM"), catch: (cause) => cause }).pipe(Effect.ignore),
|
||||
),
|
||||
Effect.repeat(Schedule.spaced("10 seconds")),
|
||||
Effect.forkScoped,
|
||||
)
|
||||
yield* Effect.addFinalizer(() =>
|
||||
currentID.pipe(
|
||||
Effect.flatMap((current) => (current === id ? fs.remove(file) : Effect.void)),
|
||||
Effect.ignore,
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
function waitForStdinClose() {
|
||||
return Effect.callback<void>((resume) => {
|
||||
const close = () => resume(Effect.void)
|
||||
|
|
|
|||
|
|
@ -3,11 +3,11 @@ import { Option } from "effect"
|
|||
import * as Effect from "effect/Effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.service.commands.get,
|
||||
Effect.fn("cli.service.get")(function* (input) {
|
||||
process.stdout.write((yield* Service.get(Option.getOrUndefined(input.key))) + EOL)
|
||||
process.stdout.write((yield* ServiceConfig.get(Option.getOrUndefined(input.key))) + EOL)
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,13 +1,16 @@
|
|||
import { EOL } from "os"
|
||||
import * as Effect from "effect/Effect"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.service.commands.restart,
|
||||
Effect.fn("cli.service.restart")(function* () {
|
||||
yield* Service.stop()
|
||||
process.stdout.write((yield* Service.start()).url + EOL)
|
||||
const options = yield* ServiceConfig.options()
|
||||
yield* Service.stop(options)
|
||||
const transport = yield* Service.start(options)
|
||||
process.stdout.write(transport.url + EOL)
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import * as Effect from "effect/Effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.service.commands.set,
|
||||
Effect.fn("cli.service.set")(function* (input) {
|
||||
yield* Service.set(input.key, input.value)
|
||||
yield* ServiceConfig.set(input.key, input.value)
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import { EOL } from "os"
|
||||
import * as Effect from "effect/Effect"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.service.commands.start,
|
||||
Effect.fn("cli.service.start")(function* () {
|
||||
process.stdout.write((yield* Service.start()).url + EOL)
|
||||
const transport = yield* Service.start(yield* ServiceConfig.options())
|
||||
process.stdout.write(transport.url + EOL)
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
import { EOL } from "os"
|
||||
import * as Effect from "effect/Effect"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.service.commands.status,
|
||||
Effect.fn("cli.service.status")(function* () {
|
||||
const found = yield* Service.discover()
|
||||
const found = yield* Service.discover(yield* ServiceConfig.options())
|
||||
process.stdout.write((found ? found.url : "stopped") + EOL)
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
import * as Effect from "effect/Effect"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.service.commands.stop,
|
||||
Effect.fn("cli.service.stop")(function* () {
|
||||
yield* Service.stop()
|
||||
yield* Service.stop(yield* ServiceConfig.options())
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import * as Effect from "effect/Effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { Service } from "../../../services/service"
|
||||
import { ServiceConfig } from "../../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.service.commands.unset,
|
||||
Effect.fn("cli.service.unset")(function* (input) {
|
||||
yield* Service.unset(input.key)
|
||||
yield* ServiceConfig.unset(input.key)
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
143
packages/cli/src/services/service-config.ts
Normal file
143
packages/cli/src/services/service-config.ts
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import { Global } from "@opencode-ai/core/global"
|
||||
import { InstallationChannel, InstallationVersion } from "@opencode-ai/core/installation/version"
|
||||
import { Service } from "@opencode-ai/client/effect"
|
||||
import { Effect, FileSystem, Schema } from "effect"
|
||||
import { randomBytes } from "crypto"
|
||||
import path from "path"
|
||||
|
||||
// The CLI's service configuration file, plus the ServiceOptions binding that
|
||||
// points the client package's service operations at this CLI: which
|
||||
// registration file (by channel), which version, and how to spawn opencode.
|
||||
|
||||
export const Info = Schema.Struct({
|
||||
hostname: Schema.optional(Schema.String),
|
||||
port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),
|
||||
password: Schema.optional(Schema.String),
|
||||
})
|
||||
export type Info = typeof Info.Type
|
||||
|
||||
const keys = ["hostname", "port", "password"] as const
|
||||
type Key = (typeof keys)[number]
|
||||
|
||||
const decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))
|
||||
|
||||
function configKey(key: string): Key {
|
||||
if (keys.includes(key as Key)) return key as Key
|
||||
throw new Error(`Unknown service config key: ${key}`)
|
||||
}
|
||||
|
||||
const env = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
const global = yield* Global.Service
|
||||
const filename = InstallationChannel === "local" ? "service-local.json" : "service.json"
|
||||
return {
|
||||
fs,
|
||||
file: path.join(global.state, filename),
|
||||
configFile: path.join(global.config, filename),
|
||||
}
|
||||
})
|
||||
|
||||
export const options = Effect.fnUntraced(function* () {
|
||||
const { file } = yield* env
|
||||
const compiled = path.basename(process.execPath).replace(/\.exe$/, "") !== "bun"
|
||||
const entrypoint = compiled ? undefined : process.argv[1]
|
||||
if (!compiled && entrypoint === undefined) return yield* Effect.fail(new Error("Failed to resolve CLI entrypoint"))
|
||||
return {
|
||||
file,
|
||||
version: InstallationVersion,
|
||||
command: [process.execPath, ...(entrypoint ? [entrypoint] : []), "serve", "--service"],
|
||||
}
|
||||
})
|
||||
|
||||
export const read = Effect.fn("cli.service-config.read")(function* () {
|
||||
const { fs, configFile } = yield* env
|
||||
return yield* fs.readFileString(configFile).pipe(
|
||||
Effect.flatMap(decodeInfo),
|
||||
Effect.catch(() => Effect.succeed({} as Info)),
|
||||
)
|
||||
})
|
||||
|
||||
const write = Effect.fn("cli.service-config.write")(function* (value: Info) {
|
||||
const { fs, configFile } = yield* env
|
||||
const temp = configFile + ".tmp"
|
||||
yield* fs.makeDirectory(path.dirname(configFile), { recursive: true })
|
||||
yield* fs.writeFileString(temp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 })
|
||||
yield* fs.rename(temp, configFile)
|
||||
})
|
||||
|
||||
export const password = Effect.fn("cli.service-config.password")(function* (value?: string) {
|
||||
const existing = yield* read()
|
||||
if (value === undefined && existing.password) return existing.password
|
||||
const next = value ?? randomBytes(32).toString("base64url")
|
||||
|
||||
// Keep one private credential across server restarts so discovered clients
|
||||
// can reconnect without exposing a password flag or environment variable.
|
||||
yield* write({ ...existing, password: next })
|
||||
return next
|
||||
})
|
||||
|
||||
export const get = Effect.fn("cli.service-config.get")(function* (key?: string) {
|
||||
if (key === undefined) {
|
||||
const { password: _password, ...safe } = yield* read()
|
||||
return JSON.stringify(safe, null, 2)
|
||||
}
|
||||
switch (configKey(key)) {
|
||||
case "hostname": {
|
||||
return (yield* read()).hostname ?? ""
|
||||
}
|
||||
case "port": {
|
||||
const port = (yield* read()).port
|
||||
return port === undefined ? "" : String(port)
|
||||
}
|
||||
case "password": {
|
||||
return yield* password()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const set = Effect.fn("cli.service-config.set")(function* (key: string, value: string) {
|
||||
switch (configKey(key)) {
|
||||
case "hostname": {
|
||||
yield* Service.stop(yield* options())
|
||||
yield* write({ ...(yield* read()), hostname: value })
|
||||
return
|
||||
}
|
||||
case "port": {
|
||||
const port = Number(value)
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error("Port must be between 1 and 65535")
|
||||
yield* Service.stop(yield* options())
|
||||
yield* write({ ...(yield* read()), port })
|
||||
return
|
||||
}
|
||||
case "password": {
|
||||
yield* Service.stop(yield* options())
|
||||
yield* password(value)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const unset = Effect.fn("cli.service-config.unset")(function* (key: string) {
|
||||
switch (configKey(key)) {
|
||||
case "hostname": {
|
||||
yield* Service.stop(yield* options())
|
||||
const { hostname: _hostname, ...next } = yield* read()
|
||||
yield* write(next)
|
||||
return
|
||||
}
|
||||
case "port": {
|
||||
yield* Service.stop(yield* options())
|
||||
const { port: _port, ...next } = yield* read()
|
||||
yield* write(next)
|
||||
return
|
||||
}
|
||||
case "password": {
|
||||
yield* Service.stop(yield* options())
|
||||
const { password: _password, ...next } = yield* read()
|
||||
yield* write(next)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export * as ServiceConfig from "./service-config"
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
import { Global } from "@opencode-ai/core/global"
|
||||
import { InstallationChannel, InstallationVersion } from "@opencode-ai/core/installation/version"
|
||||
import { ServiceEffect } from "@opencode-ai/client/service/effect"
|
||||
import { Effect, FileSystem, Schedule, Schema } from "effect"
|
||||
import { HttpServer } from "effect/unstable/http"
|
||||
import { randomBytes, randomUUID } from "crypto"
|
||||
import path from "path"
|
||||
|
||||
// Binds the client package's service operations to this CLI: which
|
||||
// registration file (by channel), which version, and how to spawn opencode.
|
||||
// Also owns the service config file and the server-side registration write.
|
||||
|
||||
const ServiceConfig = Schema.Struct({
|
||||
hostname: Schema.optional(Schema.String),
|
||||
port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),
|
||||
password: Schema.optional(Schema.String),
|
||||
})
|
||||
export type ServiceConfig = typeof ServiceConfig.Type
|
||||
|
||||
const serviceConfigKeys = ["hostname", "port", "password"] as const
|
||||
type ServiceConfigKey = (typeof serviceConfigKeys)[number]
|
||||
|
||||
const decodeServiceConfig = Schema.decodeUnknownEffect(Schema.fromJsonString(ServiceConfig))
|
||||
|
||||
function serviceConfigKey(key: string): ServiceConfigKey {
|
||||
if (serviceConfigKeys.includes(key as ServiceConfigKey)) return key as ServiceConfigKey
|
||||
throw new Error(`Unknown service config key: ${key}`)
|
||||
}
|
||||
|
||||
const env = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
const global = yield* Global.Service
|
||||
const filename = InstallationChannel === "local" ? "service-local.json" : "service.json"
|
||||
return {
|
||||
fs,
|
||||
stateDir: global.state,
|
||||
file: path.join(global.state, filename),
|
||||
configFile: path.join(global.config, filename),
|
||||
}
|
||||
})
|
||||
|
||||
const options = Effect.fnUntraced(function* () {
|
||||
const { file } = yield* env
|
||||
const compiled = path.basename(process.execPath).replace(/\.exe$/, "") !== "bun"
|
||||
const entrypoint = compiled ? undefined : process.argv[1]
|
||||
if (!compiled && entrypoint === undefined) return yield* Effect.fail(new Error("Failed to resolve CLI entrypoint"))
|
||||
return {
|
||||
file,
|
||||
version: InstallationVersion,
|
||||
command: [process.execPath, ...(entrypoint ? [entrypoint] : []), "serve", "--service"],
|
||||
}
|
||||
})
|
||||
|
||||
export const discover = Effect.fn("cli.service.discover")(function* () {
|
||||
const found = yield* ServiceEffect.discover(yield* options())
|
||||
return found?.transport
|
||||
})
|
||||
|
||||
export const start = Effect.fn("cli.service.start")(function* () {
|
||||
return yield* ServiceEffect.start(yield* options())
|
||||
})
|
||||
|
||||
export const connect = Effect.fn("cli.service.connect")(function* () {
|
||||
return yield* ServiceEffect.connect(yield* options())
|
||||
})
|
||||
|
||||
export const stop = Effect.fn("cli.service.stop")(function* () {
|
||||
return yield* ServiceEffect.stop(yield* options())
|
||||
})
|
||||
|
||||
export const config = Effect.fn("cli.service.config")(function* () {
|
||||
const { fs, configFile } = yield* env
|
||||
return yield* fs.readFileString(configFile).pipe(
|
||||
Effect.flatMap(decodeServiceConfig),
|
||||
Effect.catch(() => Effect.succeed({} as ServiceConfig)),
|
||||
)
|
||||
})
|
||||
|
||||
const writeConfig = Effect.fn("cli.service.writeConfig")(function* (value: ServiceConfig) {
|
||||
const { fs, configFile } = yield* env
|
||||
const temp = configFile + ".tmp"
|
||||
yield* fs.makeDirectory(path.dirname(configFile), { recursive: true })
|
||||
yield* fs.writeFileString(temp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 })
|
||||
yield* fs.rename(temp, configFile)
|
||||
})
|
||||
|
||||
export const password = Effect.fn("cli.service.password")(function* (value?: string) {
|
||||
const existing = yield* config()
|
||||
if (value === undefined && existing.password) return existing.password
|
||||
const next = value ?? randomBytes(32).toString("base64url")
|
||||
|
||||
// Keep one private credential across server restarts so discovered clients
|
||||
// can reconnect without exposing a password flag or environment variable.
|
||||
yield* writeConfig({ ...existing, password: next })
|
||||
return next
|
||||
})
|
||||
|
||||
export const get = Effect.fn("cli.service.get")(function* (key?: string) {
|
||||
if (key === undefined) {
|
||||
const { password: _password, ...safe } = yield* config()
|
||||
return JSON.stringify(safe, null, 2)
|
||||
}
|
||||
switch (serviceConfigKey(key)) {
|
||||
case "hostname": {
|
||||
return (yield* config()).hostname ?? ""
|
||||
}
|
||||
case "port": {
|
||||
const port = (yield* config()).port
|
||||
return port === undefined ? "" : String(port)
|
||||
}
|
||||
case "password": {
|
||||
return yield* password()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const set = Effect.fn("cli.service.set")(function* (key: string, value: string) {
|
||||
switch (serviceConfigKey(key)) {
|
||||
case "hostname": {
|
||||
yield* stop()
|
||||
yield* writeConfig({ ...(yield* config()), hostname: value })
|
||||
return
|
||||
}
|
||||
case "port": {
|
||||
const port = Number(value)
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error("Port must be between 1 and 65535")
|
||||
yield* stop()
|
||||
yield* writeConfig({ ...(yield* config()), port })
|
||||
return
|
||||
}
|
||||
case "password": {
|
||||
yield* stop()
|
||||
yield* password(value)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const unset = Effect.fn("cli.service.unset")(function* (key: string) {
|
||||
switch (serviceConfigKey(key)) {
|
||||
case "hostname": {
|
||||
yield* stop()
|
||||
const { hostname: _hostname, ...next } = yield* config()
|
||||
yield* writeConfig(next)
|
||||
return
|
||||
}
|
||||
case "port": {
|
||||
yield* stop()
|
||||
const { port: _port, ...next } = yield* config()
|
||||
yield* writeConfig(next)
|
||||
return
|
||||
}
|
||||
case "password": {
|
||||
yield* stop()
|
||||
const { password: _password, ...next } = yield* config()
|
||||
yield* writeConfig(next)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Server-side half of the registration protocol, run by `serve --service` at
|
||||
// boot. The registration embeds the password so the file alone is enough for
|
||||
// any client to discover and authenticate. service.json arbitrates ownership
|
||||
// after concurrent starts; it is not a startup lock: the atomic rename elects
|
||||
// the latest writer, the watcher self-evicts losers, and the finalizer
|
||||
// id-guard keeps an exiting server from deleting its successor's registration.
|
||||
export const register = Effect.fn("cli.service.register")(function* (address: HttpServer.Address) {
|
||||
const { fs, stateDir, file } = yield* env
|
||||
const id = randomUUID()
|
||||
const secret = yield* password()
|
||||
const temp = file + "." + id + ".tmp"
|
||||
yield* fs.makeDirectory(stateDir, { recursive: true })
|
||||
yield* fs.writeFileString(
|
||||
temp,
|
||||
JSON.stringify({
|
||||
id,
|
||||
version: InstallationVersion,
|
||||
url: HttpServer.formatAddress(address),
|
||||
pid: process.pid,
|
||||
password: secret,
|
||||
}),
|
||||
{ mode: 0o600 },
|
||||
)
|
||||
yield* fs.rename(temp, file)
|
||||
yield* ServiceEffect.readRegistration(file).pipe(
|
||||
Effect.flatMap((info) =>
|
||||
info?.id === id
|
||||
? Effect.void
|
||||
: Effect.try({ try: () => process.kill(process.pid, "SIGTERM"), catch: (cause) => cause }).pipe(Effect.ignore),
|
||||
),
|
||||
Effect.repeat(Schedule.spaced("10 seconds")),
|
||||
Effect.forkScoped,
|
||||
)
|
||||
yield* Effect.addFinalizer(() =>
|
||||
ServiceEffect.readRegistration(file).pipe(
|
||||
Effect.flatMap((info) => (info?.id === id ? fs.remove(file) : Effect.void)),
|
||||
Effect.ignore,
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
export * as Service from "./service"
|
||||
|
|
@ -4,8 +4,8 @@ import { Effect } from "effect"
|
|||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { Global } from "@opencode-ai/core/global"
|
||||
import { loadBuiltinPlugins } from "@opencode-ai/tui/builtins"
|
||||
import { OpenCode } from "@opencode-ai/client"
|
||||
import type { Transport } from "@opencode-ai/client/service"
|
||||
import { OpenCode } from "@opencode-ai/client/promise"
|
||||
import type { Transport } from "@opencode-ai/client/effect"
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
|
||||
import type { Args } from "@opencode-ai/tui/context/args"
|
||||
|
||||
|
|
|
|||
|
|
@ -5,13 +5,13 @@ import { Effect } from "effect"
|
|||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { Service } from "../src/services/service"
|
||||
import { ServiceConfig } from "../src/services/service-config"
|
||||
|
||||
test("local channel stores service config with the local service filename", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-"))
|
||||
try {
|
||||
await Effect.runPromise(
|
||||
Service.set("hostname", "127.0.0.2").pipe(
|
||||
ServiceConfig.set("hostname", "127.0.0.2").pipe(
|
||||
Effect.provide(Global.layerWith({ config: path.join(root, "config"), state: path.join(root, "state") })),
|
||||
Effect.provide(NodeFileSystem.layer),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -5,14 +5,12 @@
|
|||
"type": "module",
|
||||
"license": "MIT",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./effect": "./src/effect.ts",
|
||||
"./service": "./src/service/index.ts",
|
||||
"./service/effect": "./src/service/effect.ts"
|
||||
"./promise": "./src/promise/index.ts",
|
||||
"./effect": "./src/effect/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"generate": "bun run script/build.ts",
|
||||
"check:generated": "bun run generate && git diff --exit-code -- src/generated src/generated-effect",
|
||||
"check:generated": "bun run generate && git diff --exit-code -- src/promise/generated src/effect/generated",
|
||||
"test": "bun test --timeout 5000",
|
||||
"typecheck": "tsgo --noEmit"
|
||||
},
|
||||
|
|
@ -29,7 +27,6 @@
|
|||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@opencode-ai/core": "workspace:*",
|
||||
"@opencode-ai/httpapi-codegen": "workspace:*",
|
||||
"@opencode-ai/server": "workspace:*",
|
||||
|
|
|
|||
|
|
@ -25,11 +25,11 @@ await Effect.runPromise(
|
|||
},
|
||||
},
|
||||
}),
|
||||
fileURLToPath(new URL("../src/generated", import.meta.url)),
|
||||
fileURLToPath(new URL("../src/promise/generated", import.meta.url)),
|
||||
),
|
||||
write(
|
||||
emitEffectImported(effectContract, { module: "../contract", api: "ClientApi" }),
|
||||
fileURLToPath(new URL("../src/generated-effect", import.meta.url)),
|
||||
emitEffectImported(effectContract, { module: "../../contract", api: "ClientApi" }),
|
||||
fileURLToPath(new URL("../src/effect/generated", import.meta.url)),
|
||||
),
|
||||
write(
|
||||
emitEffectShape(effectContract, { module: "@opencode-ai/protocol/client", api: "ClientApi" }),
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { Effect, Stream, Schema } from "effect"
|
|||
import { Sse } from "effect/unstable/encoding"
|
||||
import { HttpClientError } from "effect/unstable/http"
|
||||
import { HttpApiClient } from "effect/unstable/httpapi"
|
||||
import { ClientApi } from "../contract"
|
||||
import { ClientApi } from "../../contract"
|
||||
import { ClientError } from "./client-error"
|
||||
|
||||
type RawClient = HttpApiClient.ForApi<typeof ClientApi>
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
// TODO: Keep additional network capabilities inside Schema and Protocol as the client grows; /effect must never import
|
||||
// Core or Server. Preserve these datatype exports so internal model reorganizations do not require caller migrations.
|
||||
export * from "./generated-effect/index"
|
||||
export * from "./generated/index"
|
||||
export { Service } from "./service.js"
|
||||
export type { Transport, ServiceOptions } from "./service.js"
|
||||
export { Agent } from "@opencode-ai/schema/agent"
|
||||
export { Command } from "@opencode-ai/schema/command"
|
||||
export { Credential } from "@opencode-ai/schema/credential"
|
||||
165
packages/client/src/effect/service.ts
Normal file
165
packages/client/src/effect/service.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
import { Effect, FileSystem, Option, Schedule, Schema } from "effect"
|
||||
import { spawn } from "node:child_process"
|
||||
import { homedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
// Find, start, and stop the local opencode background service.
|
||||
//
|
||||
// The service daemon advertises itself through a registration file in the
|
||||
// user's state directory: url, pid, version, and the private password, with
|
||||
// 0600 permissions. That file is the complete discovery contract — reading it
|
||||
// is all a client needs to connect. The daemon's own configuration (port,
|
||||
// persisted password) is CLI-owned and never read here.
|
||||
|
||||
export type Transport = {
|
||||
readonly url: string
|
||||
readonly headers?: RequestInit["headers"]
|
||||
}
|
||||
|
||||
export type ServiceOptions = {
|
||||
// Absolute path to the service registration file. Defaults to
|
||||
// opencode/service.json in the XDG state directory.
|
||||
readonly file?: string
|
||||
// When set, discovery only returns a server reporting this exact version,
|
||||
// and start() replaces a healthy server whose version differs.
|
||||
readonly version?: string
|
||||
// Argv used to spawn the service. Defaults to ["opencode", "serve",
|
||||
// "--service"] resolved from PATH.
|
||||
readonly command?: ReadonlyArray<string>
|
||||
}
|
||||
|
||||
// Read-only lookup: registration file plus health check and version gate.
|
||||
// Never spawns; escalation to start() is the caller's policy.
|
||||
export const discover = Effect.fn("service.discover")(function* (options: ServiceOptions = {}) {
|
||||
const registration = yield* read(options.file)
|
||||
if (registration === undefined) return undefined
|
||||
if (options.version !== undefined && registration.version !== options.version) return undefined
|
||||
const found = yield* probe(registration)
|
||||
return found?.transport
|
||||
})
|
||||
|
||||
// Idempotent ensure-running: reuses a healthy compatible server, replaces a
|
||||
// version-mismatched one, and otherwise spawns the service command detached.
|
||||
export const start = Effect.fn("service.start")(function* (options: ServiceOptions = {}) {
|
||||
const compatible = yield* discover(options)
|
||||
if (compatible !== undefined) return compatible
|
||||
const mismatched = yield* find(options)
|
||||
if (mismatched !== undefined) yield* kill(mismatched.registration, options).pipe(Effect.ignore)
|
||||
|
||||
const [command, ...args] = options.command ?? ["opencode", "serve", "--service"]
|
||||
if (command === undefined) return yield* Effect.fail(new Error("Missing service command"))
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
spawn(command, args, { detached: true, stdio: "ignore" }).unref()
|
||||
},
|
||||
catch: (cause) => new Error("Failed to start server", { cause }),
|
||||
})
|
||||
|
||||
return yield* discover(options).pipe(
|
||||
Effect.flatMap((found) =>
|
||||
found === undefined ? Effect.fail(new Error("Server is not ready")) : Effect.succeed(found),
|
||||
),
|
||||
Effect.retry(poll),
|
||||
Effect.mapError(() => new Error("Failed to start server")),
|
||||
)
|
||||
})
|
||||
|
||||
export const stop = Effect.fn("service.stop")(function* (options: ServiceOptions = {}) {
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
const existing = yield* find(options)
|
||||
if (existing !== undefined) yield* kill(existing.registration, options)
|
||||
yield* fs.remove(options.file ?? fallback()).pipe(Effect.ignore)
|
||||
})
|
||||
|
||||
function fallback() {
|
||||
const state = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state")
|
||||
return join(state, "opencode", "service.json")
|
||||
}
|
||||
|
||||
function auth(password: string): RequestInit["headers"] {
|
||||
return { authorization: "Basic " + btoa("opencode:" + password) }
|
||||
}
|
||||
|
||||
const Registration = Schema.Struct({
|
||||
id: Schema.optional(Schema.String),
|
||||
version: Schema.optional(Schema.String),
|
||||
url: Schema.String,
|
||||
pid: Schema.Int.check(Schema.isGreaterThan(0)),
|
||||
password: Schema.optional(Schema.String),
|
||||
})
|
||||
type Registration = typeof Registration.Type
|
||||
|
||||
const decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Registration))
|
||||
|
||||
// A missing or corrupt file means no valid registration; callers treat both
|
||||
// the same (the registering server self-evicts, clients rediscover).
|
||||
const read = Effect.fnUntraced(function* (file?: string) {
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
const text = yield* fs.readFileString(file ?? fallback()).pipe(Effect.option)
|
||||
if (Option.isNone(text)) return undefined
|
||||
return yield* decode(text.value).pipe(Effect.option, Effect.map(Option.getOrUndefined))
|
||||
})
|
||||
|
||||
type LocalService = {
|
||||
readonly registration: Registration
|
||||
readonly transport: Transport
|
||||
}
|
||||
|
||||
const probe = Effect.fnUntraced(function* (registration: Registration) {
|
||||
const headers = registration.password === undefined ? undefined : auth(registration.password)
|
||||
const healthy = yield* Effect.tryPromise(() =>
|
||||
fetch(new URL("/api/health", registration.url), {
|
||||
headers,
|
||||
signal: AbortSignal.timeout(2_000),
|
||||
}),
|
||||
).pipe(
|
||||
Effect.map((response) => response.ok),
|
||||
Effect.orElseSucceed(() => false),
|
||||
)
|
||||
if (!healthy) return undefined
|
||||
return { registration, transport: { url: registration.url, headers } } satisfies LocalService
|
||||
})
|
||||
|
||||
// Health-checked lookup without the version gate: lifecycle operations must be
|
||||
// able to see (and replace or stop) a server from a different version.
|
||||
const find = Effect.fnUntraced(function* (options: ServiceOptions) {
|
||||
const registration = yield* read(options.file)
|
||||
if (registration === undefined) return undefined
|
||||
return yield* probe(registration)
|
||||
})
|
||||
|
||||
// 50ms cadence bounded at ~5s, shared by stop escalation and start readiness.
|
||||
const poll = Schedule.spaced("50 millis").pipe(Schedule.both(Schedule.recurs(100)))
|
||||
|
||||
const signal = (pid: number, name: NodeJS.Signals) =>
|
||||
Effect.try({ try: () => process.kill(pid, name), catch: (cause) => cause }).pipe(Effect.ignore)
|
||||
|
||||
const stopped = Effect.fnUntraced(function* (pid: number) {
|
||||
const running = yield* Effect.try({ try: () => process.kill(pid, 0), catch: () => false }).pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
)
|
||||
if (!running) return true
|
||||
return yield* Effect.fail(new Error(`Server process ${pid} is still running`))
|
||||
})
|
||||
|
||||
function same(left: Registration, right: Registration) {
|
||||
return left.id === right.id && left.version === right.version && left.url === right.url && left.pid === right.pid
|
||||
}
|
||||
|
||||
const kill = Effect.fnUntraced(function* (info: Registration, options: ServiceOptions) {
|
||||
// A stale registration may point at a PID that has since been reused by
|
||||
// another process. Only signal the PID after authenticating the server.
|
||||
const current = yield* find(options)
|
||||
if (current === undefined || !same(current.registration, info)) return
|
||||
|
||||
yield* signal(info.pid, "SIGTERM")
|
||||
const done = yield* stopped(info.pid).pipe(Effect.retry(poll), Effect.option)
|
||||
if (Option.isSome(done)) return
|
||||
|
||||
const latest = yield* find(options)
|
||||
if (latest === undefined || !same(latest.registration, info)) return
|
||||
yield* signal(info.pid, "SIGKILL")
|
||||
yield* stopped(info.pid).pipe(Effect.retry(poll))
|
||||
})
|
||||
|
||||
export * as Service from "./service.js"
|
||||
|
|
@ -4030,6 +4030,239 @@ export type EventSubscribeOutput =
|
|||
readonly todos: ReadonlyArray<{ readonly content: string; readonly status: string; readonly priority: string }>
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "session.status"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: {
|
||||
readonly sessionID: string
|
||||
readonly status:
|
||||
| { readonly type: "idle" }
|
||||
| {
|
||||
readonly type: "retry"
|
||||
readonly attempt: number
|
||||
readonly message: string
|
||||
readonly action?: {
|
||||
readonly reason: string
|
||||
readonly provider: string
|
||||
readonly title: string
|
||||
readonly message: string
|
||||
readonly label: string
|
||||
readonly link?: string
|
||||
}
|
||||
readonly next: number
|
||||
}
|
||||
| { readonly type: "busy" }
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "session.idle"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: { readonly sessionID: string }
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "tui.prompt.append"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: { readonly text: string }
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "tui.command.execute"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: {
|
||||
readonly command:
|
||||
| "session.list"
|
||||
| "session.new"
|
||||
| "session.share"
|
||||
| "session.interrupt"
|
||||
| "session.background"
|
||||
| "session.compact"
|
||||
| "session.page.up"
|
||||
| "session.page.down"
|
||||
| "session.line.up"
|
||||
| "session.line.down"
|
||||
| "session.half.page.up"
|
||||
| "session.half.page.down"
|
||||
| "session.first"
|
||||
| "session.last"
|
||||
| "prompt.clear"
|
||||
| "prompt.submit"
|
||||
| "agent.cycle"
|
||||
| string
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "tui.toast.show"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: {
|
||||
readonly title?: string
|
||||
readonly message: string
|
||||
readonly variant: "info" | "success" | "warning" | "error"
|
||||
readonly duration?: number | undefined
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "tui.session.select"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: { readonly sessionID: string }
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "installation.updated"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: { readonly version: string }
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "installation.update-available"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: { readonly version: string }
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "vcs.branch.updated"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: { readonly branch?: string }
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "mcp.status.changed"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: { readonly server: string }
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "permission.asked"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: {
|
||||
readonly id: string
|
||||
readonly sessionID: string
|
||||
readonly permission: string
|
||||
readonly patterns: ReadonlyArray<string>
|
||||
readonly metadata: { readonly [x: string]: unknown }
|
||||
readonly always: ReadonlyArray<string>
|
||||
readonly tool?: { readonly messageID: string; readonly callID: string } | undefined
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "permission.replied"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: {
|
||||
readonly sessionID: string
|
||||
readonly requestID: string
|
||||
readonly reply: "once" | "always" | "reject"
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "question.asked"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: {
|
||||
readonly id: string
|
||||
readonly sessionID: string
|
||||
readonly questions: ReadonlyArray<{
|
||||
readonly question: string
|
||||
readonly header: string
|
||||
readonly options: ReadonlyArray<{ readonly label: string; readonly description: string }>
|
||||
readonly multiple?: boolean | undefined
|
||||
readonly custom?: boolean | undefined
|
||||
}>
|
||||
readonly tool?: { readonly messageID: string; readonly callID: string } | undefined
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "question.replied"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: {
|
||||
readonly sessionID: string
|
||||
readonly requestID: string
|
||||
readonly answers: ReadonlyArray<ReadonlyArray<string>>
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "question.rejected"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: { readonly sessionID: string; readonly requestID: string }
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown }
|
||||
readonly type: "session.error"
|
||||
readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number }
|
||||
readonly location?: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly data: {
|
||||
readonly sessionID?: string | undefined
|
||||
readonly error?:
|
||||
| {
|
||||
readonly name: "ProviderAuthError"
|
||||
readonly data: { readonly providerID: string; readonly message: string }
|
||||
}
|
||||
| {
|
||||
readonly name: "UnknownError"
|
||||
readonly data: { readonly message: string; readonly ref?: string | undefined }
|
||||
}
|
||||
| { readonly name: "MessageOutputLengthError"; readonly data: {} }
|
||||
| { readonly name: "MessageAbortedError"; readonly data: { readonly message: string } }
|
||||
| {
|
||||
readonly name: "StructuredOutputError"
|
||||
readonly data: { readonly message: string; readonly retries: number }
|
||||
}
|
||||
| {
|
||||
readonly name: "ContextOverflowError"
|
||||
readonly data: { readonly message: string; readonly responseBody?: string | undefined }
|
||||
}
|
||||
| { readonly name: "ContentFilterError"; readonly data: { readonly message: string } }
|
||||
| {
|
||||
readonly name: "APIError"
|
||||
readonly data: {
|
||||
readonly message: string
|
||||
readonly statusCode?: number | undefined
|
||||
readonly isRetryable: boolean
|
||||
readonly responseHeaders?: { readonly [x: string]: string } | undefined
|
||||
readonly responseBody?: string | undefined
|
||||
readonly metadata?: { readonly [x: string]: string } | undefined
|
||||
}
|
||||
}
|
||||
| undefined
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: string
|
||||
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
export * from "./generated/index"
|
||||
export type { Transport } from "../effect/service.js"
|
||||
export type { EventSubscribeOutput as OpenCodeEvent } from "./generated/types"
|
||||
export type OpenCodeClient = ReturnType<typeof import("./generated/client").make>
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
import { Effect } from "effect"
|
||||
import * as service from "./index.js"
|
||||
|
||||
export type { Transport, Discover, Registration, LocalService, ServiceOptions } from "./index.js"
|
||||
|
||||
export { basicAuth } from "./index.js"
|
||||
|
||||
export const readRegistration = (file?: string) => Effect.promise(() => service.readRegistration(file))
|
||||
export const discover = (options?: service.ServiceOptions) => Effect.promise(() => service.discover(options))
|
||||
export const stop = (options?: service.ServiceOptions) => Effect.promise(() => service.stop(options))
|
||||
export const start = (options?: service.ServiceOptions) =>
|
||||
Effect.tryPromise({
|
||||
try: () => service.start(options),
|
||||
catch: (cause) => new Error("Failed to start server", { cause }),
|
||||
})
|
||||
export const connect = (options?: service.ServiceOptions) =>
|
||||
Effect.tryPromise({
|
||||
try: () => service.connect(options),
|
||||
catch: (cause) => new Error("Failed to connect to server", { cause }),
|
||||
})
|
||||
|
||||
export * as ServiceEffect from "./effect.js"
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { DateTime, Effect, Stream } from "effect"
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http"
|
||||
import { AbsolutePath, Agent, Event, Location, Model, OpenCode, Prompt, Session, SessionMessage } from "../src/effect"
|
||||
import { AbsolutePath, Agent, Event, Location, Model, OpenCode, Prompt, Session, SessionMessage } from "../src/effect/index"
|
||||
|
||||
const synced = { type: "log.synced" as const, aggregateID: "ses_test", seq: Event.Seq.make(1) }
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ const server = resolve(import.meta.dir, "../../server")
|
|||
|
||||
describe("public import boundaries", () => {
|
||||
test("isolates each public entrypoint", async () => {
|
||||
const root = await bundleInputs("@opencode-ai/client", "browser")
|
||||
const root = await bundleInputs("@opencode-ai/client/promise", "browser")
|
||||
|
||||
expect(within(root, effect)).toEqual([])
|
||||
expect(within(root, schema)).toEqual([])
|
||||
|
|
@ -20,7 +20,9 @@ describe("public import boundaries", () => {
|
|||
expect(within(root, core)).toEqual([])
|
||||
expect(within(root, server)).toEqual([])
|
||||
|
||||
const network = await bundleInputs("@opencode-ai/client/effect", "browser")
|
||||
// The effect entry includes local service lifecycle (node spawn/fs), so it
|
||||
// bundles for bun; the boundary assertions below are what matter.
|
||||
const network = await bundleInputs("@opencode-ai/client/effect", "bun")
|
||||
|
||||
expect(within(network, effect).length).toBeGreaterThan(0)
|
||||
expect(within(network, schema).length).toBeGreaterThan(0)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { isSessionNotFoundError, isUnauthorizedError, OpenCode } from "../src"
|
||||
import { isSessionNotFoundError, isUnauthorizedError, OpenCode } from "../src/promise/index"
|
||||
|
||||
test("exposes every standard HTTP API group", () => {
|
||||
const client = OpenCode.make({ baseUrl: "http://localhost:3000" })
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { UI } from "@/cli/ui"
|
|||
import { errorMessage } from "@opencode-ai/tui/util/error"
|
||||
import { validateSession } from "../tui/validate-session"
|
||||
import { ServerAuth } from "@/server/auth"
|
||||
import { OpenCode } from "@opencode-ai/client"
|
||||
import { OpenCode } from "@opencode-ai/client/promise"
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
|
||||
export const AttachCommand = cmd({
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { errorMessage } from "@opencode-ai/tui/util/error"
|
|||
import { withTimeout } from "@/util/timeout"
|
||||
import { withNetworkOptions, resolveNetworkOptionsNoConfig, hasArg } from "@/cli/network"
|
||||
import { Filesystem } from "@/util/filesystem"
|
||||
import { OpenCode } from "@opencode-ai/client"
|
||||
import { OpenCode } from "@opencode-ai/client/promise"
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
import { writeHeapSnapshot } from "v8"
|
||||
import { ServerAuth } from "@/server/auth"
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -77,7 +77,7 @@ import {
|
|||
useOpencodeKeymap,
|
||||
} from "./keymap"
|
||||
|
||||
import type { OpenCodeClient } from "@opencode-ai/client"
|
||||
import type { OpenCodeClient } from "@opencode-ai/client/promise"
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
import { DialogVariant } from "./component/dialog-variant"
|
||||
import { createTuiAttention } from "./attention"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { TextAttributes } from "@opentui/core"
|
||||
import type { IntegrationConnectOauthOutput } from "@opencode-ai/client"
|
||||
import type { IntegrationConnectOauthOutput } from "@opencode-ai/client/promise"
|
||||
import type { ConnectionInfo, IntegrationInfo, IntegrationOAuthMethod } from "@opencode-ai/sdk/v2"
|
||||
import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
|
||||
import { useClipboard } from "../context/clipboard"
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import { useCommandShortcut } from "../keymap"
|
|||
import { useProject } from "../context/project"
|
||||
import { Spinner } from "./spinner"
|
||||
import { DialogWorkspaceFileChanges } from "./dialog-workspace-file-changes"
|
||||
import type { ProjectDirectoriesOutput } from "@opencode-ai/client"
|
||||
import type { ProjectDirectoriesOutput } from "@opencode-ai/client/promise"
|
||||
import { useRoute } from "../context/route"
|
||||
|
||||
export type MoveSessionSelection = { type: "directory"; directory: string; subdirectory: boolean } | { type: "new" }
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { OpenCodeClient } from "@opencode-ai/client"
|
||||
import type { OpenCodeClient } from "@opencode-ai/client/promise"
|
||||
import type { OpencodeClient, V2Event } from "@opencode-ai/sdk/v2"
|
||||
import { createGlobalEmitter } from "@solid-primitives/event-bus"
|
||||
import { onCleanup, onMount } from "solid-js"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
/** @jsxImportSource @opentui/solid */
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { OpenCodeClient } from "@opencode-ai/client"
|
||||
import type { OpenCodeClient } from "@opencode-ai/client/promise"
|
||||
import { testRender } from "@opentui/solid"
|
||||
import type { OpencodeClient, V2Event } from "@opencode-ai/sdk/v2"
|
||||
import { onMount } from "solid-js"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { OpenCode } from "@opencode-ai/client"
|
||||
import { OpenCode } from "@opencode-ai/client/promise"
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
import type { V2Event } from "@opencode-ai/sdk/v2"
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue