Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/opencode/script/route-inventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export type HonoRouteSourceCoverage = {
type BuildOptions = {
root?: string
upstreamRef?: string
upstreamHttpApiRoutes?: Route[]
requireUpstream?: boolean
}

Expand Down Expand Up @@ -149,6 +150,10 @@ const explicitlyDeferred = [
/^GET \/api\/provider\/:providerID$/,
/^\/tui\//,
/^\/sync\//,
/^GET \/formatter$/,
/^POST \/experimental\/control-plane\/move-session$/,
/^POST \/experimental\/project\/:projectID\/copy\/generate-name$/,
/^POST \/experimental\/session\/:sessionID\/background$/,
/^\/experimental\/workspace\/(?:adapter|sync-list|warp)$/,
]

Expand Down Expand Up @@ -459,6 +464,7 @@ function classify(input: {
if (input.hono && input.openapi && input.v2Sdk) return input.legacySdk ? "all-public-surfaces" : "openapi-v2-sdk"
if (input.hono && input.v2Sdk && !input.openapi) return "hono-v2-sdk"
if (input.hono && !input.openapi) return "hono-only"
if (!input.hono && input.localHttpApi && input.upstreamHttpApi) return "local-httpapi-upstream-only"
if (!input.hono && input.upstreamHttpApi) return "onlyHttpApi"
if (input.openapi && !input.hono) return "openapi-only"
if (input.legacySdk || input.v2Sdk) return "sdk-only"
Expand All @@ -479,7 +485,9 @@ export async function buildRouteInventory(options: BuildOptions = {}): Promise<R
readSdkRoutes(root, "packages/sdk/js/src/gen/sdk.gen.ts"),
readSdkRoutes(root, "packages/sdk/js/src/v2/gen/sdk.gen.ts"),
readLocalHttpApiRoutes(root),
readUpstreamHttpApiRoutes(root, upstreamRef, requireUpstream),
options.upstreamHttpApiRoutes
? Promise.resolve(uniqueRoutes(options.upstreamHttpApiRoutes))
: readUpstreamHttpApiRoutes(root, upstreamRef, requireUpstream),
])

const sets = {
Expand Down
2 changes: 1 addition & 1 deletion packages/opencode/src/cli/cmd/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const GenerateCommand = {
{
lang: "js",
source: [
`import { createOpencodeClient } from "@opencode-ai/sdk`,
`import { createOpencodeClient } from "@opencode-ai/sdk"`,
``,
`const client = createOpencodeClient()`,
`await client.${operation.operationId}({`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ const ConsoleOrgList = Schema.Struct({
orgs: Schema.Array(ConsoleOrgOption),
})

const CapabilitiesResponse = Schema.Struct({
backgroundSubagents: Schema.Boolean,
})

const ConsoleSwitchPayload = Schema.Struct({
accountID: Schema.String,
orgID: Schema.String,
Expand Down Expand Up @@ -70,6 +74,7 @@ const WorktreeDirectoryPayload = Schema.Struct({
})

export const ExperimentalPaths = {
capabilities: `${root}/capabilities`,
console: `${root}/console`,
consoleOrgs: `${root}/console/orgs`,
consoleSwitch: `${root}/console/switch`,
Expand All @@ -85,6 +90,15 @@ export const ExperimentalApi = HttpApi.make("experimental")
.add(
HttpApiGroup.make("experimental")
.add(
HttpApiEndpoint.get("capabilities", ExperimentalPaths.capabilities, {
success: CapabilitiesResponse,
}).annotateMerge(
OpenApi.annotations({
identifier: "experimental.capabilities.get",
summary: "Get experimental capabilities",
description: "Get experimental features enabled on the local OpenCode server.",
}),
),
HttpApiEndpoint.get("console", ExperimentalPaths.console, {
success: ConsoleState,
}).annotateMerge(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ const ProjectUpdatePayload = Schema.Struct({
commands: Schema.optionalKey(ProjectCommands),
})

const ProjectDirectory = Schema.Struct({
directory: Schema.String,
strategy: Schema.optionalKey(Schema.String),
})

export const ProjectApi = HttpApi.make("project")
.add(
HttpApiGroup.make("project")
Expand Down Expand Up @@ -84,6 +89,17 @@ export const ProjectApi = HttpApi.make("project")
description: "Update project properties such as name, icon, and commands.",
}),
),
HttpApiEndpoint.get("directories", "/project/:projectID/directories", {
params: ProjectIDParam,
query: WorkspaceRoutingQuery,
success: Schema.Array(ProjectDirectory),
}).annotateMerge(
OpenApi.annotations({
identifier: "project.directories",
summary: "List project directories",
description: "List known local absolute directories for a project.",
}),
),
)
.annotateMerge(
OpenApi.annotations({
Expand Down
15 changes: 15 additions & 0 deletions packages/opencode/src/server/routes/instance/httpapi/groups/pty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,25 @@ const ConnectToken = Schema.Struct({
expires_in: Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)),
})

const ShellItem = Schema.Struct({
path: Schema.String,
name: Schema.String,
acceptable: Schema.Boolean,
})

export const PtyApi = HttpApi.make("pty")
.add(
HttpApiGroup.make("pty")
.add(
HttpApiEndpoint.get("shells", `${root}/shells`, {
success: Schema.Array(ShellItem),
}).annotateMerge(
OpenApi.annotations({
identifier: "pty.shells",
summary: "List available shells",
description: "Get a list of available shells on the system.",
}),
),
HttpApiEndpoint.get("list", root, {
success: Schema.Array(PtyInfo),
}).annotateMerge(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ function jsonResponse<A>(effect: Effect.Effect<A, unknown, unknown>) {

export const experimentalHandlers = HttpApiBuilder.group(ExperimentalApi, "experimental", (handlers) =>
handlers
.handleRaw("capabilities", () => jsonResponse(Effect.succeed({ backgroundSubagents: false })))
.handleRaw("console", () => jsonResponse(getConsoleState()))
.handleRaw("consoleOrgs", () => jsonResponse(listConsoleOrgs()))
.handleRaw("consoleSwitch", (ctx) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,20 @@ export const projectHandlers = HttpApiBuilder.group(ProjectApi, "project", (hand
if (HttpServerResponse.isHttpServerResponse(project)) return project
return HttpServerResponse.jsonUnsafe(project)
}),
)
.handleRaw("directories", (ctx) =>
Effect.gen(function* () {
const projectInfo = yield* Project.Service.use((svc) => svc.get(ProjectID.make(ctx.params.projectID)))
if (!projectInfo)
return yield* projectFailure(new NotFoundError({ message: `Project not found: ${ctx.params.projectID}` }))
const directories = yield* Project.Service.use((svc) => svc.sandboxes(projectInfo.id))
const result = [projectInfo.worktree, ...directories]
.filter((directory) => directory !== "/")
.map((directory) => ({ directory }))
return HttpServerResponse.jsonUnsafe(result)
}).pipe(
Effect.catch(projectFailure),
Effect.catchDefect(projectFailure),
),
),
)
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Pty } from "@/pty"
import { PtyID } from "@/pty/schema"
import { PtyTicket } from "@/pty/ticket"
import { Shell } from "@/shell/shell"
import { NotFoundError } from "@/storage/db"
import { NamedError } from "@opencode-ai/util/error"
import { Effect } from "effect"
Expand Down Expand Up @@ -93,7 +94,18 @@ export const ptyHandlers = HttpApiBuilder.group(PtyApi, "pty", (handlers) =>
return PtyTicket.issue({ ptyID: id })
})

const shells = Effect.fn("PtyHttpApi.shells")(function* () {
return yield* Effect.promise(() => Shell.list())
})

return handlers
.handleRaw("shells", () =>
shells().pipe(
Effect.map((items) => HttpServerResponse.jsonUnsafe(items)),
Effect.catch(ptyFailure),
Effect.catchDefect(ptyFailure),
),
)
.handleRaw("list", () =>
list().pipe(
Effect.map((sessions) => HttpServerResponse.jsonUnsafe(sessions)),
Expand Down
50 changes: 50 additions & 0 deletions packages/opencode/src/shell/shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ export namespace Shell {
const BLACKLIST = new Set(["fish", "nu"])
const LOGIN = new Set(["bash", "dash", "fish", "ksh", "sh", "zsh"])
const POSIX = new Set(["bash", "dash", "ksh", "sh", "zsh"])
export type Item = {
path: string
name: string
acceptable: boolean
}

export async function killTree(proc: ChildProcess, opts?: { exited?: () => boolean }): Promise<void> {
const pid = proc.pid
Expand Down Expand Up @@ -61,6 +66,46 @@ export namespace Shell {
if (powershell) return powershell
}

function resolved(file: string) {
const shell = full(file)
const rooted = process.platform === "win32" ? path.win32.isAbsolute(shell) : path.isAbsolute(shell)
if (rooted) {
if (Filesystem.stat(shell)?.isFile()) return shell
return
}
return which(shell) || undefined
}

function item(file: string): Item | undefined {
const shell = resolved(file)
if (!shell) return
return {
path: shell,
name: which(name(shell)) ? name(shell) : shell,
acceptable: !BLACKLIST.has(name(shell)),
}
}

function win() {
return Array.from(
new Set([which("pwsh"), which("powershell"), gitbash(), process.env.COMSPEC || "cmd.exe"].filter((x): x is string => !!x)),
)
}

async function unix() {
const text = await Filesystem.readText("/etc/shells").catch(() => "")
if (!text) return ["/bin/bash", "/bin/zsh", "/bin/sh"]
const shells = Array.from(
new Set(
text
.split("\n")
.map((line) => line.trim())
.filter((line) => line && !line.startsWith("#")),
),
)
return shells.length ? shells : ["/bin/bash", "/bin/zsh", "/bin/sh"]
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function select(file: string | undefined, opts?: { acceptable?: boolean }) {
if (file && (!opts?.acceptable || !BLACKLIST.has(name(file)))) return full(file)
if (process.platform === "win32") {
Expand Down Expand Up @@ -107,4 +152,9 @@ export namespace Shell {
export const preferred = lazy(() => select(process.env.SHELL))

export const acceptable = lazy(() => select(process.env.SHELL, { acceptable: true }))

export async function list(): Promise<Item[]> {
const shells = process.platform === "win32" ? win() : await unix()
return shells.map(item).filter((x): x is Item => x !== undefined)
}
}
5 changes: 5 additions & 0 deletions packages/opencode/test/server/experimental-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ describe("experimental routes", () => {
const spec = OpenApi.fromApi(ExperimentalApi) as any

for (const [routePath, method] of [
["/experimental/capabilities", "get"],
["/experimental/console", "get"],
["/experimental/console/orgs", "get"],
["/experimental/console/switch", "post"],
Expand Down Expand Up @@ -83,6 +84,10 @@ describe("experimental routes", () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const capabilities = await requestExperimentalHttpApi("/experimental/capabilities")
expect(capabilities.status).toBe(200)
expect(await capabilities.json()).toEqual({ backgroundSubagents: false })

const consoleState = await requestExperimentalHttpApi("/experimental/console")
expect(consoleState.status).toBe(200)
expect(await consoleState.json()).toMatchObject({
Expand Down
22 changes: 22 additions & 0 deletions packages/opencode/test/server/openapi-generation-source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@ function jsonResponseSchema(spec: Awaited<ReturnType<typeof controlOpenApi>>, ro
return operation?.responses?.["200"]?.content?.["application/json"]?.schema
}

function codeSampleSources(spec: any) {
const sources: string[] = []
for (const item of Object.values(spec.paths ?? {}) as any[]) {
for (const method of ["get", "post", "put", "delete", "patch"] as const) {
const samples = item[method]?.["x-codeSamples"] ?? []
for (const sample of samples) if (typeof sample.source === "string") sources.push(sample.source)
}
}
return sources
}

function generateAfterIsolatedEventLeak() {
const script = `
import z from "zod"
Expand Down Expand Up @@ -249,4 +260,15 @@ describe("OpenAPI generation source", () => {
expect([...productionPaths].filter((routePath) => !checkedInPaths.has(routePath)).sort()).toEqual([])
expect([...checkedInPaths].filter((routePath) => !productionPaths.has(routePath)).sort()).toEqual([])
})

test("keeps checked-in OpenAPI JavaScript code samples valid", async () => {
const checkedIn = JSON.parse(await readFile(path.join(import.meta.dir, "../../../sdk/openapi.json"), "utf8"))
const samples = codeSampleSources(checkedIn)

expect(samples.length).toBeGreaterThan(0)
for (const source of samples) {
expect(source).toContain('import { createOpencodeClient } from "@opencode-ai/sdk"')
expect(source).not.toContain('import { createOpencodeClient } from "@opencode-ai/sdk\n')
}
})
})
8 changes: 7 additions & 1 deletion packages/opencode/test/server/project-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ describe("project routes", () => {
expect(spec.paths["/project/current"]).toHaveProperty("get")
expect(spec.paths["/project/git/init"]).toHaveProperty("post")
expect(spec.paths["/project/{projectID}"]).toHaveProperty("patch")
expect(spec.paths["/project/{projectID}/directories"]).toHaveProperty("get")
expect(spec.paths["/project/{projectID}"]?.patch?.responses?.["404"]).toMatchObject({
description: "Not found",
content: { "application/json": { schema: { $ref: "#/components/schemas/NotFoundError" } } },
Expand Down Expand Up @@ -85,7 +86,12 @@ describe("project routes", () => {

const current = await requestProjectHttpApi("/project/current")
expect(current.status).toBe(200)
expect(await current.json()).toMatchObject({ vcs: "git", worktree: tmp.path })
const currentBody = await current.json()
expect(currentBody).toMatchObject({ vcs: "git", worktree: tmp.path })

const directories = await requestProjectHttpApi(`/project/${currentBody.id}/directories`)
expect(directories.status).toBe(200)
expect(await directories.json()).toEqual([{ directory: tmp.path }])

const missing = await requestProjectHttpApi("/project/nonexistent-project-id", {
method: "PATCH",
Expand Down
21 changes: 21 additions & 0 deletions packages/opencode/test/server/pty-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,12 @@ describe("pty routes", () => {
test("declares the PTY JSON route group as HttpApi endpoints", () => {
const spec = OpenApi.fromApi(PtyApi) as any

expect(spec.paths).toHaveProperty("/pty/shells")
expect(spec.paths).toHaveProperty("/pty")
expect(spec.paths).toHaveProperty("/pty/{ptyID}")
expect(spec.paths).toHaveProperty("/pty/{ptyID}/connect-token")
expect(spec.paths).not.toHaveProperty("/pty/{ptyID}/connect")
expect(spec.paths["/pty/shells"]).toHaveProperty("get")
expect(spec.paths["/pty"]).toHaveProperty("get")
expect(spec.paths["/pty"]).toHaveProperty("post")
expect(spec.paths["/pty/{ptyID}"]).toHaveProperty("get")
Expand Down Expand Up @@ -124,6 +126,25 @@ describe("pty routes", () => {
})
})

test("serves available shells through the HttpApi handlers", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () => {
const response = await requestPtyHttpApi("/pty/shells")
expect(response.status).toBe(200)
const body = await response.json()
expect(body).toBeArray()
expect(body.length).toBeGreaterThan(0)
expect(body[0]).toMatchObject({
path: expect.any(String),
name: expect.any(String),
acceptable: expect.any(Boolean),
})
},
})
})

test("maps missing PTY HttpApi targets as not found", async () => {
await using tmp = await tmpdir({ git: true })
await Instance.provide({
Expand Down
Loading