Repository navigation
refactor(opencode): add pty control HttpApi coverage #1384
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
71 changes: 71 additions & 0 deletions
71
packages/opencode/src/server/routes/instance/httpapi/groups/control.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import { Auth } from "@/auth" | ||
| import { ProviderID } from "@/provider/schema" | ||
| import { Schema } from "effect" | ||
| import { HttpApi, HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" | ||
| import { BadRequestError, WorkspaceRoutingQuery } from "./common" | ||
|
|
||
| const AuthParam = Schema.Struct({ | ||
| providerID: ProviderID, | ||
| }) | ||
|
|
||
| const LogPayload = Schema.Struct({ | ||
| service: Schema.String, | ||
| level: Schema.Literals(["debug", "info", "error", "warn"]), | ||
| message: Schema.String, | ||
| extra: Schema.optional(Schema.Record(Schema.String, Schema.Any)), | ||
| }) | ||
|
|
||
| export const ControlApi = HttpApi.make("control") | ||
| .add( | ||
| HttpApiGroup.make("control") | ||
| .add( | ||
| HttpApiEndpoint.put("authSet", "/auth/:providerID", { | ||
| params: AuthParam, | ||
| payload: Auth.Info, | ||
| success: Schema.Boolean, | ||
| error: BadRequestError, | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "auth.set", | ||
| summary: "Set auth credentials", | ||
| description: "Set authentication credentials", | ||
| }), | ||
| ), | ||
| HttpApiEndpoint.delete("authRemove", "/auth/:providerID", { | ||
| params: AuthParam, | ||
| success: Schema.Boolean, | ||
| error: BadRequestError, | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "auth.remove", | ||
| summary: "Remove auth credentials", | ||
| description: "Remove authentication credentials", | ||
| }), | ||
| ), | ||
| HttpApiEndpoint.post("log", "/log", { | ||
| query: WorkspaceRoutingQuery, | ||
| payload: LogPayload, | ||
| success: Schema.Boolean, | ||
| error: BadRequestError, | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "app.log", | ||
| summary: "Write log", | ||
| description: "Write a log entry to the server logs with specified level and metadata.", | ||
| }), | ||
| ), | ||
| ) | ||
| .annotateMerge( | ||
| OpenApi.annotations({ | ||
| title: "control", | ||
| description: "HttpApi control-plane JSON routes.", | ||
| }), | ||
| ), | ||
| ) | ||
| .annotateMerge( | ||
| OpenApi.annotations({ | ||
| title: "opencode control HttpApi", | ||
| version: "0.0.1", | ||
| description: "HttpApi surface for control-plane JSON routes.", | ||
| }), | ||
| ) |
128 changes: 128 additions & 0 deletions
128
packages/opencode/src/server/routes/instance/httpapi/groups/pty.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import { PtyID } from "@/pty/schema" | ||
| import { Schema } from "effect" | ||
| import { HttpApi, HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" | ||
| import { BadRequestError, NotFoundError } from "./common" | ||
|
|
||
| const root = "/pty" | ||
|
|
||
| const PtyParam = Schema.Struct({ | ||
| ptyID: PtyID, | ||
| }) | ||
|
|
||
| const PtyInfo = Schema.Struct({ | ||
| id: PtyID, | ||
| title: Schema.String, | ||
| command: Schema.String, | ||
| args: Schema.Array(Schema.String), | ||
| cwd: Schema.String, | ||
| status: Schema.Literals(["running", "exited"]), | ||
| pid: Schema.Number, | ||
| }) | ||
|
|
||
| const PtyCreateInput = Schema.Struct({ | ||
| command: Schema.optional(Schema.String), | ||
| args: Schema.optional(Schema.Array(Schema.String)), | ||
| cwd: Schema.optional(Schema.String), | ||
| title: Schema.optional(Schema.String), | ||
| env: Schema.optional(Schema.Record(Schema.String, Schema.String)), | ||
| }) | ||
|
|
||
| const PtyUpdateInput = Schema.Struct({ | ||
| title: Schema.optional(Schema.String), | ||
| size: Schema.optional( | ||
| Schema.Struct({ | ||
| rows: Schema.Number, | ||
| cols: Schema.Number, | ||
| }), | ||
| ), | ||
| }) | ||
|
|
||
| const ConnectToken = Schema.Struct({ | ||
| ticket: Schema.String, | ||
| expires_in: Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), | ||
| }) | ||
|
|
||
| export const PtyApi = HttpApi.make("pty") | ||
| .add( | ||
| HttpApiGroup.make("pty") | ||
| .add( | ||
| HttpApiEndpoint.get("list", root, { | ||
| success: Schema.Array(PtyInfo), | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "pty.list", | ||
| summary: "List PTY sessions", | ||
| description: "Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode.", | ||
| }), | ||
| ), | ||
| HttpApiEndpoint.post("create", root, { | ||
| payload: PtyCreateInput, | ||
| success: PtyInfo, | ||
| error: BadRequestError, | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "pty.create", | ||
| summary: "Create PTY session", | ||
| description: "Create a new pseudo-terminal (PTY) session for running shell commands and processes.", | ||
| }), | ||
| ), | ||
| HttpApiEndpoint.get("get", `${root}/:ptyID`, { | ||
| params: PtyParam, | ||
| success: PtyInfo, | ||
| error: NotFoundError, | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "pty.get", | ||
| summary: "Get PTY session", | ||
| description: "Retrieve detailed information about a specific pseudo-terminal (PTY) session.", | ||
| }), | ||
| ), | ||
| HttpApiEndpoint.put("update", `${root}/:ptyID`, { | ||
| params: PtyParam, | ||
| payload: PtyUpdateInput, | ||
| success: PtyInfo, | ||
| error: [BadRequestError, NotFoundError], | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "pty.update", | ||
| summary: "Update PTY session", | ||
| description: "Update properties of an existing pseudo-terminal (PTY) session.", | ||
| }), | ||
| ), | ||
| HttpApiEndpoint.delete("remove", `${root}/:ptyID`, { | ||
| params: PtyParam, | ||
| success: Schema.Boolean, | ||
| error: NotFoundError, | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "pty.remove", | ||
| summary: "Remove PTY session", | ||
| description: "Remove and terminate a specific pseudo-terminal (PTY) session.", | ||
| }), | ||
| ), | ||
| HttpApiEndpoint.post("connectToken", `${root}/:ptyID/connect-token`, { | ||
| params: PtyParam, | ||
| success: ConnectToken, | ||
| error: NotFoundError, | ||
| }).annotateMerge( | ||
| OpenApi.annotations({ | ||
| identifier: "pty.connectToken", | ||
| summary: "Create PTY WebSocket token", | ||
| description: "Create a short-lived ticket for opening a PTY WebSocket connection.", | ||
| }), | ||
| ), | ||
| ) | ||
| .annotateMerge( | ||
| OpenApi.annotations({ | ||
| title: "pty", | ||
| description: "HttpApi PTY JSON and connect-token routes.", | ||
| }), | ||
| ), | ||
| ) | ||
| .annotateMerge( | ||
| OpenApi.annotations({ | ||
| title: "opencode pty HttpApi", | ||
| version: "0.0.1", | ||
| description: "HttpApi surface for PTY JSON and connect-token routes.", | ||
| }), | ||
| ) | ||
123 changes: 123 additions & 0 deletions
123
packages/opencode/src/server/routes/instance/httpapi/handlers/control.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import { Auth } from "@/auth" | ||
| import { ProviderID } from "@/provider/schema" | ||
| import { Log } from "@opencode-ai/core/util/log" | ||
| import { NamedError } from "@opencode-ai/util/error" | ||
| import { Effect } from "effect" | ||
| import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http" | ||
| import { HttpApiBuilder } from "effect/unstable/httpapi" | ||
| import z from "zod" | ||
| import { ControlApi } from "../groups/control" | ||
|
|
||
| const LogPayload = z.object({ | ||
| service: z.string(), | ||
| level: z.enum(["debug", "info", "error", "warn"]), | ||
| message: z.string(), | ||
| extra: z.record(z.string(), z.any()).optional(), | ||
| }) | ||
|
|
||
| type LogPayload = z.infer<typeof LogPayload> | ||
|
|
||
| function isJsonContentType(contentType: string | undefined) { | ||
| // Mirrors hono/validator's jsonRegex, reached through hono-openapi's validator("json"). | ||
| return /^application\/([a-z-.]+\+)?json(?:;\s*[a-zA-Z0-9-]+=([^;]+))*$/.test(contentType ?? "") | ||
| } | ||
|
|
||
| function badRequestJson(body: unknown) { | ||
| return HttpServerResponse.jsonUnsafe(body, { status: 400 }) | ||
| } | ||
|
|
||
| function parseJsonBody<T>(request: HttpServerRequest.HttpServerRequest, schema: z.ZodType<T>) { | ||
| return Effect.gen(function* () { | ||
| const body = isJsonContentType(request.headers["content-type"]) | ||
| ? yield* request.json.pipe( | ||
| Effect.catch(() => Effect.succeed(HttpServerResponse.raw("Malformed JSON in request body", { status: 400 }))), | ||
| ) | ||
| : {} | ||
| if (HttpServerResponse.isHttpServerResponse(body)) return body | ||
|
|
||
| const parsed = schema.safeParse(body) | ||
| if (!parsed.success) return badRequestJson({ data: body, error: parsed.error.issues, success: false }) | ||
| return parsed.data | ||
| }) | ||
| } | ||
|
|
||
| function controlFailure(error: unknown) { | ||
| if (error instanceof NamedError) return Effect.succeed(HttpServerResponse.jsonUnsafe(error.toObject(), { status: 500 })) | ||
| return Effect.succeed( | ||
| HttpServerResponse.jsonUnsafe( | ||
| new NamedError.Unknown({ message: "Unexpected server error. Check server logs for details." }).toObject(), | ||
| { status: 500 }, | ||
| ), | ||
| ) | ||
| } | ||
|
|
||
| function writeLog(payload: LogPayload) { | ||
| const logger = Log.create({ service: payload.service }) | ||
|
|
||
| switch (payload.level) { | ||
| case "debug": | ||
| logger.debug(payload.message, payload.extra) | ||
| break | ||
| case "info": | ||
| logger.info(payload.message, payload.extra) | ||
| break | ||
| case "error": | ||
| logger.error(payload.message, payload.extra) | ||
| break | ||
| case "warn": | ||
| logger.warn(payload.message, payload.extra) | ||
| break | ||
| } | ||
| } | ||
|
|
||
| export const controlHandlers = HttpApiBuilder.group(ControlApi, "control", (handlers) => | ||
| Effect.gen(function* () { | ||
| const auth = yield* Auth.Service | ||
|
|
||
| const authSet = Effect.fn("ControlHttpApi.authSet")(function* (providerID: ProviderID, info: Auth.Info) { | ||
| yield* auth.set(providerID, info) | ||
| return true | ||
| }) | ||
|
|
||
| const authRemove = Effect.fn("ControlHttpApi.authRemove")(function* (providerID: ProviderID) { | ||
| yield* auth.remove(providerID) | ||
| return true | ||
| }) | ||
|
|
||
| const log = Effect.fn("ControlHttpApi.log")(function* (payload: LogPayload) { | ||
| yield* Effect.sync(() => writeLog(payload)) | ||
| return true | ||
| }) | ||
|
|
||
| return handlers | ||
| .handleRaw("authSet", (ctx) => | ||
| Effect.gen(function* () { | ||
| const payload = yield* parseJsonBody(ctx.request, Auth.Info.zod) | ||
| if (HttpServerResponse.isHttpServerResponse(payload)) return payload | ||
| return yield* authSet(ctx.params.providerID, payload).pipe( | ||
| Effect.map((result) => HttpServerResponse.jsonUnsafe(result)), | ||
| Effect.catch(controlFailure), | ||
| Effect.catchDefect(controlFailure), | ||
| ) | ||
| }), | ||
| ) | ||
| .handleRaw("authRemove", (ctx) => | ||
| authRemove(ctx.params.providerID).pipe( | ||
| Effect.map((result) => HttpServerResponse.jsonUnsafe(result)), | ||
| Effect.catch(controlFailure), | ||
| Effect.catchDefect(controlFailure), | ||
| ), | ||
| ) | ||
| .handleRaw("log", (ctx) => | ||
| Effect.gen(function* () { | ||
| const payload = yield* parseJsonBody(ctx.request, LogPayload) | ||
| if (HttpServerResponse.isHttpServerResponse(payload)) return payload | ||
| return yield* log(payload).pipe( | ||
| Effect.map((result) => HttpServerResponse.jsonUnsafe(result)), | ||
| Effect.catch(controlFailure), | ||
| Effect.catchDefect(controlFailure), | ||
| ) | ||
| }), | ||
| ) | ||
| }), | ||
| ) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.