Compare commits

..

13 Commits

Author SHA1 Message Date
Adam c7106c1628 feat(core): enforce managed provider policies 2026-09-10 18:41:04 -05:00
Aiden Cline 872e38055e fix(ai): normalize flat Responses stream errors (#48376) 2026-09-10 18:23:32 -05:00
James Long 0c1dfa9186 refactor(tui): extract shared session rendering primitives (#48393) 2026-09-10 18:07:14 -04:00
Dax Raad 8f4d706647 feat(cli): add command docs and simplify session list 2026-09-10 16:27:12 -04:00
Aiden Cline 929374cdfd feat(core): parse JSON text results from MCP tools without an output schema (#48357) 2026-09-10 15:20:13 -05:00
opencode-agent[bot] cfa5ba700e fix(stats): canonicalize DeepSeek Flash usage (#48373) 2026-09-10 13:58:51 -05:00
Shoubhit Dash 45a2ed9a97 feat(core): per-session permission rules (#48351) 2026-09-10 22:30:53 +05:30
opencode-agent[bot] f6333546f8 fix(tui): disambiguate plugin actions (#48354)
Co-authored-by: nexxeln <95541290+nexxeln@users.noreply.github.com>
2026-09-10 22:10:01 +05:30
opencode-agent[bot] 9e153ce7b3 fix(core): raise instruction entry limit (#48350)
Co-authored-by: nexxeln <nexxeln@users.noreply.github.com>
2026-09-10 20:59:38 +05:30
Simon Klee eb357f17cf fix(tui): strip NUL characters before clipboard writes (#48337) 2026-09-10 15:47:03 +02:00
Shoubhit Dash 573d76933f fix(ai): make xAI Responses websockets work and enable them (#48318) 2026-09-10 17:27:43 +05:30
usrnk1 bb8194395a feat(desktop): respect follow-up behavior for slash commands (#48169)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-09-10 19:24:23 +08:00
opencode-agent[bot] 2e8ed86658 fix(app): move compaction status below summary (#48262)
Co-authored-by: Hona <10430890+Hona@users.noreply.github.com>
2026-09-10 18:27:08 +08:00
91 changed files with 2697 additions and 754 deletions
@@ -18,7 +18,6 @@ const WebSocketResponseCreate = Schema.StructWithRest(Schema.Struct({ type: Sche
])
const decodeMessage = ProviderShared.validateWith(Schema.decodeUnknownEffect(WebSocketResponseCreate))
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(WebSocketResponseCreate))
const decodeEvent = Schema.decodeUnknownEffect(OpenResponses.protocol.stream.event)
export interface Options {
readonly id: string
@@ -27,6 +26,7 @@ export interface Options {
readonly enabled?: (url: string) => boolean
readonly url?: (url: string) => string
readonly headers?: (headers: Headers.Headers) => Headers.Headers
readonly continuation?: OpenResponsesContinuation.Shape
}
export interface Prepared {
@@ -60,7 +60,7 @@ const driver = (options: Options, body: string): WebSocketChannelDriver => {
}),
observe: (_create, frame) =>
Effect.gen(function* () {
const event = yield* decodeEvent(frame).pipe(
const event = yield* OpenResponses.decodeChannelEvent(frame).pipe(
Effect.mapError((cause) =>
ProviderShared.eventError(options.id, `Invalid ${options.name} WebSocket event`, frame, cause),
),
@@ -163,6 +163,7 @@ export const transport = <Body>(options: Options): Transport<Body, Prepared, str
request: create.request,
message: create.message,
base,
continuation: options.continuation,
}),
}
})
@@ -6,7 +6,6 @@ import { OpenResponses } from "./open-responses.js"
const PROTOCOL = "open-responses.websocket.v1"
const VERSION = 1
const decodeEvent = Schema.decodeUnknownEffect(OpenResponses.protocol.stream.event)
interface CheckpointValue {
readonly version: typeof VERSION
@@ -15,12 +14,19 @@ interface CheckpointValue {
readonly output: ReadonlyArray<unknown>
}
/**
* Fields to send next to `previous_response_id` on an incremental step, or undefined to send the step in full.
* Whether omitted fields carry over from the continued response is provider behavior the route must know.
*/
export type Shape = (request: Readonly<Record<string, unknown>>) => Readonly<Record<string, unknown>> | undefined
export interface DriverInput {
readonly id: string
readonly name: string
readonly request: Readonly<Record<string, unknown>>
readonly message: string
readonly base: WebSocketChannelDriver
readonly continuation?: Shape
}
const checkpointValue = (checkpoint: ChannelCheckpoint | undefined): CheckpointValue | undefined => {
@@ -127,22 +133,26 @@ const rejected = (
export const driver = (input: DriverInput): WebSocketChannelDriver => {
const { previous_response_id: _previousResponseID, ...request } = input.request
const shape = input.continuation ?? ((fields: Readonly<Record<string, unknown>>) => fields)
let output: OpenResponses.StreamItem[] = []
return {
create: (checkpoint) =>
Effect.sync(() => {
output = []
const previous = checkpointValue(checkpoint)
const delta = previous ? incremental(request, previous) : undefined
if (!previous || !delta) return { message: ProviderShared.encodeJson(request), mode: "full" as const }
// Ask the route first: diffing the whole history is wasted when it declines the continuation.
const fields = previous ? shape(request) : undefined
const delta = previous && fields ? incremental(request, previous) : undefined
if (!previous || !fields || !delta)
return { message: ProviderShared.encodeJson(request), mode: "full" as const }
return {
message: ProviderShared.encodeJson({ ...request, input: delta, previous_response_id: previous.responseID }),
message: ProviderShared.encodeJson({ ...fields, input: delta, previous_response_id: previous.responseID }),
mode: "incremental" as const,
}
}),
observe: (create, frame) =>
Effect.gen(function* () {
const event = yield* decodeEvent(frame).pipe(
const event = yield* OpenResponses.decodeChannelEvent(frame).pipe(
Effect.mapError((cause) =>
ProviderShared.eventError(input.id, `Invalid ${input.name} WebSocket event`, frame, cause),
),
@@ -195,4 +205,4 @@ export const driver = (input: DriverInput): WebSocketChannelDriver => {
}
}
export const OpenResponsesContinuation = { driver } as const
export * as OpenResponsesContinuation from "./open-responses-continuation.js"
+32 -4
View File
@@ -1,4 +1,4 @@
import { Effect, Option, Schema } from "effect"
import { Effect, Option, Schema, SchemaGetter } from "effect"
import type { Content } from "@opencode/schema/tool"
import { HttpTransport } from "../route/transport/index.js"
import { Protocol } from "../route/protocol.js"
@@ -325,9 +325,8 @@ export const StreamItem = Schema.StructWithRest(
export type StreamItem = Schema.Schema.Type<typeof StreamItem>
export type OutputItem = StreamItem & { readonly id: string }
// The Responses schema puts streaming error details at the top level and
// response failures under `response.error`. WebSocket failures use an
// event-level `error` envelope, so accept all three shapes here.
// Responses-compatible providers put streaming error details at the top level or
// under `error`, and response failures under `response.error`. Accept all three shapes.
// https://www.openresponses.org/specification
const OpenResponsesErrorPayload = Schema.Struct({
type: optionalNull(Schema.String),
@@ -401,10 +400,39 @@ export const Event = Schema.StructWithRest(
headers: Schema.optional(Schema.Unknown),
}),
[Schema.Record(Schema.String, Schema.Unknown)],
).pipe(
Schema.decode({
decode: SchemaGetter.transform((event) => {
if (event.type !== "error" || event.error != null) return event
const { code, message, param, ...rest } = event
if (code === undefined && message === undefined && param === undefined) return event
// Flat errors (for example, Meta's) can also arrive through generic Responses endpoints.
return { ...rest, error: { code, message, param } }
}),
encode: SchemaGetter.passthrough(),
}),
)
export type Event = Schema.Schema.Type<typeof Event>
export type NormalizedEvent = Event & { readonly item?: OutputItem | null }
const decodeEventValue = Schema.decodeUnknownEffect(Event)
const decodeFrame = Schema.decodeUnknownEffect(ProviderShared.Json)
/**
* Decodes one WebSocket frame. xAI answers a rejected `response.create` with `{ "error": { "message", "type" } }` and no
* event type; that envelope reads as an error event so the failure classifies instead of failing decoding.
*/
export const decodeChannelEvent = (frame: string) =>
decodeFrame(frame).pipe(
Effect.flatMap((value) =>
decodeEventValue(
ProviderShared.isRecord(value) && value.type === undefined && ProviderShared.isRecord(value.error)
? { ...value, type: "error" }
: value,
),
),
)
export interface ProviderAdapter {
readonly id: string
readonly name: string
+4
View File
@@ -41,6 +41,10 @@ const responsesRoute = Route.make({
id: "openai-responses",
name: "xAI Responses",
rotateAfterMs: RESPONSES_WEBSOCKET_ROTATE_AFTER_MS,
// xAI continues a chain only from stored responses: with `store: false` (the route default) `previous_response_id`
// fails with "Response with id=… not found", so those steps are sent in full over the reused connection. It also
// rejects `instructions` next to `previous_response_id` and keeps the instructions of the response it continues.
continuation: ({ instructions: _instructions, ...request }) => (request.store === false ? undefined : request),
}),
defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } },
})
@@ -0,0 +1,78 @@
import { expect } from "bun:test"
import { Effect, Schema } from "effect"
import { LLM, LLMClient } from "../../src/index.js"
import { OpenResponses } from "../../src/protocols/open-responses.js"
import { Meta } from "../../src/providers/index.js"
import { configure } from "../../src/providers/openai-compatible-responses.js"
import { it } from "../lib/effect.js"
import { fixedResponse } from "../lib/http.js"
import { sseEvents } from "../lib/sse.js"
const decodeEvent = Schema.decodeUnknownEffect(OpenResponses.protocol.stream.event)
it.effect("normalizes flat errors in shared SSE and WebSocket decoding", () =>
Effect.gen(function* () {
const frame = {
type: "error",
sequence_number: 4,
code: "server_shutting_down",
message: "Server is shutting down. Please retry your request.",
param: null,
}
for (const decode of [decodeEvent, OpenResponses.decodeChannelEvent]) {
const event = yield* decode(JSON.stringify(frame))
expect(event).toEqual({
type: "error",
sequence_number: 4,
error: { code: frame.code, message: frame.message, param: null },
})
for (const unchanged of [
event,
{ type: "error" },
{
type: "response.failed",
response: { id: "resp_failed", error: { code: "server_error", message: "Internal server error" } },
},
{ type: "response.output_text.delta", item_id: "msg_text", delta: "Hello" },
]) {
expect(yield* decode(JSON.stringify(unchanged))).toEqual(unchanged)
}
}
}),
)
it.effect("continues to normalize untyped xAI WebSocket errors", () =>
Effect.gen(function* () {
const frame = { error: { type: "api_error", message: "gRPC error: Response with id=resp_missing not found" } }
expect(yield* OpenResponses.decodeChannelEvent(JSON.stringify(frame))).toEqual({ ...frame, type: "error" })
}),
)
it.effect("retains classification and original error bodies through Meta and generic Responses routes", () =>
Effect.gen(function* () {
const raw = `{
"type": "error",
"sequence_number": 4,
"code": "server_shutting_down",
"message": "Server is shutting down. Please retry your request.",
"param": null,
"diagnostic": "retain-original-frame"
}`
for (const model of [
Meta.configure({ apiKey: "fixture" }).responses("muse-spark-1.3"),
configure({ apiKey: "fixture", provider: "gateway", baseURL: "https://responses.example.test/v1" }).model(
"example-model",
),
]) {
const error = yield* LLMClient.generate(LLM.request({ model, prompt: "Hello" })).pipe(
Effect.provide(fixedResponse(sseEvents(raw.replaceAll("\n", "\ndata: ")))),
Effect.flip,
)
expect(error.reason._tag).toBe("ProviderInternal")
expect(error.message).toBe("server_shutting_down: Server is shutting down. Please retry your request.")
expect(error.reason.body).toBe(raw)
expect(error.reason.http?.status).toBe(200)
}
}),
)
@@ -90,7 +90,11 @@ const classifyingChannelDriver = (message: string): WebSocketChannelDriver => {
}
}
const continuationDriver = (request: Readonly<Record<string, unknown>>, base = baseChannelDriver) => {
const continuationDriver = (
request: Readonly<Record<string, unknown>>,
base = baseChannelDriver,
continuation?: OpenResponsesContinuation.Shape,
) => {
const message = ProviderShared.encodeJson(request)
return OpenResponsesContinuation.driver({
id: "openai-responses",
@@ -98,6 +102,7 @@ const continuationDriver = (request: Readonly<Record<string, unknown>>, base = b
request,
message,
base: base(message),
continuation,
})
}
@@ -921,6 +926,58 @@ describe("OpenAI Responses route", () => {
type: "provider-failure",
error: { reason: { _tag: "InvalidRequest", classification: "context-overflow" } },
})
// A retryable failure stays one: the runner retries it, and the transport has already dropped the
// checkpoint, so that retry is a full send. xAI reports every rejection this way.
const internal = ProviderShared.encodeJson({
type: "error",
error: { type: "api_error", message: "gRPC error: Response with id=resp_1 not found" },
})
expect(yield* second.observe(yield* second.create(saved), internal)).toMatchObject({
type: "provider-failure",
error: { reason: { _tag: "ProviderInternal" } },
})
}),
)
it.effect("shapes the incremental send with the route continuation", () =>
Effect.gen(function* () {
const firstRequest = {
type: "response.create",
model: "grok-4.6",
store: true,
instructions: "You are terse.",
input: [{ role: "user", content: [{ type: "input_text", text: "First" }] }],
}
const secondRequest = {
...firstRequest,
input: [...firstRequest.input, { role: "user", content: [{ type: "input_text", text: "Second" }] }],
}
const saved = checkpoint(
yield* continuationDriver(firstRequest).observe(
yield* continuationDriver(firstRequest).create(undefined),
ProviderShared.encodeJson({ type: "response.completed", response: { id: "resp_1" } }),
),
)
const trimmed = yield* continuationDriver(
secondRequest,
baseChannelDriver,
({ instructions: _, ...rest }) => rest,
).create(saved)
expect(trimmed.mode).toBe("incremental")
expect(JSON.parse(trimmed.message)).toEqual({
type: "response.create",
model: "grok-4.6",
store: true,
previous_response_id: "resp_1",
input: [{ role: "user", content: [{ type: "input_text", text: "Second" }] }],
})
// Declining the continuation sends the step in full and never sends a previous_response_id.
const declined = yield* continuationDriver(secondRequest, baseChannelDriver, () => undefined).create(saved)
expect(declined.mode).toBe("full")
expect(JSON.parse(declined.message)).toEqual(secondRequest)
}),
)
+110 -2
View File
@@ -1,11 +1,18 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { Effect, Layer, Stream } from "effect"
import { LLM, LLMEvent, Message } from "../../src/index.js"
import { XAI } from "../../src/providers.js"
import { OpenResponses } from "../../src/protocols/open-responses.js"
import { OpenAIResponses } from "../../src/protocols/openai-responses.js"
import * as ProviderShared from "../../src/protocols/shared.js"
import { XAIResponses } from "../../src/protocols/xai-responses.js"
import { LLMClient } from "../../src/route.js"
import {
LLMClient,
RequestExecutor,
WebSocketTransport,
type ChannelCheckpoint,
type WebSocketChannelDriver,
} from "../../src/route.js"
import { compileRequest } from "../../src/route/client.js"
import { it } from "../lib/effect.js"
import { fixedResponse } from "../lib/http.js"
@@ -13,6 +20,35 @@ import { sseEvents } from "../lib/sse.js"
const model = XAI.configure({ apiKey: "test", baseURL: "https://api.x.ai/v1" }).responses("grok-4.6")
/** Runs a request through the WebSocket transport and hands back its channel driver; the HTTP fallback answers. */
const channelDriver = (request: ReturnType<typeof LLM.request>) =>
Effect.gen(function* () {
let driver: WebSocketChannelDriver | undefined
yield* LLMClient.generate(request, {
webSocket: {
execute: (exchange) =>
Effect.sync(() => {
driver = exchange.driver
return { frames: exchange.fallback(), complete: Effect.void }
}),
},
}).pipe(Effect.provide(fixedResponse(sseEvents({ type: "response.completed", response: { id: "http" } }))))
if (!driver) throw new Error("Expected a WebSocket channel driver")
return driver
})
const completed = (driver: WebSocketChannelDriver, id: string) =>
Effect.gen(function* () {
const create = yield* driver.create(undefined)
yield* driver.observe(create, ProviderShared.encodeJson({ type: "response.created", response: { id } }))
const observation = yield* driver.observe(
create,
ProviderShared.encodeJson({ type: "response.completed", response: { id } }),
)
if (observation.type !== "completed" || !observation.checkpoint) throw new Error("Expected a checkpoint")
return observation.checkpoint
})
describe("xAI Responses route", () => {
it.effect("composes the Open Responses baseline with xAI extensions", () =>
Effect.gen(function* () {
@@ -162,6 +198,78 @@ describe("xAI Responses route", () => {
}),
)
it.effect("classifies xAI's untyped WebSocket error envelope", () =>
Effect.gen(function* () {
// xAI answers a rejected response.create with an error envelope that carries no event type.
const envelope = ProviderShared.encodeJson({
error: {
message:
'Request validation error: {"code":"400","error":"Argument not supported: instructions and previous_response_id together"}',
type: "api_error",
},
})
const webSocket = WebSocketTransport.makeDirect({
open: () =>
Effect.succeed({ sendText: () => Effect.void, messages: Stream.make(envelope), close: Effect.void }),
})
const error = yield* LLMClient.generate(LLM.request({ model, prompt: "Hello" }), { webSocket }).pipe(
Effect.provide(
LLMClient.layer.pipe(
Layer.provide(
Layer.succeed(
RequestExecutor.Service,
RequestExecutor.Service.of({ execute: () => Effect.die("unexpected HTTP request") }),
),
),
),
),
Effect.flip,
)
expect(error.reason._tag).toBe("ProviderInternal")
expect(error.message).toContain("Argument not supported: instructions and previous_response_id together")
expect(error.reason.body).toBe(envelope)
}),
)
it.effect("continues stored responses without instructions and sends unstored steps in full", () =>
Effect.gen(function* () {
const step = (store: boolean, ...prompts: string[]) =>
LLM.request({
model,
system: "You are terse.",
messages: prompts.map((prompt) => Message.user(prompt)),
providerOptions: { store },
})
const send = (store: boolean, checkpoint: ChannelCheckpoint) =>
channelDriver(step(store, "First", "Second")).pipe(Effect.flatMap((driver) => driver.create(checkpoint)))
const stored = yield* send(true, yield* completed(yield* channelDriver(step(true, "First")), "resp_1"))
expect(stored.mode).toBe("incremental")
expect(JSON.parse(stored.message)).toEqual({
type: "response.create",
model: "grok-4.6",
store: true,
include: ["reasoning.encrypted_content"],
previous_response_id: "resp_1",
input: [{ role: "user", content: [{ type: "input_text", text: "Second" }] }],
})
// The connection cache only serves stored responses, so the default store: false never chains.
const unstored = yield* send(false, yield* completed(yield* channelDriver(step(false, "First")), "resp_1"))
expect(unstored.mode).toBe("full")
expect(JSON.parse(unstored.message)).toMatchObject({
instructions: "You are terse.",
store: false,
input: [
{ role: "user", content: [{ type: "input_text", text: "First" }] },
{ role: "user", content: [{ type: "input_text", text: "Second" }] },
],
})
expect(JSON.parse(unstored.message).previous_response_id).toBeUndefined()
}),
)
it.effect("parses xAI hosted tool items", () =>
Effect.gen(function* () {
const item = { type: "x_search_call", id: "x_search_1", status: "completed", action: { query: "news" } }
@@ -122,7 +122,15 @@ test("renders compaction progress, summary, and outcome in order", async ({ page
)
await expect(compaction.getByRole("heading", { name: "Checkpoint" })).toBeVisible()
await expect(compaction).toContainText("Streamed implementation details.")
await expect(compaction.getByRole("status").getByLabel("Compacting", { exact: true })).toBeVisible()
const running = compaction.getByRole("status").getByLabel("Compacting", { exact: true })
await expect(running).toBeVisible()
await expect
.poll(async () => {
const summary = await compaction.locator('[data-component="text-part"]').boundingBox()
const status = await running.boundingBox()
return !!summary && !!status && status.y >= summary.y + summary.height
})
.toBe(true)
await expect(compaction.getByText("Session compacted", { exact: true })).toHaveCount(0)
await timeline.send(
+5 -10
View File
@@ -126,15 +126,9 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
if (command) {
clearSubmission(input, submission)
// Commands always steer: the server applies a command's configured
// agent and model immediately at admission, so queueing one would
// reconfigure the turn it is supposed to wait behind.
void sendCommand(
session,
{ ...value, delivery: "steer" },
command,
input.adapter.controls().model.selection.trackSessionCommit,
).catch((error) => failSubmission(input, session, "command", error, restore, value.id))
void sendCommand(session, value, command, input.adapter.controls().model.selection.trackSessionCommit).catch(
(error) => failSubmission(input, session, "command", error, restore, value.id),
)
return
}
} finally {
@@ -326,7 +320,8 @@ async function sendCommand(
track?: ModelSelection["trackSessionCommit"],
) {
const request = await buildSubmissionRequest(session, value)
await applySelection(session, value.selection, track)
// Like queued prompts, queued commands must not apply the composer's selection to active work.
if (value.delivery === "steer") await applySelection(session, value.selection, track)
await session.api.command({
sessionID: session.id,
command: command.command,
@@ -47,7 +47,7 @@ const handler = Effect.fn("cli.session.list")(function* (
null,
2,
)
: formatTable(page.data)) + EOL
: formatList(page.data)) + EOL
const write = Effect.tryPromise(
() =>
new Promise<void>((resolve, reject) => {
@@ -96,18 +96,14 @@ export default Runtime.handler(Commands.commands.session.commands.list, (input)
),
)
function formatTable(sessions: ReadonlyArray<SessionInfo>) {
const rows = sessions.map((session) => ({
id: session.id,
title: (session.title ?? "Untitled session").replace(/[\r\n\t]/g, " "),
updated: new Date(session.time.updated).toLocaleString(),
}))
const idWidth = Math.max(20, ...rows.map((row) => row.id.length))
const titleWidth = Math.max(25, ...rows.map((row) => row.title.length))
const header = `${"Session ID".padEnd(idWidth)} ${"Title".padEnd(titleWidth)} Updated`
return [
header,
"─".repeat(header.length),
...rows.map((row) => `${row.id.padEnd(idWidth)} ${row.title.padEnd(titleWidth)} ${row.updated}`),
].join(EOL)
function formatList(sessions: ReadonlyArray<SessionInfo>) {
return sessions
.map((session) =>
[
session.id,
(session.title ?? "Untitled session").replace(/[\r\n\t]/g, " "),
new Date(session.time.updated).toLocaleString(),
].join("\t"),
)
.join(EOL)
}
+19 -1
View File
@@ -11,6 +11,7 @@ import type { RelativePath } from "@opencode/schema/schema"
import type { Brand } from "effect"
import type { Model } from "@opencode/schema/model"
import type { DateTime } from "effect"
import type { Permission } from "@opencode/schema/permission"
import type { SessionMessage } from "@opencode/schema/session-message"
import type { SessionInbox } from "@opencode/schema/session-inbox"
import type { PromptInput } from "@opencode/schema/prompt-input"
@@ -26,7 +27,6 @@ import type { Integration } from "@opencode/schema/integration"
import type { Form } from "@opencode/schema/form"
import type { Mcp } from "@opencode/schema/mcp"
import type { Credential } from "@opencode/schema/credential"
import type { Permission } from "@opencode/schema/permission"
import type { PermissionSaved } from "@opencode/schema/permission-saved"
import type { FileSystem } from "@opencode/schema/filesystem"
import type { Command } from "@opencode/schema/command"
@@ -209,6 +209,7 @@ export type SessionCreateInput = {
readonly model?: Model.Ref | undefined
readonly location?: Location.Ref | undefined
readonly metadata?: Session.Metadata | undefined
readonly permissions?: Permission.Ruleset | undefined
}
export type SessionCreateOutput = Session.Info
export type SessionCreateOperation<E = never> = (input?: SessionCreateInput) => Effect.Effect<SessionCreateOutput, E>
@@ -437,6 +438,7 @@ export type SessionLogOutput =
readonly agent?: Agent.ID | undefined
readonly model?: Model.Ref | undefined
readonly metadata?: Session.Metadata | undefined
readonly permissions?: Permission.Ruleset | undefined
readonly version: string
}
}
@@ -489,6 +491,15 @@ export type SessionLogOutput =
readonly location?: Location.Ref | undefined
readonly data: { readonly sessionID: Session.ID; readonly title: string }
}
| {
readonly id: Event.ID
readonly created: number
readonly metadata?: { readonly [x: string]: unknown } | undefined
readonly type: "session.permissions.updated"
readonly durable: { readonly aggregateID: string; readonly seq: Event.Seq; readonly version: Event.Version }
readonly location?: Location.Ref | undefined
readonly data: { readonly sessionID: Session.ID; readonly permissions: Permission.Ruleset }
}
| {
readonly id: Event.ID
readonly created: number
@@ -1585,6 +1596,12 @@ export type PermissionReplyOperation<E = never> = (
input: PermissionReplyInput,
) => Effect.Effect<PermissionReplyOutput, E>
export type PermissionRulesInput = { readonly sessionID: Session.ID; readonly permissions: Permission.Ruleset }
export type PermissionRulesOutput = void
export type PermissionRulesOperation<E = never> = (
input: PermissionRulesInput,
) => Effect.Effect<PermissionRulesOutput, E>
export interface PermissionApi<E = never> {
readonly request: { readonly list: PermissionRequestListOperation<E> }
readonly saved: { readonly list: PermissionSavedListOperation<E>; readonly remove: PermissionSavedRemoveOperation<E> }
@@ -1592,6 +1609,7 @@ export interface PermissionApi<E = never> {
readonly list: PermissionListOperation<E>
readonly get: PermissionGetOperation<E>
readonly reply: PermissionReplyOperation<E>
readonly rules: PermissionRulesOperation<E>
}
export type FileListInput = {
@@ -181,6 +181,8 @@ import type {
PermissionGetOutput,
PermissionReplyInput,
PermissionReplyOutput,
PermissionRulesInput,
PermissionRulesOutput,
FileListInput,
FileListOutput,
FileFindInput,
@@ -395,6 +397,7 @@ const EndpointSessionCreate = (raw: RawClient["server.session"]) => (input?: Ses
model: input?.["model"],
location: input?.["location"],
metadata: input?.["metadata"],
permissions: input?.["permissions"],
},
}).pipe(
Effect.mapError(mapClientError),
@@ -1145,6 +1148,14 @@ const EndpointPermissionReply = (raw: RawClient["server.permission"]) => (input:
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointPermissionRules = (raw: RawClient["server.permission"]) => (input: PermissionRulesInput) =>
preserveEffect<PermissionRulesOutput>()(
raw["session.permission.rules"]({
params: { sessionID: input["sessionID"] },
payload: { permissions: input["permissions"] },
}).pipe(Effect.mapError(mapClientError)),
)
const adaptGroupPermission = (raw: RawClient["server.permission"]) => ({
request: { list: EndpointPermissionRequestList(raw) },
saved: { list: EndpointPermissionSavedList(raw), remove: EndpointPermissionSavedRemove(raw) },
@@ -1152,6 +1163,7 @@ const adaptGroupPermission = (raw: RawClient["server.permission"]) => ({
list: EndpointPermissionList(raw),
get: EndpointPermissionGet(raw),
reply: EndpointPermissionReply(raw),
rules: EndpointPermissionRules(raw),
})
const EndpointFileList = (raw: RawClient["server.fs"]) => (input?: FileListInput) =>
@@ -175,6 +175,8 @@ import type {
PermissionGetOutput,
PermissionReplyInput,
PermissionReplyOutput,
PermissionRulesInput,
PermissionRulesOutput,
FileReadInput,
FileReadOutput,
FileListInput,
@@ -565,6 +567,7 @@ export function make(options: ClientOptions) {
model: input?.["model"],
location: input?.["location"],
metadata: input?.["metadata"],
permissions: input?.["permissions"],
},
successStatus: 200,
declaredStatuses: [400, 401],
@@ -1566,6 +1569,18 @@ export function make(options: ClientOptions) {
},
requestOptions,
),
rules: (input: PermissionRulesInput, requestOptions?: RequestOptions) =>
request<PermissionRulesOutput>(
{
method: "PUT",
path: `/api/session/${encodeURIComponent(input.sessionID)}/permission/rules`,
body: { permissions: input["permissions"] },
successStatus: 204,
declaredStatuses: [400, 401, 404],
empty: true,
},
requestOptions,
),
},
file: {
read: (input: FileReadInput, requestOptions?: RequestOptions) =>
+127 -42
View File
@@ -551,28 +551,6 @@ export type InstructionEntryInfo = { key: InstructionEntryKey; value: JsonValue
export type InstructionEntrySnapshot = Array<{ key: InstructionEntryKey; value: JsonValue; removed: boolean }>
export type SessionCreated = {
id: string
created: number
metadata?: { [x: string]: any }
type: "session.created"
durable: { aggregateID: string; seq: number; version: 1 }
location?: LocationRef
data: {
sessionID: string
projectID: string
location: LocationRef
subpath?: string
parentID?: string
slug: string
title?: string
agent?: string
model?: ModelRef
metadata?: SessionMetadata
version: string
}
}
export type SessionAgentSelected = {
id: string
created: number
@@ -1651,24 +1629,6 @@ export type SessionInboxMove = {
delivery: SessionInboxDelivery
}
export type SessionInfo = {
id: string
parentID?: string
fork?: { sessionID: string; boundary: SessionForkBoundary }
projectID: string
agent?: string
model?: ModelRef
cost: MoneyUSD
tokens: TokenUsageInfo
outcome?: "succeeded" | "failed" | "interrupted"
time: { created: number; updated: number; idle?: number; viewed?: number; archived?: number }
title?: string
location: LocationRef
subpath?: string
metadata?: SessionMetadata
revert?: SessionRevert
}
export type SessionRevertStaged = {
id: string
created: number
@@ -1912,6 +1872,58 @@ export type AgentInfo = {
permissions: PermissionRuleset
}
export type SessionPermissionsUpdated = {
id: string
created: number
metadata?: { [x: string]: any }
type: "session.permissions.updated"
durable: { aggregateID: string; seq: number; version: 1 }
location?: LocationRef
data: { sessionID: string; permissions: PermissionRuleset }
}
export type SessionInfo = {
id: string
parentID?: string
fork?: { sessionID: string; boundary: SessionForkBoundary }
projectID: string
agent?: string
model?: ModelRef
cost: MoneyUSD
tokens: TokenUsageInfo
outcome?: "succeeded" | "failed" | "interrupted"
time: { created: number; updated: number; idle?: number; viewed?: number; archived?: number }
title?: string
location: LocationRef
subpath?: string
metadata?: SessionMetadata
permissions?: PermissionRuleset
revert?: SessionRevert
}
export type SessionCreated = {
id: string
created: number
metadata?: { [x: string]: any }
type: "session.created"
durable: { aggregateID: string; seq: number; version: 1 }
location?: LocationRef
data: {
sessionID: string
projectID: string
location: LocationRef
subpath?: string
parentID?: string
slug: string
title?: string
agent?: string
model?: ModelRef
metadata?: SessionMetadata
permissions?: PermissionRuleset
version: string
}
}
export type ConfigEntry =
| {
type: "document"
@@ -2084,8 +2096,6 @@ export type ConfigEntry =
| { type: "agents"; path: string }
| { type: "claude"; path: string }
export type SessionsResponse = { data: Array<SessionInfo>; cursor: { previous?: string | null; next?: string | null } }
export type SessionInboxUser = {
id: string
sessionID: string
@@ -2140,6 +2150,8 @@ export type FormFields = [FormField, ...Array<FormField>]
export type FormFields2 = [FormField1, ...Array<FormField1>]
export type SessionsResponse = { data: Array<SessionInfo>; cursor: { previous?: string | null; next?: string | null } }
export type SessionInboxInfo = SessionInboxUser | SessionInboxSynthetic | SessionInboxCompaction | SessionInboxMove
export type SessionInboxEnqueued = {
@@ -2233,6 +2245,7 @@ export type SessionEventDurable =
| SessionModelSelected
| SessionMoved
| SessionRenamed
| SessionPermissionsUpdated
| SessionViewed
| SessionDeleted
| SessionForked
@@ -2292,6 +2305,7 @@ export type V2Event =
| SessionModelSelected
| SessionMoved
| SessionRenamed
| SessionPermissionsUpdated
| SessionViewed
| SessionUsageUpdated
| SessionDeleted
@@ -2804,6 +2818,11 @@ export type SessionCreateInput = {
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
readonly location?: { readonly directory: string; readonly workspaceID?: string } | null
readonly metadata?: { readonly [x: string]: JsonValue } | null
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}> | null
}["id"]
readonly title?: {
readonly id?: string | null
@@ -2812,6 +2831,11 @@ export type SessionCreateInput = {
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
readonly location?: { readonly directory: string; readonly workspaceID?: string } | null
readonly metadata?: { readonly [x: string]: JsonValue } | null
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}> | null
}["title"]
readonly agent?: {
readonly id?: string | null
@@ -2820,6 +2844,11 @@ export type SessionCreateInput = {
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
readonly location?: { readonly directory: string; readonly workspaceID?: string } | null
readonly metadata?: { readonly [x: string]: JsonValue } | null
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}> | null
}["agent"]
readonly model?: {
readonly id?: string | null
@@ -2828,6 +2857,11 @@ export type SessionCreateInput = {
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
readonly location?: { readonly directory: string; readonly workspaceID?: string } | null
readonly metadata?: { readonly [x: string]: JsonValue } | null
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}> | null
}["model"]
readonly location?: {
readonly id?: string | null
@@ -2836,6 +2870,11 @@ export type SessionCreateInput = {
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
readonly location?: { readonly directory: string; readonly workspaceID?: string } | null
readonly metadata?: { readonly [x: string]: JsonValue } | null
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}> | null
}["location"]
readonly metadata?: {
readonly id?: string | null
@@ -2844,7 +2883,25 @@ export type SessionCreateInput = {
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
readonly location?: { readonly directory: string; readonly workspaceID?: string } | null
readonly metadata?: { readonly [x: string]: JsonValue } | null
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}> | null
}["metadata"]
readonly permissions?: {
readonly id?: string | null
readonly title?: string | null
readonly agent?: string | null
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
readonly location?: { readonly directory: string; readonly workspaceID?: string } | null
readonly metadata?: { readonly [x: string]: JsonValue } | null
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}> | null
}["permissions"]
}
export type SessionCreateOutput = { data: SessionInfo }["data"]
@@ -2882,6 +2939,11 @@ export type SessionImportInput = {
readonly location: { readonly directory: string; readonly workspaceID?: string }
readonly subpath?: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}>
readonly revert?: {
readonly messageID: string
readonly partID?: string
@@ -3187,6 +3249,11 @@ export type SessionImportInput = {
readonly location: { readonly directory: string; readonly workspaceID?: string }
readonly subpath?: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}>
readonly revert?: {
readonly messageID: string
readonly partID?: string
@@ -3492,6 +3559,11 @@ export type SessionImportInput = {
readonly location: { readonly directory: string; readonly workspaceID?: string }
readonly subpath?: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly permissions?: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}>
readonly revert?: {
readonly messageID: string
readonly partID?: string
@@ -5753,6 +5825,19 @@ export type PermissionReplyInput = {
export type PermissionReplyOutput = void
export type PermissionRulesInput = {
readonly sessionID: { readonly sessionID: string }["sessionID"]
readonly permissions: {
readonly permissions: ReadonlyArray<{
readonly action: string
readonly resource: string
readonly effect: "allow" | "deny" | "ask"
}>
}["permissions"]
}
export type PermissionRulesOutput = void
export type FileReadInput = {
readonly location?: {
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
+4
View File
@@ -695,6 +695,10 @@ export function createData(config: CreateDataInput) {
})
return
}
case "session.permissions.updated":
if (store.session.info[event.data.sessionID])
setStore("session", "info", event.data.sessionID, "permissions", event.data.permissions)
return
case "session.moved": {
const current = store.session.info[event.data.sessionID]
if (current) {
+16 -2
View File
@@ -8,6 +8,7 @@ import { Provider } from "./provider.js"
import { Bus } from "./bus.js"
import { State } from "./state.js"
import { Integration } from "./integration.js"
import { ProviderPolicy } from "./provider-policy.js"
export type ProviderRecord = {
provider: Provider.MutableInfo
@@ -63,6 +64,7 @@ const layer = Layer.effect(
Effect.gen(function* () {
const bus = yield* Bus.Service
const integrations = yield* Integration.Service
const policies = yield* ProviderPolicy.Service
const available = (provider: Provider.Info, integration: Integration.Info | undefined) => {
if (provider.activation === "disabled") return false
@@ -146,11 +148,15 @@ const layer = Layer.effect(
provider: {
get: Effect.fn("Catalog.provider.get")(function* (providerID) {
if (!ProviderPolicy.allows(yield* policies.read(), providerID)) return
return state.get().providers.get(providerID)?.provider
}),
all: Effect.fn("Catalog.provider.all")(function* () {
return Array.fromIterable(state.get().providers.values()).map((record) => record.provider)
const policy = yield* policies.read()
return Array.fromIterable(state.get().providers.values())
.map((record) => record.provider)
.filter((provider) => ProviderPolicy.allows(policy, provider.id))
}),
available: Effect.fn("Catalog.provider.available")(function* () {
@@ -163,6 +169,7 @@ const layer = Layer.effect(
model: {
get: Effect.fn("Catalog.model.get")(function* (providerID, modelID) {
if (!ProviderPolicy.allows(yield* policies.read(), providerID)) return
const record = state.get().providers.get(providerID)
if (!record) return
const model = record.models.get(modelID)
@@ -170,8 +177,10 @@ const layer = Layer.effect(
}),
all: Effect.fn("Catalog.model.all")(function* () {
const policy = yield* policies.read()
return pipe(
Array.fromIterable(state.get().providers.values()),
Array.filter((record) => ProviderPolicy.allows(policy, record.provider.id)),
Array.flatMap((record) => {
return Array.fromIterable(record.models.values()).map((model) => projectModel(model, record.provider))
}),
@@ -209,6 +218,7 @@ const layer = Layer.effect(
}),
small: Effect.fn("Catalog.model.small")(function* (providerID) {
if (!ProviderPolicy.allows(yield* policies.read(), providerID)) return
const record = state.get().providers.get(providerID)
if (!record) return
const models = pipe(
@@ -237,4 +247,8 @@ const layer = Layer.effect(
const SMALL_MODEL_FAMILY_PRIORITY = ["gpt-luna", "gemini-flash-lite", "gemini-flash", "claude-haiku"]
export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node, Integration.node] })
export const node = makeLocationNode({
service: Service,
layer,
deps: [Bus.node, Integration.node, ProviderPolicy.node],
})
-27
View File
@@ -1,27 +0,0 @@
export * as ConfigPolicyPlugin from "./policy.js"
import { define } from "@opencode/plugin/effect/plugin"
import { Document } from "@opencode/schema/config"
import { Effect } from "effect"
import { Config } from "../../config.js"
import { Wildcard } from "../../util/wildcard.js"
import { ConfigEntryObserver } from "./entry-observer.js"
export const Plugin = define({
id: "opencode.config.policy",
effect: Effect.fn(function* (ctx) {
const config = yield* Config.Service
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.catalog.reload())
yield* ctx.catalog.transform((catalog) => {
// User-global policy takes priority over policy authored by a repository.
const policies = loaded.entries
.filter((entry): entry is Document => entry.type === "document")
.toReversed()
.flatMap((entry) => entry.info.experimental?.policies ?? [])
for (const record of catalog.provider.list()) {
const policy = policies.findLast((policy) => Wildcard.match(record.provider.id, policy.resource))
if (policy?.effect === "deny") catalog.provider.remove(record.provider.id)
}
})
}),
})
+2
View File
@@ -45,6 +45,7 @@ import m42 from "./migration/20260812181746_session_inbox.js"
import m43 from "./migration/20260812213948_worktree.js"
import m44 from "./migration/20260819222447_session_viewed_state.js"
import m45 from "./migration/20260823191254_nullable_workspace_binding.js"
import m46 from "./migration/20260910120000_clear_v1_session_permission.js"
export const migrations = [
m00,
@@ -93,4 +94,5 @@ export const migrations = [
m43,
m44,
m45,
m46,
] satisfies DatabaseMigration.Migration[]
@@ -0,0 +1,13 @@
import { Effect } from "effect"
import type { DatabaseMigration } from "../migration.js"
const migration: DatabaseMigration.Migration = {
id: "20260910120000_clear_v1_session_permission",
up(tx) {
return Effect.gen(function* () {
yield* tx.run(`UPDATE \`session_v2\` SET \`permission\` = NULL;`)
})
},
}
export default migration
@@ -600,7 +600,7 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
id, ${projectID}, workspace_id, parent_id, slug, directory, path, title, version, share_url,
summary_additions, summary_deletions, summary_files, summary_diffs, metadata, cost,
tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write,
revert, permission, agent, model, time_created, time_updated, time_compacting, time_archived
revert, NULL, agent, model, time_created, time_updated, time_compacting, time_archived
FROM session
WHERE id = ${nextID.id}
`)
+4
View File
@@ -72,6 +72,10 @@ export const layer = Layer.effect(
const text: Interface["text"] = (input) =>
runText(input).pipe(
Effect.catchTag(
["ProviderPolicy.Unavailable", "ProviderPolicy.Denied"],
(error) => new UnavailableError({ message: error.message }),
),
Effect.catchTag(
"Integration.Authorization",
() =>
+7 -1
View File
@@ -12,6 +12,7 @@ import { Integration } from "./integration.js"
import { Capabilities, ID, Info, Ref, VariantID } from "./model.js"
import { Npm } from "@opencode/util/npm"
import { Provider } from "./provider.js"
import { ProviderPolicy } from "./provider-policy.js"
export class VariantUnavailableError extends Schema.TaggedError<VariantUnavailableError>()(
"SessionRunnerModel.VariantUnavailableError",
@@ -66,6 +67,8 @@ export class UnsupportedCompactionError extends Schema.TaggedError<UnsupportedCo
}
export type Error =
| ProviderPolicy.Unavailable
| ProviderPolicy.Denied
| VariantUnavailableError
| UnsupportedPackageError
| UnresolvedProviderVariablesError
@@ -291,10 +294,12 @@ export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const policies = yield* ProviderPolicy.Service
const integrations = yield* Integration.Service
const npm = yield* Npm.Service
const aisdk = yield* AISDK.Service
const load = Effect.fn("ModelResolver.resolveModel")(function* (selected: Info, variant?: VariantID) {
yield* policies.assert(selected.providerID)
const provider = yield* catalog.provider.get(selected.providerID)
const connection = yield* integrations.connection.active(
provider?.integrationID ?? Integration.ID.make(selected.providerID),
@@ -328,6 +333,7 @@ export const layer = Layer.effect(
})
return Service.of({
resolve: Effect.fn("ModelResolver.resolve")(function* (requested) {
yield* policies.assert(requested?.providerID)
const selected = requested
? yield* catalog.model.get(requested.providerID, requested.id)
: yield* catalog.model
@@ -394,5 +400,5 @@ function usesAPIKeyAuth(packageName: string | undefined) {
export const node = makeLocationNode({
service: Service,
layer,
deps: [Catalog.node, Integration.node, Npm.node, AISDK.node],
deps: [Catalog.node, Integration.node, Npm.node, AISDK.node, ProviderPolicy.node],
})
+1 -1
View File
@@ -154,7 +154,7 @@ const layer = Layer.effect(
const session = yield* sessions.get(sessionID)
if (!session) return yield* new SessionErrors.NotFoundError({ sessionID })
const agent = yield* agents.resolve(agentID ?? session.agent)
return agent?.permissions ?? missingAgentPermissions
return merge(agent?.permissions ?? missingAgentPermissions, session.permissions ?? [])
})
function denied(input: Pick<Request, "action" | "resources">, rules: Permission.Ruleset) {
+3
View File
@@ -404,6 +404,7 @@ export const make = Effect.fn("PluginHost.make")(function* (
: Effect.fail(new Error(`Permission request not found: ${input.requestID}`)),
),
),
rules: sessions.setPermissions,
},
plugin: {
list: () => response(plugin.list()),
@@ -509,6 +510,8 @@ export const make = Effect.fn("PluginHost.make")(function* (
title: input?.title,
agent: input?.agent,
model: input?.model,
metadata: input?.metadata,
permissions: input?.permissions,
location:
input?.location ?? Location.Ref.make({ directory: location.directory, workspaceID: location.workspaceID }),
}),
+3 -2
View File
@@ -20,7 +20,7 @@ import { ConfigInstructionPlugin } from "../config/plugin/instruction.js"
import { ConfigLocationWatcherPlugin } from "../config/plugin/location-watcher.js"
import { ConfigMcpPlugin } from "../config/plugin/mcp.js"
import { ConfigProviderPlugin } from "../config/plugin/provider.js"
import { ConfigPolicyPlugin } from "../config/plugin/policy.js"
import { ProviderPolicy } from "../provider-policy.js"
import { ConfigReferencePlugin } from "../config/plugin/reference.js"
import { ConfigShellPlugin } from "../config/plugin/shell.js"
import { ConfigSnapshotPlugin } from "../config/plugin/snapshot.js"
@@ -98,6 +98,7 @@ const services = [
Agent.Service,
AppProcess.Service,
Catalog.Service,
ProviderPolicy.Service,
Command.Service,
Config.Service,
Credential.Service,
@@ -147,6 +148,7 @@ export const requirements = LayerNode.group([
Agent.node,
AppProcess.node,
Catalog.node,
ProviderPolicy.node,
Command.node,
Config.node,
Credential.node,
@@ -241,7 +243,6 @@ const post = [
ConfigWebSearchPlugin.Plugin,
ConfigWorktreePlugin.Plugin,
VariantPlugin.Plugin,
ConfigPolicyPlugin.Plugin,
] as const satisfies readonly InternalPlugin[]
export const list = Effect.fn("PluginInternal.list")(function* () {
+85 -11
View File
@@ -10,6 +10,8 @@ import { Provider } from "../../provider.js"
import { WebSearch } from "../../websearch.js"
import { ConfigProvider } from "@opencode/schema/config/provider"
import { Money } from "@opencode/schema/money"
import { ConfigPolicy } from "@opencode/schema/config/policy"
import { ProviderPolicy } from "../../provider-policy.js"
const defaultServer = "https://opencode.ai/console"
const clientID = "opencode-cli"
@@ -19,7 +21,27 @@ const RemoteResponse = Schema.Struct({
websearch: Schema.Struct({
providerID: WebSearch.ID,
}).pipe(Schema.optional),
experimental: Schema.Unknown,
managedPolicy: Schema.Unknown,
})
const RemotePolicy = Schema.Struct({
experimental: Schema.Struct({
policies: Schema.Array(ConfigPolicy.Info).check(
Schema.makeFilter((statements) =>
statements.every(
(statement) =>
statement.resource.length > 0 &&
statement.resource.length <= 256 &&
statement.resource.trim() === statement.resource,
),
),
),
}),
managedPolicy: ProviderPolicy.Descriptor,
})
class RemoteFailure extends Schema.TaggedError<RemoteFailure>()("OpenCode.RemoteConfigFailure", {
transient: Schema.Boolean,
}) {}
const Device = Schema.Struct({
device_code: Schema.String,
user_code: Schema.String,
@@ -102,31 +124,41 @@ function oauth(http: HttpClient.HttpClient) {
} satisfies IntegrationOAuthMethodRegistration
}
export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope.Scope>({
export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | ProviderPolicy.Service | Scope.Scope>({
id: "opencode.provider.opencode",
effect: Effect.fn(function* (ctx) {
const bus = yield* Bus.Service
const http = yield* HttpClient.HttpClient
const policies = yield* ProviderPolicy.Service
const loading = Semaphore.makeUnsafe(1)
type ActiveConnection = Effect.Success<ReturnType<typeof ctx.integration.connection.active>>
let snapshot: {
config: typeof RemoteResponse.Type | undefined
config: Effect.Success<ReturnType<typeof fetchConfig>> | undefined
connection: ActiveConnection
} = { config: undefined, connection: undefined }
identity?: string
stale: boolean
} = { config: undefined, connection: undefined, stale: false }
const load = Effect.fn("OpencodePlugin.load")(function* () {
const connection = yield* ctx.integration.connection.active("opencode")
const credential = connection
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.orElseSucceed(() => undefined))
: undefined
const identity = connection && credential ? ProviderPolicy.identity(connection, credential) : undefined
const config = credential
? yield* fetchConfig(http, credential).pipe(
Effect.catch((cause) =>
Effect.logWarning("failed to load OpenCode provider config", { cause }).pipe(Effect.as(undefined)),
Effect.logWarning("Failed to load workspace provider policy", { transient: cause.transient }).pipe(
Effect.as(
cause.transient && identity !== undefined && snapshot.identity === identity && snapshot.config
? { ...snapshot.config, stale: true }
: undefined,
),
),
),
)
: undefined
return { config, connection }
return { config, connection, identity, stale: config?.stale ?? false }
})
yield* ctx.integration.transform((editor) => {
@@ -138,6 +170,16 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope
})
snapshot = yield* load()
yield* policies.set(
snapshot.config && snapshot.identity
? {
identity: snapshot.identity,
descriptor: snapshot.config.managedPolicy,
statements: snapshot.config.experimental.policies,
stale: snapshot.stale,
}
: undefined,
)
yield* ctx.catalog.transform((catalog) => {
for (const [providerID, item] of Object.entries(snapshot.config?.providers ?? {})) {
const source = catalog.provider.get(item.canonical ?? providerID)
@@ -284,6 +326,16 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope
const apply = Effect.fn("OpencodePlugin.apply")(function* (next: typeof snapshot) {
snapshot = next
yield* policies.set(
next.config && next.identity
? {
identity: next.identity,
descriptor: next.config.managedPolicy,
statements: next.config.experimental.policies,
stale: next.stale,
}
: undefined,
)
yield* Effect.all([ctx.catalog.reload(), ctx.websearch.reload()], { concurrency: 2, discard: true })
})
const refresh = () => loading.withPermit(load().pipe(Effect.andThen(apply)))
@@ -307,27 +359,49 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope
}),
})
function fetchConfig(http: HttpClient.HttpClient, value: Credential.Value) {
const fetchConfig = Effect.fn("OpenCode.fetchConfig")(function* (http: HttpClient.HttpClient, value: Credential.Value) {
const metadata = value.metadata
const orgID = typeof metadata?.orgID === "string" ? metadata.orgID : undefined
const token = value.type === "oauth" ? value.access : value.key
return http
const server = yield* normalizeServer(serverUrl(value)).pipe(
Effect.mapError(() => new RemoteFailure({ transient: false })),
)
return yield* http
.execute(
HttpClientRequest.get(`${serverUrl(value)}/api/v2/config`).pipe(
HttpClientRequest.get(`${server}/api/v2/config`).pipe(
HttpClientRequest.acceptJson,
HttpClientRequest.bearerToken(token),
HttpClientRequest.setHeaders(orgID ? { "x-org-id": orgID } : {}),
),
)
.pipe(
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
Effect.mapError(() => new RemoteFailure({ transient: true })),
Effect.flatMap((response) => {
if (response.status === 404) return Effect.undefined
return HttpClientResponse.filterStatusOk(response).pipe(
if (response.status < 200 || response.status >= 300)
return Effect.fail(new RemoteFailure({ transient: response.status >= 500 || response.status === 429 }))
return Effect.succeed(response).pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(RemoteResponse)),
Effect.flatMap((config) =>
Schema.decodeUnknownEffect(RemotePolicy, { onExcessProperty: "error" })({
experimental: config.experimental,
managedPolicy: config.managedPolicy,
}).pipe(Effect.map((policy) => ({ ...config, ...policy, stale: false }))),
),
Effect.flatMap((config) =>
orgID !== undefined && config.managedPolicy.workspaceID !== orgID
? Effect.fail(new RemoteFailure({ transient: false }))
: Effect.succeed(config),
),
Effect.mapError(() => new RemoteFailure({ transient: false })),
)
}),
Effect.timeoutOrElse({
duration: Duration.seconds(20),
orElse: () => Effect.fail(new RemoteFailure({ transient: true })),
}),
)
}
})
function serverUrl(value: Credential.Value) {
return typeof value.metadata?.server === "string" ? value.metadata.server : defaultServer
+1
View File
@@ -101,6 +101,7 @@ export const XAIPlugin = define({
for (const model of provider.models.values()) {
catalog.model.update(providerID, model.id, (draft) => {
draft.capabilities.responsesWebsockets = true
draft.websocket = true
})
}
})
+3
View File
@@ -88,6 +88,9 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
enabled.add(plugin.id)
}
// Console's connected-workspace policy source cannot be removed by authored
// plugin directives. Its final enforcement lives outside the plugin registry.
if (pre.some((plugin) => plugin.id === "opencode.provider.opencode")) enabled.add("opencode.provider.opencode")
const ordered = [
...pre.filter((plugin) => enabled.has(plugin.id)),
...[...packages.values()].filter((plugin) => enabled.has(plugin.id)),
+125
View File
@@ -0,0 +1,125 @@
export * as ProviderPolicy from "./provider-policy.js"
import { ConfigPolicy } from "@opencode/schema/config/policy"
import { Event } from "@opencode/schema/config"
import { Catalog } from "@opencode/schema/catalog"
import { ProviderPolicyMatcher } from "@opencode/util/opencode-policy-matcher"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import { Context, Effect, Layer, Schema, Stream } from "effect"
import { Bus } from "./bus.js"
import { Config } from "./config.js"
import { Credential } from "./credential.js"
import { Integration } from "./integration.js"
import { IntegrationConnection } from "./integration/connection.js"
export class Unavailable extends Schema.TaggedError<Unavailable>()("ProviderPolicy.Unavailable", {}) {
override get message() {
return "Workspace policy unavailable. Reconnect to OpenCode Console and try again."
}
}
export class Denied extends Schema.TaggedError<Denied>()("ProviderPolicy.Denied", { providerID: Schema.String }) {
override get message() {
return `Provider ${this.providerID} is denied by your OpenCode provider policy.`
}
}
export const Descriptor = Schema.Struct({
schemaVersion: Schema.Literal(1),
workspaceID: Schema.String.check(Schema.isNonEmpty()),
revision: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
})
export type Managed = {
readonly identity: string
readonly descriptor: typeof Descriptor.Type
readonly statements: readonly ConfigPolicy.Info[]
readonly stale: boolean
}
export type Snapshot = {
readonly status: "disconnected" | "ready" | "stale" | "unavailable"
readonly statements: readonly ConfigPolicy.Info[]
readonly workspaceID?: string
readonly revision?: number
}
export interface Interface {
readonly read: () => Effect.Effect<Snapshot>
readonly set: (value: Managed | undefined) => Effect.Effect<void>
readonly assert: (providerID?: string) => Effect.Effect<void, Unavailable | Denied>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/ProviderPolicy") {}
// Internal connection binding; this value can contain a service key and must never be logged or exposed.
export function identity(
connection: Pick<IntegrationConnection.Info, "type"> & { readonly id?: string; readonly name?: string },
credential: Credential.Value,
) {
return JSON.stringify([
connection.type,
connection.id ?? connection.name,
credential.metadata?.server ?? "https://opencode.ai/console",
credential.metadata?.orgID,
credential.type === "key" ? credential.key : undefined,
])
}
export function allows(snapshot: Snapshot, providerID: string) {
return (
snapshot.status !== "unavailable" &&
ProviderPolicyMatcher.evaluate(snapshot.statements, providerID, process.platform === "win32").effect !== "deny"
)
}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service
const integrations = yield* Integration.Service
const credentials = yield* Credential.Service
const bus = yield* Bus.Service
let managed: Managed | undefined
const read = Effect.fn("ProviderPolicy.read")(function* () {
const statements = (yield* config.entries())
.filter((entry) => entry.type === "document")
.toReversed()
.flatMap((entry) => entry.info.experimental?.policies ?? [])
const connection = yield* integrations.connection.active(Integration.ID.make("opencode"))
if (!connection) return { status: "disconnected", statements } as const
const credential =
connection.type === "credential"
? (yield* credentials.get(connection.id))?.value
: process.env[connection.name]
? Credential.Key.make({ type: "key", key: process.env[connection.name]! })
: undefined
if (!credential || !managed || managed.identity !== identity(connection, credential))
return { status: "unavailable", statements } as const
return {
status: managed.stale ? "stale" : "ready",
statements: [...statements, ...managed.statements],
workspaceID: managed.descriptor.workspaceID,
revision: managed.descriptor.revision,
} as const
})
yield* bus.subscribe(Event.Updated).pipe(
Stream.runForEach(() => bus.publish(Catalog.Event.Updated, {})),
Effect.forkScoped({ startImmediately: true }),
)
return Service.of({
read,
set: (value) =>
Effect.sync(() => {
managed = value
}),
assert: Effect.fn("ProviderPolicy.assert")(function* (providerID) {
const snapshot = yield* read()
if (snapshot.status === "unavailable") return yield* new Unavailable()
if (providerID !== undefined && !allows(snapshot, providerID)) return yield* new Denied({ providerID })
}),
})
}),
)
export const node = makeLocationNode({
service: Service,
layer,
deps: [Config.node, Integration.node, Credential.node, Bus.node],
})
+10 -2
View File
@@ -18,6 +18,7 @@ import { SessionMessageTable } from "./session/sql.js"
import { SessionSchema } from "./session/schema.js"
import { RelativePath } from "./schema.js"
import { Agent } from "@opencode/schema/agent"
import type { Permission } from "@opencode/schema/permission"
import { App } from "./app.js"
import { Slug } from "./util/slug.js"
import path from "path"
@@ -81,6 +82,7 @@ type CreateBaseInput = {
agent?: Agent.ID
model?: Model.Ref
metadata?: SessionSchema.Metadata
permissions?: Permission.Ruleset
}
type CreateInput = CreateBaseInput &
({ location: Location.Ref; parentID?: never } | { parentID: SessionSchema.ID; location?: never })
@@ -157,6 +159,10 @@ export interface Interface {
readonly switchAgent: (input: { sessionID: SessionSchema.ID; agent: Agent.ID }) => Effect.Effect<void, NotFoundError>
readonly switchModel: (input: { sessionID: SessionSchema.ID; model: Model.Ref }) => Effect.Effect<void, NotFoundError>
readonly rename: (input: { sessionID: SessionSchema.ID; title: string }) => Effect.Effect<void, NotFoundError>
readonly setPermissions: (input: {
sessionID: SessionSchema.ID
permissions: Permission.Ruleset
}) => Effect.Effect<void, NotFoundError>
readonly move: SessionMove.Interface["move"]
readonly prompt: (
input: Parameters<Session.Handle["prompt"]>[0] & { sessionID: SessionSchema.ID },
@@ -248,9 +254,10 @@ const layer = Layer.effect(
subpath: RelativePath.make(path.relative(project.directory, location.directory).replaceAll("\\", "/")),
title: input.title,
agent: input.agent,
// Children inherit metadata the way they inherit location, so
// host policies that read it treat the family uniformly.
// Children inherit metadata and permissions the way they inherit
// location, so host policies that read them treat the family uniformly.
metadata: input.metadata ?? parent?.metadata,
permissions: input.permissions ?? parent?.permissions,
model: input.model
? {
id: Model.ID.make(input.model.id),
@@ -387,6 +394,7 @@ const layer = Layer.effect(
switchAgent: (input) => sessions.forSession(input.sessionID).switchAgent(input),
switchModel: (input) => sessions.forSession(input.sessionID).switchModel(input),
rename: (input) => sessions.forSession(input.sessionID).rename(input),
setPermissions: (input) => sessions.forSession(input.sessionID).setPermissions(input),
move: moves.move,
compact: (input) => sessions.forSession(input.sessionID).compact(input),
wait: (sessionID) => sessions.forSession(sessionID).wait(),
+2 -1
View File
@@ -1,6 +1,7 @@
export * as SessionContext from "./context.js"
import { Model } from "@opencode/schema/model"
import { Permission } from "../permission.js"
import { Context, Effect, Layer } from "effect"
import { Agent } from "../agent.js"
import { Catalog } from "../catalog.js"
@@ -129,7 +130,7 @@ const layer = Layer.effect(
if (!agent.info) return yield* new AgentNotFoundError({ sessionID: session.id, agent: session.agent ?? agent.id })
const loaded = yield* Effect.all(
{
tools: registry.snapshot(agent.info.permissions),
tools: registry.snapshot(Permission.merge(agent.info.permissions, session.permissions ?? [])),
builtins: builtins.load(sessionID),
discovery: discovery.load(),
skills: skillInstructions.load(agent),
+1
View File
@@ -50,6 +50,7 @@ export function fromRow(row: typeof SessionTable.$inferSelect): SessionSchema.In
}),
subpath: row.path ? RelativePath.make(row.path) : undefined,
metadata: row.metadata ?? undefined,
permissions: row.permission ?? undefined,
revert: row.revert ? decodeRevert(row.revert) : undefined,
outcome: row.idle_outcome ?? undefined,
time: {
@@ -116,6 +116,7 @@ export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
)
}),
"session.renamed": () => Effect.void,
"session.permissions.updated": () => Effect.void,
"session.deleted": () => Effect.void,
"session.forked": () => Effect.void,
"session.inbox.delivered": () => Effect.void,
+10
View File
@@ -160,6 +160,7 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
agent: parent.agent,
model: parent.model,
metadata: parent.metadata,
permission: parent.permission,
version: parent.version,
cost: 0,
tokens_input: 0,
@@ -450,6 +451,7 @@ const layer = Layer.effectDiscard(
agent: event.data.agent,
model: event.data.model,
metadata: event.data.metadata,
permission: event.data.permissions,
version: event.data.version,
time_created: event.created,
time_updated: event.created,
@@ -571,6 +573,14 @@ const layer = Layer.effectDiscard(
.run()
.pipe(Effect.orDie),
)
yield* bus.project(SessionEvent.PermissionsUpdated, (event) =>
db
.update(SessionTable)
.set({ permission: event.data.permissions, time_updated: event.created })
.where(eq(SessionTable.id, event.data.sessionID))
.run()
.pipe(Effect.orDie),
)
yield* bus.project(SessionEvent.Viewed, (event) => {
const idle = event.data.idle
return db
+4 -1
View File
@@ -6,6 +6,7 @@ import { Model } from "@opencode/schema/model"
import { Provider } from "@opencode/schema/provider"
import { Context, Effect, Layer, Schema } from "effect"
import { ModelResolver } from "../../model-resolver.js"
import { ProviderPolicy } from "../../provider-policy.js"
import { SessionSchema } from "../schema.js"
export class ModelNotSelectedError extends Schema.TaggedError<ModelNotSelectedError>()(
@@ -80,8 +81,10 @@ const layer = Layer.effect(
Service,
Effect.gen(function* () {
const resolver = yield* ModelResolver.Service
const policies = yield* ProviderPolicy.Service
return Service.of({
resolve: Effect.fn("SessionRunnerModel.resolve")(function* (session, available) {
yield* policies.assert(session.model?.providerID)
// Location plugins populate and filter the catalog asynchronously during layer startup.
if (!session.model) {
const resolved = yield* resolver.resolve()
@@ -102,4 +105,4 @@ const layer = Layer.effect(
}),
)
export const node = makeLocationNode({ service: Service, layer, deps: [ModelResolver.node] })
export const node = makeLocationNode({ service: Service, layer, deps: [ModelResolver.node, ProviderPolicy.node] })
+11
View File
@@ -3,6 +3,7 @@ export * as Session from "./session.js"
import { DateTime, Effect, Fiber, Scope } from "effect"
import type { Agent } from "@opencode/schema/agent"
import type { Model } from "@opencode/schema/model"
import type { Permission } from "@opencode/schema/permission"
import { Event } from "@opencode/schema/event"
import { FSUtil } from "@opencode/util/fs-util"
import { Bus } from "../bus.js"
@@ -72,6 +73,13 @@ export const make = Effect.fn("Session.make")(function* () {
yield* get(sessionID)
yield* bus.publish(SessionEvent.Renamed, { sessionID, title: input.title })
})
const setPermissions = Effect.fn("Session.setPermissions")(function* (
sessionID: SessionSchema.ID,
input: { permissions: Permission.Ruleset },
) {
yield* get(sessionID)
yield* bus.publish(SessionEvent.PermissionsUpdated, { sessionID, permissions: input.permissions })
})
const switchAgent = Effect.fn("Session.switchAgent")(function* (
sessionID: SessionSchema.ID,
input: { agent: Agent.ID },
@@ -334,6 +342,7 @@ export const make = Effect.fn("Session.make")(function* () {
message,
view,
rename,
setPermissions,
switchAgent,
switchModel,
inbox,
@@ -356,6 +365,7 @@ export const make = Effect.fn("Session.make")(function* () {
const message = operations.message.bind(undefined, sessionID)
const view = operations.view.bind(undefined, sessionID)
const rename = operations.rename.bind(undefined, sessionID)
const setPermissions = operations.setPermissions.bind(undefined, sessionID)
const switchAgent = operations.switchAgent.bind(undefined, sessionID)
const switchModel = operations.switchModel.bind(undefined, sessionID)
const inbox = operations.inbox.bind(undefined, sessionID)
@@ -381,6 +391,7 @@ export const make = Effect.fn("Session.make")(function* () {
message,
view,
rename,
setPermissions,
switchAgent,
switchModel,
inbox,
+2 -2
View File
@@ -5,7 +5,7 @@ import { ProjectTable } from "../project/sql.js"
import type { SessionMessage } from "./message.js"
import type { SessionInbox } from "./inbox.js"
import type { FileDiff } from "@opencode/schema/file-diff"
import type { PermissionV1 } from "@opencode/schema/permission-v1"
import type { Permission } from "@opencode/schema/permission"
import type { Project } from "@opencode/schema/project"
import type { SessionSchema } from "./schema.js"
import type { Workspace } from "@opencode/schema/workspace"
@@ -49,7 +49,7 @@ export const SessionTable = sqliteTable(
tokens_cache_read: integer().notNull().default(0),
tokens_cache_write: integer().notNull().default(0),
revert: text({ mode: "json" }).$type<Session.Revert | RevertV1>(),
permission: text({ mode: "json" }).$type<PermissionV1.Ruleset>(),
permission: text({ mode: "json" }).$type<Permission.Ruleset>(),
agent: text(),
model: text({ mode: "json" }).$type<{
id: string
+4 -12
View File
@@ -96,9 +96,7 @@ export const get = Effect.fn("SessionStats.get")(function* (input: Input = {}) {
JOIN ${SessionTable} AS session ON session.id = message.session_id
WHERE message.type IN ('user', 'assistant')
AND message.time_created < ${to}
AND (session.fork_session_id IS NULL
OR NOT EXISTS (SELECT 1 FROM ${SessionTable} AS parent WHERE parent.id = session.fork_session_id)
OR message.time_created >= session.time_created)
AND (session.fork_session_id IS NULL OR message.time_created >= session.time_created)
${project}
`,
)
@@ -145,9 +143,7 @@ export const get = Effect.fn("SessionStats.get")(function* (input: Input = {}) {
WHERE message.type IN ('user', 'assistant')
AND message.time_created >= ${range.from}
AND message.time_created < ${range.to}
AND (session.fork_session_id IS NULL
OR NOT EXISTS (SELECT 1 FROM ${SessionTable} AS parent WHERE parent.id = session.fork_session_id)
OR message.time_created >= session.time_created)
AND (session.fork_session_id IS NULL OR message.time_created >= session.time_created)
${project}
`,
)
@@ -208,9 +204,7 @@ export const get = Effect.fn("SessionStats.get")(function* (input: Input = {}) {
WHERE message.type = 'assistant'
AND message.time_created >= ${range.from}
AND message.time_created < ${range.to}
AND (session.fork_session_id IS NULL
OR NOT EXISTS (SELECT 1 FROM ${SessionTable} AS parent WHERE parent.id = session.fork_session_id)
OR message.time_created >= session.time_created)
AND (session.fork_session_id IS NULL OR message.time_created >= session.time_created)
AND json_extract(content.value, '$.type') = 'tool'
${project}
)
@@ -252,9 +246,7 @@ export const get = Effect.fn("SessionStats.get")(function* (input: Input = {}) {
WHERE message.type = 'assistant'
AND message.time_created >= ${range.from}
AND message.time_created < ${range.to}
AND (session.fork_session_id IS NULL
OR NOT EXISTS (SELECT 1 FROM ${SessionTable} AS parent WHERE parent.id = session.fork_session_id)
OR message.time_created >= session.time_created)
AND (session.fork_session_id IS NULL OR message.time_created >= session.time_created)
AND json_extract(content.value, '$.type') = 'tool'
${project}
`,
@@ -3,6 +3,7 @@ import { Tool } from "@opencode/schema/tool"
import { SessionError } from "@opencode/schema/session-error"
import { Permission } from "../permission.js"
import { Integration } from "../integration.js"
import { ProviderPolicy } from "../provider-policy.js"
import { AgentNotFoundError, StepFailedError, UserInterruptedError } from "./error.js"
import { SessionRunnerModel } from "./runner/model.js"
@@ -51,6 +52,8 @@ export function toSessionError(cause: unknown): SessionError.Error {
if (cause instanceof AgentNotFoundError) return { type: "unknown", message: cause.message }
if (cause instanceof UserInterruptedError) return { type: "aborted", message: cause.message }
if (
cause instanceof ProviderPolicy.Unavailable ||
cause instanceof ProviderPolicy.Denied ||
cause instanceof SessionRunnerModel.ModelNotSelectedError ||
cause instanceof SessionRunnerModel.ModelUnavailableError ||
cause instanceof SessionRunnerModel.VariantUnavailableError ||
+1
View File
@@ -103,6 +103,7 @@ const layer = Layer.effect(
agent: input.data.info.agent,
model: input.data.info.model,
metadata: input.data.info.metadata,
permissions: input.data.info.permissions,
},
{
location: input.location,
+12 -1
View File
@@ -99,8 +99,19 @@ export const layer = Layer.effect(
},
)
const text = content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
const output = () => {
if (result.structured !== undefined) return result.structured
if (text === "") return null
// Agents assume JSON returned as text is already an object, so parse it when the server declares no schema.
if (tool.outputSchema === undefined && (text.startsWith("{") || text.startsWith("["))) {
try {
return JSON.parse(text)
} catch {}
}
return text
}
return {
output: result.structured ?? (text === "" ? null : text),
output: output(),
...(content.length === 0 ? {} : { content }),
}
}).pipe(
+10 -16
View File
@@ -2,10 +2,7 @@ import { describe, expect } from "bun:test"
import { Document, Event, Info, type Entry } from "@opencode/schema/config"
import { Catalog } from "@opencode/core/catalog"
import { Config } from "@opencode/core/config"
import { ConfigPolicyPlugin } from "@opencode/core/config/plugin/policy"
import { Bus } from "@opencode/core/bus"
import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { Provider } from "@opencode/core/provider"
import { Effect, Schema } from "effect"
import { testEffect } from "../lib/effect"
@@ -24,13 +21,13 @@ const policies = (...items: { effect: "allow" | "deny"; resource: string }[]) =>
}),
})
const addPlugin = Effect.fn(function* (entries: Entry[]) {
const plugin = yield* Plugin.Service
const host = yield* PluginHost.make(plugin)
yield* ConfigPolicyPlugin.Plugin.effect(host).pipe(Effect.provide(Config.testLayer(entries)))
const setEntries = Effect.fn(function* (entries: Entry[]) {
const config = yield* Config.Service
const current = yield* config.entries()
current.splice(0, current.length, ...entries)
})
describe("ConfigPolicyPlugin.Plugin", () => {
describe("Provider policy catalog boundary", () => {
it.effect("filters plugin-provided providers with ordered wildcard policies", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
@@ -39,7 +36,7 @@ describe("ConfigPolicyPlugin.Plugin", () => {
catalog.provider.update(Provider.ID.anthropic, () => {})
catalog.provider.update(Provider.ID.make("company-internal"), () => {})
})
yield* addPlugin([
yield* setEntries([
policies(
{ effect: "deny", resource: "*" },
{ effect: "allow", resource: "anthropic" },
@@ -57,7 +54,7 @@ describe("ConfigPolicyPlugin.Plugin", () => {
Effect.gen(function* () {
const catalog = yield* Catalog.Service
yield* catalog.transform((catalog) => catalog.provider.update(Provider.ID.openai, () => {}))
yield* addPlugin([
yield* setEntries([
policies({ effect: "deny", resource: "openai" }),
policies({ effect: "allow", resource: "openai" }),
])
@@ -70,17 +67,14 @@ describe("ConfigPolicyPlugin.Plugin", () => {
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const bus = yield* Bus.Service
const test = yield* Config.Test
const plugin = yield* Plugin.Service
const host = yield* PluginHost.make(plugin)
yield* catalog.transform((catalog) => catalog.provider.update(Provider.ID.openai, () => {}))
yield* ConfigPolicyPlugin.Plugin.effect(host)
yield* setEntries([policies({ effect: "deny", resource: "openai" })])
expect(yield* catalog.provider.get(Provider.ID.openai)).toBeUndefined()
yield* test.setEntries([policies({ effect: "allow", resource: "openai" })])
yield* setEntries([policies({ effect: "allow", resource: "openai" })])
yield* bus.publish(Event.Updated, {})
yield* waitUntil(catalog.provider.get(Provider.ID.openai).pipe(Effect.map((provider) => provider !== undefined)))
}).pipe(Effect.provide(Config.testLayer([policies({ effect: "deny", resource: "openai" })]))),
}),
)
})
+5 -1
View File
@@ -1,3 +1,4 @@
import { ProviderPolicy } from "@opencode/core/provider-policy"
import { expect } from "bun:test"
import { LanguageModel } from "@opencode/ai"
import { OpenAIChat } from "@opencode/ai/protocols"
@@ -67,7 +68,10 @@ const aisdk = Layer.mock(AISDK.Service, {
})
const client = TestLLM.testLayer({ fallback: TestLLM.text("OK", "generate") })
const resolver = ModelResolver.layer.pipe(Layer.provide(Layer.mergeAll(catalog, integrations, npm, aisdk)))
const resolver = ModelResolver.layer.pipe(
Layer.provide(Layer.mock(ProviderPolicy.Service, { assert: () => Effect.void })),
Layer.provide(Layer.mergeAll(catalog, integrations, npm, aisdk)),
)
const it = testEffect(Generate.layer.pipe(Layer.provide(Layer.merge(resolver, client))))
const resolverIt = testEffect(resolver)
+74
View File
@@ -324,6 +324,32 @@ const mcp = Layer.mock(Mcp.Service, {
description: "Status",
inputSchema: { type: "object", properties: {} },
}),
new Mcp.Tool({
server: Mcp.ServerName.make("demo"),
name: "issues",
description: "Returns JSON as text",
inputSchema: { type: "object", properties: {} },
}),
new Mcp.Tool({
server: Mcp.ServerName.make("demo"),
name: "count",
description: "Returns a number as text",
inputSchema: { type: "object", properties: {} },
}),
new Mcp.Tool({
server: Mcp.ServerName.make("demo"),
name: "typed",
description: "Declares a string output and returns JSON as text",
inputSchema: { type: "object", properties: {} },
outputSchema: { type: "string" },
}),
new Mcp.Tool({
server: Mcp.ServerName.make("direct"),
name: "issues",
codemode: false,
description: "Returns JSON as text",
inputSchema: { type: "object", properties: {} },
}),
new Mcp.Tool({
server: Mcp.ServerName.make("direct"),
name: "lookup",
@@ -374,6 +400,20 @@ const mcp = Layer.mock(Mcp.Service, {
isError: false,
content: [{ type: "text", text: "hello" }],
})
if (input.name === "issues" || input.name === "typed")
return new Mcp.ToolResult({
server: Mcp.ServerName.make(input.server),
tool: input.name,
isError: false,
content: [{ type: "text", text: '{"issues":[{"id":1}]}' }],
})
if (input.name === "count")
return new Mcp.ToolResult({
server: Mcp.ServerName.make(input.server),
tool: input.name,
isError: false,
content: [{ type: "text", text: "42" }],
})
return new Mcp.ToolResult({
server: Mcp.ServerName.make(input.server),
tool: input.name,
@@ -1943,6 +1983,7 @@ it.effect("advertises MCP output schemas to Code Mode", () =>
expect(toolSet.definitions.map((tool) => tool.name)).toEqual([
"direct_fail",
"direct_issues",
"direct_lookup",
"direct_media",
"execute",
@@ -2033,6 +2074,39 @@ it.effect("returns content-only MCP results through Code Mode", () =>
}),
)
it.effect("parses JSON text results from MCP tools without an output schema", () =>
Effect.gen(function* () {
assertion = yield* Deferred.make<Permission.AssertInput>()
decision = Effect.void
const registry = yield* Tool.Service
const registration = yield* McpTool.Service
yield* registration.flush
const toolSet = yield* registry.snapshot()
const run = (code: string) =>
toolSet
.execute({
sessionID: Session.ID.make("ses_mcp_json_text"),
...toolIdentity,
call: { type: "tool-call", id: `call_${code.length}`, name: "execute", input: { code } },
})
.pipe(Effect.map((execution) => execution.output.output))
expect(yield* run("return (await tools.demo.issues({})).issues[0].id")).toBe("1")
expect(yield* run("return typeof (await tools.demo.count({}))")).toBe("string")
expect(yield* run("return typeof (await tools.demo.typed({}))")).toBe("string")
// Outside Code Mode the content the model reads is the original text.
expect(
yield* toolSet.execute({
sessionID: Session.ID.make("ses_mcp_json_text"),
...toolIdentity,
call: { type: "tool-call", id: "call_direct_issues", name: "direct_issues", input: {} },
}),
).toMatchObject({ output: { issues: [{ id: 1 }] }, content: [{ type: "text", text: '{"issues":[{"id":1}]}' }] })
}),
)
it.effect("advertises MCP tools directly when Code Mode is disabled for the server", () =>
Effect.gen(function* () {
const registry = yield* Tool.Service
+5 -1
View File
@@ -1,3 +1,4 @@
import { ProviderPolicy } from "@opencode/core/provider-policy"
import { describe, expect } from "bun:test"
import { LLM, LanguageModel, Message } from "@opencode/ai"
import { OpenAIChat } from "@opencode/ai/protocols"
@@ -384,7 +385,10 @@ describe("ModelResolver", () => {
},
model: () => Effect.die("unused"),
})
const layer = ModelResolver.layer.pipe(Layer.provide(Layer.mergeAll(catalog, integrations, npm, aisdk)))
const layer = ModelResolver.layer.pipe(
Layer.provide(Layer.mock(ProviderPolicy.Service, { assert: () => Effect.void })),
Layer.provide(Layer.mergeAll(catalog, integrations, npm, aisdk)),
)
return withConfigEnv({}, () =>
Effect.gen(function* () {
+28
View File
@@ -224,6 +224,34 @@ describe("Permission", () => {
}),
)
it.effect("merges session rules after agent rules and before saved approvals", () =>
Effect.gen(function* () {
yield* setup([{ action: "*", resource: "*", effect: "allow" }])
const { db } = yield* Database.Service
const service = yield* Permission.Service
const setSession = (permission: Permission.Ruleset) =>
db
.update(SessionTable)
.set({ permission })
.where(eq(SessionTable.id, Session.ID.make("ses_test")))
.run()
.pipe(Effect.orDie)
yield* setSession([{ action: "edit", resource: "/original/**", effect: "deny" }])
expect(yield* service.ask(assertion({ action: "edit", resources: ["/original/src/index.ts"] }))).toMatchObject({
effect: "deny",
})
yield* setRules([])
const saved = yield* PermissionSaved.Service
yield* saved.add({ projectID: Project.ID.global, action: "bash", resources: ["pwd"] })
yield* setSession([{ action: "bash", resource: "*", effect: "deny" }])
expect(yield* service.ask(assertion({ action: "bash", resources: ["pwd"] }))).toMatchObject({ effect: "deny" })
yield* setSession([{ action: "bash", resource: "*", effect: "ask" }])
expect(yield* service.ask(assertion({ action: "bash", resources: ["pwd"] }))).toMatchObject({ effect: "allow" })
}),
)
it.effect("uses saved bash approvals while preserving configured deny precedence", () =>
Effect.gen(function* () {
yield* setup()
+3
View File
@@ -1,6 +1,7 @@
import { Agent } from "@opencode/core/agent"
import { AISDK } from "@opencode/core/aisdk"
import { Catalog } from "@opencode/core/catalog"
import { ProviderPolicy } from "@opencode/core/provider-policy"
import { Command } from "@opencode/core/command"
import { Config } from "@opencode/core/config"
import { Credential } from "@opencode/core/credential"
@@ -78,6 +79,8 @@ export const PluginTestLayer = AppNodeBuilder.build(
Agent.node,
AISDK.node,
Catalog.node,
ProviderPolicy.node,
Config.node,
Command.node,
Integration.node,
KV.node,
+1
View File
@@ -108,6 +108,7 @@ export function host(overrides: Overrides = {}): Plugin.Context {
list: () => Effect.die("unused permission.list"),
get: () => Effect.die("unused permission.get"),
reply: () => Effect.die("unused permission.reply"),
rules: () => Effect.die("unused permission.rules"),
},
plugin: overrides.plugin ?? {
list: () => Effect.die("unused plugin.list"),
@@ -89,6 +89,10 @@ function eventually<A>(
})
}
function managedPolicy(workspaceID = "org_test") {
return { experimental: { policies: [] }, managedPolicy: { schemaVersion: 1, workspaceID, revision: 0 } }
}
const cost = (input: number, output = 0) => [
{
input: Money.USDPerMillionTokens.make(input),
@@ -366,6 +370,7 @@ describe("OpencodePlugin", () => {
requests.push(`${request.method} ${new URL(request.url).pathname}`)
const origin = new URL(request.url).origin
return Response.json({
...managedPolicy(request.headers.get("x-org-id") ?? "org_test"),
providers: {
remote: {
canonical: "openai",
@@ -544,9 +549,10 @@ describe("OpencodePlugin", () => {
const state = { advertised: false, requests: 0 }
const server = Bun.serve({
port: 0,
fetch: () => {
fetch: (request) => {
state.requests++
return Response.json({
...managedPolicy(request.headers.get("x-org-id") ?? "org_test"),
providers: {},
...(state.advertised ? { websearch: { providerID: "opencode" } } : {}),
})
@@ -634,6 +640,7 @@ describe("OpencodePlugin", () => {
if (path === "/api/v2/config") {
if (state.waitForConfig) await gate.promise
return Response.json({
...managedPolicy(request.headers.get("x-org-id") ?? "org_test"),
providers: {},
...(state.advertised
? {
@@ -781,6 +788,7 @@ describe("OpencodePlugin", () => {
fetch: (request) => {
if (new URL(request.url).pathname === "/console/api/v2/config") {
return Response.json({
...managedPolicy(request.headers.get("x-org-id") ?? "org_test"),
providers: {},
websearch: {
providerID: "managed-search",
@@ -843,6 +851,7 @@ describe("OpencodePlugin", () => {
requests.push(url.pathname)
if (url.pathname === "/console/api/v2/config") {
return Response.json({
...managedPolicy(request.headers.get("x-org-id") ?? "org_test"),
providers: {},
websearch: {
providerID: "opencode",
@@ -893,6 +902,7 @@ describe("OpencodePlugin", () => {
const url = new URL(request.url)
if (url.pathname === "/api/v2/config") {
return Response.json({
...managedPolicy(request.headers.get("x-org-id") ?? "org_test"),
providers: {},
websearch: {
providerID: "opencode",
@@ -987,6 +997,7 @@ describe("OpencodePlugin", () => {
})
}
return Response.json({
...managedPolicy(request.headers.get("x-org-id") ?? "org_test"),
providers: {
remote: {
canonical: "openai",
@@ -1152,13 +1163,12 @@ describe("OpencodePlugin", () => {
draft.cost = cost(1)
})
})
// An env credential has no server metadata, so the plugin would ask the
// default Console for remote config; answer 404 (no remote config) locally.
// Environment credentials also require a valid managed-policy response.
yield* addPlugin().pipe(
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status: 404 }))),
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ providers: {}, ...managedPolicy() }))),
),
),
)
@@ -0,0 +1,51 @@
import { describe, expect } from "bun:test"
import { Catalog } from "@opencode/core/catalog"
import { Credential } from "@opencode/core/credential"
import { Integration } from "@opencode/core/integration"
import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { OpencodePlugin } from "@opencode/core/plugin/provider/opencode"
import { Provider } from "@opencode/core/provider"
import { ProviderPolicy } from "@opencode/core/provider-policy"
import { Effect } from "effect"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
const it = testEffect(PluginTestLayer)
// Run from Console's policy E2E with a freshly issued local service-account key.
describe.skipIf(!process.env.OPENCODE_CONSOLE_POLICY_URL)("Published Console policy", () => {
it.live("loads the real managed config and enforces the policy published in the browser", () =>
Effect.gen(function* () {
const credentials = yield* Credential.Service
const catalog = yield* Catalog.Service
const policies = yield* ProviderPolicy.Service
yield* catalog.transform((editor) => {
editor.provider.update(Provider.ID.openai, () => {})
editor.provider.update(Provider.ID.make("company-prod"), () => {})
})
yield* credentials.create({
integrationID: Integration.ID.make("opencode"),
value: Credential.Key.make({
type: "key",
key: process.env.OPENCODE_CONSOLE_POLICY_KEY!,
metadata: {
server: process.env.OPENCODE_CONSOLE_POLICY_URL!,
orgID: process.env.OPENCODE_CONSOLE_POLICY_ORG!,
},
}),
})
const plugin = yield* Plugin.Service
const host = yield* PluginHost.make(plugin)
yield* OpencodePlugin.effect(host)
expect(yield* policies.read()).toMatchObject({
status: "ready",
workspaceID: process.env.OPENCODE_CONSOLE_POLICY_ORG,
revision: 1,
})
expect(yield* catalog.provider.get(Provider.ID.openai)).toBeUndefined()
expect(yield* catalog.provider.get(Provider.ID.make("company-prod"))).toBeDefined()
expect(yield* policies.assert("openai").pipe(Effect.flip)).toBeInstanceOf(ProviderPolicy.Denied)
}),
)
})
@@ -0,0 +1,207 @@
import { describe, expect } from "bun:test"
import { Catalog } from "@opencode/core/catalog"
import { Config } from "@opencode/core/config"
import { Credential } from "@opencode/core/credential"
import { Integration } from "@opencode/core/integration"
import { ModelResolver } from "@opencode/core/model-resolver"
import { Model } from "@opencode/core/model"
import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { OpencodePlugin } from "@opencode/core/plugin/provider/opencode"
import { Provider } from "@opencode/core/provider"
import { ProviderPolicy } from "@opencode/core/provider-policy"
import { Document, Info } from "@opencode/schema/config"
import { Effect, Schema } from "effect"
import { TestClock } from "effect/testing"
import { drain } from "../lib/clock"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
const it = testEffect(PluginTestLayer)
const rule = (effect: "allow" | "deny", resource: string) => ({ action: "provider.use" as const, effect, resource })
const document = (policies: ReturnType<typeof rule>[], workspaceID = "org_policy", revision = 1) => ({
providers: {},
experimental: { policies },
managedPolicy: { schemaVersion: 1, workspaceID, revision },
})
const activate = Effect.gen(function* () {
const plugin = yield* Plugin.Service
const host = yield* PluginHost.make(plugin)
yield* OpencodePlugin.effect(host)
})
const refresh = TestClock.adjust("10 minutes").pipe(Effect.andThen(drain))
describe("Managed provider policy", () => {
it.effect("accepts revision-zero defaults without requiring policy publication", () =>
Effect.acquireUseRelease(
Effect.sync(() => Bun.serve({ port: 0, fetch: () => Response.json(document([], "org_policy", 0)) })),
(server) =>
Effect.gen(function* () {
const credentials = yield* Credential.Service
const catalog = yield* Catalog.Service
const policies = yield* ProviderPolicy.Service
yield* catalog.transform((editor) => editor.provider.update(Provider.ID.openai, () => {}))
yield* credentials.create({
integrationID: Integration.ID.make("opencode"),
value: Credential.Key.make({
type: "key",
key: "test-key",
metadata: { server: server.url.origin, orgID: "org_policy" },
}),
})
yield* activate
expect(yield* policies.read()).toMatchObject({ status: "ready", revision: 0, workspaceID: "org_policy" })
expect(yield* catalog.provider.get(Provider.ID.openai)).toBeDefined()
yield* policies.assert("openai")
}),
(server) => Effect.promise(() => server.stop(true)),
),
)
it.effect(
"composes organization rules last, filters every catalog view, retains only valid same-identity snapshots, and clears explicitly",
() =>
Effect.acquireUseRelease(
Effect.sync(() => {
const state = { status: 200, body: document([rule("deny", "*"), rule("allow", "remote")]) as unknown }
const server = Bun.serve({ port: 0, fetch: () => Response.json(state.body, { status: state.status }) })
return { state, server }
}),
({ state, server }) =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const credentials = yield* Credential.Service
const policies = yield* ProviderPolicy.Service
const config = yield* Config.Service
const entries = yield* config.entries()
entries.push(
new Document({
type: "document",
info: Schema.decodeUnknownSync(Info)({
experimental: { policies: [rule("deny", "remote"), rule("allow", "openai")] },
}),
}),
)
yield* catalog.transform((editor) => {
for (const id of ["openai", "remote"]) {
editor.provider.update(Provider.ID.make(id), (provider) => {
provider.activation = "enabled"
})
editor.model.update(Provider.ID.make(id), Model.ID.make("model"), () => {})
}
})
const previouslySelected = yield* catalog.model.get(Provider.ID.openai, Model.ID.make("model"))
if (!previouslySelected) return yield* Effect.die("Expected local model")
const credential = yield* credentials.create({
integrationID: Integration.ID.make("opencode"),
value: Credential.Key.make({
type: "key",
key: "test-key",
metadata: { server: server.url.origin, orgID: "org_policy" },
}),
})
expect((yield* policies.read()).status).toBe("unavailable")
expect(yield* catalog.provider.all()).toEqual([])
yield* activate
expect((yield* policies.read()).status).toBe("ready")
expect(yield* catalog.provider.get(Provider.ID.make("remote"))).toBeDefined()
expect(yield* catalog.provider.get(Provider.ID.openai)).toBeUndefined()
expect((yield* catalog.model.all()).map((model) => model.providerID)).toEqual([Provider.ID.make("remote")])
expect(yield* catalog.model.get(Provider.ID.openai, Model.ID.make("model"))).toBeUndefined()
expect(yield* catalog.model.small(Provider.ID.openai)).toBeUndefined()
yield* catalog.transform((editor) =>
editor.provider.update(Provider.ID.openai, (provider) => {
provider.activation = "enabled"
}),
)
expect(yield* catalog.provider.get(Provider.ID.openai)).toBeUndefined()
expect(yield* policies.assert("openai").pipe(Effect.flip)).toBeInstanceOf(ProviderPolicy.Denied)
const loadError = yield* Effect.gen(function* () {
const resolver = yield* ModelResolver.Service
return yield* resolver.resolveModel(previouslySelected).pipe(Effect.flip)
}).pipe(Effect.provide(ModelResolver.layer))
expect(loadError).toBeInstanceOf(ProviderPolicy.Denied)
state.status = 503
yield* refresh
expect((yield* policies.read()).status).toBe("stale")
expect(yield* catalog.provider.get(Provider.ID.make("remote"))).toBeDefined()
expect(yield* catalog.provider.get(Provider.ID.openai)).toBeUndefined()
state.status = 200
state.body = { providers: {} }
yield* refresh
expect((yield* policies.read()).status).toBe("unavailable")
expect(yield* catalog.model.available()).toEqual([])
expect(yield* policies.assert("remote").pipe(Effect.flip)).toBeInstanceOf(ProviderPolicy.Unavailable)
state.body = document([], "org_policy", 2)
yield* refresh
expect((yield* policies.read()).revision).toBe(2)
expect(yield* catalog.provider.get(Provider.ID.openai)).toBeDefined()
expect(yield* catalog.provider.get(Provider.ID.make("remote"))).toBeUndefined()
state.status = 503
yield* credentials.update(credential.id, {
value: Credential.Key.make({
type: "key",
key: "other-key",
metadata: { server: server.url.origin, orgID: "org_other" },
}),
})
yield* drain
expect((yield* policies.read()).status).toBe("unavailable")
state.status = 200
yield* refresh
expect((yield* policies.read()).status).toBe("unavailable")
state.body = document([rule("deny", "*")], "org_other", 0)
yield* refresh
expect((yield* policies.read()).workspaceID).toBe("org_other")
expect(yield* catalog.provider.all()).toEqual([])
yield* credentials.remove(credential.id)
yield* drain
expect((yield* policies.read()).status).toBe("disconnected")
expect(yield* catalog.provider.get(Provider.ID.openai)).toBeDefined()
}),
({ server }) => Effect.promise(() => server.stop(true)),
),
)
for (const scenario of [
{ name: "missing descriptor", body: { providers: {}, experimental: { policies: [] } }, status: 200 },
{
name: "unsupported version",
body: { ...document([]), managedPolicy: { schemaVersion: 2, workspaceID: "org_policy", revision: 1 } },
status: 200,
},
{ name: "unknown conditions", body: document([{ ...rule("allow", "*"), ...{ condition: {} } }]), status: 200 },
{ name: "empty resource", body: document([rule("allow", "")]), status: 200 },
{ name: "absent policies", body: { ...document([]), experimental: {} }, status: 200 },
{ name: "revoked authorization", body: document([]), status: 403 },
{ name: "old Console", body: {}, status: 404 },
{ name: "cold outage", body: {}, status: 503 },
]) {
it.effect(`fails closed on ${scenario.name}`, () =>
Effect.acquireUseRelease(
Effect.sync(() =>
Bun.serve({ port: 0, fetch: () => Response.json(scenario.body, { status: scenario.status }) }),
),
(server) =>
Effect.gen(function* () {
const credentials = yield* Credential.Service
const catalog = yield* Catalog.Service
const policies = yield* ProviderPolicy.Service
yield* catalog.transform((editor) => editor.provider.update(Provider.ID.openai, () => {}))
yield* credentials.create({
integrationID: Integration.ID.make("opencode"),
value: Credential.Key.make({
type: "key",
key: "test-key",
metadata: { server: server.url.origin, orgID: "org_policy" },
}),
})
yield* activate
expect((yield* policies.read()).status).toBe("unavailable")
expect(yield* catalog.provider.all()).toEqual([])
}),
(server) => Effect.promise(() => server.stop(true)),
),
)
}
})
@@ -69,7 +69,7 @@ describe("XAIPlugin", () => {
}),
)
it.effect("keeps xAI Responses WebSockets opt-in", () =>
it.effect("enables xAI Responses WebSockets", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const providerID = Provider.ID.make("xai")
@@ -84,7 +84,7 @@ describe("XAIPlugin", () => {
const model = yield* catalog.model.get(providerID, Model.ID.make("grok-4.6"))
expect(model?.capabilities.responsesWebsockets).toBe(true)
expect(model?.websocket).toBeUndefined()
expect(model?.websocket).toBe(true)
}),
)
})
@@ -10,6 +10,7 @@ import { LayerNode } from "@opencode/util/effect/layer-node"
import { Global } from "@opencode/util/global"
import { Npm } from "@opencode/util/npm"
import { Bus } from "@opencode/core/bus"
import { Config } from "@opencode/core/config"
import { Command } from "@opencode/core/command"
import { Database } from "@opencode/core/database/database"
import { Watcher } from "@opencode/core/filesystem/watcher"
@@ -111,6 +112,36 @@ const failed = (plugins: Plugin.Interface) =>
)
describe("PluginSupervisor reload", () => {
for (const selector of ["-*", "-opencode.*", "-opencode.provider.opencode"]) {
it.live(`keeps the managed policy source active despite ${selector}`, () =>
Effect.gen(function* () {
const directory = yield* tmpdirScoped()
yield* Effect.promise(() =>
Bun.write(path.join(directory.path, ".opencode/opencode.json"), JSON.stringify({ plugins: [selector] })),
)
const locations = yield* LocationServiceMap.Service
yield* Effect.gen(function* () {
const plugins = yield* Plugin.Service
yield* plugins.awaitActivation
const config = yield* Config.Service
expect(
(yield* config.entries()).some(
(entry) => entry.type === "document" && entry.info.plugins?.includes(selector),
),
).toBe(true)
const inventory = yield* plugins.list()
expect(inventory.find((plugin) => plugin.id === "opencode.provider.opencode")?.state.status).toBe("active")
if (selector !== "-opencode.provider.opencode")
expect(
inventory.some((plugin) => plugin.id === "opencode.provider.openai" && plugin.state.status === "active"),
).toBe(false)
}).pipe(
Effect.scoped,
Effect.provide(locations.get(Location.Ref.make({ directory: AbsolutePath.make(directory.path) }))),
)
}),
)
}
;(
[
{ name: "on a helper-only save", helper: "nested/helper.ts", touchEntry: false },
+39 -2
View File
@@ -388,6 +388,32 @@ describe("Session.create", () => {
}),
)
it.effect("stores permission rules, inherits them through children and forks, and replaces them", () =>
Effect.gen(function* () {
const session = yield* Session.Service
const bus = yield* Bus.Service
const { db } = yield* Database.Service
const permissions = [{ action: "edit", resource: "/original/**", effect: "deny" as const }]
const created = yield* session.create({ location, permissions })
expect(created.permissions).toEqual(permissions)
expect((yield* session.create({ parentID: created.id })).permissions).toEqual(permissions)
expect((yield* session.create({ parentID: created.id, permissions: [] })).permissions).toEqual([])
yield* session.prompt({ sessionID: created.id, text: "Fork context", resume: false })
yield* SessionInbox.promote(db, bus, created.id, "steer")
const forked = yield* session.fork({ sessionID: created.id, boundary: { type: "through" } })
expect(forked.permissions).toEqual(permissions)
const replaced = [{ action: "shell", resource: "*", effect: "ask" as const }]
yield* session.setPermissions({ sessionID: created.id, permissions: replaced })
expect((yield* session.get(created.id)).permissions).toEqual(replaced)
expect(
yield* session.setPermissions({ sessionID: Session.ID.create(), permissions: replaced }).pipe(Effect.flip),
).toBeInstanceOf(Session.NotFoundError)
}),
)
it.effect("inherits location from an existing parent when omitted", () =>
Effect.gen(function* () {
const session = yield* Session.Service
@@ -1330,7 +1356,12 @@ describe("SessionTransfer", () => {
const transfer = yield* SessionTransfer.Service
const bus = yield* Bus.Service
const { db } = yield* Database.Service
const template = yield* session.create({ location, title: "Exported", metadata: { channel: "C123" } })
const template = yield* session.create({
location,
title: "Exported",
metadata: { channel: "C123" },
permissions: [{ action: "edit", resource: "*", effect: "deny" }],
})
const sessionID = Session.ID.create()
const sourceMessageID = SessionMessage.ID.create()
const errorMessageID = SessionMessage.ID.create()
@@ -1376,7 +1407,13 @@ describe("SessionTransfer", () => {
})
const messages = yield* session.messages({ sessionID, order: "asc" })
expect(imported).toMatchObject({ id: sessionID, title: "Exported", location, metadata: { channel: "C123" } })
expect(imported).toMatchObject({
id: sessionID,
title: "Exported",
location,
metadata: { channel: "C123" },
permissions: [{ action: "edit", resource: "*", effect: "deny" }],
})
expect(imported.time).toMatchObject({
updated: DateTime.makeUnsafe(1_000),
idle: DateTime.makeUnsafe(200),
+10 -1
View File
@@ -1944,7 +1944,16 @@ describe("SessionRunnerLLM", () => {
expect(yield* entries.list(sessionID)).toEqual([{ key: "nullable", value: null }])
})
scenario("rejects API instruction entries larger than 8KB", function* () {
scenario("accepts API instruction entries up to 256 KiB", function* () {
const entries = yield* InstructionEntry.Service
const value = "x".repeat(InstructionEntry.MaxValueBytes - 2)
yield* entries.put({ sessionID, key: "large", value })
expect(yield* entries.list(sessionID)).toEqual([{ key: "large", value }])
})
scenario("rejects API instruction entries larger than 256 KiB", function* () {
const entries = yield* InstructionEntry.Service
const exit = yield* entries
-68
View File
@@ -16,7 +16,6 @@ import { SessionMessageTable, SessionTable } from "@opencode/core/session/sql"
import { SessionStats } from "@opencode/core/session/stats"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { DateTime, Effect, Schema } from "effect"
import { eq } from "drizzle-orm"
import { testEffect } from "./lib/effect"
const it = testEffect(AppNodeBuilder.build(Database.node))
@@ -31,73 +30,6 @@ const encodeMessage = Schema.encodeSync(SessionMessage.Info)
const encodeUsage = Schema.encodeSync(SessionEvent.UsageRecorded.data)
describe("SessionStats", () => {
it.effect("counts inherited fork usage after the parent is deleted", () =>
Effect.gen(function* () {
const db = (yield* Database.Service).db
const parentID = Session.ID.make("ses_stats_deleted_parent")
const orphanID = Session.ID.make("ses_stats_orphan_fork")
yield* db
.insert(ProjectTable)
.values({ id: projectID, worktree: AbsolutePath.make("/stats"), name: "stats", sandboxes: [] })
.run()
.pipe(Effect.orDie)
yield* db
.insert(SessionTable)
.values([
{ id: parentID, project_id: projectID, slug: "parent", directory: "/stats", version: "test" },
{
id: orphanID,
project_id: projectID,
fork_session_id: parentID,
slug: "fork",
directory: "/stats",
version: "test",
time_created: Date.UTC(2026, 0, 4),
},
])
.run()
.pipe(Effect.orDie)
yield* db
.insert(SessionMessageTable)
.values([
messageRow(parentID, 1, assistant("msg_stats_deleted_parent", Date.UTC(2026, 0, 2, 10), [])),
messageRow(
orphanID,
1,
assistant("msg_stats_orphan_inherited", Date.UTC(2026, 0, 2, 10), [
SessionMessage.AssistantTool.make({
type: "tool",
id: "call_inherited",
name: "read",
state: SessionMessage.ToolStateCompleted.make({
status: "completed",
input: {},
content: [{ type: "text", text: "ok" }],
}),
time: { created: DateTime.makeUnsafe(Date.UTC(2026, 0, 2, 10)) },
}),
]),
),
messageRow(orphanID, 2, assistant("msg_stats_orphan_new", Date.UTC(2026, 0, 5, 10), [])),
])
.run()
.pipe(Effect.orDie)
yield* db.delete(SessionTable).where(eq(SessionTable.id, parentID)).run().pipe(Effect.orDie)
const stats = yield* SessionStats.get({ to: Date.UTC(2026, 1, 1), timezone: "UTC", tools: "detail" })
expect(DateTime.toEpochMillis(stats.range.from)).toBe(Date.UTC(2026, 0, 2, 10))
expect(stats.steps).toBe(2)
expect(stats.tokens).toEqual({ input: 20, output: 10, reasoning: 4, cache: { read: 8, write: 2 } })
expect(stats.cost).toBe(Money.USD.make(3))
expect(stats.tools).toMatchObject({
mode: "detail",
totals: { calls: 1, succeeded: 1, failed: 0, unfinished: 0 },
})
}),
)
it.effect("aggregates activity and tool reliability without reading message payloads outside the range", () =>
Effect.gen(function* () {
const db = (yield* Database.Service).db
+1 -1
View File
@@ -19,6 +19,6 @@ export interface PermissionHooks {
readonly evaluate: PermissionEvaluation
}
export type PermissionDomain = Pick<PermissionApi<unknown>, "list" | "get" | "reply"> & {
export type PermissionDomain = Pick<PermissionApi<unknown>, "list" | "get" | "reply" | "rules"> & {
readonly hook: Hooks<PermissionHooks>
}
+1
View File
@@ -438,6 +438,7 @@ export function fromPromise(plugin: Plugin) {
list: adaptApiMethod(PermissionEndpoints["session.permission.list"], host.permission.list),
get: adaptApiMethod(PermissionEndpoints["session.permission.get"], host.permission.get),
reply: adaptApiMethod(PermissionEndpoints["session.permission.reply"], host.permission.reply),
rules: adaptApiMethod(PermissionEndpoints["session.permission.rules"], host.permission.rules),
},
plugin: {
list: adaptApiMethod(PluginEndpoints["plugin.list"], host.plugin.list),
+1 -1
View File
@@ -19,6 +19,6 @@ export interface PermissionHooks {
readonly evaluate: PermissionEvaluation
}
export type PermissionDomain = Pick<PermissionApi, "list" | "get" | "reply"> & {
export type PermissionDomain = Pick<PermissionApi, "list" | "get" | "reply" | "rules"> & {
readonly hook: Hooks<PermissionHooks>
}
@@ -132,4 +132,21 @@ export const makePermissionGroup = <
}),
),
)
.add(
HttpApiEndpoint.put("session.permission.rules", "/api/session/:sessionID/permission/rules", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ permissions: Permission.Ruleset }),
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
})
.middleware(sessionLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "v2.session.permission.rules",
summary: "Replace session permission rules",
description:
"Replace the session-scoped permission rules. Rules are evaluated after the agent's rules, and the last matching rule wins.",
}),
),
)
.annotateMerge(OpenApi.annotations({ title: "permission", description: "Experimental permission routes." }))
+2
View File
@@ -27,6 +27,7 @@ import {
import { Agent } from "@opencode/schema/agent"
import { Skill } from "@opencode/schema/skill"
import { Model } from "@opencode/schema/model"
import { Permission } from "@opencode/schema/permission"
import { Location } from "@opencode/schema/location"
import { SessionEvent } from "@opencode/schema/session-event"
import { EventLog } from "@opencode/schema/event-log"
@@ -175,6 +176,7 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S>(sessionLo
model: Model.Ref.pipe(Schema.optional),
location: Location.Ref.pipe(Schema.optional),
metadata: Session.Metadata.pipe(Schema.optional),
permissions: Permission.Ruleset.pipe(Schema.optional),
}),
success: Schema.Struct({ data: Session.Info }),
}).annotateMerge(
+1 -1
View File
@@ -27,7 +27,7 @@ export const Snapshot = Schema.Array(
).annotate({ identifier: "InstructionEntry.Snapshot" })
export type Snapshot = typeof Snapshot.Type
export const MaxValueBytes = 8 * 1024
export const MaxValueBytes = 256 * 1024
export class ValueTooLargeError extends Schema.TaggedError<ValueTooLargeError>()(
"InstructionEntryValueTooLargeError",
+13
View File
@@ -25,6 +25,7 @@ import { TokenUsage } from "./token-usage.js"
import { SessionInbox } from "./session-inbox.js"
import { Project } from "./project.js"
import { SessionFork } from "./session-fork.js"
import { Permission } from "./permission.js"
export { FileAttachment }
@@ -62,6 +63,7 @@ export const Created = Event.durable({
model: Model.Ref.pipe(optional),
/** Host-supplied annotations resolved at creation, including any inherited from a parent. */
metadata: SessionMetadata.pipe(optional),
permissions: Permission.Ruleset.pipe(optional),
version: Schema.String,
},
})
@@ -109,6 +111,16 @@ export const Renamed = Event.durable({
})
export type Renamed = typeof Renamed.Type
export const PermissionsUpdated = Event.durable({
type: "session.permissions.updated",
...options,
schema: {
...Base,
permissions: Permission.Ruleset,
},
})
export type PermissionsUpdated = typeof PermissionsUpdated.Type
export const Viewed = Event.durable({
type: "session.viewed",
...options,
@@ -634,6 +646,7 @@ export const Definitions = Event.inventory(
ModelSelected,
Moved,
Renamed,
PermissionsUpdated,
Viewed,
UsageUpdated,
Deleted,
+3
View File
@@ -10,6 +10,7 @@ import { SessionEvent } from "./session-event.js"
import { SessionID } from "./session-id.js"
import { SessionMetadata } from "./session-metadata.js"
import { Money } from "./money.js"
import { Permission } from "./permission.js"
import { TokenUsage } from "./token-usage.js"
import { Revert } from "./session-revert.js"
import { SessionFork } from "./session-fork.js"
@@ -54,6 +55,8 @@ export const Info = Schema.Struct({
location: Location.Ref,
subpath: RelativePath.pipe(optional),
metadata: Metadata.pipe(optional),
/** Evaluated after the agent's rules; the last matching rule wins. */
permissions: Permission.Ruleset.pipe(optional),
revert: Revert.pipe(optional),
}).annotate({ identifier: "Session.Info" })
@@ -115,6 +115,7 @@ describe("public event manifest", () => {
"session.model.selected.1",
"session.moved.1",
"session.renamed.1",
"session.permissions.updated.1",
"session.viewed.1",
"session.message.content.updated.1",
"session.usage.recorded.1",
@@ -83,6 +83,15 @@ export const PermissionHandler = HttpApiBuilder.group(Api, "server.permission",
return HttpApiSchema.NoContent.make()
}),
)
.handle(
"session.permission.rules",
Effect.fn(function* (ctx) {
yield* sessions
.setPermissions({ sessionID: ctx.params.sessionID, permissions: ctx.payload.permissions })
.pipe(Effect.catchTag("Session.NotFoundError", missingSession))
return HttpApiSchema.NoContent.make()
}),
)
.handle(
"permission.saved.list",
Effect.fn(function* (ctx) {
+1
View File
@@ -120,6 +120,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
agent: ctx.payload.agent,
model: ctx.payload.model,
metadata: ctx.payload.metadata,
permissions: ctx.payload.permissions,
location: ctx.payload.location ?? { directory: AbsolutePath.make(process.cwd()) },
})
.pipe(Effect.orDie),
@@ -427,17 +427,6 @@ export function SessionCompactionMessage(props: { message: SessionMessageCompact
<div class="py-2">
<TimelineSeparator label={i18n.t("ui.messagePart.compaction.started")} />
</div>
<Show when={props.message.status === "running"}>
<div role="status" class="py-2">
<BasicTool
icon="archive"
trigger={{ title: i18n.t("ui.messagePart.compaction.running") }}
status="running"
locked
hideDetails
/>
</div>
</Show>
<Show when={summary().trim()}>
<div data-component="text-part" data-timeline-part-id={props.message.id}>
<div data-slot="text-part-body">
@@ -449,6 +438,17 @@ export function SessionCompactionMessage(props: { message: SessionMessageCompact
</div>
</div>
</Show>
<Show when={props.message.status === "running"}>
<div role="status" class="py-2">
<BasicTool
icon="archive"
trigger={{ title: i18n.t("ui.messagePart.compaction.running") }}
status="running"
locked
hideDetails
/>
</div>
</Show>
<Show when={props.message.status !== "running"}>
<div class="py-2">
<TimelineSeparator label={label()} />
@@ -39,6 +39,7 @@ describe("inference stat normalization", () => {
})
test("merges renamed models under their current name", () => {
expect(statModel("deepseek-flash", "")).toBe("deepseek-v4.1-flash")
expect(statModel("x-preview-f", "")).toBe("ox-alpha")
expect(statModel("xiaomi/mimo-v2.5", "")).toBe("mimo-v2.5")
expect(toModelAggregate(aggregate("x-preview-f", "openai"))).toMatchObject([
@@ -14,6 +14,7 @@ export const MODEL_AUTHOR_RULES = [
] as const
export const EXCLUDED_MODELS = new Set(["alpha-gpt-next"])
export const MODEL_NAME_ALIASES: Record<string, string> = {
"deepseek-flash": "deepseek-v4.1-flash",
"x-preview-f": "ox-alpha",
"xiaomi/mimo-v2.5": "mimo-v2.5",
}
+2 -1
View File
@@ -51,7 +51,8 @@ export function createClipboardAdapter(clipboard: CoreClipboardService): OwnedCl
throw new Error(`Unexpected clipboard MIME type: ${result.representation.mimeType}`)
},
async write(text) {
const result = await clipboard.writeText(text, {
// OpenTUI rejects NUL before any destination; host clipboard text cannot contain it.
const result = await clipboard.writeText(text.replaceAll("\0", ""), {
destination: "all-available",
selection: "clipboard",
})
+1
View File
@@ -274,6 +274,7 @@ export const Definitions = {
"permission.prompt.fullscreen": keybind("ctrl+f", "Toggle permission prompt fullscreen"),
"plugins.toggle": keybind("return", "Toggle plugin"),
"dialog.mcp.toggle": keybind("space", "Toggle MCP server"),
"dialog.plugins.error": keybind("space", "View plugin error"),
"dialog.plugins.install": keybind("shift+i", "Install plugin from plugin dialog"),
"dialog.plugins.update": keybind("ctrl+u", "Update plugin from plugin dialog"),
"dialog.plugins.check": keybind("ctrl+r", "Check for plugin updates from plugin dialog"),
@@ -223,6 +223,15 @@ export function PluginsDialog(props: {
disabled: checking(),
onTrigger: check,
},
{
title: "view error",
command: "dialog.plugins.error",
hidden: !pluginError(focusedTui()),
onTrigger: (option) => {
const entry = entries().find((entry) => entry.key === option.value)
if (pluginError(entry)) setDetail(entry)
},
},
{
title: toggleTitle(),
command: "plugins.toggle",
@@ -239,7 +248,7 @@ export function PluginsDialog(props: {
},
]}
footer={
<Show when={pluginError(focusedEntry())}>
<Show when={pluginError(focusedEntry()) && !focusedTui()}>
<text>
<span style={{ fg: props.context.theme.text.default }}>
<b>enter</b>
+3 -280
View File
@@ -1,6 +1,5 @@
import {
batch,
createContext,
createEffect,
createMemo,
createSignal,
@@ -12,7 +11,6 @@ import {
onMount,
Show,
Switch,
useContext,
type Accessor,
} from "solid-js"
import path from "node:path"
@@ -29,7 +27,6 @@ import { createSyntaxStyleMemo, ThemeContextProvider, useTheme, useThemes } from
import { BoxRenderable, ScrollBoxRenderable, addDefaultParsers, TextAttributes, RGBA, MouseEvent } from "@opentui/core"
import { Prompt, type PromptRef } from "../../component/prompt"
import type {
ModelInfo,
SessionMessageInfo,
SessionMessageAssistant,
SessionMessageAssistantReasoning,
@@ -111,6 +108,9 @@ import { createDelayedPresence } from "../../util/delayed-presence"
import { SessionLocationMissing } from "./location-missing"
import { isRecord } from "../../util/record"
import { createHistoryPrepend } from "./history"
import { context, use, type PendingAction } from "./render-context"
import { INLINE_TOOL_ICON_WIDTH, InlineToolRow, ReasoningPart, reasoningContent, TextPart } from "./message-parts"
export { InlineToolRow } from "./message-parts"
addDefaultParsers(parsers.parsers)
@@ -121,34 +121,6 @@ const BACKGROUND_TOOL_HINT_DELAY = 3_000
// The tail comfortably overfills a tall viewport; older rows mount as the reader approaches them.
const TRANSCRIPT_TAIL_ROWS = 40
const TRANSCRIPT_BACKFILL_CHUNK = 60
type PendingAction = "steer" | "queue" | "cancel"
const context = createContext<{
/** Content width: terminal width minus vertical tabs, sidebar, and padding. */
width: number
/**
* Shared reactive terminal size. Transcript-row components must read this
* instead of calling useTerminalDimensions(), which registers one renderer
* resize listener per mounted component and grows with transcript length.
*/
terminal: { width: number; height: number }
sessionID: string
thinkingMode: () => ThinkingMode
markdownMode: () => "source" | "rendered"
groupExploration: () => boolean
diffWrapMode: () => "word" | "none"
models: () => ModelInfo[]
messageIndex: (messageID: string) => number | undefined
config: ReturnType<typeof useConfig>["data"]
mutatePending: (action: PendingAction, inboxID: string) => Promise<boolean>
pendingDelivery: (inboxID: string) => SessionInbox.Delivery | undefined
}>()
function use() {
const ctx = useContext(context)
if (!ctx) throw new Error("useContext must be used within a Session component")
return ctx
}
export function Session(props: {
scrollRef?: (scroll: ScrollBoxRenderable | undefined) => void
@@ -2462,160 +2434,6 @@ function AssistantRetry(props: { retry: SessionMessageAssistant["retry"] }) {
)
}
const INLINE_TOOL_ICON_WIDTH = 2
function ReasoningPart(props: {
last: boolean
part: SessionMessageAssistantReasoning
message: SessionMessageAssistant
}) {
const theme = useTheme()
const { currentSyntax: syntax } = useThemes()
const thinkingSyntax = createSyntaxStyleMemo(() => generateThinkingSyntax(syntax(), theme.text.subdued))
const ctx = use()
// Collapsed by default in hide mode: a single line throughout, so the
// layout never shifts. Click to open the full markdown block, click to close.
const [expanded, setExpanded] = createSignal(false)
const content = createMemo(() => reasoningContent(props.part))
const isDone = createMemo(
() => props.part.time?.completed !== undefined || props.message.time.completed !== undefined,
)
const inMinimal = createMemo(() => ctx.thinkingMode() === "hide")
const duration = createMemo(() => {
const end = props.part.time?.completed ?? props.message.time.completed
const start = props.part.time?.created ?? props.message.time.created
return end === undefined ? 0 : Math.max(0, end - start)
})
const summary = createMemo(() => reasoningSummary(content()))
const toggle = () => {
if (!inMinimal()) return
setExpanded((prev) => !prev)
}
return (
<Show when={content()}>
<box paddingLeft={3} flexDirection="column" flexShrink={0}>
<box
border={!inMinimal() || expanded() ? ["left"] : undefined}
customBorderChars={SplitBorder.customBorderChars}
borderColor={theme.raise(theme.background.default)}
paddingLeft={!inMinimal() || expanded() ? 1 : 0}
>
<box onMouseUp={toggle}>
<ReasoningHeader
toggleable={inMinimal()}
open={!inMinimal() || expanded()}
done={isDone()}
title={inMinimal() && !expanded() ? summary().title : null}
duration={isDone() ? Locale.duration(duration()) : undefined}
/>
</box>
</box>
<Show when={!inMinimal() || expanded()}>
<box marginTop={1}>
<box
border={["left"]}
customBorderChars={SplitBorder.customBorderChars}
borderColor={theme.raise(theme.background.default)}
paddingLeft={inMinimal() ? 3 : 1}
>
<code
filetype="markdown"
drawUnstyledText={false}
streaming={true}
syntaxStyle={thinkingSyntax()}
content={content()}
conceal={ctx.markdownMode() === "rendered"}
fg={theme.text.subdued}
/>
</box>
</box>
</Show>
</box>
</Show>
)
}
function reasoningContent(part: SessionMessageAssistantReasoning) {
// OpenRouter encrypts some reasoning blocks; drop the placeholder.
return part.text.replace("[REDACTED]", "").trim()
}
function ReasoningHeader(props: {
toggleable: boolean
open: boolean
done: boolean
title: string | null
duration?: string
}) {
const theme = useTheme()
const fg = () =>
props.open
? RGBA.fromValues(
theme.text.feedback.warning.default.r,
theme.text.feedback.warning.default.g,
theme.text.feedback.warning.default.b,
0.6,
)
: theme.text.feedback.warning.default
return (
<Switch>
<Match when={!props.done}>
<box flexDirection="row">
<Spinner color={fg()}>{props.title ? "Thinking: " + props.title : "Thinking"}</Spinner>
</box>
</Match>
<Match when={true}>
<text fg={fg()} wrapMode="none">
<Show when={props.toggleable}>
<span>{props.open ? "- " : "+ "}</span>
</Show>
<span>Thought</span>
<Show when={props.title || props.duration}>
<span>: </span>
</Show>
<Show when={props.title}>
<span>{props.title}</span>
</Show>
<Show when={props.duration}>
<span>
{props.title ? " · " : ""}
{props.duration}
</span>
</Show>
</text>
</Match>
</Switch>
)
}
function TextPart(props: { last: boolean; part: SessionMessageAssistantText; message: SessionMessageAssistant }) {
const ctx = use()
const theme = useTheme()
const { currentSyntax: syntax } = useThemes()
const plugins = usePlugin()
return (
<Show when={props.part.text.trim()}>
<box paddingLeft={3} flexShrink={0}>
{/* Configure custom nodes before parsing; apply content before streaming so completion keeps the final tokens. */}
<markdown
syntaxStyle={syntax()}
renderNode={plugins.markdown()}
content={props.part.text.trim()}
streaming={props.message.time.completed === undefined}
internalBlockMode="top-level"
tableOptions={{ style: "grid", cellPaddingX: 1 }}
conceal={ctx.markdownMode() === "rendered"}
fg={theme.markdown.text}
bg={theme.background.default}
/>
</box>
</Show>
)
}
// Pending messages moved to individual tool pending functions
function ToolPart(props: { part: SessionMessageAssistantTool; images?: boolean }) {
@@ -2918,101 +2736,6 @@ function InlineTool(props: {
)
}
export function InlineToolRow(props: {
icon: string
iconColor?: RGBA
color?: RGBA
errorColor?: RGBA
failed?: boolean
denied?: boolean
error?: string
errorExpanded?: boolean
complete: unknown
pending: string
failure?: string
spinner?: boolean
status?: JSX.Element
children: JSX.Element
onMouseOver?: () => void
onMouseOut?: () => void
onMouseUp?: () => void
}) {
return (
<box paddingLeft={3} onMouseOver={props.onMouseOver} onMouseOut={props.onMouseOut} onMouseUp={props.onMouseUp}>
<Switch>
<Match when={props.spinner}>
<Show when={props.status} fallback={<Spinner color={props.color} children={props.children} />}>
{(status) => (
<box flexDirection="row" gap={1}>
<Spinner color={props.color} />
<InlineToolLabel color={props.color} status={status()}>
{props.children}
</InlineToolLabel>
</box>
)}
</Show>
</Match>
<Match when={true}>
<Show fallback={<Spinner color={props.color}>{props.pending}</Spinner>} when={props.complete || props.failed}>
<box flexDirection="row">
<text
width={INLINE_TOOL_ICON_WIDTH}
fg={props.failed ? props.errorColor : (props.iconColor ?? props.color)}
attributes={props.denied ? TextAttributes.STRIKETHROUGH : undefined}
>
{props.icon}
</text>
<Show
when={props.status}
fallback={
<text
flexGrow={1}
fg={props.failed ? props.errorColor : props.color}
attributes={props.denied ? TextAttributes.STRIKETHROUGH : undefined}
>
{props.failed && !props.complete ? (props.failure ?? props.children) : props.children}
</text>
}
>
{(status) => (
<InlineToolLabel
color={props.failed ? props.errorColor : props.color}
denied={props.denied}
status={status()}
>
{props.failed && !props.complete ? (props.failure ?? props.children) : props.children}
</InlineToolLabel>
)}
</Show>
</box>
</Show>
</Match>
</Switch>
<Show when={props.failed && props.errorExpanded}>
<box paddingLeft={INLINE_TOOL_ICON_WIDTH}>
<text fg={props.errorColor}>{props.error}</text>
</box>
</Show>
</box>
)
}
function InlineToolLabel(props: { color?: RGBA; denied?: boolean; status: JSX.Element; children: JSX.Element }) {
return (
<box flexDirection="row" flexWrap="wrap" columnGap={1} flexGrow={1}>
<text
maxWidth="100%"
flexShrink={0}
fg={props.color}
attributes={props.denied ? TextAttributes.STRIKETHROUGH : undefined}
>
{props.children}
</text>
{props.status}
</box>
)
}
function StatusBadge(props: { children: string }) {
const theme = useTheme()
return (
@@ -0,0 +1,269 @@
import { createMemo, createSignal, Match, Show, Switch } from "solid-js"
import { RGBA, TextAttributes } from "@opentui/core"
import type { JSX } from "@opentui/solid"
import type {
SessionMessageAssistant,
SessionMessageAssistantReasoning,
SessionMessageAssistantText,
} from "@opencode/client"
import { Spinner } from "../../component/spinner"
import { createSyntaxStyleMemo, useTheme, useThemes } from "../../context/theme"
import { reasoningSummary } from "../../context/thinking"
import { usePlugin } from "../../plugin/context"
import { SplitBorder } from "../../ui/border"
import { Locale } from "../../util/locale"
import { use } from "./render-context"
import { generateThinkingSyntax } from "./thinking-syntax"
export const INLINE_TOOL_ICON_WIDTH = 2
export function ReasoningPart(props: {
last: boolean
part: SessionMessageAssistantReasoning
message: SessionMessageAssistant
}) {
const theme = useTheme()
const { currentSyntax: syntax } = useThemes()
const thinkingSyntax = createSyntaxStyleMemo(() => generateThinkingSyntax(syntax(), theme.text.subdued))
const ctx = use()
// Collapsed by default in hide mode: a single line throughout, so the
// layout never shifts. Click to open the full markdown block, click to close.
const [expanded, setExpanded] = createSignal(false)
const content = createMemo(() => reasoningContent(props.part))
const isDone = createMemo(
() => props.part.time?.completed !== undefined || props.message.time.completed !== undefined,
)
const inMinimal = createMemo(() => ctx.thinkingMode() === "hide")
const duration = createMemo(() => {
const end = props.part.time?.completed ?? props.message.time.completed
const start = props.part.time?.created ?? props.message.time.created
return end === undefined ? 0 : Math.max(0, end - start)
})
const summary = createMemo(() => reasoningSummary(content()))
const toggle = () => {
if (!inMinimal()) return
setExpanded((prev) => !prev)
}
return (
<Show when={content()}>
<box paddingLeft={3} flexDirection="column" flexShrink={0}>
<box
border={!inMinimal() || expanded() ? ["left"] : undefined}
customBorderChars={SplitBorder.customBorderChars}
borderColor={theme.raise(theme.background.default)}
paddingLeft={!inMinimal() || expanded() ? 1 : 0}
>
<box onMouseUp={toggle}>
<ReasoningHeader
toggleable={inMinimal()}
open={!inMinimal() || expanded()}
done={isDone()}
title={inMinimal() && !expanded() ? summary().title : null}
duration={isDone() ? Locale.duration(duration()) : undefined}
/>
</box>
</box>
<Show when={!inMinimal() || expanded()}>
<box marginTop={1}>
<box
border={["left"]}
customBorderChars={SplitBorder.customBorderChars}
borderColor={theme.raise(theme.background.default)}
paddingLeft={inMinimal() ? 3 : 1}
>
<code
filetype="markdown"
drawUnstyledText={false}
streaming={true}
syntaxStyle={thinkingSyntax()}
content={content()}
conceal={ctx.markdownMode() === "rendered"}
fg={theme.text.subdued}
/>
</box>
</box>
</Show>
</box>
</Show>
)
}
export function reasoningContent(part: SessionMessageAssistantReasoning) {
// OpenRouter encrypts some reasoning blocks; drop the placeholder.
return part.text.replace("[REDACTED]", "").trim()
}
function ReasoningHeader(props: {
toggleable: boolean
open: boolean
done: boolean
title: string | null
duration?: string
}) {
const theme = useTheme()
const fg = () =>
props.open
? RGBA.fromValues(
theme.text.feedback.warning.default.r,
theme.text.feedback.warning.default.g,
theme.text.feedback.warning.default.b,
0.6,
)
: theme.text.feedback.warning.default
return (
<Switch>
<Match when={!props.done}>
<box flexDirection="row">
<Spinner color={fg()}>{props.title ? "Thinking: " + props.title : "Thinking"}</Spinner>
</box>
</Match>
<Match when={true}>
<text fg={fg()} wrapMode="none">
<Show when={props.toggleable}>
<span>{props.open ? "- " : "+ "}</span>
</Show>
<span>Thought</span>
<Show when={props.title || props.duration}>
<span>: </span>
</Show>
<Show when={props.title}>
<span>{props.title}</span>
</Show>
<Show when={props.duration}>
<span>
{props.title ? " · " : ""}
{props.duration}
</span>
</Show>
</text>
</Match>
</Switch>
)
}
export function TextPart(props: {
last: boolean
part: SessionMessageAssistantText
message: SessionMessageAssistant
}) {
const ctx = use()
const theme = useTheme()
const { currentSyntax: syntax } = useThemes()
const plugins = usePlugin()
return (
<Show when={props.part.text.trim()}>
<box paddingLeft={3} flexShrink={0}>
{/* Configure custom nodes before parsing; apply content before streaming so completion keeps the final tokens. */}
<markdown
syntaxStyle={syntax()}
renderNode={plugins.markdown()}
content={props.part.text.trim()}
streaming={props.message.time.completed === undefined}
internalBlockMode="top-level"
tableOptions={{ style: "grid", cellPaddingX: 1 }}
conceal={ctx.markdownMode() === "rendered"}
fg={theme.markdown.text}
bg={theme.background.default}
/>
</box>
</Show>
)
}
export function InlineToolRow(props: {
icon: string
iconColor?: RGBA
color?: RGBA
errorColor?: RGBA
failed?: boolean
denied?: boolean
error?: string
errorExpanded?: boolean
complete: unknown
pending: string
failure?: string
spinner?: boolean
status?: JSX.Element
children: JSX.Element
onMouseOver?: () => void
onMouseOut?: () => void
onMouseUp?: () => void
}) {
return (
<box paddingLeft={3} onMouseOver={props.onMouseOver} onMouseOut={props.onMouseOut} onMouseUp={props.onMouseUp}>
<Switch>
<Match when={props.spinner}>
<Show when={props.status} fallback={<Spinner color={props.color} children={props.children} />}>
{(status) => (
<box flexDirection="row" gap={1}>
<Spinner color={props.color} />
<InlineToolLabel color={props.color} status={status()}>
{props.children}
</InlineToolLabel>
</box>
)}
</Show>
</Match>
<Match when={true}>
<Show fallback={<Spinner color={props.color}>{props.pending}</Spinner>} when={props.complete || props.failed}>
<box flexDirection="row">
<text
width={INLINE_TOOL_ICON_WIDTH}
fg={props.failed ? props.errorColor : (props.iconColor ?? props.color)}
attributes={props.denied ? TextAttributes.STRIKETHROUGH : undefined}
>
{props.icon}
</text>
<Show
when={props.status}
fallback={
<text
flexGrow={1}
fg={props.failed ? props.errorColor : props.color}
attributes={props.denied ? TextAttributes.STRIKETHROUGH : undefined}
>
{props.failed && !props.complete ? (props.failure ?? props.children) : props.children}
</text>
}
>
{(status) => (
<InlineToolLabel
color={props.failed ? props.errorColor : props.color}
denied={props.denied}
status={status()}
>
{props.failed && !props.complete ? (props.failure ?? props.children) : props.children}
</InlineToolLabel>
)}
</Show>
</box>
</Show>
</Match>
</Switch>
<Show when={props.failed && props.errorExpanded}>
<box paddingLeft={INLINE_TOOL_ICON_WIDTH}>
<text fg={props.errorColor}>{props.error}</text>
</box>
</Show>
</box>
)
}
function InlineToolLabel(props: { color?: RGBA; denied?: boolean; status: JSX.Element; children: JSX.Element }) {
return (
<box flexDirection="row" flexWrap="wrap" columnGap={1} flexGrow={1}>
<text
maxWidth="100%"
flexShrink={0}
fg={props.color}
attributes={props.denied ? TextAttributes.STRIKETHROUGH : undefined}
>
{props.children}
</text>
{props.status}
</box>
)
}
@@ -0,0 +1,34 @@
import { createContext, useContext } from "solid-js"
import type { ModelInfo } from "@opencode/client"
import type { SessionInbox } from "@opencode/schema/session-inbox"
import type { useConfig } from "../../config"
import type { ThinkingMode } from "../../context/thinking"
export type PendingAction = "steer" | "queue" | "cancel"
export const context = createContext<{
/** Content width: terminal width minus vertical tabs, sidebar, and padding. */
width: number
/**
* Shared reactive terminal size. Transcript-row components must read this
* instead of calling useTerminalDimensions(), which registers one renderer
* resize listener per mounted component and grows with transcript length.
*/
terminal: { width: number; height: number }
sessionID: string
thinkingMode: () => ThinkingMode
markdownMode: () => "source" | "rendered"
groupExploration: () => boolean
diffWrapMode: () => "word" | "none"
models: () => ModelInfo[]
messageIndex: (messageID: string) => number | undefined
config: ReturnType<typeof useConfig>["data"]
mutatePending: (action: PendingAction, inboxID: string) => Promise<boolean>
pendingDelivery: (inboxID: string) => SessionInbox.Delivery | undefined
}>()
export function use() {
const ctx = useContext(context)
if (!ctx) throw new Error("useContext must be used within a Session component")
return ctx
}
@@ -13,6 +13,10 @@ import { ThemeProvider, useThemes } from "../../../src/context/theme"
// the context back, so the context must load first exactly as it does in the app.
import type { usePlugin } from "../../../src/plugin/context"
import "../../../src/plugin/context"
import { ClientProvider } from "../../../src/context/client"
import { DataProvider } from "../../../src/context/data"
import { LocationProvider } from "../../../src/context/location"
import { RouteProvider } from "../../../src/context/route"
import { PluginsDialog } from "../../../src/feature-plugins/system/plugins"
import { DialogProvider } from "../../../src/ui/dialog"
import { ToastProvider } from "../../../src/ui/toast"
@@ -32,11 +36,19 @@ function packagePlugin(outdated: boolean): PluginInfo {
}
}
async function renderPlugins(root: string, inventory: { list: PluginInfo[]; check: PluginInfo[] }) {
async function renderPlugins(
root: string,
inventory: { list: PluginInfo[]; check: PluginInfo[] },
tui?: {
registered: { id: string; source: "builtin" | "external"; active: boolean }[]
list: { target: string; id?: string; status: "active" | "inactive" | "failed"; error?: string }[]
},
) {
const state = path.join(root, "state")
await mkdir(state, { recursive: true })
const requests: { path: string; body: unknown }[] = []
const toasts: ToastOptions[] = []
const activations: string[] = []
const location = { directory: root, project: { id: "proj_test", directory: root, canonical: root } }
const transport = createFetch(async (url, request) => {
if (url.pathname === "/api/plugin") return json({ location, data: inventory.list })
@@ -49,13 +61,14 @@ async function renderPlugins(root: string, inventory: { list: PluginInfo[]; chec
return new Response(null, { status: 204 })
}
})
const api = createApi(transport.fetch)
function Harness() {
function Content() {
onCleanup(Keymap.use().mode.push("modal"))
const theme = useThemes().currentTokens()
const context = {
client: createApi(transport.fetch),
client: api,
data: { location: { default: () => ({ directory: root }) }, on: () => () => {} },
get theme() {
return theme
@@ -66,9 +79,12 @@ async function renderPlugins(root: string, inventory: { list: PluginInfo[]; chec
},
} as unknown as Context
const plugins = {
registered: () => [],
list: () => [],
activate: async () => true,
registered: () => tui?.registered ?? [],
list: () => tui?.list ?? [],
activate: async (id: string) => {
activations.push(id)
return true
},
deactivate: async () => true,
} as unknown as ReturnType<typeof usePlugin>
return <PluginsDialog context={context} plugins={plugins} />
@@ -77,15 +93,23 @@ async function renderPlugins(root: string, inventory: { list: PluginInfo[]; chec
return (
<TestTuiContexts directory={root} paths={{ home: root, state, worktree: root }}>
<ConfigProvider config={createTuiResolvedConfig()}>
<Keymap.Provider>
<ThemeProvider mode="dark" source={emptyThemeSource}>
<ToastProvider>
<DialogProvider>
<Content />
</DialogProvider>
</ToastProvider>
</ThemeProvider>
</Keymap.Provider>
<RouteProvider initialRoute={{ type: "home" }}>
<ClientProvider api={api}>
<DataProvider directory={root}>
<LocationProvider>
<Keymap.Provider>
<ThemeProvider mode="dark" source={emptyThemeSource}>
<ToastProvider>
<DialogProvider>
<Content />
</DialogProvider>
</ToastProvider>
</ThemeProvider>
</Keymap.Provider>
</LocationProvider>
</DataProvider>
</ClientProvider>
</RouteProvider>
</ConfigProvider>
</TestTuiContexts>
)
@@ -93,10 +117,46 @@ async function renderPlugins(root: string, inventory: { list: PluginInfo[]; chec
const app = await testRender(() => <Harness />, { width: 80, height: 20, kittyKeyboard: true })
app.renderer.start()
await app.waitForFrame((frame) => frame.includes("team.plugins") || frame.includes("local.plugin"))
return { app, requests, toasts }
const expected = tui?.list[0]?.id ?? inventory.list[0]?.id ?? "local.plugin"
await app.waitForFrame((frame) => frame.includes(expected))
return { app, requests, toasts, activations }
}
test("failed TUI plugins keep enter to enable and use space to show the error", async () => {
await using tmp = await tmpdir()
const fixture = await renderPlugins(
tmp.path,
{ list: [], check: [] },
{
registered: [{ id: "broken.plugin", source: "external", active: false }],
list: [
{
target: "./broken.ts",
id: "broken.plugin",
status: "failed",
error: "Plugin setup failed",
},
],
},
)
try {
await fixture.app.waitForFrame((frame) => frame.includes("broken.plugin") && frame.includes("view error"))
expect(fixture.app.captureCharFrame()).toContain("enable")
fixture.app.mockInput.pressEnter()
await fixture.app.waitFor(() => fixture.activations.length === 1)
expect(fixture.activations).toEqual(["broken.plugin"])
fixture.app.mockInput.pressKey(" ")
await fixture.app.waitForFrame(
(frame) => frame.includes("TUI plugin error") && frame.includes("Plugin setup failed"),
)
} finally {
fixture.app.renderer.destroy()
}
})
test("checking for updates refreshes the inventory and reveals the update action", async () => {
await using tmp = await tmpdir()
const fixture = await renderPlugins(tmp.path, { list: [packagePlugin(false)], check: [packagePlugin(true)] })
+13
View File
@@ -102,6 +102,19 @@ test("uses all available routes but skips the process host remotely", async () =
expect(writes).toEqual({ host: 0, terminal: 1 })
})
test("removes NUL characters before writing", async () => {
const writes: string[] = []
const clipboard = createClipboardAdapter(
coreClipboard({
onWrite: (text) => writes.push(text),
}),
)
expect(await clipboard.write("before\0after")).toBeUndefined()
expect(await clipboard.write("clean")).toBeUndefined()
expect(writes).toEqual(["beforeafter", "clean"])
})
test("rejects only when no clipboard route accepted the write", async () => {
const writes: [string, ClipboardWriteOptions][] = []
const failure = new Error("native clipboard failed")
@@ -0,0 +1,25 @@
export * as ProviderPolicyMatcher from "./opencode-policy-matcher.js"
// Shared verbatim with OpenCode packages/util/src/opencode-policy-matcher.ts.
// Keep the paired conformance check passing when changing these semantics.
export type Statement = {
readonly action: "provider.use"
readonly resource: string
readonly effect: "allow" | "deny"
}
export function match(input: string, pattern: string, windows: boolean) {
const normalized = input.replaceAll("\\", "/")
const escaped = pattern
.replaceAll("\\", "/")
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*/g, ".*")
.replace(/\?/g, ".")
const expression = escaped.endsWith(" .*") ? escaped.slice(0, -3) + "( .*)?" : escaped
return new RegExp("^" + expression + "$", windows ? "si" : "s").test(normalized)
}
export function evaluate(statements: readonly Statement[], resource: string, windows: boolean) {
const index = statements.findLastIndex((statement) => match(resource, statement.resource, windows))
return { effect: index === -1 ? ("inherit" as const) : statements[index]!.effect, index: index === -1 ? null : index }
}
@@ -0,0 +1,146 @@
[
{
"name": "no organization override",
"rules": [],
"resource": "openai",
"unix": "inherit",
"windows": "inherit",
"index": null
},
{
"name": "last match wins",
"rules": [
{
"action": "provider.use",
"effect": "deny",
"resource": "*"
},
{
"action": "provider.use",
"effect": "allow",
"resource": "openai"
}
],
"resource": "openai",
"unix": "allow",
"windows": "allow",
"index": 1
},
{
"name": "wildcard after exact wins",
"rules": [
{
"action": "provider.use",
"effect": "allow",
"resource": "openai"
},
{
"action": "provider.use",
"effect": "deny",
"resource": "*"
}
],
"resource": "openai",
"unix": "deny",
"windows": "deny",
"index": 1
},
{
"name": "anchored wildcard",
"rules": [
{
"action": "provider.use",
"effect": "deny",
"resource": "company-*"
}
],
"resource": "not-company-a",
"unix": "inherit",
"windows": "inherit",
"index": null
},
{
"name": "question matches one",
"rules": [
{
"action": "provider.use",
"effect": "deny",
"resource": "company-?"
}
],
"resource": "company-ab",
"unix": "inherit",
"windows": "inherit",
"index": null
},
{
"name": "slash normalization",
"rules": [
{
"action": "provider.use",
"effect": "allow",
"resource": "company/*"
}
],
"resource": "company\\model",
"unix": "allow",
"windows": "allow",
"index": 0
},
{
"name": "case differs by platform",
"rules": [
{
"action": "provider.use",
"effect": "deny",
"resource": "OpenAI"
}
],
"resource": "openai",
"unix": "inherit",
"windows": "deny",
"index": 0
},
{
"name": "regex characters are literal",
"rules": [
{
"action": "provider.use",
"effect": "deny",
"resource": "company.[ab]"
}
],
"resource": "company.a",
"unix": "inherit",
"windows": "inherit",
"index": null
},
{
"name": "trailing wildcard space",
"rules": [
{
"action": "provider.use",
"effect": "allow",
"resource": "company *"
}
],
"resource": "company",
"unix": "allow",
"windows": "allow",
"index": 0
},
{
"name": "question matches exactly one",
"rules": [
{
"action": "provider.use",
"effect": "deny",
"resource": "comp?ny"
}
],
"resource": "company",
"unix": "deny",
"windows": "deny",
"index": 0
}
]
@@ -0,0 +1,34 @@
import { expect, it } from "bun:test"
import { Schema } from "effect"
import { ProviderPolicyMatcher } from "../src/opencode-policy-matcher.js"
const cases = Schema.decodeUnknownSync(
Schema.Array(
Schema.Struct({
name: Schema.String,
rules: Schema.Array(
Schema.Struct({
action: Schema.Literal("provider.use"),
effect: Schema.Literals(["allow", "deny"]),
resource: Schema.String,
}),
),
resource: Schema.String,
unix: Schema.Literals(["allow", "deny", "inherit"]),
windows: Schema.Literals(["allow", "deny", "inherit"]),
index: Schema.NullOr(Schema.Int),
}),
),
)(await Bun.file(new URL("./opencode-policy-cases.json", import.meta.url)).json())
for (const scenario of cases) {
it(scenario.name, () => {
for (const windows of [false, true]) {
const effect = windows ? scenario.windows : scenario.unix
expect(ProviderPolicyMatcher.evaluate(scenario.rules, scenario.resource, windows)).toEqual({
effect,
index: effect === "inherit" ? null : scenario.index,
})
}
})
}
@@ -656,6 +656,16 @@ const request = await ctx.permission.get({ sessionID, requestID })
await ctx.permission.reply({ sessionID, requestID, reply: "once" })
```
Replace the session-scoped permission rules. They are evaluated after the agent's rules, and the
last matching rule wins. Child sessions inherit the rules in effect when they are created.
```ts
await ctx.permission.rules({
sessionID,
permissions: [{ action: "edit", resource: "/path/to/original/checkout/**", effect: "deny" }],
})
```
### Sessions
Create or read a session.
@@ -0,0 +1,548 @@
---
title: "commands"
description: "Reference for the opencode2 command line."
---
Every command accepts `--help` for its full flag list, for example `opencode2 run --help`. Commands that talk to a server also accept `--standalone` to run a private server and `--server <url>` to target a specific one.
## run
`opencode2 run` sends a message and prints the reply without opening the interactive interface.
```bash
$ opencode2 run "Explain this repository"
```
Choose a model.
```bash
$ opencode2 run --model anthropic/claude-sonnet-4-5 "Refactor parseToken"
```
Continue the last session.
```bash
$ opencode2 run --continue "Now handle the expired case"
```
Emit newline-delimited JSON for scripts.
```bash
$ opencode2 run --format json "List the TODO comments"
```
Attach files to the message.
```bash
$ opencode2 run --file src/server.ts --file src/client.ts "Review these for bugs"
```
Run with a specific agent.
```bash
$ opencode2 run --agent build "Fix the failing test"
```
View all subcommands and flags.
```bash
$ opencode2 run --help
```
## mini
`opencode2 mini` starts the minimal interactive interface instead of the full-screen TUI.
```bash
$ opencode2 mini
```
Continue the last session.
```bash
$ opencode2 mini --continue
```
Start with a model and an initial prompt.
```bash
$ opencode2 mini --model anthropic/claude-sonnet-4-5 --prompt "Summarize this repository"
```
View all subcommands and flags.
```bash
$ opencode2 mini --help
```
## session
`opencode2 session` manages sessions.
```bash
$ opencode2 session list
```
Limit the list and print JSON.
```bash
$ opencode2 session list --max-count 20 --format json
```
Delete a session and its child sessions.
```bash
$ opencode2 session delete ses_9c1b08
```
Export session data as JSON.
```bash
$ opencode2 session export ses_4f2a1c
```
Redact sensitive transcript and file data when exporting.
```bash
$ opencode2 session export ses_4f2a1c --sanitize
```
Import session data from a JSON file or URL.
```bash
$ opencode2 session import session.json
```
Import into a specific directory.
```bash
$ opencode2 session import session.json --directory ~/code/project
```
View all subcommands and flags.
```bash
$ opencode2 session --help
```
## auth
`opencode2 auth` manages AI providers and credentials.
```bash
$ opencode2 auth list
```
List them as JSON.
```bash
$ opencode2 auth list --format json
```
Log in to a provider.
```bash
$ opencode2 auth login anthropic
```
Log in with a specific authentication method.
```bash
$ opencode2 auth login anthropic --method api-key
```
Log out of a saved account.
```bash
$ opencode2 auth logout anthropic work
```
Switch the active account for an integration.
```bash
$ opencode2 auth switch anthropic work
```
View all subcommands and flags.
```bash
$ opencode2 auth --help
```
## models
`opencode2 models` lists every available model.
```bash
$ opencode2 models
```
View all subcommands and flags.
```bash
$ opencode2 models --help
```
## mcp
`opencode2 mcp` manages MCP (Model Context Protocol) servers.
```bash
$ opencode2 mcp list
```
Add a remote server.
```bash
$ opencode2 mcp add context7 --url https://mcp.context7.com/mcp
```
Add a local server to the global config.
```bash
$ opencode2 mcp add everything --global -- npx -y @modelcontextprotocol/server-everything
```
Add a local server with an environment variable.
```bash
$ opencode2 mcp add everything --env LOG_LEVEL=debug -- npx -y @modelcontextprotocol/server-everything
```
Add a remote server with a header.
```bash
$ opencode2 mcp add context7 --url https://mcp.context7.com/mcp --header CONTEXT7_API_KEY=secret
```
Authenticate with an OAuth-capable remote server.
```bash
$ opencode2 mcp auth sentry
```
Remove stored OAuth credentials for a server.
```bash
$ opencode2 mcp logout sentry
```
View all subcommands and flags.
```bash
$ opencode2 mcp --help
```
## plugin
`opencode2 plugin` manages plugins.
```bash
$ opencode2 plugin list
```
Include built-in server plugins.
```bash
$ opencode2 plugin list --builtin
```
Install a plugin and add it to the global configuration.
```bash
$ opencode2 plugin add @example/opencode-tui
```
Check package plugins for updates.
```bash
$ opencode2 plugin check
```
Update package plugins.
```bash
$ opencode2 plugin update
```
Remove a plugin from global configuration.
```bash
$ opencode2 plugin remove @example/opencode-tui
```
View all subcommands and flags.
```bash
$ opencode2 plugin --help
```
## stats
`opencode2 stats` shows shareable usage statistics.
```bash
$ opencode2 stats
```
Show the last 7 days.
```bash
$ opencode2 stats --days 7
```
Show model usage.
```bash
$ opencode2 stats --models
```
Show cost and token details.
```bash
$ opencode2 stats --cost
```
Print JSON instead of a report.
```bash
$ opencode2 stats --json
```
View all subcommands and flags.
```bash
$ opencode2 stats --help
```
## serve
`opencode2 serve` starts the API and web server. See [Web](/cli/web).
```bash
$ opencode2 serve
```
Bind to all interfaces on a fixed port.
```bash
$ opencode2 serve --hostname 0.0.0.0 --port 4096
```
Allow a browser client from another origin.
```bash
$ opencode2 serve --cors https://app.example.com
```
View all subcommands and flags.
```bash
$ opencode2 serve --help
```
## pair
`opencode2 pair` shows server pairing information, including URLs, credentials, and a QR code.
```bash
$ opencode2 pair
```
Advertise an external URL in the QR code.
```bash
$ opencode2 pair --url https://dev.example.com
```
View all subcommands and flags.
```bash
$ opencode2 pair --help
```
## service
`opencode2 service` manages the background server. See [Web](/cli/web).
```bash
$ opencode2 service start
```
Restart it.
```bash
$ opencode2 service restart
```
Show its status.
```bash
$ opencode2 service status
```
Stop it.
```bash
$ opencode2 service stop
```
Read a setting.
```bash
$ opencode2 service get hostname
```
Set a setting.
```bash
$ opencode2 service set hostname 0.0.0.0
```
Allow an extra CORS origin.
```bash
$ opencode2 service set cors https://app.example.com
```
Pass an environment variable to the server process.
```bash
$ opencode2 service set env OPENCODE_LOG_LEVEL DEBUG
```
Reset a setting to its default.
```bash
$ opencode2 service unset hostname
```
View all subcommands and flags.
```bash
$ opencode2 service --help
```
## api
`opencode2 api` makes a request to the running server.
```bash
$ opencode2 api GET /api/session
```
Call an operation ID with a query parameter.
```bash
$ opencode2 api v2.session.list --param limit=10
```
Send a JSON body.
```bash
$ opencode2 api v2.session.create --data '{"title": "New session"}'
```
Add a request header.
```bash
$ opencode2 api GET /api/session -H "accept: application/json"
```
View all subcommands and flags.
```bash
$ opencode2 api --help
```
## acp
`opencode2 acp` starts an Agent Client Protocol server over stdin and stdout for editor integrations. It runs until the client closes the connection.
```bash
$ opencode2 acp
```
View all subcommands and flags.
```bash
$ opencode2 acp --help
```
## debug
`opencode2 debug` provides debugging and troubleshooting tools.
```bash
$ opencode2 debug agents
```
List configuration sources.
```bash
$ opencode2 debug config
```
Show global paths.
```bash
$ opencode2 debug paths
```
Print a single path.
```bash
$ opencode2 debug paths db
```
View all subcommands and flags.
```bash
$ opencode2 debug --help
```
## upgrade
`opencode2 upgrade` upgrades OpenCode to the latest or a specific version. Alias: `update`.
```bash
$ opencode2 upgrade
```
Upgrade to a specific version with a specific package manager.
```bash
$ opencode2 upgrade 1.18.15 --method bun
```
View all subcommands and flags.
```bash
$ opencode2 upgrade --help
```
## uninstall
`opencode2 uninstall` removes OpenCode and all related files.
```bash
$ opencode2 uninstall
```
Preview what would be removed.
```bash
$ opencode2 uninstall --dry-run
```
Keep configuration and session data.
```bash
$ opencode2 uninstall --keep-config --keep-data
```
View all subcommands and flags.
```bash
$ opencode2 uninstall --help
```
+74
View File
@@ -0,0 +1,74 @@
---
title: "Web"
description: "Run OpenCode in the browser."
---
OpenCode ships with a web ui that is served from the same server that powers the
TUI. It's available by default and password protected.
## Access
```bash
$ opencode2 pair
URLs http://127.0.0.1:49374
Username opencode
Password ********
```
By default the server runs on port 49374 and listens only on localhost. You can
change this config with the `opencode2 service` command.
## Configure
Set any option with `opencode2 service set`:
```bash
# Listen on every network interface
$ opencode2 service set hostname 0.0.0.0
# Use a fixed port instead of the channel default
$ opencode2 service set port 49374
# Replace the generated password
$ opencode2 service set password "a-long-secret"
# Allow a web client served from another origin
$ opencode2 service set cors https://app.example.com,https://other.example.com
# Pass an environment variable to the server process
$ opencode2 service set env OPENCODE_LOG_LEVEL DEBUG
```
Changing a setting stops the background server. To apply the new config
```bash
$ opencode2 service start
```
## Standalone
`opencode2 serve` runs the same server in the foreground instead of through the
shared background service.
```bash
$ opencode2 serve --hostname 0.0.0.0 --port 4096
server listening on http://0.0.0.0:4096
server password <password>
```
Use it when you want to:
- Run OpenCode on a shared, always-on, or remote host, then connect clients with
`opencode2 --server <url>`.
- Control the hostname, port, and CORS origins for a single process.
- Run under a supervisor like systemd, Docker, or another environment that expects
a foreground process.
- Keep a dedicated server instead of the shared background service.
Connect a client to it with `--server`:
```bash
$ opencode2 --server http://127.0.0.1:4096
```
-18
View File
@@ -247,24 +247,6 @@ field, but it does not run formatters yet.
See the [formatters guide](/formatters) for accepted fields and current limitations.
### LSP
Define language server settings for compatibility and future use. V2 accepts
this field, but it does not start language servers yet.
```jsonc
{
"lsp": {
"typescript": {
"command": ["typescript-language-server", "--stdio"],
"extensions": [".ts", ".tsx"],
},
},
}
```
See the [LSP guide](/lsp) for accepted fields and current limitations.
### Media
Control how oversized images loaded by the `read` tool are resized or rejected
-103
View File
@@ -1,103 +0,0 @@
---
title: "LSP"
---
Language Server Protocol (LSP) integrations can provide code diagnostics,
symbols, definitions, references, and other language-aware context.
<Callout type="warning">
OpenCode V2 does not yet have an LSP runtime or built-in language servers. The `lsp` configuration is accepted and
preserved, but it does not currently start or download servers, expose an LSP tool, or add diagnostics to file tool
results.
</Callout>
## Built-in servers
There are no built-in LSP servers in the current V2 implementation. Setting
`lsp` to `true` declares that built-ins should be enabled, but has no runtime
effect until V2 provides a server registry and LSP runtime.
```jsonc title="opencode.jsonc"
{
"$schema": "https://opencode.ai/config.json",
"lsp": true,
}
```
## Configuration
The `lsp` field accepts a boolean or an object keyed by server name:
```jsonc title="opencode.jsonc"
{
"$schema": "https://opencode.ai/config.json",
"lsp": {
"custom-typescript": {
"command": ["typescript-language-server", "--stdio"],
"extensions": [".ts", ".tsx"],
"env": {
"TSS_LOG": "-level verbose",
},
"initialization": {
"preferences": {
"importModuleSpecifierPreference": "relative",
},
},
},
},
}
```
Each enabled server entry has this shape:
| Property | Type | Required | Description |
| ---------------- | ------------------------- | -------- | --------------------------------------------------------------------------------------------- |
| `command` | `string[]` | Yes | Executable followed by any arguments. |
| `extensions` | `string[]` | No | File extensions associated with the server, including the leading dot. |
| `disabled` | `boolean` | No | Disables the entry when `true`. |
| `env` | `Record<string, string>` | No | Environment variables for the server process. The property is named `env`, not `environment`. |
| `initialization` | `Record<string, unknown>` | No | Server-specific options for the LSP `initialize` request. |
The only entry that may omit `command` is the disable-only form:
```jsonc
{
"lsp": {
"typescript": {
"disabled": true,
},
},
}
```
Server names are arbitrary. The V2 schema permits `extensions` to be omitted,
including for a custom server, although a future runtime will need a way to
associate that server with files.
## Disable LSP
Omit `lsp` when no configuration is needed. Set it to `false` to explicitly
disable the whole integration, including when a lower-priority configuration
set it to `true` or supplied an object:
```jsonc title="opencode.jsonc"
{
"$schema": "https://opencode.ai/config.json",
"lsp": false,
}
```
Use `{ "disabled": true }` under a server name to disable one server while
retaining the object form. `OPENCODE_DISABLE_LSP_DOWNLOAD` is not used by V2;
V2 currently performs no automatic LSP downloads.
## Current usage
V2 loads and validates the configuration shape for compatibility and future
integration. It does not currently use LSP when reading, writing, editing, or
patching files, and those tools do not notify a language server or return LSP
diagnostics.
For reliable feedback today, have the agent run the project's lint, typecheck,
test, or compiler commands. Record those commands in an `AGENTS.md` file or a
skill so the agent knows when and where to run them.
+5 -4
View File
@@ -110,10 +110,11 @@ role for other Foundry models. If a request fails because the token belongs to a
## WebSocket transport
OpenAI and supported Azure Responses models keep one WebSocket connection open per session and send each step over it
instead of opening a new HTTP request. While the request prefix is unchanged, consecutive steps only transmit what was
added since the previous response, which cuts upload volume on long sessions. Provider compaction runs over the same
connection.
OpenAI, xAI, and supported Azure Responses models keep one WebSocket connection open per session and send each step
over it instead of opening a new HTTP request. While the request prefix is unchanged, consecutive steps only transmit
what was added since the previous response, which cuts upload volume on long sessions. OpenAI provider compaction runs
over the same connection. xAI continues a chain only from stored responses, so with its default `store: false` each step
is sent in full over the reused connection.
The connection is transparent. When the provider closes the socket, the next step reconnects; when a connection cannot
be opened at all, the session continues over HTTP. Plugins that register `http.request` or `http.response` hooks for a
+2 -32
View File
@@ -1,35 +1,5 @@
---
title: "Session sharing"
title: "Sharing"
---
Session sharing is not yet available in OpenCode V2. V2 does not currently
publish sessions, upload conversation history to a sharing service, or create
public links.
There is no functional share or unshare server API endpoint.
## Configuration
The V2 configuration schema accepts a `share` field with three values:
```jsonc title="opencode.jsonc"
{
"$schema": "https://opencode.ai/config.json",
"share": "manual",
}
```
- `"manual"` represents sharing only when explicitly requested.
- `"auto"` represents automatically sharing new sessions.
- `"disabled"` represents preventing session sharing.
These values are parsed but are not acted on by the current V2 runtime. In
particular, setting `"auto"` does not publish sessions. If `share` is omitted,
V2 leaves the sharing policy unspecified.
## Beta limitations
V2 currently provides no public session viewer, share URL, history sync,
retention controls, or unshare/delete operation. Until those surfaces are
implemented in the V2 server and protocol, keep using sessions locally and do
not treat the `share` configuration field as a privacy or publishing control.
OpenCode V2 does not support session sharing yet.
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: "Session warming"
title: "Warming"
---
Session warming sends periodic model requests for recently active sessions.
+4 -8
View File
@@ -30,7 +30,6 @@ export const docsSections: DocsSection[] = [
{
title: "Configure",
items: [
{ title: "LSP", slug: "lsp" },
{ title: "Agents", slug: "agents" },
{ title: "Models", slug: "models" },
{ title: "Skills", slug: "skills" },
@@ -46,8 +45,8 @@ export const docsSections: DocsSection[] = [
{ title: "MCP servers", slug: "mcp-servers" },
{ title: "Permissions", slug: "permissions" },
{ title: "Instructions", slug: "instructions" },
{ title: "Session sharing", slug: "sharing" },
{ title: "Session warming", slug: "warming" },
{ title: "Sharing", slug: "sharing" },
{ title: "Warming", slug: "warming" },
],
},
{
@@ -67,11 +66,8 @@ export const docsSections: DocsSection[] = [
items: [
{ title: "Intro", slug: "cli" },
{ title: "Config", slug: "cli/config" },
],
},
{
title: "Configure",
items: [
{ title: "Web", slug: "cli/web" },
{ title: "Commands", slug: "cli/commands" },
{ title: "Theme", slug: "cli/theme" },
{ title: "Plugins", slug: "cli/plugins" },
{ title: "Keybinds", slug: "cli/keybinds" },
+69 -33
View File
@@ -1,10 +1,10 @@
# Provider Policy
Status: **Implemented.**
Status: **Implemented, including paired Console managed-policy support in the working tree.** Release and deployment are separate; this spec does not name a minimum released client version.
## Purpose
Policies control whether an operation on a named resource is allowed. Statements are authored in configuration files and applied by a terminal catalog plugin.
Policies control whether an operation on a named resource is allowed. Statements come from authored configuration and, while connected to Console, an authenticated managed response. A core policy service enforces the combined result at catalog reads and model resolution.
The first policy consumer is provider availability:
@@ -24,9 +24,9 @@ A provider can be correctly configured and have valid credentials while policy s
- Replace legacy `enabled_providers` and `disabled_providers`.
- Keep the default experience unchanged when users specify no policy.
- Support wildcard matching for actions and resources.
- Provide one small policy vocabulary that can later cover operations such as `plugin.load` or `mcp.connect`.
- Let user policy override repository policy, and later allow organization-managed policy to override both.
- Support wildcard matching for provider-ID resources.
- Support the literal `provider.use` action; other actions require separate implementation.
- Let user policy override repository policy, and organization-managed policy override both.
- Keep evaluation simple: matching statements are applied in order and the last match wins.
## Non-Goals
@@ -34,7 +34,7 @@ A provider can be correctly configured and have valid credentials while policy s
- Policies do not configure endpoints, credentials, models, or provider options.
- Policies do not make unusable resources usable.
- Policies do not currently provide conditions, principals, approval prompts, or enforced configuration values.
- This spec does not define how organization-managed policies are delivered.
- Policies do not pin a provider's endpoint, require gateway routing, enroll devices, sandbox arbitrary executable plugins, or cancel in-flight requests.
## Statement Shape
@@ -55,24 +55,24 @@ A provider can be correctly configured and have valid credentials while policy s
```ts
interface PolicyInfo {
effect: "allow" | "deny"
action: string
action: "provider.use"
resource: string
}
```
`ConfigPolicy` owns the statement schema. The policy plugin interprets the supported `provider.use` action after all other catalog transforms have run.
`ConfigPolicy` owns the statement schema. `ProviderPolicy` interprets it outside the removable plugin registry. Managed responses validate the complete policy strictly: unknown fields/actions/effects, empty or untrimmed resources, and resources over 256 characters are invalid. Console allows up to 100 custom statements; generated presets may have more.
## Matching
Both `action` and `resource` use opencode's existing wildcard matching behavior.
The action must be exactly `provider.use`; `provider.*` is invalid. Resources use anchored `*` (zero or more characters) and `?` (one character) wildcards. Backslashes normalize to slashes. Windows matches case-insensitively; macOS and Linux match case-sensitively. Matching retains the existing optional trailing ` *` behavior. Patterns are not regular expressions or IAM resource names.
Examples:
| Action | Resource | Matches |
| -------------- | ----------- | ---------------------------------------------------------------------------- |
| `provider.use` | `openai` | Only use of provider ID `openai` |
| `provider.use` | `company-*` | Use of provider IDs such as `company-us` and `company-eu` |
| `provider.*` | `*` | Any provider operation on any provider, if more actions are introduced later |
| Action | Resource | Matches |
| -------------- | ----------- | --------------------------------------------------------- |
| `provider.use` | `openai` | Only use of provider ID `openai` |
| `provider.use` | `company-*` | Use of provider IDs such as `company-us` and `company-eu` |
| `provider.use` | `*` | Every provider ID |
No pattern-specific precedence exists. A specific resource does not automatically beat a wildcard resource. Written/evaluation order controls the result.
@@ -81,23 +81,18 @@ No pattern-specific precedence exists. A specific resource does not automaticall
To evaluate an operation and resource:
1. Start with `allow`.
2. Consider every statement whose `action` and `resource` match the requested action and resource.
2. Consider every `provider.use` statement whose resource matches the provider ID.
3. Each matching statement replaces the current decision with its `effect`.
4. The last matching statement determines the result.
Conceptually:
```ts
function evaluate(action: string, resource: string, fallback: Policy.Effect, statements: Policy.Info[]) {
return (
statements.findLast(
(statement) => Wildcard.match(action, statement.action) && Wildcard.match(resource, statement.resource),
)?.effect ?? fallback
)
}
const decision = ProviderPolicyMatcher.evaluate(statements, providerID, process.platform === "win32")
const allowed = decision.effect !== "deny"
```
Each caller supplies the default effect appropriate for its operation. Catalog provider use supplies `"allow"`, so no provider policy statements means normal behavior continues: otherwise usable providers are allowed.
The pure matcher returns `allow`, `deny`, or `inherit`, plus the winning statement index. `inherit` permits otherwise usable providers. An active Console connection without a valid compatible managed snapshot is separately gated as unavailable; it never falls back to unrestricted provider use.
## Ordering Within One Config Document
@@ -193,7 +188,7 @@ The relative policy precedence of direct project files and `.opencode` files is
## Organization-Managed Policy
Organization-managed policy is not ordinary authored config. When implemented, managed statements must be appended after the reversed authored statements so they have final authority.
Organization-managed policy is not ordinary authored config. Managed statements append after the reversed authored statements, before a single final evaluation. This lets an organization allow override a user deny without trying to resurrect a provider already removed by an earlier policy filter.
```text
repository policy -> user-global policy -> organization-managed policy
@@ -201,18 +196,56 @@ repository policy -> user-global policy -> organization-managed policy
Plugins must not be allowed to add, remove, or override policy statements. Plugins can contribute functionality or configured providers; policy determines whether opencode permits an operation through its managed execution paths.
The built-in `opencode.provider.opencode` loader remains active under ordinary removal selectors such as `-*`, `-opencode.*`, and `-opencode.provider.opencode`. The policy service is not a removable plugin, and policy mutation is not exposed through the plugin context API. Late catalog transforms still pass through policy checks when read.
Provider policy is not a full sandbox for executable plugins. A denied provider must not be usable through the normal provider/model path, but arbitrary plugin code requires separate governance if that becomes a compliance requirement.
### Console contract
The authenticated `GET /api/v2/config` response includes providers and required managed fields:
```json
{
"providers": {},
"experimental": { "policies": [] },
"managedPolicy": {
"schemaVersion": 1,
"workspaceID": "org_example",
"revision": 7
}
}
```
The loader validates the policy without silently dropping unsupported fields. Trust comes from the authenticated loader and active connection, not the presence of a descriptor in a local file. Policy and provider data are applied from the same validated response. The descriptor identifies the saved authoring revision; generated preset output can also change when Console connections change. Refresh compares the whole snapshot, not only the revision.
Console offers default access, only workspace provider IDs, and custom ordered rules. Default access denies `opencode` when Console emits no connection with that ID. Managed-only denies `*` then allows each exact emitted ID. Custom `[]` explicitly removes organization overrides. Custom mode replaces the legacy v1 managed-only setting; it is not converted to v1 rules.
An org that has never published policies still receives a valid revision-zero descriptor and rules derived from its existing provider settings, even with Console's publication flag disabled. The client accepts defaults without requiring administrator setup. The current client nevertheless requires a valid response for every connected org: a cold-start outage or old server blocks even a policy-free org because its policy state is not yet known. There is no persisted opt-in exemption before that first fetch.
### Connection and failure behavior
- Disconnected: apply authored local rules.
- Connected before a valid compatible snapshot: block all normal provider/model resolution, including local providers, with an actionable policy-unavailable error.
- Valid response: apply managed rules after local rules.
- Same-identity transient refresh failure (network, timeout, 429, or 5xx): retain the last validated in-memory snapshot and mark it stale internally.
- Missing, malformed, unsupported, wrong-workspace, or authorization-rejected response: mark policy unavailable. Failure never means an empty policy.
- Server, workspace, or service-key switch: require a valid snapshot for the new identity. Never carry the previous identity's rules forward.
- Valid explicit `[]`: clear organization overrides; local rules remain.
Binding includes connection identity, server, selected organization metadata, and the service key where applicable. The response workspace must match organization metadata when present. OAuth access-token refresh does not change this identity. The raw binding stays internal and must never be logged or exposed.
The existing loader polls every ten minutes and refreshes on connection changes. There is no durable offline cache, fleet acknowledgment, or in-flight revocation. Disconnecting Console leaves the scope of this feature.
Deploy Console's required response contract first, release the compatible client next, then enable Console's `opencode-policies` publication flag. A new client connected to an old server intentionally blocks. Older clients may ignore the fields; do not claim enforcement for them. Turning off publication does not remove an already published policy.
## Interaction With Provider Configuration
```jsonc
{
"providers": {
"company-ai": {
"endpoint": {
"type": "openai/responses",
"url": "https://ai.company.example/v1/responses",
},
"package": "@opencode/ai/providers/openai",
"settings": { "baseURL": "https://ai.company.example/v1" },
},
},
"experimental": {
@@ -224,7 +257,7 @@ Provider policy is not a full sandbox for executable plugins. A denied provider
}
```
The provider entry configures `company-ai`; the policy statements make it the only provider permitted for use.
The provider entry configures `company-ai`; the policy statements make that ID the only provider permitted for use. Credentials and models are still required. Local provider overlays may change an allowed ID's package, endpoint, or other transport fields; a provider-ID allowlist is not endpoint enforcement.
Provider policy applies regardless of how a provider becomes known or usable, including:
@@ -236,16 +269,19 @@ Provider policy applies regardless of how a provider becomes known or usable, in
## Applying Provider Policy
Provider records and model overrides are assembled before checking provider policy. Otherwise later provider loading could recreate a provider that was already filtered.
Provider records and model overrides remain in the underlying catalog. Public reads check policy so later provider loading cannot bypass filtering, while a later valid allow can expose an otherwise usable provider again.
Flow:
1. Build provider/model catalog entries.
2. Apply configured provider and model overrides.
3. Run the terminal config policy transform.
4. Remove providers denied by the final matching `provider.use` statement.
3. Read one policy snapshot containing reversed authored rules followed by managed rules.
4. Filter all public provider/model catalog views using the final decision.
5. Assert policy again at model resolution, including resolution of a previously selected model value.
Config reload refreshes the plugin's policy snapshot and rebuilds the catalog.
Config updates publish catalog-updated events. Managed refresh updates the policy snapshot before rebuilding catalog/search projections. Session errors distinguish denied/unavailable policy in their messages while using the existing error protocol.
The pure matcher and fixtures are duplicated in Console's shared package and this repository's util package. Console's `scripts/check-opencode-policy-conformance.ts` verifies byte-for-byte equality. Tests cover precedence, platform matching, catalog views, previously selected model resolution, loader protection, failure transitions, and identity changes. An opt-in paired integration test consumes a policy published through Console's real browser/API/database flow. These checks do not establish deployed fleet behavior or successful billable provider requests.
## Legacy Migration