Compare commits

...
37 changed files with 859 additions and 265 deletions

No files matched your search

@@ -33,7 +33,7 @@ const Options = Schema.Struct({
store: lenient(Schema.Boolean),
thinkingLevel: lenient(ThinkingLevel),
thinkingSummaries: lenient(knownString<"auto" | "none">()),
serviceTier: lenient(knownString<"standard" | "flex" | "priority">()),
serviceTier: lenient(knownString<"standard" | "flex" | "priority" | "deferred">()),
})
export type OptionsInput = typeof Options.Encoded
export type ProviderOptionsInput = OptionsInput
@@ -9,7 +9,8 @@ export type OpenAITextVerbosity = OpenResponsesOptions.TextVerbosity
// in lockstep with `openai-node/src/resources/responses/responses.ts`.
export const OpenAIResponseIncludables = OpenResponsesOptions.ResponseIncludables
export type OpenAIResponseIncludable = OpenResponsesOptions.ResponseIncludable
export const OpenAIServiceTiers = [...OpenResponsesOptions.ServiceTiers, "scale"] as const
// Mirrors OpenAI's `ServiceTier` union from the official SDK.
export const OpenAIServiceTiers = [...OpenResponsesOptions.ServiceTiers, "scale", "fast", "ultrafast"] as const
export type OpenAIServiceTier = (typeof OpenAIServiceTiers)[number] | (string & {})
export const OpenAIReasoningEffort = OpenResponsesOptions.ReasoningEffort
@@ -9,6 +9,7 @@ LLM.request({ model: selected, prompt: "Hello", providerOptions: { reasoningEffo
LLM.request({ model: selected, prompt: "Hello", providerOptions: { textVerbosity: "low" } })
LLM.request({ model: selected, prompt: "Hello", providerOptions: { textVerbosity: "verbose" } })
LLM.request({ model: selected, prompt: "Hello", providerOptions: { serviceTier: "scale" } })
LLM.request({ model: selected, prompt: "Hello", providerOptions: { serviceTier: "ultrafast" } })
LLM.request({ model: selected, prompt: "Hello", providerOptions: { serviceTier: "future-tier" } })
LLM.request({ model: chat, prompt: "Hello", providerOptions: { reasoningEffort: "max" } })
LLM.request({ model: chat, prompt: "Hello", providerOptions: { reasoningEffort: "experimental" } })
@@ -325,11 +325,13 @@ describe("OpenAI Responses route", () => {
}),
)
it.effect("passes through provider-defined service tiers", () =>
it.effect("passes through provider-defined and future service tiers", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(LLMRequest.update(request, { providerOptions: { serviceTier: "scale" } }))
for (const serviceTier of ["scale", "ultrafast", "future-tier"]) {
const prepared = yield* compileRequest(LLMRequest.update(request, { providerOptions: { serviceTier } }))
expect(prepared.body.service_tier).toBe("scale")
expect(prepared.body.service_tier).toBe(serviceTier)
}
}),
)
+3 -3
View File
@@ -143,7 +143,7 @@ test("open file tab browses, searches, and tracks missing files", async ({ page
const panel = page.locator("#review-panel")
const sidebar = panel.locator('[data-slot="session-review-v2-sidebar"]')
const sidebarToggle = panel.getByRole("button", { name: "Toggle file tree" })
const contextButton = page.getByRole("button", { name: "View context usage" })
const contextButton = page.getByRole("button", { name: "Toggle session context" })
const openFile = panel.getByRole("button", { name: "Open file" })
const tab = (name: string) => panel.getByRole("tab", { name, exact: true })
await contextButton.click()
@@ -309,7 +309,7 @@ test("context closes the side region only when its button opened it", async ({ p
})
const panel = page.locator("#review-panel")
const toggle = page.getByRole("button", { name: "Toggle review", exact: true })
const contextButton = page.getByRole("button", { name: "View context usage" })
const contextButton = page.getByRole("button", { name: "Toggle session context" })
const context = panel.getByRole("tab", { name: "Context", exact: true })
await contextButton.click()
@@ -630,7 +630,7 @@ test("restores review state and the side-panel tab per session", async ({ page }
await page.getByRole("option", { name: "Branch changes" }).click()
await page.getByRole("button", { name: "beta.ts" }).click()
await selectedFile("beta.ts")
await page.getByRole("button", { name: "View context usage" }).click()
await page.getByRole("button", { name: "Toggle session context" }).click()
await selectedTab("Context")
await switchSession("Gamma review state")
@@ -7,14 +7,23 @@ import type {
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { useServerSDK } from "@/runtime/server/client"
import { formatServerError } from "@/runtime/server/errors"
import { useData } from "@/runtime/server/current"
import { createEffect, createMemo, on, onCleanup } from "solid-js"
import { createStore, produce } from "solid-js/store"
export type ProviderConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }>
export type ProviderConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" | "external" }>
type Authorization = IntegrationOauthConnectOutput["data"]
type Polling = {
generation: number
timer?: ReturnType<typeof setTimeout>
disposed: boolean
// An attempt the server still considers open; cancelled when the dialog goes away.
attempt?: Authorization
}
// OpenCode Go and OpenCode Zen both bill through the OpenCode Console, so the
// Console sign-in is the connection method for both providers.
export const CONSOLE_INTEGRATION = "opencode"
@@ -35,7 +44,7 @@ export function providerFormDefaults(fields: ProviderConnectMethod["form"]) {
if (actual === undefined) return false
const equal = Array.isArray(actual)
? typeof condition.value === "string" && actual.includes(condition.value)
? actual.some((item) => item === condition.value)
: actual === condition.value
return condition.op === "eq" ? equal : !equal
@@ -43,7 +52,7 @@ export function providerFormDefaults(fields: ProviderConnectMethod["form"]) {
if (!active) return answer
return { ...answer, [field.key]: field.default }
return Object.assign(answer, { [field.key]: field.default })
}, {})
}
@@ -74,9 +83,8 @@ export function createProviderConnectionController(options: {
// Not createResource: the dialog is owned by whichever page opened it, so reading a pending
// resource here would suspend that page's <Suspense> and blank the screen behind the dialog.
const [integration, setIntegration] = createStore({
const [integration, setIntegration] = createStore<{ loading: boolean; latest?: IntegrationInfo }>({
loading: true,
latest: undefined as IntegrationInfo | undefined,
})
createEffect(
@@ -100,7 +108,8 @@ export function createProviderConnectionController(options: {
const methods = createMemo<ProviderConnectMethod[]>(() => {
const values = integration.latest?.methods.filter(
(method): method is ProviderConnectMethod => method.type === "key" || method.type === "oauth",
(method): method is ProviderConnectMethod =>
method.type === "key" || method.type === "oauth" || method.type === "external",
)
if (values?.length) return [...values]
@@ -108,14 +117,19 @@ export function createProviderConnectionController(options: {
return [{ type: "key", label: language.t("provider.connect.method.apiKey") }]
})
const [store, setStore] = createStore({
methodIndex: undefined as number | undefined,
authorization: undefined as Authorization | undefined,
formAnswer: undefined as FormAnswer | undefined,
const [store, setStore] = createStore<{
methodIndex?: number
authorization?: Authorization
formAnswer?: FormAnswer
// Nothing is in flight until a method is selected; `busy()` reads this, so a truthy initial
// value would keep multi-method providers on the spinner instead of the method list.
state: undefined as "pending" | "waiting" | "refreshing" | "ready" | "error" | "form" | undefined,
error: undefined as string | undefined,
state?: "pending" | "waiting" | "refreshing" | "ready" | "error" | "form"
error?: string
auto: boolean
connected: boolean
browserFailed: boolean
statusFailed: boolean
}>({
auto: false,
// The credential is stored; a retry only needs to reload the catalogs.
connected: false,
@@ -124,12 +138,9 @@ export function createProviderConnectionController(options: {
statusFailed: false,
})
const polling = {
const polling: Polling = {
generation: 0,
timer: undefined as ReturnType<typeof setTimeout> | undefined,
disposed: false,
// An attempt the server still considers open; cancelled when the dialog goes away.
attempt: undefined as Authorization | undefined,
}
const currentMethod = createMemo(() =>
@@ -206,8 +217,6 @@ export function createProviderConnectionController(options: {
)
}
const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error))
const cancelAttempt = () => {
const attempt = polling.attempt
polling.attempt = undefined
@@ -276,7 +285,9 @@ export function createProviderConnectionController(options: {
setStore("statusFailed", true)
dispatch({
type: "auth.error",
error: isConsole() ? language.t("provider.connect.console.statusFailed") : errorMessage(result.error),
error: isConsole()
? language.t("provider.connect.console.statusFailed")
: formatServerError(result.error, language.t),
})
return
@@ -358,8 +369,6 @@ export function createProviderConnectionController(options: {
return
}
if (selected.type !== "oauth") return
if (selected.form?.some((field) => field.type !== "string")) {
dispatch({ type: "auth.error", error: language.t("provider.connect.error.unsupportedFields") })
@@ -368,11 +377,35 @@ export function createProviderConnectionController(options: {
dispatch({ type: "auth.pending" })
if (selected.type === "external") {
const saved = await serverSDK.api.integration.connect
.external({
integrationID: options.provider(),
methodID: selected.id,
answer: Object.keys(merged).length ? merged : undefined,
location: location(),
})
.then(() => ({ ok: true as const }))
.catch((error) => ({ ok: false as const, error }))
if (polling.disposed || generation !== polling.generation) return
if (!saved.ok) {
dispatch({ type: "auth.error", error: formatServerError(saved.error, language.t) })
return
}
await finish()
return
}
const result = await serverSDK.api.integration.oauth
.connect({
integrationID: options.provider(),
methodID: selected.id,
...(Object.keys(merged).length ? { answer: merged } : {}),
answer: Object.keys(merged).length ? merged : undefined,
location: location(),
})
.then((response) => {
@@ -404,7 +437,9 @@ export function createProviderConnectionController(options: {
if (!result.ok) {
dispatch({
type: "auth.error",
error: isConsole() ? language.t("provider.connect.console.startFailed") : errorMessage(result.error),
error: isConsole()
? language.t("provider.connect.console.startFailed")
: formatServerError(result.error, language.t),
})
return
@@ -448,7 +483,7 @@ export function createProviderConnectionController(options: {
integrationID: options.keyProvider?.() ?? options.provider(),
location: location(),
key,
...(store.formAnswer ? { answer: store.formAnswer } : {}),
answer: store.formAnswer,
})
await finish()
}
@@ -468,7 +503,8 @@ export function createProviderConnectionController(options: {
.then(() => ({ ok: true as const }))
.catch((error) => ({ ok: false as const, error }))
if (!result.ok) return errorMessage(result.error) || language.t("provider.connect.oauth.code.invalid")
if (!result.ok)
return formatServerError(result.error, language.t, language.t("provider.connect.oauth.code.invalid"))
await finish()
return undefined
@@ -496,11 +532,13 @@ export function createProviderConnectionController(options: {
authorization: () => store.authorization,
browserFailed: () => store.browserFailed,
// True while nothing useful can be shown yet: the integration is loading, a method is
// about to be picked automatically, or the authorization request is in flight.
// about to be picked automatically, the authorization request is in flight, or an external
// method, which has no view of its own, is refreshing the catalogs after saving.
busy: () =>
integration.loading ||
(store.methodIndex === undefined && !store.auto && autoIndex() !== undefined) ||
store.state === "pending",
store.state === "pending" ||
(store.state === "refreshing" && currentMethod()?.type === "external"),
auth: {
state: () => store.state,
error: () => store.error,
@@ -127,9 +127,29 @@ const authenticate = Effect.fn("cli.auth.login.authenticate")(function* (
) {
if (method.type === "key") return yield* keyLogin(client, integration, method, answer)
if (method.type === "command") return yield* commandLogin(client, integration, method)
if (method.type === "external") return yield* externalLogin(client, integration, method, answer)
return yield* oauthLogin(client, integration, method, answer)
})
const externalLogin = Effect.fn("cli.auth.login.external")(function* (
client: OpenCodeClient,
integration: IntegrationInfo,
method: Extract<ConnectMethod, { type: "external" }>,
answer?: FormAnswer,
) {
const progress = spinner()
progress.start("Saving credential...")
yield* request((signal) =>
client.integration.connect.external(
{ integrationID: integration.id, methodID: method.id, answer, location },
{ signal },
),
).pipe(
Effect.tap(() => Effect.sync(() => progress.stop(`Connected to ${integration.name}`))),
Effect.tapCause(() => Effect.sync(() => progress.stop("Authentication failed", 1))),
)
})
const keyLogin = Effect.fn("cli.auth.login.key")(function* (
client: OpenCodeClient,
integration: IntegrationInfo,
+16 -1
View File
@@ -1597,6 +1597,18 @@ export type IntegrationConnectKeyOperation<E = never> = (
input: IntegrationConnectKeyInput,
) => Effect.Effect<IntegrationConnectKeyOutput, E>
export type IntegrationConnectExternalInput = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined } | undefined
readonly methodID: Integration.MethodID
readonly answer?: Form.Answer | undefined
readonly label?: string | undefined
}
export type IntegrationConnectExternalOutput = void
export type IntegrationConnectExternalOperation<E = never> = (
input: IntegrationConnectExternalInput,
) => Effect.Effect<IntegrationConnectExternalOutput, E>
export type IntegrationOauthConnectInput = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined } | undefined
@@ -1687,7 +1699,10 @@ export interface IntegrationApi<E = never> {
readonly list: IntegrationListOperation<E>
readonly get: IntegrationGetOperation<E>
readonly wellknown: { readonly add: IntegrationWellknownAddOperation<E> }
readonly connect: { readonly key: IntegrationConnectKeyOperation<E> }
readonly connect: {
readonly key: IntegrationConnectKeyOperation<E>
readonly external: IntegrationConnectExternalOperation<E>
}
readonly oauth: {
readonly connect: IntegrationOauthConnectOperation<E>
readonly status: IntegrationOauthStatusOperation<E>
+13 -1
View File
@@ -127,6 +127,8 @@ import type {
IntegrationWellknownAddOutput,
IntegrationConnectKeyInput,
IntegrationConnectKeyOutput,
IntegrationConnectExternalInput,
IntegrationConnectExternalOutput,
IntegrationOauthConnectInput,
IntegrationOauthConnectOutput,
IntegrationOauthStatusInput,
@@ -897,6 +899,16 @@ const EndpointIntegrationConnectKey = (raw: RawClient["server.integration"]) =>
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointIntegrationConnectExternal =
(raw: RawClient["server.integration"]) => (input: IntegrationConnectExternalInput) =>
preserveEffect<IntegrationConnectExternalOutput>()(
raw["integration.connect.external"]({
params: { integrationID: input["integrationID"] },
query: { location: input["location"] },
payload: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointIntegrationOauthConnect =
(raw: RawClient["server.integration"]) => (input: IntegrationOauthConnectInput) =>
preserveEffect<IntegrationOauthConnectOutput>()(
@@ -965,7 +977,7 @@ const adaptGroupIntegration = (raw: RawClient["server.integration"]) => ({
list: EndpointIntegrationList(raw),
get: EndpointIntegrationGet(raw),
wellknown: { add: EndpointIntegrationWellknownAdd(raw) },
connect: { key: EndpointIntegrationConnectKey(raw) },
connect: { key: EndpointIntegrationConnectKey(raw), external: EndpointIntegrationConnectExternal(raw) },
oauth: {
connect: EndpointIntegrationOauthConnect(raw),
status: EndpointIntegrationOauthStatus(raw),
@@ -121,6 +121,8 @@ import type {
IntegrationWellknownAddOutput,
IntegrationConnectKeyInput,
IntegrationConnectKeyOutput,
IntegrationConnectExternalInput,
IntegrationConnectExternalOutput,
IntegrationOauthConnectInput,
IntegrationOauthConnectOutput,
IntegrationOauthStatusInput,
@@ -1228,6 +1230,19 @@ export function make(options: ClientOptions) {
},
requestOptions,
),
external: (input: IntegrationConnectExternalInput, requestOptions?: RequestOptions) =>
request<IntegrationConnectExternalOutput>(
{
method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/external`,
query: { location: input["location"] },
body: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
successStatus: 204,
declaredStatuses: [400, 401, 404],
empty: true,
},
requestOptions,
),
},
oauth: {
connect: (input: IntegrationOauthConnectInput, requestOptions?: RequestOptions) =>
@@ -2314,6 +2314,8 @@ export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string;
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
export type IntegrationExternalMethod = { id: string; type: "external"; label: string; form?: FormFields }
export type CredentialEntry = {
id: string
integrationID: string
@@ -2351,6 +2353,7 @@ export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationExternalMethod
| IntegrationEnvMethod
export type FormCreated = {
@@ -5688,6 +5691,28 @@ export type IntegrationConnectKeyInput = {
export type IntegrationConnectKeyOutput = void
export type IntegrationConnectExternalInput = {
readonly integrationID: { readonly integrationID: string }["integrationID"]
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
readonly methodID: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["methodID"]
readonly answer?: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["answer"]
readonly label?: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["label"]
}
export type IntegrationConnectExternalOutput = void
export type IntegrationOauthConnectInput = {
readonly integrationID: { readonly integrationID: string }["integrationID"]
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
+6 -2
View File
@@ -2,10 +2,14 @@ export * as ConfigMarkdown from "./markdown.js"
import matter from "gray-matter"
export function parse(content: string) {
// Passing options bypasses gray-matter's module-global content cache, which
// it populates before parsing: a failed YAML parse poisons the entry and
// every later parse of the same content replays it without throwing, so the
// sanitize fallback below never runs. Upstream: jonschlinkert/gray-matter#166.
try {
return matter(content)
return matter(content, {})
} catch {
return matter(sanitize(content))
return matter(sanitize(content), {})
}
}
+53 -1
View File
@@ -45,6 +45,9 @@ export type CommandMethod = Integration.CommandMethod
export const KeyMethod = Integration.KeyMethod
export type KeyMethod = Integration.KeyMethod
export const ExternalMethod = Integration.ExternalMethod
export type ExternalMethod = Integration.ExternalMethod
export const EnvMethod = Integration.EnvMethod
export type EnvMethod = Integration.EnvMethod
@@ -82,6 +85,11 @@ export interface KeyImplementation {
readonly method: KeyMethod
}
export interface ExternalImplementation {
readonly integrationID: ID
readonly method: ExternalMethod
}
export interface CommandImplementation {
readonly integrationID: ID
readonly method: CommandMethod
@@ -92,7 +100,12 @@ export interface EnvImplementation {
readonly method: EnvMethod
}
export type Implementation = OAuthImplementation | CommandImplementation | KeyImplementation | EnvImplementation
export type Implementation =
| OAuthImplementation
| CommandImplementation
| KeyImplementation
| ExternalImplementation
| EnvImplementation
export const Attempt = Integration.Attempt
export type Attempt = Integration.Attempt
@@ -180,6 +193,17 @@ export interface Interface extends State.Transformable<Editor> {
/** User-facing label for the stored credential. */
readonly label?: string
}) => Effect.Effect<void, AuthorizationError>
/** Runs an external method and stores a reference configured by its form answers. */
readonly external: (input: {
/** Integration receiving the credential. */
readonly integrationID: ID
/** External method that defines the form and credential source. */
readonly methodID: MethodID
/** Values collected from the method's form fields. */
readonly answer?: Form.Answer
/** User-facing label for the stored credential. */
readonly label?: string
}) => Effect.Effect<void, AuthorizationError>
/** Selects a stored credential as the active integration connection. */
readonly activate: (credentialID: Credential.ID) => Effect.Effect<void>
/** Updates a stored credential exposed as a connection. */
@@ -327,6 +351,8 @@ const layer = Layer.effect(
return method.id === implementation.method.id
if (method.type === "command" && implementation.method.type === "command")
return method.id === implementation.method.id
if (method.type === "external" && implementation.method.type === "external")
return method.id === implementation.method.id
return true
})
if (index === -1) current.methods.push(implementation.method as Types.DeepMutable<Method>)
@@ -345,6 +371,7 @@ const layer = Layer.effect(
if (candidate.type !== method.type) return false
if (candidate.type === "oauth" && method.type === "oauth") return candidate.id === method.id
if (candidate.type === "command" && method.type === "command") return candidate.id === method.id
if (candidate.type === "external" && method.type === "external") return candidate.id === method.id
return true
})
if (index !== -1) current.methods.splice(index, 1)
@@ -736,6 +763,31 @@ const layer = Layer.effect(
}),
})
}),
external: Effect.fn("Integration.connection.external")(function* (input) {
const method = state
.get()
.integrations.get(input.integrationID)
?.methods.find((method) => method.type === "external" && method.id === input.methodID)
if (method?.type !== "external")
return yield* new AuthorizationError({ cause: new Error(`External method not found: ${input.methodID}`) })
const answer = input.answer ?? {}
if (method.form) {
const invalid = Form.validateFields(method.form) ?? Form.validateAnswer(method.form, answer)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
if (!method.form && Object.keys(answer).length > 0) {
return yield* new AuthorizationError({ cause: new Error("External method does not accept a form answer") })
}
yield* createCredential({
integrationID: input.integrationID,
label: input.label,
value: Credential.External.make({
type: "external",
methodID: method.id,
...(Object.keys(answer).length > 0 ? { metadata: answer } : {}),
}),
})
}),
activate: Effect.fn("Integration.connection.activate")((credentialID) => credentials.activate(credentialID)),
update: Effect.fn("Integration.connection.update")((credentialID, updates) =>
credentials.update(credentialID, updates),
+13
View File
@@ -286,6 +286,13 @@ export const make = Effect.fn("PluginHost.make")(function* (
answer: input.answer,
label: input.label,
}),
external: (input) =>
integration.connection.external({
integrationID: Integration.ID.make(input.integrationID),
methodID: Integration.MethodID.make(input.methodID),
answer: input.answer,
label: input.label,
}),
},
oauth: {
connect: (input) =>
@@ -665,6 +672,12 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
}
}
if (input.method.type === "external") {
return {
integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
}
}
return {
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
@@ -13,6 +13,7 @@ import { Integration } from "../../integration.js"
import { Model } from "../../model.js"
import { OauthCallbackPage } from "../../oauth/page.js"
import { Provider } from "../../provider.js"
import { SessionAffinity } from "../../session/affinity.js"
import type { PluginInternal } from "../internal.js"
// First-time sign-in registers a user-owned client; OpenAI returns its issued client ID on the callback.
@@ -264,6 +265,21 @@ export const ChatGPTPlugin = define({
}),
{ providerID },
)
yield* ctx.session.hook(
"model.request",
(evt) =>
Effect.gen(function* () {
if (!chatgpt) return
const session = yield* ctx.session
.get({ sessionID: evt.sessionID })
.pipe(Effect.orElseSucceed(() => undefined))
// Mirror the Codex client's session headers: ChatGPT derives prompt-cache affinity from session-id.
evt.headers["session-id"] = session ? SessionAffinity.get(session) : evt.sessionID
evt.headers["thread-id"] = evt.sessionID
evt.headers["x-client-request-id"] = evt.sessionID
}),
{ providerID },
)
yield* ctx.provider.transform((providers) => {
const item = providers.get(providerID)
if (!item) return
+25 -5
View File
@@ -55,7 +55,7 @@ const forkTitle = (value?: string) => {
return `${value} (fork #1)`
}
function applyUsage(db: DatabaseService, sessionID: SessionSchema.ID, value: Usage) {
function applyUsage(db: DatabaseService, sessionID: SessionSchema.ID, value: Usage, timeUpdated?: number) {
return db
.update(SessionTable)
.set({
@@ -65,13 +65,22 @@ function applyUsage(db: DatabaseService, sessionID: SessionSchema.ID, value: Usa
tokens_reasoning: sql`${SessionTable.tokens_reasoning} + ${value.tokens.reasoning}`,
tokens_cache_read: sql`${SessionTable.tokens_cache_read} + ${value.tokens.cache.read}`,
tokens_cache_write: sql`${SessionTable.tokens_cache_write} + ${value.tokens.cache.write}`,
time_updated: sql`${SessionTable.time_updated}`,
time_updated: timeUpdated ?? sql`${SessionTable.time_updated}`,
})
.where(eq(SessionTable.id, sessionID))
.run()
.pipe(Effect.orDie)
}
function touch(db: DatabaseService, event: MessageEvent) {
return db
.update(SessionTable)
.set({ time_updated: event.created })
.where(eq(SessionTable.id, event.data.sessionID))
.run()
.pipe(Effect.orDie)
}
const publishSessionUsage = Effect.fn("SessionProjector.publishUsage")(function* (
db: DatabaseService,
bus: Bus.Interface,
@@ -681,19 +690,30 @@ const layer = Layer.effectDiscard(
yield* bus.project(SessionEvent.Skill.Activated, (event) => run(db, event))
yield* bus.project(SessionEvent.Shell.Started, (event) => run(db, event))
yield* bus.project(SessionEvent.Shell.Ended, (event) => run(db, event))
yield* bus.project(SessionEvent.Step.Started, (event) => run(db, event))
yield* bus.project(SessionEvent.Step.Started, (event) =>
Effect.gen(function* () {
yield* run(db, event)
yield* touch(db, event)
}),
)
yield* bus.project(SessionEvent.Step.Streamed, (event) => run(db, event))
yield* bus.project(SessionEvent.Step.Ended, (event) =>
Effect.gen(function* () {
yield* run(db, event)
yield* applyUsage(db, event.data.sessionID, event.data)
yield* applyUsage(db, event.data.sessionID, event.data, event.created)
}),
)
yield* bus.project(SessionEvent.Step.Failed, (event) =>
Effect.gen(function* () {
yield* run(db, event)
if (event.data.cost !== undefined && event.data.tokens !== undefined)
yield* applyUsage(db, event.data.sessionID, { cost: event.data.cost, tokens: event.data.tokens })
yield* applyUsage(
db,
event.data.sessionID,
{ cost: event.data.cost, tokens: event.data.tokens },
event.created,
)
else yield* touch(db, event)
}),
)
yield* bus.project(SessionEvent.Text.Started, (event) => run(db, event))
@@ -0,0 +1,35 @@
import { describe, expect, test } from "bun:test"
import { ConfigMarkdown } from "@opencode/core/config/markdown"
const invalidYaml = `---
description: Use when the user needs to crawl pages. Keywords: crawl, scrape
---
body`
describe("ConfigMarkdown.parse", () => {
test("recovers unquoted-colon frontmatter via the sanitize fallback", () => {
const parsed = ConfigMarkdown.parse(invalidYaml)
expect(parsed.data.description).toBe("Use when the user needs to crawl pages. Keywords: crawl, scrape")
expect(parsed.content.trim()).toBe("body")
})
test("recovers the same content again after a previous failed parse", () => {
// gray-matter caches by content before parsing; a poisoned entry used to
// make every later parse of the same text return silently without data.
expect(() => ConfigMarkdown.parse("---\ndescription: [unclosed\n---\nbody")).toThrow()
const parsed = ConfigMarkdown.parse(invalidYaml)
expect(parsed.data.description).toBe("Use when the user needs to crawl pages. Keywords: crawl, scrape")
})
test("keeps throwing for the same unparseable content on every call", () => {
const input = "---\ndescription: [unclosed\n---\nbody"
expect(() => ConfigMarkdown.parse(input)).toThrow()
expect(() => ConfigMarkdown.parse(input)).toThrow()
})
test("parses plain content without frontmatter", () => {
const parsed = ConfigMarkdown.parse("just body")
expect(parsed.content).toBe("just body")
expect(parsed.data).toEqual({})
})
})
+1
View File
@@ -32,6 +32,7 @@ const integrations = Layer.mock(Integration.Service, {
active: () => Effect.undefined,
resolve: () => Effect.die("unused"),
key: () => Effect.die("unused"),
external: () => Effect.die("unused"),
activate: () => Effect.die("unused"),
update: () => Effect.die("unused"),
remove: () => Effect.die("unused"),
+1
View File
@@ -330,6 +330,7 @@ function resourceMcpLayer(
active: unusedIntegration,
resolve: unusedIntegration,
key: unusedIntegration,
external: unusedIntegration,
activate: unusedIntegration,
update: unusedIntegration,
remove: unusedIntegration,
@@ -372,6 +372,7 @@ describe("ModelResolver", () => {
},
resolve: () => Effect.die("unused"),
key: () => Effect.die("unused"),
external: () => Effect.die("unused"),
activate: () => Effect.die("unused"),
update: () => Effect.die("unused"),
remove: () => Effect.die("unused"),
+13 -1
View File
@@ -78,6 +78,7 @@ export function host(overrides: Overrides = {}): Plugin.Context {
get: () => Effect.die("unused integration.get"),
connect: {
key: () => Effect.die("unused integration.connect.key"),
external: () => Effect.die("unused integration.connect.external"),
},
oauth: {
connect: () => Effect.die("unused integration.oauth.connect"),
@@ -297,6 +298,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
get: () => Effect.die("unused integration.get"),
connect: {
key: () => Effect.die("unused integration.connect.key"),
external: () => Effect.die("unused integration.connect.external"),
},
oauth: {
connect: () => Effect.die("unused integration.oauth.connect"),
@@ -409,6 +411,16 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
})
return
}
if (input.method.type === "external") {
editor.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: {
...input.method,
id: Integration.MethodID.make(input.method.id),
},
})
return
}
editor.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
@@ -459,7 +471,7 @@ export function webSearchHost(websearch: WebSearch.Interface): Plugin.Context["w
}
function internalMethod(value: IntegrationMethod): Integration.Method {
if (value.type === "oauth" || value.type === "command") {
if (value.type === "oauth" || value.type === "command" || value.type === "external") {
return { ...value, id: Integration.MethodID.make(value.id) }
}
return value
@@ -73,10 +73,14 @@ const authorize = Effect.fn(function* () {
return new URL(attempt.url)
})
const request = Effect.fn(function* (providerID: Provider.ID, baseURL: string) {
const request = Effect.fn(function* (
providerID: Provider.ID,
baseURL: string,
sessionID = Session.ID.make("ses_test"),
) {
const hooks = yield* PluginHooks.Service
const event = yield* hooks.trigger("session", "model.request", {
sessionID: Session.ID.make("ses_test"),
sessionID,
agent: Agent.ID.make("build"),
model: Model.Ref.make({ providerID, id: Model.ID.make("gpt-5.5") }),
kind: "primary",
@@ -767,8 +771,21 @@ describe("ChatGPTPlugin", () => {
expect(provider.settings?.baseURL).toBe("https://api.openai.com/v1")
expect(provider.headers).not.toHaveProperty("x-openai-chatpass-test")
expect(direct.baseURL).toBe("https://api.openai.com/v1")
expect(direct.headers).toEqual({})
expect(direct.headers).toEqual({
"session-id": "ses_test",
"thread-id": "ses_test",
"x-client-request-id": "ses_test",
})
expect(direct.hasHttpHooks).toBe(false)
const sessions = yield* Session.Service
const location = yield* Location.Service
const parent = yield* sessions.create({ location: { directory: location.directory } })
const child = yield* sessions.create({ parentID: parent.id })
expect((yield* request(Provider.ID.openai, "https://api.openai.com/v1", child.id)).headers).toEqual({
"session-id": parent.id,
"thread-id": child.id,
"x-client-request-id": child.id,
})
const eligible = required(yield* models.get(Provider.ID.openai, Model.ID.make("gpt-5.5")))
expect(eligible.package).toBe("@opencode/ai/providers/openai")
expect(eligible.headers).not.toHaveProperty("x-openai-chatpass-test")
@@ -845,6 +862,7 @@ describe("ChatGPTPlugin", () => {
expect(provider.settings?.transport).toBe("websocket")
expect(model.settings?.transport).toBeUndefined()
expect(direct.baseURL).toBe("https://api.openai.com/v1")
expect(direct.headers).toEqual({})
expect(direct.hasHttpHooks).toBe(false)
expect(provider.headers).not.toHaveProperty("x-openai-chatpass-test")
expect(required(yield* models.get(Provider.ID.openai, Model.ID.make("gpt-4.1"))).enabled).toBe(true)
@@ -1,5 +1,6 @@
import { describe, expect } from "bun:test"
import { DateTime, Effect, Fiber, Option, Schema, Stream } from "effect"
import { TestClock } from "effect/testing"
import { asc, eq, sql } from "drizzle-orm"
import { Database } from "@opencode/core/database/database"
import { Agent } from "@opencode/core/agent"
@@ -760,4 +761,51 @@ describe("SessionProjector", () => {
])
}),
)
it.effect("bumps session time_updated on step lifecycle events", () =>
Effect.gen(function* () {
const db = yield* seedSession({ time_created: 0, time_updated: 0 })
const bus = yield* Bus.Service
const updated = () =>
db.select({ time_updated: SessionTable.time_updated }).from(SessionTable).get().pipe(Effect.orDie)
const first = SessionMessage.ID.make("msg_touch_first")
const second = SessionMessage.ID.make("msg_touch_second")
yield* TestClock.setTime(5)
yield* bus.publish(SessionEvent.Step.Started, {
sessionID,
assistantMessageID: first,
agent: build,
model,
started: 5,
})
expect(yield* updated()).toEqual({ time_updated: 5 })
yield* TestClock.setTime(9)
yield* bus.publish(SessionEvent.Step.Ended, {
sessionID,
assistantMessageID: first,
finish: "stop",
cost: Money.USD.make(0),
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
})
expect(yield* updated()).toEqual({ time_updated: 9 })
yield* TestClock.setTime(12)
yield* bus.publish(SessionEvent.Step.Started, {
sessionID,
assistantMessageID: second,
agent: build,
model,
started: 12,
})
yield* TestClock.setTime(15)
yield* bus.publish(SessionEvent.Step.Failed, {
sessionID,
assistantMessageID: second,
error: { type: "provider.invalid-request", message: "Failed" },
})
expect(yield* updated()).toEqual({ time_updated: 15 })
}),
)
})
@@ -5,6 +5,7 @@ export default {
"usage.usage": "Context",
"usage.cost": "Cost",
"usage.view": "View context usage",
"usage.toggle": "Toggle session context",
"systemPrompt.title": "System Prompt",
"rawMessages.title": "Raw messages",
"export.session": "Export session",
@@ -1,6 +1,6 @@
import { Show, createMemo, type ComponentProps, type JSX } from "solid-js"
import { ProgressCircle } from "@opencode/ui/progress-circle"
import { IconButton } from "@opencode/ui/icon-button"
import { Button } from "@opencode/ui/button"
import { Tooltip } from "@opencode/ui/tooltip"
import { useI18n } from "@opencode/ui/context/i18n"
import { useExtension, type MountedSession } from "../sdk"
@@ -62,6 +62,12 @@ export function SessionContextUsage(props: {
}
})
const tokens = createMemo(() =>
new Intl.NumberFormat(i18n.locale(), { notation: "compact", maximumFractionDigits: 0 })
.format(context()?.total ?? 0)
.toLocaleLowerCase(i18n.locale()),
)
const cost = createMemo(() => {
return usd().format(info()?.cost ?? 0)
})
@@ -89,7 +95,7 @@ export function SessionContextUsage(props: {
const compactCircle = () => (
<div class="flex items-center justify-center">
<ProgressCircle appearance="compact" percentage={context()?.usage ?? 0} />
<ProgressCircle appearance="compact" size={16} percentage={context()?.usage ?? 0} />
</div>
)
@@ -103,18 +109,31 @@ export function SessionContextUsage(props: {
return (
<Show when={props.session.id}>
<Tooltip value={tooltipValue()} placement={props.placement ?? "top"} shift={-8}>
<Tooltip
value={variant() === "indicator" ? tooltipValue() : ctx.t("usage.toggle")}
placement={props.placement ?? "top"}
>
<Show
when={variant() === "indicator"}
fallback={
<IconButton
<Button
type="button"
variant="ghost-muted"
size="large"
icon={compactCircle()}
class="group shrink-0"
style={{ padding: "0 6px", color: "var(--v2-text-text-faint)" }}
onClick={openContext}
aria-label={ctx.t("usage.view")}
/>
aria-expanded={layout.state(`${ctx.id}:main`, props.session) === "visible"}
aria-label={ctx.t("usage.toggle")}
>
<span class="flex items-center gap-2 whitespace-nowrap group-active:text-v2-text-text-muted">
{compactCircle()}
<span>{tokens()}</span>
<span aria-hidden="true" class="flex w-1.5 shrink-0 items-center justify-center">
·
</span>
<span>{cost()}</span>
</span>
</Button>
}
>
{circle()}
+12
View File
@@ -28,6 +28,13 @@ export interface IntegrationKeyMethod {
readonly form?: Form.Fields
}
export interface IntegrationExternalMethod {
readonly id: string
readonly type: "external"
readonly label: string
readonly form?: Form.Fields
}
export interface IntegrationEnvMethod {
readonly type: "env"
readonly names: ReadonlyArray<string>
@@ -37,6 +44,7 @@ export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationExternalMethod
| IntegrationEnvMethod
export type IntegrationOAuthAuthorization = {
@@ -70,6 +78,10 @@ export type IntegrationMethodRegistration =
readonly integrationID: string
readonly method: IntegrationKeyMethod
}
| {
readonly integrationID: string
readonly method: IntegrationExternalMethod
}
| {
readonly integrationID: string
readonly method: IntegrationEnvMethod
+4
View File
@@ -356,6 +356,10 @@ export function fromPromise(plugin: Plugin) {
get: adaptApiMethod(IntegrationEndpoints["integration.get"], host.integration.get),
connect: {
key: adaptApiMethod(IntegrationEndpoints["integration.connect.key"], host.integration.connect.key),
external: adaptApiMethod(
IntegrationEndpoints["integration.connect.external"],
host.integration.connect.external,
),
},
oauth: {
connect: adaptApiMethod(
@@ -27,6 +27,13 @@ export interface IntegrationKeyMethod {
readonly form?: Form.Fields
}
export interface IntegrationExternalMethod {
readonly id: string
readonly type: "external"
readonly label: string
readonly form?: Form.Fields
}
export interface IntegrationEnvMethod {
readonly type: "env"
readonly names: ReadonlyArray<string>
@@ -36,6 +43,7 @@ export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationExternalMethod
| IntegrationEnvMethod
export type IntegrationOAuthAuthorization = {
@@ -68,6 +76,7 @@ export type IntegrationMethodRegistration =
readonly integrationID: string
readonly method: IntegrationKeyMethod
}
| { readonly integrationID: string; readonly method: IntegrationExternalMethod }
| { readonly integrationID: string; readonly method: IntegrationEnvMethod }
export interface IntegrationEditor {
+7 -3
View File
@@ -18,7 +18,7 @@ import { AgentGroup } from "./groups/agent.js"
import { PluginGroup } from "./groups/plugin.js"
import { ServerGroup } from "./groups/server.js"
import { DebugGroup } from "./groups/debug.js"
import { PtyGroup } from "./groups/pty.js"
import { makePtyGroup } from "./groups/pty.js"
import { PersistentPtyGroup } from "./groups/persistent-pty.js"
import { ShellGroup } from "./groups/shell.js"
import { ReferenceGroup } from "./groups/reference.js"
@@ -47,12 +47,15 @@ type LocationGroups<LocationId extends HttpApiMiddleware.AnyId> =
| HttpApiGroup.AddMiddleware<typeof CommandGroup, LocationId>
| HttpApiGroup.AddMiddleware<typeof SkillGroup, LocationId>
| HttpApiGroup.AddMiddleware<typeof RpcGroup, LocationId>
| HttpApiGroup.AddMiddleware<typeof PtyGroup, LocationId>
| HttpApiGroup.AddMiddleware<typeof ShellGroup, LocationId>
| HttpApiGroup.AddMiddleware<typeof ReferenceGroup, LocationId>
| HttpApiGroup.AddMiddleware<typeof VcsGroup, LocationId>
| HttpApiGroup.AddMiddleware<typeof ConfigGroup, LocationId>
type PtyGroups<LocationId extends HttpApiMiddleware.AnyId, LocationService> = ReturnType<
typeof makePtyGroup<LocationId, LocationService>
>
type SessionGroups<
SessionLocationId extends HttpApiMiddleware.AnyId,
SessionLocationService,
@@ -95,6 +98,7 @@ type ApiGroups<
| typeof CredentialGroup
| LocationGroups<LocationId>
| LocationGroup<LocationId, LocationService>
| PtyGroups<LocationId, LocationService>
| FormGroups<LocationId, LocationService>
| SessionGroups<SessionLocationId, SessionLocationService, FormLocationId, FormLocationService>
| MixedMiddlewareGroups<LocationId, LocationService, SessionLocationId, SessionLocationService>
@@ -173,7 +177,7 @@ const makeApiFromGroup = <
.add(SkillGroup.middleware(locationMiddleware))
.add(RpcGroup.middleware(locationMiddleware))
.add(eventGroup)
.add(PtyGroup.middleware(locationMiddleware))
.add(makePtyGroup(locationMiddleware))
.add(PersistentPtyGroup)
.add(ShellGroup.middleware(locationMiddleware))
.add(ReferenceGroup.middleware(locationMiddleware))
@@ -79,6 +79,27 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
}),
),
)
.add(
HttpApiEndpoint.post("integration.connect.external", "/api/integration/:integrationID/connect/external", {
params: { integrationID: Integration.ID },
query: LocationQuery,
payload: Schema.Struct({
methodID: Integration.MethodID,
answer: Schema.optional(Form.Answer),
label: Schema.optional(Schema.String),
}),
success: HttpApiSchema.NoContent,
error: [IntegrationNotFoundError, InvalidRequestError],
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "integration.connect.external",
summary: "Connect with external credentials",
description: "Run an external authentication method and store a reference to its credential source.",
}),
),
)
.add(
HttpApiEndpoint.post("integration.oauth.connect", "/api/integration/:integrationID/connect/oauth", {
params: { integrationID: Integration.ID },
+127 -124
View File
@@ -1,9 +1,9 @@
import { Pty } from "@opencode/schema/pty"
import { PtyTicket } from "@opencode/schema/pty-ticket"
import { Location } from "@opencode/schema/location"
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
import { ForbiddenError, PtyNotFoundError } from "../errors.js"
import { Context, Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
import { ForbiddenError, LocationNotFoundError, PtyNotFoundError } from "../errors.js"
import { LocationQuery, locationQueryOpenApi } from "./location.js"
export const PTY_CONNECT_TICKET_QUERY = "ticket"
@@ -18,127 +18,130 @@ export function hasPtyConnectTicketURL(url: URL) {
return PTY_CONNECT_PATH.test(url.pathname) && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
}
export const PtyGroup = HttpApiGroup.make("server.pty")
.add(
HttpApiEndpoint.get("pty.list", "/api/pty", {
query: LocationQuery,
success: Location.response(Schema.Array(Pty.Info)),
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
export const makePtyGroup = <LocationId extends HttpApiMiddleware.AnyId, LocationService>(
locationMiddleware: Context.Key<LocationId, LocationService>,
) =>
HttpApiGroup.make("server.pty")
.add(
HttpApiEndpoint.get("pty.list", "/api/pty", {
query: LocationQuery,
success: Location.response(Schema.Array(Pty.Info)),
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.list",
summary: "List PTY sessions",
description: "List PTY sessions for a location, including exited sessions retained until removal.",
}),
),
)
.add(
HttpApiEndpoint.post("pty.create", "/api/pty", {
query: LocationQuery,
payload: Pty.CreateInput,
success: Location.response(Pty.Info),
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.create",
summary: "Create PTY session",
description: "Create a pseudo-terminal session for a location.",
}),
),
)
.add(
HttpApiEndpoint.get("pty.get", "/api/pty/:ptyID", {
params: { ptyID: Pty.ID },
query: LocationQuery,
success: Location.response(Pty.Info),
error: PtyNotFoundError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.get",
summary: "Get PTY session",
description: "Get one PTY session, including its exit code once exited.",
}),
),
)
.add(
HttpApiEndpoint.put("pty.update", "/api/pty/:ptyID", {
params: { ptyID: Pty.ID },
query: LocationQuery,
payload: Pty.UpdateInput,
success: Location.response(Pty.Info),
error: PtyNotFoundError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.update",
summary: "Update PTY session",
description: "Update the title or viewport size of one PTY session.",
}),
),
)
.add(
HttpApiEndpoint.delete("pty.remove", "/api/pty/:ptyID", {
params: { ptyID: Pty.ID },
query: LocationQuery,
success: HttpApiSchema.NoContent,
error: PtyNotFoundError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.remove",
summary: "Remove PTY session",
description: "Terminate and remove one PTY session.",
}),
),
)
.add(
HttpApiEndpoint.post("pty.connectToken", "/api/pty/:ptyID/connect-token", {
params: { ptyID: Pty.ID },
query: LocationQuery,
headers: Schema.Struct({ [PTY_CONNECT_TOKEN_HEADER]: Schema.optional(Schema.String) }),
success: Location.response(PtyTicket.ConnectToken),
error: [ForbiddenError, PtyNotFoundError],
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.connect.token",
summary: "Create PTY WebSocket token",
description: "Create a short-lived single-use ticket for opening a PTY WebSocket connection.",
}),
),
)
.middleware(locationMiddleware)
.add(
// Query fields are decoded in the raw handler before upgrade work.
HttpApiEndpoint.get("pty.connect", "/api/pty/:ptyID/connect", {
params: { ptyID: Pty.ID },
success: Schema.Boolean,
error: [ForbiddenError, PtyNotFoundError, LocationNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "pty.list",
summary: "List PTY sessions",
description: "List PTY sessions for a location, including exited sessions retained until removal.",
identifier: "pty.connect",
summary: "Connect to PTY session",
description: "Establish a WebSocket connection streaming PTY output and accepting terminal input.",
transform: (operation) => ({
...operation,
"x-websocket": true,
parameters: [
...(operation.parameters ?? []),
...["location[directory]", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({
in: "query",
name,
schema: { type: "string" },
})),
],
}),
}),
),
)
.add(
HttpApiEndpoint.post("pty.create", "/api/pty", {
query: LocationQuery,
payload: Pty.CreateInput,
success: Location.response(Pty.Info),
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.create",
summary: "Create PTY session",
description: "Create a pseudo-terminal session for a location.",
}),
),
)
.add(
HttpApiEndpoint.get("pty.get", "/api/pty/:ptyID", {
params: { ptyID: Pty.ID },
query: LocationQuery,
success: Location.response(Pty.Info),
error: PtyNotFoundError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.get",
summary: "Get PTY session",
description: "Get one PTY session, including its exit code once exited.",
}),
),
)
.add(
HttpApiEndpoint.put("pty.update", "/api/pty/:ptyID", {
params: { ptyID: Pty.ID },
query: LocationQuery,
payload: Pty.UpdateInput,
success: Location.response(Pty.Info),
error: PtyNotFoundError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.update",
summary: "Update PTY session",
description: "Update the title or viewport size of one PTY session.",
}),
),
)
.add(
HttpApiEndpoint.delete("pty.remove", "/api/pty/:ptyID", {
params: { ptyID: Pty.ID },
query: LocationQuery,
success: HttpApiSchema.NoContent,
error: PtyNotFoundError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.remove",
summary: "Remove PTY session",
description: "Terminate and remove one PTY session.",
}),
),
)
.add(
HttpApiEndpoint.post("pty.connectToken", "/api/pty/:ptyID/connect-token", {
params: { ptyID: Pty.ID },
query: LocationQuery,
headers: Schema.Struct({ [PTY_CONNECT_TOKEN_HEADER]: Schema.optional(Schema.String) }),
success: Location.response(PtyTicket.ConnectToken),
error: [ForbiddenError, PtyNotFoundError],
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
OpenApi.annotations({
identifier: "pty.connect.token",
summary: "Create PTY WebSocket token",
description: "Create a short-lived single-use ticket for opening a PTY WebSocket connection.",
}),
),
)
.add(
// Query fields are decoded in the raw handler after the existence check so a missing
// session responds with an empty 404 before any upgrade work.
HttpApiEndpoint.get("pty.connect", "/api/pty/:ptyID/connect", {
params: { ptyID: Pty.ID },
success: Schema.Boolean,
error: [ForbiddenError, PtyNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "pty.connect",
summary: "Connect to PTY session",
description: "Establish a WebSocket connection streaming PTY output and accepting terminal input.",
transform: (operation) => ({
...operation,
"x-websocket": true,
parameters: [
...(operation.parameters ?? []),
...["location[directory]", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({
in: "query",
name,
schema: { type: "string" },
})),
],
}),
}),
),
)
.annotateMerge(OpenApi.annotations({ title: "pty", description: "Experimental location-scoped PTY routes." }))
)
.annotateMerge(OpenApi.annotations({ title: "pty", description: "Experimental location-scoped PTY routes." }))
+10 -1
View File
@@ -38,13 +38,22 @@ export const KeyMethod = Schema.Struct({
form: optional(Form.Fields),
}).annotate({ identifier: "Integration.KeyMethod" })
/** Saves a reference to credentials managed outside opencode, configured by the form answers. */
export interface ExternalMethod extends Schema.Schema.Type<typeof ExternalMethod> {}
export const ExternalMethod = Schema.Struct({
id: MethodID,
type: Schema.Literal("external"),
label: Schema.String,
form: optional(Form.Fields),
}).annotate({ identifier: "Integration.ExternalMethod" })
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
export const EnvMethod = Schema.Struct({
type: Schema.Literal("env"),
names: Schema.Array(Schema.String),
}).annotate({ identifier: "Integration.EnvMethod" })
export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, EnvMethod])
export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, ExternalMethod, EnvMethod])
.pipe(Schema.toTaggedUnion("type"))
.annotate({ identifier: "Integration.Method" })
export type Method = typeof Method.Type
@@ -84,6 +84,26 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
return HttpApiSchema.NoContent.make()
}),
)
.handle(
"integration.connect.external",
Effect.fn(function* (ctx) {
const service = yield* Integration.Service
if (!(yield* service.get(ctx.params.integrationID)))
return yield* new IntegrationNotFoundError({
integrationID: ctx.params.integrationID,
message: `Integration not found: ${ctx.params.integrationID}`,
})
yield* authorize(
service.connection.external({
integrationID: ctx.params.integrationID,
methodID: ctx.payload.methodID,
answer: ctx.payload.answer,
label: ctx.payload.label,
}),
)
return HttpApiSchema.NoContent.make()
}),
)
.handle(
"integration.oauth.connect",
Effect.fn(function* (ctx) {
@@ -108,14 +108,13 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment
.handleRaw(
"persistentPty.connect",
Effect.fn("PersistentPtyHandler.connect")(function* (ctx) {
if (!isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors))
return HttpServerResponse.empty({ status: 403 })
const url = new URL(ctx.request.url, "http://localhost")
const ticket = url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
if (ticket) {
const valid = isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors)
? yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID })
: false
if (!valid) return HttpServerResponse.empty({ status: 403 })
}
if (ticket && !(yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID })))
return HttpServerResponse.empty({ status: 403 })
const cursor = Number(url.searchParams.get("cursor") ?? "0")
const role = url.searchParams.get("role") === "observer" ? "observer" : "controller"
+86 -74
View File
@@ -2,6 +2,7 @@ import { Pty } from "@opencode/core/pty"
import { PtyProtocol } from "@opencode/core/pty/protocol"
import { PtyTicket } from "@opencode/core/pty/ticket"
import { Location } from "@opencode/core/location"
import { LocationServiceMap } from "@opencode/core/location-service-map"
import { Effect, Queue } from "effect"
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http"
import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi"
@@ -14,7 +15,7 @@ import {
PTY_CONNECT_TOKEN_HEADER,
PTY_CONNECT_TOKEN_HEADER_VALUE,
} from "@opencode/protocol/groups/pty"
import { response } from "../location"
import { locationErrors, requestRef, response } from "../location"
import { PtyEnvironment } from "../pty-environment"
import { runPtySocket } from "./pty-socket"
@@ -25,6 +26,7 @@ const ticketScope = Effect.gen(function* () {
export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) =>
Effect.gen(function* () {
const locations = yield* LocationServiceMap.Service
const tickets = yield* PtyTicket.Service
const cors = yield* CorsConfig
const environment = yield* PtyEnvironment.Service
@@ -142,83 +144,93 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) =>
.handleRaw(
"pty.connect",
Effect.fn("PtyHandler.connect")(function* (ctx) {
const pty = yield* Pty.Service
const exists = yield* pty.get(ctx.params.ptyID).pipe(
Effect.as(true),
Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(false)),
)
if (!exists) return HttpServerResponse.empty({ status: 404 })
if (!isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors))
return HttpServerResponse.empty({ status: 403 })
const ref = LocationServiceMap.canonical(requestRef(ctx.request))
const url = new URL(ctx.request.url, "http://localhost")
const ticket = url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
if (ticket) {
const valid = isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors)
? yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID, ...(yield* ticketScope) })
: false
if (!valid) return HttpServerResponse.empty({ status: 403 })
}
const parsedCursor = url.searchParams.get("cursor")
const cursorNumber = parsedCursor === null ? undefined : Number(parsedCursor)
const cursor =
cursorNumber !== undefined && Number.isSafeInteger(cursorNumber) && cursorNumber >= -1
? cursorNumber
: undefined
const socket = yield* Effect.orDie(ctx.request.upgrade)
const write = yield* socket.writer
const closeAccepted = (event: Socket.CloseEvent) =>
socket
.runRaw(() => Effect.void, { onOpen: write(event).pipe(Effect.catch(() => Effect.void)) })
.pipe(
Effect.timeout("1 second"),
Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void),
Effect.catch(() => Effect.void),
)
// Outbound frames flow through one queue drained by a single writer so replay, live
// output, and the close frame keep their order.
// TODO: Integrate graceful-shutdown socket tracking before clients migrate to this route.
const outbox = yield* Queue.unbounded<string | Uint8Array | Socket.CloseEvent>()
const attachment = yield* pty
.attach(ctx.params.ptyID, {
cursor,
onData: (chunk) => Queue.offerUnsafe(outbox, chunk),
onEnd: () => Queue.offerUnsafe(outbox, new Socket.CloseEvent(1000)),
})
.pipe(
Effect.catchTags({
"Pty.NotFoundError": () =>
closeAccepted(new Socket.CloseEvent(4404, "session not found")).pipe(Effect.as(undefined)),
"Pty.ExitedError": () =>
closeAccepted(new Socket.CloseEvent(4404, "session exited")).pipe(Effect.as(undefined)),
}),
)
if (!attachment) return HttpServerResponse.empty()
for (const chunk of PtyProtocol.chunks(attachment.replay)) Queue.offerUnsafe(outbox, chunk)
Queue.offerUnsafe(outbox, PtyProtocol.metaFrame(attachment.cursor))
attachment.activate()
const drain = Effect.gen(function* () {
while (true) {
const item = yield* Queue.take(outbox)
yield* write(item)
if (item instanceof Socket.CloseEvent) return
}
})
yield* runPtySocket(
drain,
socket.runRaw((message) => {
const decoded = PtyProtocol.decodeInput(message)
if (decoded !== undefined) attachment.write(decoded)
}),
attachment.detach,
).pipe(
Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void),
Effect.orDie,
if (
ticket &&
!(yield* tickets.consume({
ticket,
ptyID: ctx.params.ptyID,
directory: ref.directory,
workspaceID: ref.workspaceID,
}))
)
return HttpServerResponse.empty()
return HttpServerResponse.empty({ status: 403 })
return yield* Effect.gen(function* () {
const pty = yield* Pty.Service
const exists = yield* pty.get(ctx.params.ptyID).pipe(
Effect.as(true),
Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(false)),
)
if (!exists) return HttpServerResponse.empty({ status: 404 })
const parsedCursor = url.searchParams.get("cursor")
const cursorNumber = parsedCursor === null ? undefined : Number(parsedCursor)
const cursor =
cursorNumber !== undefined && Number.isSafeInteger(cursorNumber) && cursorNumber >= -1
? cursorNumber
: undefined
const socket = yield* Effect.orDie(ctx.request.upgrade)
const write = yield* socket.writer
const closeAccepted = (event: Socket.CloseEvent) =>
socket
.runRaw(() => Effect.void, { onOpen: write(event).pipe(Effect.catch(() => Effect.void)) })
.pipe(
Effect.timeout("1 second"),
Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void),
Effect.catch(() => Effect.void),
)
// Outbound frames flow through one queue drained by a single writer so replay, live
// output, and the close frame keep their order.
// TODO: Integrate graceful-shutdown socket tracking before clients migrate to this route.
const outbox = yield* Queue.unbounded<string | Uint8Array | Socket.CloseEvent>()
const attachment = yield* pty
.attach(ctx.params.ptyID, {
cursor,
onData: (chunk) => Queue.offerUnsafe(outbox, chunk),
onEnd: () => Queue.offerUnsafe(outbox, new Socket.CloseEvent(1000)),
})
.pipe(
Effect.catchTags({
"Pty.NotFoundError": () =>
closeAccepted(new Socket.CloseEvent(4404, "session not found")).pipe(Effect.as(undefined)),
"Pty.ExitedError": () =>
closeAccepted(new Socket.CloseEvent(4404, "session exited")).pipe(Effect.as(undefined)),
}),
)
if (!attachment) return HttpServerResponse.empty()
for (const chunk of PtyProtocol.chunks(attachment.replay)) Queue.offerUnsafe(outbox, chunk)
Queue.offerUnsafe(outbox, PtyProtocol.metaFrame(attachment.cursor))
attachment.activate()
const drain = Effect.gen(function* () {
while (true) {
const item = yield* Queue.take(outbox)
yield* write(item)
if (item instanceof Socket.CloseEvent) return
}
})
yield* runPtySocket(
drain,
socket.runRaw((message) => {
const decoded = PtyProtocol.decodeInput(message)
if (decoded !== undefined) attachment.write(decoded)
}),
attachment.detach,
).pipe(
Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void),
Effect.orDie,
)
return HttpServerResponse.empty()
}).pipe(Effect.provide(locations.get(ref)), locationErrors)
}),
)
}),
+78
View File
@@ -249,8 +249,86 @@ it.live("applies custom CORS origins to HTTP responses and PTY ticket checks", (
)
// Allowed origins pass the ticket guard and reach the missing-terminal lookup.
expect(ticket.status).toBe(allowed ? 404 : 403)
const invalidTicket = yield* Effect.promise(() =>
handler(
new Request("http://opencode.local/api/pty/pty_missing/connect?ticket=invalid&location[directory]=/tmp", {
headers: { origin },
}),
),
)
expect(invalidTicket.status).toBe(403)
const connect = yield* Effect.promise(() =>
handler(
new Request("http://opencode.local/api/pty/pty_missing/connect", {
headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` },
}),
),
)
expect(connect.status).toBe(allowed ? 404 : 403)
const persistentConnect = yield* Effect.promise(() =>
handler(
new Request("http://opencode.local/api/experimental/persistent-pty/pty_missing/connect?cursor=-1", {
headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` },
}),
),
)
expect(persistentConnect.status).toBe(allowed ? 400 : 403)
}),
)
const loaded = yield* Effect.promise(() =>
handler(
new Request("http://opencode.local/api/debug/location", {
headers: { authorization: `Basic ${btoa("opencode:secret")}` },
}),
).then((response) => response.json()),
)
expect(loaded).toEqual([{ directory: process.cwd() }])
const created = (yield* Effect.promise(() =>
handler(
new Request("http://opencode.local/api/pty", {
method: "POST",
headers: {
authorization: `Basic ${btoa("opencode:secret")}`,
"content-type": "application/json",
},
body: JSON.stringify({ command: process.execPath, args: ["-e", "setInterval(() => {}, 1000)"] }),
}),
).then((response) => response.json()),
)) as { data: { id: string } }
const issued = (yield* Effect.promise(() =>
handler(
new Request(`http://opencode.local/api/pty/${created.data.id}/connect-token`, {
method: "POST",
headers: {
authorization: `Basic ${btoa("opencode:secret")}`,
"x-opencode-ticket": "1",
},
}),
).then((response) => response.json()),
)) as { data: { ticket: string } }
yield* Effect.promise(() =>
handler(
new Request(`http://opencode.local/api/pty/${created.data.id}`, {
method: "DELETE",
headers: { authorization: `Basic ${btoa("opencode:secret")}` },
}),
),
)
const consumed = yield* Effect.promise(() =>
handler(new Request(`http://opencode.local/api/pty/${created.data.id}/connect?ticket=${issued.data.ticket}`)),
)
expect(consumed.status).toBe(404)
const replayed = yield* Effect.promise(() =>
handler(new Request(`http://opencode.local/api/pty/${created.data.id}/connect?ticket=${issued.data.ticket}`)),
)
expect(replayed.status).toBe(403)
}).pipe(Effect.scoped),
)
@@ -309,9 +309,62 @@ function openMethod(
))
return
}
if (method.type === "external") {
void beginExternal(integration, method, location, dialog, onConnected)
return
}
void beginOAuth(integration, method, location, dialog, onConnected)
}
async function beginExternal(
integration: IntegrationInfo,
method: Extract<ConnectMethod, { type: "external" }>,
location: LocationRef,
dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected,
) {
const answer = method.form ? await formAnswer(dialog, method.label, method.form) : undefined
if (answer === null) return
dialog.replace(() => (
<ExternalStarting
integration={integration}
method={method}
location={location}
answer={answer}
onConnected={onConnected}
/>
))
}
function ExternalStarting(props: {
integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "external" }>
location: LocationRef
answer?: FormAnswer
onConnected?: OnIntegrationConnected
}) {
const data = useData()
const dialog = useDialog()
const client = useClient()
const toast = useToast()
onMount(() => {
void client.api.integration.connect
.external({
integrationID: props.integration.id,
location: locationQuery(props.location),
methodID: props.method.id,
...(props.answer ? { answer: props.answer } : {}),
})
.then(() => connected(props.integration, props.location, data, dialog, toast, props.onConnected))
.catch((cause) => {
toast.show({ variant: "error", message: errorMessage(cause) })
dialog.clear()
})
})
return <OAuthView title={props.method.label} message="Connecting…" />
}
async function beginKey(
integration: IntegrationInfo,
method: Extract<ConnectMethod, { type: "key" }>,