Compare commits

..

2 Commits

Author SHA1 Message Date
Kit Langton 46148bbc6c Revert "feat(tui): load external plugin exports"
This reverts commit fdd6498909.
2026-07-17 14:40:53 -04:00
Kit Langton fdd6498909 feat(tui): load external plugin exports 2026-07-17 14:19:56 -04:00
48 changed files with 290 additions and 2203 deletions
+1 -2
View File
@@ -2,8 +2,7 @@ export { LLMClient } from "./route/client"
export { Auth } from "./route/auth"
export { Provider } from "./provider"
export { ProviderPackage } from "./provider-package"
export { classifyProviderFailure, isContextOverflow, isContextOverflowFailure } from "./provider-error"
export type { ProviderFailure } from "./provider-error"
export { isContextOverflow, isContextOverflowFailure } from "./provider-error"
export type {
RouteModelInput,
RouteRoutedModelInput,
@@ -1,6 +1,6 @@
import { EventStreamCodec } from "@smithy/eventstream-codec"
import { fromUtf8, toUtf8 } from "@smithy/util-utf8"
import { Effect, Option, Schema, Stream } from "effect"
import { Effect, Stream } from "effect"
import { Framing } from "../route/framing"
import { ProviderShared } from "./shared"
@@ -53,13 +53,8 @@ const consumeFrames = (route: string) => (state: FrameBufferState, chunk: Uint8A
})
cursor = { buffer: cursor.buffer, offset: cursor.offset + totalLength }
const messageType = decoded.headers[":message-type"]?.value
const eventType =
messageType === "event"
? decoded.headers[":event-type"]?.value
: messageType === "exception"
? decoded.headers[":exception-type"]?.value
: undefined
if (decoded.headers[":message-type"]?.value !== "event") continue
const eventType = decoded.headers[":event-type"]?.value
if (typeof eventType !== "string") continue
const payload = utf8.decode(decoded.body)
if (!payload) continue
@@ -89,52 +84,4 @@ export const framing = (route: string): Framing.Definition<object> => ({
frame: (bytes) => bytes.pipe(Stream.mapAccumEffect(() => initialFrameBuffer, consumeFrames(route))),
})
class StreamExceptionError extends Error {
constructor(
message: string,
readonly code: string,
) {
super(message)
}
}
// The AI SDK Bedrock decoder ignores AWS exception frames before its language
// model stream can expose them. Fail the byte stream first so the shared AI SDK
// adapter can classify the transport error instead of accepting a false finish.
export function monitorExceptions(response: Response) {
if (!response.body || !response.headers.get("content-type")?.includes("application/vnd.amazon.eventstream"))
return response
let state = initialFrameBuffer
const body = response.body.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
state = appendChunk(state, chunk)
while (state.buffer.length - state.offset >= 4) {
const view = state.buffer.subarray(state.offset)
const totalLength = new DataView(view.buffer, view.byteOffset, view.byteLength).getUint32(0, false)
if (view.length < totalLength) break
const decoded = eventCodec.decode(view.subarray(0, totalLength))
state = { buffer: state.buffer, offset: state.offset + totalLength }
const exceptionType = decoded.headers[":exception-type"]?.value
if (decoded.headers[":message-type"]?.value === "exception" && typeof exceptionType === "string") {
const payload = Option.getOrUndefined(
Schema.decodeUnknownOption(Schema.UnknownFromJsonString)(utf8.decode(decoded.body)),
)
const message =
ProviderShared.isRecord(payload) && typeof payload.message === "string" ? payload.message : undefined
controller.error(new StreamExceptionError(message ?? `Bedrock ${exceptionType}`, exceptionType))
return
}
}
controller.enqueue(chunk)
},
}),
)
return new Response(body, {
headers: new Headers(response.headers),
status: response.status,
statusText: response.statusText,
})
}
export * as BedrockEventStream from "./bedrock-event-stream"
+25 -68
View File
@@ -46,45 +46,24 @@ export const isContextOverflowFailure = (failure: unknown) =>
: Schema.is(ProviderErrorEvent)(failure) && failure.classification === "context-overflow"
const decodeJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString)
const CONTENT_POLICY_CODES = new Set(["content_filter", "content_policy_violation", "safety"])
const QUOTA_CODES = new Set(["insufficient_quota", "usage_not_included", "billing_error"])
const RATE_LIMIT_CODES = new Set(["resource_exhausted", "throttlingexception", "too_many_requests"])
const SERVER_CODES = new Set([
"api_error",
"internal",
"internal_error",
"internal_server_error",
"internalserverexception",
"modelstreamerrorexception",
"modeltimeoutexception",
"overloaded_error",
"response_error",
"server_error",
"server_is_overloaded",
"serviceunavailableexception",
])
const INVALID_REQUEST_CODES = new Set([
"invalid_argument",
"invalid_prompt",
"invalid_request_error",
"model_not_found",
"not_found",
"not_found_error",
"resourcenotfoundexception",
"request_too_large",
"validationexception",
])
const RATE_LIMIT_TEXT = /rate increased too quickly|rate[-_\s]?limit|throttl|too[_\s]?many[_\s]?requests/i
const INVALID_REQUEST_CODES = new Set(["invalid_prompt", "invalid_request_error", "validationexception"])
const RATE_LIMIT_TEXT = /rate increased too quickly|rate[-_\s]?limit|too[_\s]?many[_\s]?requests/i
const QUOTA_TEXT = /insufficient[-_\s]?quota|quota[-_\s]?exceeded/i
const CONTENT_POLICY_TEXT =
/content[-_\s]?(?:filter|policy)|safety (?:filter|policy|rating)|blocked (?:by|due to) safety/i
const INVALID_REQUEST_TEXT = /validation (?:error|exception)/i
const SERVER_TEXT = /internal server error|service unavailable/i
const CONTENT_POLICY_TEXT = /content[-_\s]?policy|content_filter|safety/i
export interface ProviderFailure {
readonly message: string
/** Provider text used only for classification and never retained on the resulting reason. */
readonly evidence?: string | undefined
readonly status?: number | undefined
readonly code?: string | undefined
readonly retryAfterMs?: number | undefined
@@ -97,11 +76,10 @@ export interface ProviderFailure {
// session retry policy never needs provider-specific string matching.
export function classifyProviderFailure(input: ProviderFailure): LLMError["reason"] {
const body = input.http?.body ?? ""
const evidence = input.evidence ?? ""
const codes = [input.code, ...providerCodes(body), ...providerCodes(input.message), ...providerCodes(evidence)]
const codes = [input.code, ...providerCodes(body), ...providerCodes(input.message)]
.filter((code): code is string => code !== undefined)
.map((code) => code.toLowerCase())
const texts = [body, input.message, evidence]
const text = body || input.message
const common = { message: input.message, providerMetadata: input.providerMetadata, http: input.http }
const clientScoped = input.status === undefined || (input.status >= 400 && input.status < 500)
@@ -109,44 +87,32 @@ export function classifyProviderFailure(input: ProviderFailure): LLMError["reaso
clientScoped &&
(codes.includes("context_length_exceeded") ||
codes.includes("model_context_window_exceeded") ||
texts.some(isContextOverflow))
isContextOverflow(text))
)
return new InvalidRequestReason({ ...common, classification: "context-overflow" })
if (codes.some((code) => CONTENT_POLICY_CODES.has(code)) || texts.some((text) => CONTENT_POLICY_TEXT.test(text)))
return new ContentPolicyReason(common)
if (
codes.some((code) => QUOTA_CODES.has(code)) ||
(input.status === 429 && texts.some((text) => QUOTA_TEXT.test(text)))
)
if (CONTENT_POLICY_TEXT.test(text)) return new ContentPolicyReason(common)
if (codes.some((code) => QUOTA_CODES.has(code)) || (input.status === 429 && QUOTA_TEXT.test(text)))
return new QuotaExceededReason(common)
if (input.status === 401) return new AuthenticationReason({ ...common, kind: "invalid" })
if (input.status === 403) return new AuthenticationReason({ ...common, kind: "insufficient-permissions" })
if (codes.some((code) => code === "authentication_error" || code === "unauthenticated"))
return new AuthenticationReason({ ...common, kind: "invalid" })
if (
codes.some(
(code) => code === "accessdeniedexception" || code === "permission_error" || code === "permission_denied",
)
)
if (codes.includes("authentication_error")) return new AuthenticationReason({ ...common, kind: "invalid" })
if (codes.includes("permission_error"))
return new AuthenticationReason({ ...common, kind: "insufficient-permissions" })
if (codes.some((code) => code.includes("rate_limit") || RATE_LIMIT_CODES.has(code)))
return new RateLimitReason({
...common,
retryAfterMs: input.retryAfterMs,
rateLimit: input.rateLimit,
})
if (texts.some((text) => RATE_LIMIT_TEXT.test(text)))
return new RateLimitReason({
...common,
retryAfterMs: input.retryAfterMs,
rateLimit: input.rateLimit,
})
if (codes.some((code) => INVALID_REQUEST_CODES.has(code)) || texts.some((text) => INVALID_REQUEST_TEXT.test(text)))
return new InvalidRequestReason(common)
if (
codes.some((code) => SERVER_CODES.has(code) || code.includes("unavailable")) ||
texts.some((text) => SERVER_TEXT.test(text))
codes.some((code) => code.includes("rate_limit") || code === "too_many_requests" || code === "throttlingexception")
)
return new RateLimitReason({
...common,
retryAfterMs: input.retryAfterMs,
rateLimit: input.rateLimit,
})
if (RATE_LIMIT_TEXT.test(text))
return new RateLimitReason({
...common,
retryAfterMs: input.retryAfterMs,
rateLimit: input.rateLimit,
})
if (codes.some((code) => SERVER_CODES.has(code) || code.includes("exhausted") || code.includes("unavailable")))
return new ProviderInternalReason({
...common,
status: input.status,
@@ -165,6 +131,7 @@ export function classifyProviderFailure(input: ProviderFailure): LLMError["reaso
status: input.status,
retryAfterMs: input.retryAfterMs,
})
if (codes.some((code) => INVALID_REQUEST_CODES.has(code))) return new InvalidRequestReason(common)
if (
input.status === 400 ||
input.status === 404 ||
@@ -180,17 +147,7 @@ function providerCodes(value: string) {
const decoded = Option.getOrUndefined(decodeJson(value))
if (!isRecord(decoded)) return []
const error = isRecord(decoded.error) ? decoded.error : undefined
const response = isRecord(decoded.response) ? decoded.response : undefined
const responseError = isRecord(response?.error) ? response.error : undefined
return [
decoded.code,
decoded.status,
error?.code,
error?.type,
error?.status,
responseError?.code,
responseError?.type,
].filter((value): value is string => typeof value === "string")
return [decoded.code, error?.code, error?.type].filter((value): value is string => typeof value === "string")
}
function isRecord(value: unknown): value is Record<string, unknown> {
+12 -47
View File
@@ -240,32 +240,7 @@ const statusError =
})
})
const TIMEOUT_CODES = new Set([
"ETIMEDOUT",
"UND_ERR_BODY_TIMEOUT",
"UND_ERR_CONNECT_TIMEOUT",
"UND_ERR_HEADERS_TIMEOUT",
])
const errorCause = (error: unknown) => {
if (HttpClientError.isHttpClientError(error) && "cause" in error.reason) return error.reason.cause
return error instanceof Error ? error.cause : undefined
}
const errorCode = (error: unknown) => {
if (typeof error !== "object" || error === null) return undefined
const code = Reflect.get(error, "code")
return typeof code === "string" ? code.toUpperCase() : undefined
}
const errorMessage = (error: unknown, fallback: string) => {
const cause = errorCause(error)
if (cause instanceof Error) return cause.message
if (error instanceof Error) return error.message
return fallback
}
export const mapHttpClientError = (error: unknown, redactedNames: ReadonlyArray<string | RegExp>) => {
const toHttpError = (redactedNames: ReadonlyArray<string | RegExp>) => (error: unknown) => {
const transportError = (input: {
readonly message: string
readonly kind?: string | undefined
@@ -282,30 +257,23 @@ export const mapHttpClientError = (error: unknown, redactedNames: ReadonlyArray<
}),
})
const cause = errorCause(error)
const code = errorCode(cause) ?? errorCode(error)
const request = HttpClientError.isHttpClientError(error) ? error.request : undefined
if (
Cause.isTimeoutError(error) ||
Cause.isTimeoutError(cause) ||
(error instanceof Error && error.name === "TimeoutError") ||
(cause instanceof Error && cause.name === "TimeoutError") ||
(code !== undefined && TIMEOUT_CODES.has(code))
)
return transportError({ message: errorMessage(error, "HTTP transport timed out"), kind: code ?? "Timeout", request })
if (!HttpClientError.isHttpClientError(error)) {
return transportError({ message: errorMessage(error, "HTTP transport failed"), kind: code })
if (Cause.isTimeoutError(error)) {
return transportError({ message: error.message, kind: "Timeout" })
}
if (!HttpClientError.isHttpClientError(error)) {
return transportError({ message: "HTTP transport failed" })
}
const request = "request" in error ? error.request : undefined
if (error.reason._tag === "TransportError") {
return transportError({
message: error.reason.description ?? errorMessage(error, "HTTP transport failed"),
kind: code ?? error.reason._tag,
message: error.reason.description ?? "HTTP transport failed",
kind: error.reason._tag,
request,
})
}
return transportError({
message: errorMessage(error, `HTTP transport failed: ${error.reason._tag}`),
kind: code ?? error.reason._tag,
message: `HTTP transport failed: ${error.reason._tag}`,
kind: error.reason._tag,
request,
})
}
@@ -319,10 +287,7 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient> = Layer.e
const redactedNames = yield* Headers.CurrentRedactedNames
return yield* http
.execute(request)
.pipe(
Effect.mapError((error) => mapHttpClientError(error, redactedNames)),
Effect.flatMap(statusError(request, redactedNames)),
)
.pipe(Effect.mapError(toHttpError(redactedNames)), Effect.flatMap(statusError(request, redactedNames)))
})
return Service.of({
execute: executeOnce,
+1 -2
View File
@@ -9,8 +9,7 @@ export type {
Interface as LLMClientShape,
Service as LLMClientService,
} from "./client"
export { RequestExecutor, Service, fetchLayer, layer } from "./executor"
export type { Interface } from "./executor"
export * from "./executor"
export { Auth } from "./auth"
export { AuthOptions } from "./auth-options"
export { Endpoint } from "./endpoint"
+8 -5
View File
@@ -6,7 +6,6 @@ import { Framing } from "../framing"
import type { Transport, TransportPrepareInput } from "./index"
import * as ProviderShared from "../../protocols/shared"
import { mergeJsonRecords, type LLMRequest } from "../../schema"
import { mapHttpClientError } from "../executor"
export type JsonRequestInput<Body> = TransportPrepareInput<Body>
@@ -135,10 +134,14 @@ export const httpJson = <Body, Frame>(input: HttpJsonInput<Body, Frame>): HttpJs
.execute(prepared.request)
.pipe(
Effect.map((response) =>
Stream.unwrap(
Effect.map(Headers.CurrentRedactedNames, (redactedNames) =>
prepared.framing.frame(
response.stream.pipe(Stream.mapError((error) => mapHttpClientError(error, redactedNames))),
prepared.framing.frame(
response.stream.pipe(
Stream.mapError((error) =>
ProviderShared.eventError(
`${request.model.provider}/${request.model.route.id}`,
`Failed to read ${request.model.provider}/${request.model.route.id} stream`,
ProviderShared.errorText(error),
),
),
),
),
+1 -1
View File
@@ -121,7 +121,6 @@ describe("RequestExecutor", () => {
yield* classify("Request rate increased too quickly")
yield* classify('{"type":"error","error":{"type":"too_many_requests"}}')
yield* classify('{"type":"error","error":{"code":"rate_limit_exceeded"}}')
yield* classify('{"code":"resource_exhausted"}')
}),
)
@@ -136,6 +135,7 @@ describe("RequestExecutor", () => {
expect(error.reason).toMatchObject({ _tag: "ProviderInternal" })
}).pipe(Effect.provide(responsesLayer([new Response(body, { status: 400 })])))
yield* classify('{"code":"resource_exhausted"}')
yield* classify('{"code":"service_unavailable"}')
}),
)
+2 -2
View File
@@ -63,14 +63,14 @@ export const dynamicResponse = (handler: Handler) => runtimeLayer(handlerLayer(h
* Layer that emits the supplied SSE chunks and then aborts mid-stream. Used to
* exercise transport errors that surface during parsing.
*/
export const truncatedStream = (chunks: ReadonlyArray<string>, error: unknown = new Error("connection reset")) =>
export const truncatedStream = (chunks: ReadonlyArray<string>) =>
dynamicResponse((input) =>
Effect.sync(() => {
const encoder = new TextEncoder()
const stream = new ReadableStream({
start(controller) {
for (const chunk of chunks) controller.enqueue(encoder.encode(chunk))
controller.error(error)
controller.error(new Error("connection reset"))
},
})
return input.respond(stream, { headers: SSE_HEADERS })
+4 -68
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"
import { HttpContext, HttpRequestDetails, isContextOverflow } from "../src"
import { isContextOverflow } from "../src"
import { classifyProviderFailure } from "../src/provider-error"
describe("provider error classification", () => {
@@ -7,33 +7,6 @@ describe("provider error classification", () => {
expect(isContextOverflow("tokens in request more than max tokens allowed")).toBe(true)
})
test("checks overflow evidence in the message when the response body is uninformative", () => {
expect(
classifyProviderFailure({
message: "Input is too long for requested model",
status: 400,
http: new HttpContext({
request: new HttpRequestDetails({ method: "POST", url: "https://provider.test", headers: {} }),
body: "{}",
}),
}),
).toMatchObject({ classification: "context-overflow" })
})
test("lets semantic invalid-request codes override server status", () => {
expect(classifyProviderFailure({ message: "too large", status: 500, code: "request_too_large" })._tag).toBe(
"InvalidRequest",
)
})
test("does not treat incidental safety text as a content-policy failure", () => {
expect(classifyProviderFailure({ message: "Internal safety check failed", status: 500 })._tag).toBe(
"ProviderInternal",
)
expect(classifyProviderFailure({ message: "Blocked by safety policy", status: 400 })._tag).toBe("ContentPolicy")
expect(classifyProviderFailure({ message: "Blocked", status: 400, code: "SAFETY" })._tag).toBe("ContentPolicy")
})
test("classifies V1 plain-text rate limit fallbacks", () => {
expect(
[
@@ -55,48 +28,12 @@ describe("provider error classification", () => {
).toEqual(["RateLimit", "RateLimit", "RateLimit", "RateLimit"])
})
test("classifies canonical provider retry codes", () => {
test("classifies V1 overloaded provider codes", () => {
expect(
['{"code":"resource_exhausted"}', '{"code":"service_unavailable"}'].map(
(message) => classifyProviderFailure({ message })._tag,
),
).toEqual(["RateLimit", "ProviderInternal"])
})
test("keeps temporary per-minute quota wording retryable", () => {
expect(classifyProviderFailure({ message: "You exceeded your per-minute quota", status: 429 })._tag).toBe(
"RateLimit",
)
})
test("classifies canonical Google error codes", () => {
expect(
["UNAUTHENTICATED", "PERMISSION_DENIED", "INVALID_ARGUMENT", "NOT_FOUND", "INTERNAL"].map(
(code) => classifyProviderFailure({ message: "Provider failed", code })._tag,
),
).toEqual(["Authentication", "Authentication", "InvalidRequest", "InvalidRequest", "ProviderInternal"])
})
test("classifies stripped Bedrock stream errors from their messages", () => {
expect(
["Internal server error", "Throttling exception", "Validation error: invalid input"].map(
(message) => classifyProviderFailure({ message })._tag,
),
).toEqual(["ProviderInternal", "RateLimit", "InvalidRequest"])
})
test("classifies documented Bedrock exception codes", () => {
expect(
["accessDeniedException", "modelTimeoutException", "resourceNotFoundException"].map(
(code) => classifyProviderFailure({ message: "Bedrock failed", code })._tag,
),
).toEqual(["Authentication", "ProviderInternal", "InvalidRequest"])
})
test("classifies Anthropic not-found stream errors as invalid requests", () => {
expect(classifyProviderFailure({ message: "Model unavailable", code: "not_found_error" })._tag).toBe(
"InvalidRequest",
)
).toEqual(["ProviderInternal", "ProviderInternal"])
})
test("classifies nested provider codes when a top-level code is also present", () => {
@@ -105,9 +42,8 @@ describe("provider error classification", () => {
'{"code":"bad_request","error":{"code":"usage_not_included"}}',
'{"code":"bad_request","error":{"code":"server_error"}}',
'{"code":"bad_request","error":{"type":"invalid_request_error"}}',
'{"type":"response.failed","response":{"error":{"code":"server_error"}}}',
].map((message) => classifyProviderFailure({ message })._tag),
).toEqual(["QuotaExceeded", "ProviderInternal", "InvalidRequest", "ProviderInternal"])
).toEqual(["QuotaExceeded", "ProviderInternal", "InvalidRequest"])
})
test("keeps unknown and malformed provider payloads non-retryable", () => {
@@ -6,7 +6,6 @@ import { CacheHint, LLM, Message, ToolCallPart, ToolChoice } from "../../src"
import { LLMClient } from "../../src/route"
import { AmazonBedrock } from "../../src/providers"
import * as BedrockConverse from "../../src/protocols/bedrock-converse"
import { BedrockEventStream } from "../../src/protocols/bedrock-event-stream"
import { it } from "../lib/effect"
import { fixedResponse } from "../lib/http"
import {
@@ -35,16 +34,6 @@ const eventFrame = (type: string, payload: object) =>
body: utf8Encoder.encode(JSON.stringify(payload)),
})
const exceptionFrame = (type: string, payload: object) =>
codec.encode({
headers: {
":message-type": { type: "string", value: "exception" },
":exception-type": { type: "string", value: type },
":content-type": { type: "string", value: "application/json" },
},
body: utf8Encoder.encode(JSON.stringify(payload)),
})
const concat = (frames: ReadonlyArray<Uint8Array>) => {
const total = frames.reduce((sum, frame) => sum + frame.length, 0)
const out = new Uint8Array(total)
@@ -59,8 +48,6 @@ const concat = (frames: ReadonlyArray<Uint8Array>) => {
const eventStreamBody = (...payloads: ReadonlyArray<readonly [string, object]>) =>
concat(payloads.map(([type, payload]) => eventFrame(type, payload)))
const exceptionStreamBody = (type: string, payload: object) => exceptionFrame(type, payload)
// Override the default SSE content-type with the binary event-stream type so
// the cassette layer treats the body as bytes when recording.
const fixedBytes = (bytes: Uint8Array) =>
@@ -370,10 +357,10 @@ describe("Bedrock Converse route", () => {
it.effect("classifies throttlingException as a rate limit", () =>
Effect.gen(function* () {
const body = concat([
eventStreamBody(["messageStart", { role: "assistant" }]),
exceptionStreamBody("throttlingException", { message: "Slow down" }),
])
const body = eventStreamBody(
["messageStart", { role: "assistant" }],
["throttlingException", { message: "Slow down" }],
)
const error = yield* LLMClient.generate(baseRequest).pipe(Effect.provide(fixedBytes(body)), Effect.flip)
expect(error.reason).toMatchObject({ _tag: "RateLimit", message: "Slow down" })
@@ -384,7 +371,7 @@ describe("Bedrock Converse route", () => {
Effect.gen(function* () {
const error = yield* LLMClient.generate(baseRequest).pipe(
Effect.provide(
fixedBytes(exceptionStreamBody("validationException", { message: "Input is too long for requested model" })),
fixedBytes(eventStreamBody(["validationException", { message: "Input is too long for requested model" }])),
),
Effect.flip,
)
@@ -397,35 +384,6 @@ describe("Bedrock Converse route", () => {
}),
)
it.effect("fails monitored AI SDK bodies on exception wire frames", () =>
Effect.gen(function* () {
const response = BedrockEventStream.monitorExceptions(
new Response(exceptionStreamBody("throttlingException", { message: "Slow down" }), {
headers: { "content-type": "application/vnd.amazon.eventstream" },
}),
)
const error = yield* Effect.tryPromise({
try: () => response.arrayBuffer(),
catch: (error) => error,
}).pipe(Effect.flip)
expect(error).toMatchObject({ code: "throttlingException", message: "Slow down" })
}),
)
it.effect("classifies serviceUnavailableException wire frames as provider failures", () =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(baseRequest).pipe(
Effect.provide(
fixedBytes(exceptionStreamBody("serviceUnavailableException", { message: "Service unavailable" })),
),
Effect.flip,
)
expect(error.reason).toMatchObject({ _tag: "ProviderInternal", message: "Service unavailable" })
}),
)
it.effect("rejects requests with no auth path", () =>
Effect.gen(function* () {
const unsignedModel = AmazonBedrock.configure({
+1 -16
View File
@@ -651,22 +651,7 @@ describe("OpenAI Chat route", () => {
])
const error = yield* LLMClient.generate(request).pipe(Effect.provide(layer), Effect.flip)
expect(error).toMatchObject({ reason: { _tag: "Transport", message: "connection reset" } })
}),
)
it.effect("classifies response body timeouts as transport timeouts", () =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(request).pipe(
Effect.provide(
truncatedStream([], Object.assign(new Error("body timed out"), { code: "UND_ERR_BODY_TIMEOUT" })),
),
Effect.flip,
)
expect(error).toMatchObject({
reason: { _tag: "Transport", kind: "UND_ERR_BODY_TIMEOUT", message: "body timed out" },
})
expect(error.message).toContain("Failed to read openai/openai-chat stream")
}),
)
-4
View File
@@ -114,10 +114,6 @@ export const Commands = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCO
}),
],
}),
Spec.make("plugin", {
description: "Manage plugins",
commands: [Spec.make("list", { description: "List active plugins" })],
}),
Spec.make("migrate", { description: "Migrate v1 data to v2" }),
Spec.make("mini", {
description: "Start the minimal interactive interface",
@@ -1,24 +0,0 @@
import { EOL } from "node:os"
import { Effect } from "effect"
import { OpenCode } from "@opencode-ai/client"
import { Service } from "@opencode-ai/client/effect/service"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { ServiceConfig } from "../../../services/service-config"
export default Runtime.handler(
Commands.commands.plugin.commands.list,
Effect.fn("cli.plugin.list")(function* () {
const options = yield* ServiceConfig.options()
const found = yield* Service.discover(options)
const endpoint = found ?? (yield* Service.ensure(options))
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const response = yield* Effect.promise(() => client.plugin.list({ location: { directory: process.cwd() } }))
const plugins = response.data.toSorted((a, b) => a.id.localeCompare(b.id))
if (plugins.length === 0) {
process.stdout.write("No plugins loaded" + EOL)
return
}
process.stdout.write(plugins.map((plugin) => plugin.id).join(EOL) + EOL)
}),
)
-3
View File
@@ -32,9 +32,6 @@ const Handlers = Runtime.handlers(Commands, {
auth: () => import("./commands/handlers/mcp/auth"),
logout: () => import("./commands/handlers/mcp/logout"),
},
plugin: {
list: () => import("./commands/handlers/plugin/list"),
},
migrate: () => import("./commands/handlers/migrate"),
mini: () => import("./commands/handlers/mini"),
run: () => import("./commands/handlers/run"),
+1 -3
View File
@@ -108,9 +108,7 @@ const runtime = CodeMode.make({ tools: { opencode: api.tools } })
It is synchronous and returns `{ tools, skipped }`: operations with unsupported encodings, non-JSON bodies, binary
responses, or streaming land in `skipped` instead of producing broken tools. Auth is resolved host-side and never
model-visible; generated tools require `HttpClient.HttpClient` in the environment. `readOnly` properties are omitted
from request signatures and `writeOnly` properties from response signatures. These JSON Schemas are model-facing, not
runtime filters: nested value bodies and server responses pass through unchanged. See the option docstrings in
model-visible; generated tools require `HttpClient.HttpClient` in the environment. See the option docstrings in
`src/openapi/types.ts` for full semantics.
## Outputs
+1 -5
View File
@@ -5,15 +5,11 @@ The initial adapter intentionally skips operations it cannot execute correctly.
- Cookie parameters, authentication, and cookie-header merging.
- Matrix, label, space-delimited, pipe-delimited, `allowReserved`, and parameter `content` serialization.
- External references and complete nested `$defs` support.
- `$anchor` and nested `$id` resource resolution in directional (`readOnly`/`writeOnly`) projection.
- Use-site cleanup for `allOf` branches that reference shared component schemas: per-direction component definitions are projected globally, so a directional annotation declared only at one use site cannot remove the property from a referenced component's definition.
- Hidden-name cleanup inside `then`/`else`/`dependentSchemas`/`dependentRequired`, which constrain the same instance as `allOf`; a hidden property may remain named in those keywords.
- Projection inside `not`/`if`/`contains`, whose semantics would invert or shift if constraints were removed; those subschemas pass through unchanged, and a `$ref` from such a context to a projected `$defs` or component definition still observes hiding.
- Iterative traversal for pathologically deep schema nesting: the directional scan and projection recurse per level and overflow the stack around ten thousand levels, below the pre-existing converter limit of roughly fifty thousand; `fromSpec` throws a catchable `RangeError` either way.
- Relative or templated server URLs and server variables.
- Base URLs containing query strings or fragments.
- Runtime response-schema validation and full content negotiation.
- Binary response values and explicit byte-oriented return types.
- Request/response projection for `readOnly` and `writeOnly` properties.
- SSE, WebSocket, and other streaming transports.
- Recovery of responses rejected by a status-filtering `HttpClient`.
- Configurable request and response size limits.
+3 -7
View File
@@ -3,7 +3,6 @@ import { make, type Definition } from "../tool.js"
import { invoke } from "./runtime.js"
import {
componentDefinitions,
hasDirectionalSchemas,
inputSchema,
isRecord,
methods,
@@ -39,10 +38,7 @@ export const fromSpec = (options: Options): Result => {
const document = options.spec
const schemes = securitySchemes(document)
const defaultSecurity = securityRequirements(document.security)
const requestDefinitions = componentDefinitions(document, "request")
const responseDefinitions = hasDirectionalSchemas(document)
? componentDefinitions(document, "response")
: requestDefinitions
const definitions = componentDefinitions(document)
const paths = isRecord(document.paths) ? document.paths : {}
const used = new Set<string>()
const namespaces = new Set<string>()
@@ -61,7 +57,7 @@ export const fromSpec = (options: Options): Result => {
summary: nonEmptyString(operationValue.summary),
description: nonEmptyString(operationValue.description),
}
const output = operationOutput(document, operationValue, responseDefinitions)
const output = operationOutput(document, operationValue, definitions)
if (!output.ok) {
skipped.push({ method: operation.method, path, reason: output.reason })
continue
@@ -106,7 +102,7 @@ export const fromSpec = (options: Options): Result => {
segments,
make({
description: operation.description ?? operation.summary ?? `${operation.method} ${path}`,
input: inputSchema(input.fields, requestDefinitions),
input: inputSchema(input.fields, definitions),
output: output.value,
run: (input) => invoke(plan, input),
}),
+14 -233
View File
@@ -27,225 +27,22 @@ export const nonEmptyString = (value: unknown): string | undefined =>
export const own = <T>(record: Readonly<Record<string, T>>, key: string): T | undefined =>
Object.hasOwn(record, key) ? record[key] : undefined
const resolvePointer = (root: unknown, ref: string): unknown =>
ref
.slice(2)
.split("/")
.map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~"))
.reduce<unknown>((item, segment) => (isRecord(item) ? own(item, segment) : undefined), root)
export const resolve = (document: Document, value: unknown): unknown => {
const next = (current: unknown, seen: ReadonlySet<string>): unknown => {
if (!isRecord(current)) return current
const ref = nonEmptyString(own(current, "$ref"))
const ref = nonEmptyString(current.$ref)
if (ref === undefined || !ref.startsWith("#/") || seen.has(ref)) return current
const target = resolvePointer(document, ref)
const target = ref
.slice(2)
.split("/")
.map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~"))
.reduce<unknown>((item, segment) => (isRecord(item) ? own(item, segment) : undefined), document)
return target === undefined ? current : next(target, new Set([...seen, ref]))
}
return next(value, new Set())
}
// Model-facing directional projection: request schemas omit `readOnly` properties,
// response schemas omit `writeOnly` properties, and `required` stays consistent.
// Runtime values pass through unchanged.
type SchemaDirection = "request" | "response"
type SchemaResource = { readonly value: unknown; readonly root: unknown }
const hiddenKeyword = { request: "readOnly", response: "writeOnly" } as const
// Resolves one `$ref` hop so every link of a chain has its own sibling declarations
// inspected; cycles terminate in the callers' cycle solver. Local `$defs`/`definitions`
// pointers resolve against the schema being projected, other pointers rebase onto the target.
const resolveResource = (document: Document, resource: SchemaResource): SchemaResource => {
if (!isRecord(resource.value)) return resource
const ref = nonEmptyString(own(resource.value, "$ref"))
if (ref === undefined || !ref.startsWith("#/")) return resource
const local = ref.startsWith("#/$defs/") || ref.startsWith("#/definitions/")
const target = resolvePointer(local ? resource.root : document, ref)
if (target === undefined) return resource
return { value: target, root: local ? resource.root : target }
}
// Hidden-ness and hidden names are memoized per schema object and direction so
// diamond-shaped reference graphs stay linear. Documents are assumed immutable once
// projected; a schema reachable under multiple resolution roots reuses the first result.
type Solver<T> = {
readonly values: Map<unknown, T>
// Discovery index per schema whose strongly connected component is unresolved.
readonly pending: Map<unknown, number>
readonly stack: Array<unknown>
}
type DirectionCache = {
readonly hidden: Solver<boolean>
readonly names: Solver<ReadonlySet<string>>
}
const emptyCache = (): DirectionCache => ({
hidden: { values: new Map(), pending: new Map(), stack: [] },
names: { values: new Map(), pending: new Map(), stack: [] },
})
const projectionCaches = new WeakMap<Document, Record<SchemaDirection, DirectionCache>>()
const projectionCache = (document: Document, direction: SchemaDirection): DirectionCache => {
const existing = projectionCaches.get(document)
if (existing !== undefined) return existing[direction]
const created = { request: emptyCache(), response: emptyCache() }
projectionCaches.set(document, created)
return created[direction]
}
// Tarjan's strongly connected components: cycle members all reach the same
// declarations, so the component root's value is final for every member. Only resolved
// components are cached, keeping results independent of traversal order.
type CycleScope = { lowlink: number }
const solveCycles = <T>(
solver: Solver<T>,
key: unknown,
provisional: T,
scope: CycleScope,
compute: (inner: CycleScope) => T,
): T => {
const cached = solver.values.get(key)
if (cached !== undefined) return cached
const pending = solver.pending.get(key)
if (pending !== undefined) {
scope.lowlink = Math.min(scope.lowlink, pending)
return provisional
}
// Components pop as contiguous stack suffixes, so pending indices stay 0..size-1.
const index = solver.pending.size
const base = solver.stack.length
solver.pending.set(key, index)
solver.stack.push(key)
const inner: CycleScope = { lowlink: Infinity }
const value = compute(inner)
if (inner.lowlink < index) {
scope.lowlink = Math.min(scope.lowlink, inner.lowlink)
return value
}
for (const member of solver.stack.splice(base)) {
solver.pending.delete(member)
solver.values.set(member, value)
}
return value
}
// Most documents have no directional keywords; one cached scan skips projection entirely.
const directionalDocuments = new WeakMap<Document, boolean>()
export const hasDirectionalSchemas = (document: Document): boolean => {
const cached = directionalDocuments.get(document)
if (cached !== undefined) return cached
const contains = (value: unknown): boolean => {
if (Array.isArray(value)) return value.some(contains)
if (!isRecord(value)) return false
if (own(value, "readOnly") === true || own(value, "writeOnly") === true) return true
return Object.values(value).some(contains)
}
const result = contains(document)
directionalDocuments.set(document, result)
return result
}
// OpenAPI 3.1 allows keywords as siblings of `$ref`, so a schema's own declarations
// are inspected before following the reference.
const isHidden = (
document: Document,
resource: SchemaResource,
direction: SchemaDirection,
scope: CycleScope = { lowlink: Infinity },
): boolean => {
const value = resource.value
if (!isRecord(value)) return false
if (own(value, hiddenKeyword[direction]) === true) return true
return solveCycles(projectionCache(document, direction).hidden, value, false, scope, (inner) => {
const target = resolveResource(document, resource)
return (
asArray(own(value, "allOf")).some((item) => isHidden(document, { ...resource, value: item }, direction, inner)) ||
(target.value !== value && isHidden(document, target, direction, inner))
)
})
}
// Hidden property names declared by a schema itself or inherited through `$ref` and
// `allOf` composition, so sibling `required` lists stay consistent after projection.
const hiddenNames = (
document: Document,
resource: SchemaResource,
direction: SchemaDirection,
scope: CycleScope = { lowlink: Infinity },
): ReadonlySet<string> => {
const value = resource.value
if (!isRecord(value)) return new Set()
return solveCycles(projectionCache(document, direction).names, value, new Set(), scope, (inner) => {
const properties = own(value, "properties")
const declared = isRecord(properties)
? Object.entries(properties)
.filter(([, property]) => isHidden(document, { ...resource, value: property }, direction))
.map(([name]) => name)
: []
const composed = asArray(own(value, "allOf")).flatMap((item) => [
...hiddenNames(document, { ...resource, value: item }, direction, inner),
])
const target = resolveResource(document, resource)
const referenced = target.value === value ? [] : hiddenNames(document, target, direction, inner)
return new Set([...declared, ...composed, ...referenced])
})
}
// `not`/`if`/`contains` subschemas pass through unprojected: they negate or select
// rather than assert, so removing hidden properties would invert their semantics.
const nestedSchemas = new Set([
"items",
"additionalProperties",
"unevaluatedProperties",
"propertyNames",
"then",
"else",
])
const nestedSchemaLists = new Set(["anyOf", "oneOf", "prefixItems"])
const nestedSchemaMaps = new Set(["patternProperties", "dependentSchemas", "$defs", "definitions"])
const directionalSchema = (
document: Document,
resource: SchemaResource,
direction: SchemaDirection,
excluded: ReadonlySet<string> = new Set(),
): unknown => {
if (!isRecord(resource.value)) return resource.value
const hidden = new Set([...excluded, ...hiddenNames(document, resource, direction)])
const project = (item: unknown, inherited: ReadonlySet<string> = new Set()): unknown =>
directionalSchema(document, { ...resource, value: item }, direction, inherited)
return Object.fromEntries(
Object.entries(resource.value).map(([key, item]) => {
if (key === "properties" && isRecord(item)) {
return [
key,
Object.fromEntries(
Object.entries(item)
.filter(([name]) => !hidden.has(name))
.map(([name, property]) => [name, project(property)]),
),
]
}
if (key === "required" && Array.isArray(item)) {
return [key, item.filter((name) => typeof name !== "string" || !hidden.has(name))]
}
// allOf branches share one object; hidden names apply across every branch.
if (key === "allOf" && Array.isArray(item)) return [key, item.map((entry) => project(entry, hidden))]
if (nestedSchemas.has(key)) return [key, project(item)]
if (nestedSchemaLists.has(key) && Array.isArray(item)) return [key, item.map((entry) => project(entry))]
if (nestedSchemaMaps.has(key) && isRecord(item)) {
return [key, Object.fromEntries(Object.entries(item).map(([name, entry]) => [name, project(entry)]))]
}
return [key, item]
}),
)
}
const normalizeSchema = (document: Document, value: unknown): JsonSchema => {
const projectSchema = (document: Document, value: unknown): JsonSchema => {
if (!isRecord(value)) return {}
const normalized = nonEmptyString(document.openapi)?.startsWith("3.0")
? fromSchemaOpenApi3_0(value)
@@ -255,21 +52,10 @@ const normalizeSchema = (document: Document, value: unknown): JsonSchema => {
: { ...normalized.schema, $defs: normalized.definitions }
}
const projectSchema = (document: Document, value: unknown, direction: SchemaDirection): JsonSchema =>
normalizeSchema(
document,
hasDirectionalSchemas(document) ? directionalSchema(document, { value, root: value }, direction) : value,
)
export const componentDefinitions = (
document: Document,
direction: SchemaDirection,
): Readonly<Record<string, JsonSchema>> => {
export const componentDefinitions = (document: Document): Readonly<Record<string, JsonSchema>> => {
const components = isRecord(document.components) ? document.components : {}
const schemas = isRecord(components.schemas) ? components.schemas : {}
return Object.fromEntries(
Object.entries(schemas).map(([name, value]) => [name, projectSchema(document, value, direction)]),
)
return Object.fromEntries(Object.entries(schemas).map(([name, value]) => [name, projectSchema(document, value)]))
}
const withDefinitions = (schema: JsonSchema, definitions: Readonly<Record<string, JsonSchema>>): JsonSchema => {
@@ -371,7 +157,7 @@ const operationParameters = (
if (style === "deepObject" && !explode) {
return { ok: false, reason: `query parameter '${name}' uses deepObject with explode=false` }
}
const base = projectSchema(document, resolved.schema, "request")
const base = projectSchema(document, resolved.schema)
const description = nonEmptyString(resolved.description)
unordered.push({
name,
@@ -405,10 +191,7 @@ const operationBody = (
reason: `request body has no JSON content (declared: ${Object.keys(content).join(", ") || "none"})`,
}
}
const resolvedSchema = resolve(document, selected.schema)
const schema = hasDirectionalSchemas(document)
? directionalSchema(document, { value: resolvedSchema, root: resolvedSchema }, "request")
: resolvedSchema
const schema = resolve(document, selected.schema)
const required = resolved.required === true
if (!isFlattenableObjectBody(schema, required)) {
return {
@@ -419,7 +202,7 @@ const operationBody = (
name: "body",
location: "body",
required,
schema: projectSchema(document, selected.schema, "request"),
schema: projectSchema(document, selected.schema),
style: undefined,
explode: undefined,
},
@@ -434,13 +217,11 @@ const operationBody = (
return {
ok: true,
value: {
// Field schemas were already projected with the body as resolution root; a second
// directional pass rooted at the field would misresolve shadowed local $defs.
fields: Object.entries(schema.properties).map(([name, value]) => ({
name,
location: "body" as const,
required: required && requiredProperties.has(name),
schema: normalizeSchema(document, value),
schema: projectSchema(document, value),
style: undefined,
explode: undefined,
})),
@@ -558,7 +339,7 @@ export const operationOutput = (
continue
}
if (!isRecord(value) || value.schema === undefined) return { ok: true, value: undefined }
outcomes.push(projectSchema(document, value.schema, "response"))
outcomes.push(projectSchema(document, value.schema))
}
}
if (outcomes.length === 0) return { ok: true, value: undefined }
+3 -594
View File
@@ -59,53 +59,6 @@ const singleOperation = (operation: Record<string, unknown>, method = "get"): Do
},
})
const directionalSpec = (openapi: string): Document => ({
openapi,
paths: {
"/users": {
post: {
operationId: "users.create",
requestBody: {
required: true,
content: { "application/json": { schema: { $ref: "#/components/schemas/User" } } },
},
responses: {
200: {
description: "Created",
content: { "application/json": { schema: { $ref: "#/components/schemas/User" } } },
},
},
},
},
},
components: {
schemas: {
ReadOnlyID: { type: "string", readOnly: true },
User: {
type: "object",
additionalProperties: false,
required: ["id", "name", "password", "profile", "generated"],
properties: {
id: { type: "string", readOnly: true },
name: { type: "string" },
password: { type: "string", writeOnly: true },
profile: {
type: "object",
additionalProperties: false,
required: ["createdAt", "secret", "label"],
properties: {
createdAt: { type: "string", readOnly: true },
secret: { type: "string", writeOnly: true },
label: { type: "string" },
},
},
generated: { $ref: "#/components/schemas/ReadOnlyID" },
},
},
},
},
})
describe("OpenAPI.fromSpec", () => {
test("covers a representative API from generation through execution", async () => {
const resolutions: Array<string> = []
@@ -401,550 +354,6 @@ describe("OpenAPI.fromSpec", () => {
expect(tool.output.$defs).toMatchObject({ Local: { type: "string" }, Global: { type: "number" } })
})
test("projects read-only and write-only properties by schema direction", () => {
for (const version of ["3.0.3", "3.1.0"]) {
const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec: directionalSpec(version) }).tools, "users.create")
if (!Tool.isDefinition(tool) || !isRecord(tool.input) || !isRecord(tool.output)) {
throw new Error(`users.create was not generated for OpenAPI ${version}`)
}
expect(inputTypeScript(tool)).toBe(
"{ name: string; password: string; profile: { secret: string; label: string } }",
)
expect(outputTypeScript(tool)).toBe(
"{ id: string; name: string; profile: { createdAt: string; label: string }; generated: string }",
)
const requestDefinitions = isRecord(tool.input.$defs) ? tool.input.$defs : {}
const responseDefinitions = isRecord(tool.output.$defs) ? tool.output.$defs : {}
const requestUser = isRecord(requestDefinitions.User) ? requestDefinitions.User : {}
const responseUser = isRecord(responseDefinitions.User) ? responseDefinitions.User : {}
expect(Object.keys(isRecord(requestUser.properties) ? requestUser.properties : {})).toEqual([
"name",
"password",
"profile",
])
expect(requestUser.required).toEqual(["name", "password", "profile"])
expect(Object.keys(isRecord(responseUser.properties) ? responseUser.properties : {})).toEqual([
"id",
"name",
"profile",
"generated",
])
expect(responseUser.required).toEqual(["id", "name", "profile", "generated"])
}
})
test("projects directional annotations through local refs and allOf composition", () => {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: singleOperation(
{
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
additionalProperties: false,
required: ["local", "composed", "name"],
properties: {
local: { $ref: "#/$defs/ReadOnlyValue" },
composed: { allOf: [{ $ref: "#/$defs/ReadOnlyValue" }] },
name: { type: "string" },
},
$defs: {
ReadOnlyValue: { type: "string", readOnly: true },
},
},
},
},
},
},
"post",
),
}).tools,
"test",
)
if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
expect(inputTypeScript(tool)).toBe("{ name: string }")
})
test("honors declarations that are siblings of a $ref", () => {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: {
openapi: "3.1.0",
paths: {
"/test": {
post: {
operationId: "test",
responses: { 200: { description: "Success" } },
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
additionalProperties: false,
required: ["record"],
properties: {
record: {
$ref: "#/components/schemas/Base",
properties: { extra: { type: "string", readOnly: true }, note: { type: "string" } },
required: ["extra", "note", "id"],
},
},
},
},
},
},
},
},
},
components: {
schemas: {
Base: {
type: "object",
required: ["id", "name"],
properties: { id: { type: "string", readOnly: true }, name: { type: "string" } },
},
},
},
},
}).tools,
"test",
)
if (!Tool.isDefinition(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
const record = isRecord(properties.record) ? properties.record : {}
const definitions = isRecord(tool.input.$defs) ? tool.input.$defs : {}
const base = isRecord(definitions.Base) ? definitions.Base : {}
expect(Object.keys(isRecord(record.properties) ? record.properties : {})).toEqual(["note"])
expect(record.required).toEqual(["note"])
expect(Object.keys(isRecord(base.properties) ? base.properties : {})).toEqual(["name"])
expect(base.required).toEqual(["name"])
})
test("honors directional declarations on intermediate reference hops", () => {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: {
...singleOperation(
{
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
additionalProperties: false,
required: ["secret", "name"],
properties: {
// Hidden only by the sibling declaration on the middle hop.
secret: { $ref: "#/components/schemas/Middle" },
name: { type: "string" },
},
},
},
},
},
},
"post",
),
components: {
schemas: {
Middle: { $ref: "#/components/schemas/Plain", readOnly: true },
Plain: { type: "string" },
},
},
},
}).tools,
"test",
)
if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
expect(inputTypeScript(tool)).toBe("{ name: string }")
})
test("projects cyclic component references without hanging", () => {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: {
openapi: "3.1.0",
paths: {
"/test": {
post: {
operationId: "test",
responses: { 200: { description: "Success" } },
requestBody: {
required: true,
content: { "application/json": { schema: { $ref: "#/components/schemas/Node" } } },
},
},
},
},
components: {
schemas: {
Node: {
type: "object",
required: ["id", "name", "child"],
properties: {
id: { type: "string", readOnly: true },
name: { type: "string" },
child: { $ref: "#/components/schemas/Node" },
},
},
},
},
},
}).tools,
"test",
)
if (!Tool.isDefinition(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
const definitions = isRecord(tool.input.$defs) ? tool.input.$defs : {}
const node = isRecord(definitions.Node) ? definitions.Node : {}
expect(Object.keys(isRecord(node.properties) ? node.properties : {})).toEqual(["name", "child"])
expect(node.required).toEqual(["name", "child"])
})
test("projects diamond-shaped reference graphs in linear time", () => {
// Each component references the next twice; without memoized hidden-ness this is 2^30 work.
const depth = 30
const schemas = Object.fromEntries(
Array.from({ length: depth }, (_, index) => [
`C${index}`,
index === depth - 1
? { type: "object", properties: { id: { type: "string", readOnly: true }, name: { type: "string" } } }
: { allOf: [{ $ref: `#/components/schemas/C${index + 1}` }, { $ref: `#/components/schemas/C${index + 1}` }] },
]),
)
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: {
openapi: "3.1.0",
paths: {
"/test": {
post: {
operationId: "test",
responses: { 200: { description: "Success" } },
requestBody: {
required: true,
content: { "application/json": { schema: { $ref: "#/components/schemas/C0" } } },
},
},
},
},
components: { schemas },
},
}).tools,
"test",
)
if (!Tool.isDefinition(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
const definitions = isRecord(tool.input.$defs) ? tool.input.$defs : {}
const leaf = isRecord(definitions[`C${depth - 1}`]) ? definitions[`C${depth - 1}`] : {}
expect(Object.keys(isRecord(leaf.properties) ? leaf.properties : {})).toEqual(["name"])
})
test("resolves hiding through reference cycles regardless of evaluation order", () => {
// `Wrap` is hidden only through the cycle member `Loop`; evaluating a property that
// enters the cycle at `Loop` first must not freeze a provisional result for `Wrap`.
const schemas = {
Wrap: { allOf: [{ $ref: "#/components/schemas/Loop" }] },
Loop: { allOf: [{ $ref: "#/components/schemas/Wrap" }, { readOnly: true }] },
}
const body = (properties: Record<string, unknown>) => ({
required: true,
content: {
"application/json": {
schema: {
type: "object",
additionalProperties: false,
required: [...Object.keys(properties), "name"],
properties: { ...properties, name: { type: "string" } },
},
},
},
})
for (const properties of [
{ a: { $ref: "#/components/schemas/Loop" }, b: { $ref: "#/components/schemas/Wrap" } },
{ a: { $ref: "#/components/schemas/Wrap" }, b: { $ref: "#/components/schemas/Loop" } },
]) {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: { ...singleOperation({ requestBody: body(properties) }, "post"), components: { schemas } },
}).tools,
"test",
)
if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
expect(inputTypeScript(tool)).toBe("{ name: string }")
}
})
test("keeps not, if, and contains subschemas unprojected", () => {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: singleOperation(
{
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
additionalProperties: false,
required: ["record"],
properties: {
record: {
type: "object",
// Removing `secret` here would turn `not` unsatisfiable and
// flip which branch of `if` applies; both must pass through.
not: { required: ["secret"], properties: { secret: { type: "string", readOnly: true } } },
if: { required: ["kind"], properties: { kind: { type: "string", readOnly: true } } },
},
},
},
},
},
},
},
"post",
),
}).tools,
"test",
)
if (!Tool.isDefinition(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
const record: Record<string, unknown> = isRecord(properties.record) ? properties.record : {}
expect(record.not).toEqual({ required: ["secret"], properties: { secret: { type: "string", readOnly: true } } })
expect(record.if).toEqual({ required: ["kind"], properties: { kind: { type: "string", readOnly: true } } })
})
test("does not hide properties whose direction is declared only in anyOf or oneOf alternatives", () => {
// Deliberate scope bound: alternatives may apply, so a directional declaration on
// one alternative does not hide the property; the annotation is preserved as-is.
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: singleOperation(
{
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
additionalProperties: false,
required: ["choice", "pick"],
properties: {
choice: { anyOf: [{ type: "string", readOnly: true }, { type: "number" }] },
pick: { oneOf: [{ type: "string", readOnly: true }, { type: "number" }] },
},
},
},
},
},
},
"post",
),
}).tools,
"test",
)
if (!Tool.isDefinition(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
const choice: Record<string, unknown> = isRecord(properties.choice) ? properties.choice : {}
const pick: Record<string, unknown> = isRecord(properties.pick) ? properties.pick : {}
expect(Object.keys(properties)).toEqual(["choice", "pick"])
expect(choice.anyOf).toEqual([{ type: "string", readOnly: true }, { type: "number" }])
expect(pick.oneOf).toEqual([{ type: "string", readOnly: true }, { type: "number" }])
})
test("does not misresolve shadowed local $defs when flattening body fields", () => {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: singleOperation(
{
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
additionalProperties: false,
required: ["record"],
$defs: { Value: { type: "string" } },
properties: {
record: {
type: "object",
required: ["x"],
properties: { x: { $ref: "#/$defs/Value" } },
// Shadows the body-level Value; must not affect the body-rooted projection.
$defs: { Value: { type: "string", readOnly: true } },
},
},
},
},
},
},
},
"post",
),
}).tools,
"test",
)
if (!Tool.isDefinition(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
const record = isRecord(properties.record) ? properties.record : {}
expect(Object.keys(isRecord(record.properties) ? record.properties : {})).toEqual(["x"])
expect(record.required).toEqual(["x"])
})
test("projects directional annotations inside parameter schemas", () => {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: singleOperation({
parameters: [
{
name: "filter",
in: "query",
required: true,
schema: {
type: "object",
required: ["state", "id"],
properties: { state: { type: "string" }, id: { type: "string", readOnly: true } },
},
},
],
}),
}).tools,
"test",
)
if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
expect(inputTypeScript(tool)).toBe("{ filter: { state: string } }")
})
test("ignores inherited directional annotations", () => {
const inherited: Record<string, unknown> = { type: "string" }
Object.setPrototypeOf(inherited, { readOnly: true })
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: singleOperation({
parameters: [
{
name: "filter",
in: "query",
required: true,
schema: {
type: "object",
// The own annotation on `id` keeps projection active for the document,
// so `value` pins that prototype-inherited annotations are not read.
properties: { value: inherited, id: { type: "string", readOnly: true } },
required: ["value", "id"],
},
},
],
}),
}).tools,
"test",
)
if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
expect(inputTypeScript(tool)).toBe("{ filter: { value: string } }")
})
test("cleans required properties across allOf branches", () => {
const tool = toolAt(
OpenAPI.fromSpec({
baseUrl,
spec: singleOperation(
{
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["id", "name"],
allOf: [
{
type: "object",
required: ["id", "name"],
properties: { id: { type: "string", readOnly: true }, name: { type: "string" } },
},
],
},
},
},
},
},
"post",
),
}).tools,
"test",
)
if (!Tool.isDefinition(tool) || !isRecord(tool.input)) throw new Error("test was not generated")
const properties = isRecord(tool.input.properties) ? tool.input.properties : {}
const body = isRecord(properties.body) ? properties.body : {}
const allOf = Array.isArray(body.allOf) ? body.allOf : []
const branch = isRecord(allOf[0]) ? allOf[0] : {}
expect(body.required).toEqual(["name"])
expect(branch.required).toEqual(["name"])
expect(Object.keys(isRecord(branch.properties) ? branch.properties : {})).toEqual(["name"])
})
test("keeps directional schemas model-facing while preserving runtime pass-through", async () => {
const client = recordingClient(() =>
json({
id: "server-id",
name: "Ada",
password: "returned-by-server",
profile: { createdAt: "today", secret: "returned-secret", label: "primary" },
generated: "generated-id",
}),
)
const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec: directionalSpec("3.1.0") }).tools, "users.create")
if (!Tool.isDefinition(tool)) throw new Error("users.create was not generated")
const result = await Effect.runPromise(
tool
.run({
id: "ignored-top-level",
generated: "ignored-generated",
name: "Ada",
password: "request-secret",
profile: { createdAt: "sent-nested", secret: "nested-secret", label: "primary" },
})
.pipe(Effect.provide(client.layer)),
)
expect(client.requests[0]?.body).toEqual({
name: "Ada",
password: "request-secret",
profile: { createdAt: "sent-nested", secret: "nested-secret", label: "primary" },
})
expect(result).toMatchObject({ password: "returned-by-server", profile: { secret: "returned-secret" } })
})
test("documents that the opencode fixture is unauthenticated", async () => {
const spec = await opencodeSpec()
const components = isRecord(spec.components) ? spec.components : {}
@@ -1116,9 +525,9 @@ describe("OpenAPI.fromSpec", () => {
expect(client.requests[0]?.url).toBe(
`${baseUrl}/test?tags=first+value&tags=second%26value&state=open+now&page=2&location%5Bdirectory%5D=%2Ftmp%2Fa+b&location%5Bworkspace%5D=work%261`,
)
await expect(Effect.runPromise(tool.run({ tags: [{}] }).pipe(Effect.provide(client.layer)))).rejects.toThrow(
"Parameter 'tags' contains an unsupported nested value.",
)
await expect(
Effect.runPromise(tool.run({ tags: [{}] }).pipe(Effect.provide(client.layer))),
).rejects.toThrow("Parameter 'tags' contains an unsupported nested value.")
await expect(
Effect.runPromise(tool.run({ filter: { state: {} } }).pipe(Effect.provide(client.layer))),
).rejects.toThrow("Query parameter 'filter' contains an unsupported nested value.")
+19 -200
View File
@@ -1,45 +1,28 @@
export * as AISDK from "./aisdk"
import { makeLocationNode } from "./effect/app-node"
import {
APICallError,
EmptyResponseBodyError,
InvalidArgumentError,
InvalidPromptError,
InvalidResponseDataError,
JSONParseError,
LoadAPIKeyError,
LoadSettingError,
NoContentGeneratedError,
NoSuchModelError,
TypeValidationError,
UnsupportedFunctionalityError,
type JSONSchema7,
type JSONValue,
type LanguageModelV3,
type LanguageModelV3CallOptions,
type LanguageModelV3FinishReason,
type LanguageModelV3FunctionTool,
type LanguageModelV3Message,
type LanguageModelV3Prompt,
type LanguageModelV3StreamPart,
type LanguageModelV3ToolChoice,
type SharedV3ProviderOptions,
import type {
JSONSchema7,
JSONValue,
LanguageModelV3,
LanguageModelV3CallOptions,
LanguageModelV3FinishReason,
LanguageModelV3FunctionTool,
LanguageModelV3Message,
LanguageModelV3Prompt,
LanguageModelV3StreamPart,
LanguageModelV3ToolChoice,
SharedV3ProviderOptions,
} from "@ai-sdk/provider"
import {
AuthenticationReason,
classifyProviderFailure,
FinishReason,
InvalidRequestReason,
InvalidProviderOutputReason,
LLMEvent,
LLMError,
Model,
ProviderID,
ProviderInternalReason,
ProviderMetadata,
ToolResultValue,
TransportReason,
UnknownProviderReason,
type ContentPart,
type LLMRequest,
@@ -47,7 +30,6 @@ import {
type UsageInput,
} from "@opencode-ai/ai"
import { Auth, Endpoint, type AnyRoute } from "@opencode-ai/ai/route"
import { BedrockEventStream } from "@opencode-ai/ai/protocols/bedrock-event-stream"
import { Cause, Context, Effect, Layer, Option, Schema, Scope, Stream } from "effect"
import { ModelV2 } from "./model"
import { ProviderV2 } from "./provider"
@@ -58,8 +40,6 @@ type UserContent = Extract<LanguageModelV3Message, { role: "user" }>["content"]
type AssistantContent = Extract<LanguageModelV3Message, { role: "assistant" }>["content"]
type ToolResultContent = Extract<AssistantContent[number], { type: "tool-result" }>
class ChunkTimeoutError extends Error {}
export interface SDKEvent {
readonly model: ModelV2.Info
readonly package: string
@@ -84,7 +64,7 @@ function wrapSSE(res: Response, ms: number, ctl: AbortController) {
async pull(ctrl) {
const part = await new Promise<Awaited<ReturnType<typeof reader.read>>>((resolve, reject) => {
const id = setTimeout(() => {
const err = new ChunkTimeoutError("SSE read timed out")
const err = new Error("SSE read timed out")
ctl.abort(err)
void reader.cancel(err)
reject(err)
@@ -173,9 +153,8 @@ function prepareOptions(model: ModelV2.Info, pkg: string) {
...opts,
timeout: false,
})
const response = pkg === "@ai-sdk/amazon-bedrock" ? BedrockEventStream.monitorExceptions(res) : res
if (!chunkAbortCtl || typeof chunkTimeout !== "number") return response
return wrapSSE(response, chunkTimeout, chunkAbortCtl)
if (!chunkAbortCtl || typeof chunkTimeout !== "number") return res
return wrapSSE(res, chunkTimeout, chunkAbortCtl)
}
return options
@@ -737,41 +716,10 @@ function messageValue(input: unknown) {
}
function llmError(method: string, error: unknown) {
if (error instanceof LLMError) return error
const cause = error instanceof Error ? error.cause : undefined
const failures = [error, cause]
const code = failures.map(machineCode).find((value) => value !== undefined)
const providerCode = apiFailureCode(error)?.toLowerCase()
const reason = (() => {
if (
error instanceof ChunkTimeoutError ||
failures.some((failure) => failure instanceof Error && failure.name === "TimeoutError") ||
providerCode === "timeout_error" ||
(code !== undefined && TRANSPORT_TIMEOUT_CODES.has(code))
)
return new TransportReason({ message: errorMessage(error), kind: code ?? "Timeout" })
if (APICallError.isInstance(error)) return apiCallReason(error)
if (code !== undefined && TRANSPORT_CONNECTION_CODES.has(code))
return new TransportReason({ message: errorMessage(error), kind: code })
const malformed = failures.find(isMalformedError)
if (malformed) return new InvalidProviderOutputReason({ message: malformed.message })
if (LoadAPIKeyError.isInstance(error)) return new AuthenticationReason({ message: error.message, kind: "missing" })
if (NoSuchModelError.isInstance(error)) return new InvalidRequestReason({ message: error.message })
if (
LoadSettingError.isInstance(error) ||
InvalidPromptError.isInstance(error) ||
InvalidArgumentError.isInstance(error) ||
UnsupportedFunctionalityError.isInstance(error)
)
return new InvalidRequestReason({ message: error.message })
const providerReason = classifyProviderFailure({
message: apiFailureMessage(error),
code: apiFailureCode(error),
status: apiFailureStatus(error),
})
if (providerReason._tag !== "UnknownProvider") return providerReason
return new UnknownProviderReason({ message: errorMessage(error) })
})()
const reason =
error instanceof LLMError
? new InvalidProviderOutputReason({ message: error.message })
: new UnknownProviderReason({ message: error instanceof Error ? error.message : String(error) })
return new LLMError({
module: "AISDK",
method,
@@ -779,133 +727,4 @@ function llmError(method: string, error: unknown) {
})
}
function apiCallReason(error: APICallError) {
const malformed = isMalformedError(error.cause) ? error.cause : undefined
if (error.statusCode !== undefined && error.statusCode < 400 && malformed)
return new InvalidProviderOutputReason({ message: malformed.message })
const evidence = apiFailureEvidence(error.responseBody)
const code = apiFailureCode(error.data) ?? apiFailureCode(evidence)
if (error.statusCode === undefined) {
const reason =
code === undefined && evidence === undefined
? undefined
: classifyProviderFailure({ message: error.message, code, evidence })
if (reason && reason._tag !== "UnknownProvider") return reason
if (error.isRetryable) return new TransportReason({ message: error.message })
return reason ?? new UnknownProviderReason({ message: error.message })
}
const retryAfter = retryAfterMs(error.responseHeaders)
const reason = classifyProviderFailure({
message: error.message,
evidence,
status: error.statusCode,
code,
retryAfterMs: retryAfter,
})
if (!error.isRetryable || (reason._tag !== "UnknownProvider" && reason._tag !== "InvalidRequest")) return reason
if (classifyProviderFailure({ message: error.message, evidence, code })._tag !== "UnknownProvider") return reason
return new ProviderInternalReason({ message: error.message, status: error.statusCode, retryAfterMs: retryAfter })
}
const TRANSPORT_TIMEOUT_CODES = new Set([
"ETIMEDOUT",
"UND_ERR_BODY_TIMEOUT",
"UND_ERR_CONNECT_TIMEOUT",
"UND_ERR_HEADERS_TIMEOUT",
])
const TRANSPORT_CONNECTION_CODES = new Set([
"CONNECTIONCLOSED",
"CONNECTIONREFUSED",
"EAI_AGAIN",
"ECONNREFUSED",
"ECONNRESET",
"EHOSTUNREACH",
"ENETUNREACH",
"ENOTFOUND",
"EPIPE",
"FAILEDTOOPENSOCKET",
"UND_ERR_SOCKET",
])
const FAILURE_EVIDENCE_LIMIT = 65_536
function field(error: unknown, name: string) {
return typeof error === "object" && error !== null ? Reflect.get(error, name) : undefined
}
function machineCode(error: unknown) {
const code = field(error, "code")
return typeof code === "string" ? code.toUpperCase() : undefined
}
function apiFailureCode(error: unknown): string | undefined {
if (typeof error === "string") {
const decoded = Option.getOrUndefined(Schema.decodeUnknownOption(Schema.UnknownFromJsonString)(error))
return apiFailureCode(decoded)
}
const nested = field(error, "error") ?? field(field(error, "response"), "error")
const nestedCode = nested === undefined || nested === error ? undefined : apiFailureCode(nested)
if (nestedCode) return nestedCode
if (typeof field(error, "originalMessage") === "string" && typeof field(error, "originalStatusCode") === "number")
return "modelstreamerrorexception"
const code = field(error, "code")
if (typeof code === "string" || typeof code === "number") return String(code)
const status = field(error, "status")
if (typeof status === "string") return status
const type = field(error, "type")
if (typeof type === "string" && type !== "error") return type
}
function apiFailureMessage(error: unknown): string {
const message = field(error, "message")
if (typeof message === "string") return message
const originalMessage = field(error, "originalMessage")
if (typeof originalMessage === "string") return originalMessage
const nested = field(error, "error") ?? field(field(error, "response"), "error")
return nested === undefined || nested === error ? String(error) : apiFailureMessage(nested)
}
function apiFailureStatus(error: unknown): number | undefined {
const status = field(error, "status")
const statusCode = field(error, "statusCode")
const originalStatusCode = field(error, "originalStatusCode")
const code = field(error, "code")
const value = [status, statusCode, originalStatusCode, code]
.map((value) => (typeof value === "number" ? value : typeof value === "string" ? Number(value) : undefined))
.find((value) => value !== undefined && Number.isInteger(value) && value >= 400 && value < 600)
if (value !== undefined) return value
const nested = field(error, "error") ?? field(field(error, "response"), "error")
return nested === undefined || nested === error ? undefined : apiFailureStatus(nested)
}
function apiFailureEvidence(error: string | undefined) {
return error === undefined ? undefined : error.slice(0, FAILURE_EVIDENCE_LIMIT)
}
function retryAfterMs(headers: Record<string, string> | undefined) {
if (!headers) return undefined
const normalized = Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]))
const millis = Number(normalized["retry-after-ms"])
if (Number.isFinite(millis)) return Math.max(0, millis)
const value = normalized["retry-after"]
if (!value) return undefined
const seconds = Number(value)
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000)
const date = Date.parse(value)
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now())
}
function errorMessage(error: unknown) {
return error instanceof Error ? error.message : String(error)
}
function isMalformedError(error: unknown): error is Error {
return (
InvalidResponseDataError.isInstance(error) ||
JSONParseError.isInstance(error) ||
TypeValidationError.isInstance(error) ||
EmptyResponseBodyError.isInstance(error) ||
NoContentGeneratedError.isInstance(error)
)
}
export const node = makeLocationNode({ service: Service, layer: locationLayer, deps: [] })
+1 -1
View File
@@ -17,7 +17,7 @@ type Summary = typeof Summary.Type
const entries = (servers: ReadonlyArray<Summary>) =>
servers.flatMap((server) => [
` <server name="${server.server}">`,
` Use tools from this server through \`execute\` under \`tools[${JSON.stringify(McpTool.namespace(server.server))}]\`.`,
` Use tools from this server through \`execute\` under \`tools[${JSON.stringify(McpTool.group(server.server))}]\`.`,
...server.instructions.split("\n").map((line) => ` ${line}`),
" </server>",
])
+1 -5
View File
@@ -142,11 +142,7 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
continue
}
const plugin = yield* load(operation).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("failed to load plugin", { target: operation.target, cause }).pipe(Effect.as(undefined)),
),
)
const plugin = yield* load(operation).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
if (!plugin) continue
const previous = packages.get(operation.target)
if (previous) enabled.delete(previous.id)
+1 -1
View File
@@ -29,7 +29,7 @@ Leaves own resolution, permission, and side-effect ordering. Translate only expe
## Registration
Built-ins and plugin tools register through `Tools.Service.register({ [name]: tool })`. Registrations may provide a
namespace, which flattens direct model names to `<namespace>_<tool>`, and default into CodeMode (`codemode` defaults true;
group, which flattens direct model names to `<group>_<tool>`, and default into CodeMode (`codemode` defaults true;
`codemode: false` keeps the tool on the provider's native tool list).
Registrations are scoped:
+20 -4
View File
@@ -39,7 +39,7 @@ type CollectedFiles = {
interface Registration {
readonly tool: AnyTool
readonly name: string
readonly namespace?: string
readonly group?: string
}
export const create = (registrations: ReadonlyMap<string, Registration>) => {
@@ -47,7 +47,7 @@ export const create = (registrations: ReadonlyMap<string, Registration>) => {
invoke: (name: string, registration: Registration, input: unknown) => Effect.Effect<unknown, unknown>,
hooks?: CodeMode.ToolCallHooks,
) => {
const tools: Record<string, Tool.Definition<never>> = {}
const tools: Record<string, Tool.Definition<never> | Record<string, Tool.Definition<never>>> = {}
for (const [name, registration] of registrations) {
const child = definition(name, registration.tool)
const value = Tool.make({
@@ -56,8 +56,24 @@ export const create = (registrations: ReadonlyMap<string, Registration>) => {
output: child.outputSchema,
run: (input) => invoke(name, registration, input),
})
const path = registration.namespace === undefined ? registration.name : `${registration.namespace}.${registration.name}`
tools[path] = value
if (registration.group === undefined) {
const path = registration.name
if (Object.hasOwn(tools, path)) throw new TypeError(`CodeMode tool namespace conflict: ${path}`)
tools[path] = value
continue
}
const path = registration.name
const namespace = registration.group
const group = tools[namespace]
if (group && Tool.isDefinition(group)) throw new TypeError(`CodeMode tool namespace conflict: ${namespace}`)
if (group) {
if (Object.hasOwn(group, path)) throw new TypeError(`CodeMode tool namespace conflict: ${namespace}.${path}`)
group[path] = value
continue
}
const entries: Record<string, Tool.Definition<never>> = {}
entries[path] = value
tools[namespace] = entries
}
return CodeMode.make<typeof tools>({ tools, ...hooks })
}
+4 -5
View File
@@ -13,11 +13,10 @@ import { Tools } from "./tools"
import { ToolRegistry } from "./registry"
/**
* Registry namespace and permission action names for MCP tools.
* Registry group and permission action names for MCP tools.
*/
export const namespace = (server: string) => server.replace(/[^a-zA-Z0-9_-]/g, "_")
export const name = (server: string, tool: string) =>
`${namespace(server)}_${tool.replace(/[^a-zA-Z0-9_-]/g, "_")}`
export const group = (server: string) => server.replace(/[^a-zA-Z0-9_-]/g, "_")
export const name = (server: string, tool: string) => `${group(server)}_${tool.replace(/[^a-zA-Z0-9_-]/g, "_")}`
export const layer = Layer.effectDiscard(
Effect.gen(function* () {
@@ -108,7 +107,7 @@ export const layer = Layer.effectDiscard(
const next = yield* Scope.fork(scope)
yield* Effect.forEach(
groups,
([server, record]) => tools.register(record, { namespace: namespace(server) }),
([group, record]) => tools.register(record, { group }),
{
discard: true,
},
+4 -13
View File
@@ -10,15 +10,7 @@ import { SessionSchema } from "../session/schema"
import { ToolOutputStore } from "../tool-output-store"
import { Wildcard } from "../util/wildcard"
import { ExecuteTool } from "./execute"
import {
definition,
permission,
registrationEntries,
RegistrationError,
settle,
validateNamespace,
type AnyTool,
} from "./tool"
import { definition, permission, registrationEntries, RegistrationError, settle, type AnyTool } from "./tool"
import { Tools } from "./tools"
import { ToolHooks } from "./hooks"
import { makeLocationNode } from "../effect/app-node"
@@ -103,7 +95,7 @@ const registryLayer = Layer.effect(
type Registration = {
readonly tool: AnyTool
readonly name: string
readonly namespace?: string
readonly group?: string
readonly codemode: boolean
}
const local = new Map<string, Array<{ readonly token: object; readonly registration: Registration }>>()
@@ -194,8 +186,7 @@ const registryLayer = Layer.effect(
return Service.of({
register: Effect.fn("ToolRegistry.register")(function* (tools, options) {
if (options?.namespace !== undefined) yield* validateNamespace(options.namespace)
const entries = registrationEntries(tools, options?.namespace)
const entries = registrationEntries(tools, options?.group)
if (entries.length === 0) return
const codemode = options?.codemode ?? true
const reserved = codemode ? undefined : entries.find((entry) => entry.key === "execute")
@@ -214,7 +205,7 @@ const registryLayer = Layer.effect(
registration: {
tool: entry.tool,
name: entry.name,
namespace: entry.namespace,
group: entry.group,
codemode,
},
},
+3 -454
View File
@@ -1,19 +1,11 @@
import {
APICallError,
InvalidPromptError,
InvalidResponseDataError,
LoadAPIKeyError,
type LanguageModelV3,
type LanguageModelV3CallOptions,
type LanguageModelV3StreamPart,
} from "@ai-sdk/provider"
import type { LanguageModelV3CallOptions } from "@ai-sdk/provider"
import { AISDK } from "@opencode-ai/core/aisdk"
import { ModelV2 } from "@opencode-ai/core/model"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { InvalidRequestReason, LLM, LLMError, Message } from "@opencode-ai/ai"
import { LLM, Message } from "@opencode-ai/ai"
import { LLMClient } from "@opencode-ai/ai/route"
import { expect } from "bun:test"
import { Effect, Stream } from "effect"
import { Effect } from "effect"
import { testEffect } from "./lib/effect"
const it = testEffect(AISDK.locationLayer)
@@ -27,49 +19,6 @@ const model = (packageName: string, settings: Record<string, unknown> = {}) =>
limit: { context: 100, output: 20 },
})
const failingLanguage = (error: unknown): LanguageModelV3 => ({
specificationVersion: "v3",
provider: "test-provider",
modelId: "api-model",
supportedUrls: {},
doGenerate: async () => {
throw error
},
doStream: async () => {
throw error
},
})
const streamingLanguage = (...events: LanguageModelV3StreamPart[]): LanguageModelV3 => ({
...failingLanguage(new Error("unused")),
doStream: async () => ({
stream: new ReadableStream<LanguageModelV3StreamPart>({
start(controller) {
events.forEach((event) => controller.enqueue(event))
controller.close()
},
}),
request: { body: {} },
}),
})
const streamFailure = (language: LanguageModelV3) =>
Effect.gen(function* () {
const aisdk = yield* AISDK.Service
yield* aisdk.hook.sdk((event) => {
event.sdk = {}
})
yield* aisdk.hook.language((event) => {
event.language = language
})
const resolved = yield* aisdk.model(model("@ai-sdk/openai"))
const request = LLM.request({ model: resolved, prompt: "Hello" })
const prepared = yield* LLMClient.prepare<LanguageModelV3CallOptions>(request)
return yield* resolved.route
.streamPrepared(prepared.body, request, { http: { execute: () => Effect.die("unused") } })
.pipe(Stream.runDrain, Effect.flip)
})
it.effect("keys language models by package and flattened overlays", () =>
Effect.gen(function* () {
const aisdk = yield* AISDK.Service
@@ -289,403 +238,3 @@ it.effect("projects replay metadata onto AI SDK prompt parts", () =>
])
}),
)
it.effect("classifies AI SDK API failures", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "Bad Request",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 400,
responseBody: '{"error":{"code":"insufficient_quota","detail":"quota-body-secret"}}',
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "QuotaExceeded" } })
expect("http" in error.reason ? error.reason.http : undefined).toBeUndefined()
expect(JSON.stringify(error)).not.toContain("quota-body-secret")
}),
)
it.effect("keeps retryable quota responses terminal", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "Quota exceeded",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 429,
responseBody: '{"error":{"code":"insufficient_quota"}}',
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "QuotaExceeded" } })
}),
)
it.effect("uses response bodies as transient classification evidence", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "Bad Request",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 400,
responseBody: "Input is too long for requested model overflow-body-secret",
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "InvalidRequest", classification: "context-overflow" } })
expect("http" in error.reason ? error.reason.http : undefined).toBeUndefined()
expect(JSON.stringify(error)).not.toContain("overflow-body-secret")
}),
)
it.effect("honors retryable AI SDK request timeouts", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "HTTP 408",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 408,
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "ProviderInternal", status: 408 } })
}),
)
it.effect("honors retryable AI SDK conflicts", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "HTTP 409",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 409,
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "ProviderInternal", status: 409 } })
}),
)
it.effect("keeps semantic invalid requests terminal on retryable statuses", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "Conflict",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 409,
responseBody: '{"error":{"code":"request_too_large"}}',
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "InvalidRequest" } })
}),
)
it.effect("retries unknown coded conflicts", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "Conflict",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 409,
responseBody: '{"error":{"code":"conflict"}}',
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "ProviderInternal", status: 409 } })
}),
)
it.effect("preserves AI SDK retry delays without HTTP diagnostics", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "Too Many Requests",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 429,
responseHeaders: { "Retry-After-Ms": "250" },
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "RateLimit", retryAfterMs: 250 } })
expect("http" in error.reason ? error.reason.http : undefined).toBeUndefined()
}),
)
it.effect("classifies statusless retryable API failures as transport failures", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "Cannot connect to API",
url: "https://provider.test/v1",
requestBodyValues: {},
isRetryable: true,
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "Transport" } })
}),
)
it.effect("classifies AI SDK timeouts", () =>
Effect.gen(function* () {
const timeout = yield* streamFailure(failingLanguage(new DOMException("timed out", "TimeoutError")))
expect(timeout).toMatchObject({ reason: { _tag: "Transport", kind: "Timeout" } })
}),
)
it.effect("classifies AI SDK connection failures", () =>
Effect.gen(function* () {
const reset = yield* streamFailure(
failingLanguage(Object.assign(new Error("connection reset"), { code: "ECONNRESET" })),
)
expect(reset).toMatchObject({ reason: { _tag: "Transport", kind: "ECONNRESET" } })
}),
)
it.effect("classifies Bun connection failures", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(Object.assign(new Error("connection refused"), { code: "ConnectionRefused" })),
)
expect(error).toMatchObject({ reason: { _tag: "Transport", kind: "CONNECTIONREFUSED" } })
}),
)
it.effect("classifies structured AI SDK stream errors", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
streamingLanguage({ type: "error", error: { type: "overloaded_error", message: "Overloaded" } }),
)
expect(error).toMatchObject({ reason: { _tag: "ProviderInternal", message: "Overloaded" } })
}),
)
it.effect("classifies AI Gateway errors with statusCode", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
streamingLanguage({
type: "error",
error: { type: "internal_server_error", message: "Gateway failed", statusCode: 503 },
}),
)
expect(error).toMatchObject({ reason: { _tag: "ProviderInternal", status: 503 } })
}),
)
it.effect("classifies AI Gateway timeouts as retryable", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
streamingLanguage({
type: "error",
error: { type: "timeout_error", message: "Gateway timed out", statusCode: 408 },
}),
)
expect(error).toMatchObject({ reason: { _tag: "Transport", kind: "Timeout" } })
}),
)
it.effect("classifies stripped Bedrock model stream errors", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
streamingLanguage({
type: "error",
error: {
message: "The model stream failed",
originalMessage: "Upstream provider failed",
originalStatusCode: 424,
},
}),
)
expect(error).toMatchObject({ reason: { _tag: "ProviderInternal", status: 424 } })
}),
)
it.effect("classifies structured stream messages without codes", () =>
Effect.gen(function* () {
const error = yield* streamFailure(streamingLanguage({ type: "error", error: { message: "Rate limit exceeded" } }))
expect(error).toMatchObject({ reason: { _tag: "RateLimit" } })
}),
)
it.effect("classifies nested OpenAI Responses stream errors", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
streamingLanguage({
type: "error",
error: {
type: "response.failed",
response: { error: { code: "server_error", message: "Provider failed" } },
},
}),
)
expect(error).toMatchObject({ reason: { _tag: "ProviderInternal", message: "Provider failed" } })
}),
)
it.effect("classifies numeric string stream statuses", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
streamingLanguage({ type: "error", error: { code: "503", message: "Unavailable" } }),
)
expect(error).toMatchObject({ reason: { _tag: "ProviderInternal", status: 503 } })
}),
)
it.effect("classifies readable stream failures", () =>
Effect.gen(function* () {
const error = yield* streamFailure({
...failingLanguage(new Error("unused")),
doStream: async () => ({
stream: new ReadableStream<LanguageModelV3StreamPart>({
start(controller) {
controller.error(Object.assign(new Error("connection reset"), { code: "ECONNRESET" }))
},
}),
request: { body: {} },
}),
})
expect(error).toMatchObject({ method: "readStream", reason: { _tag: "Transport", kind: "ECONNRESET" } })
}),
)
it.live("times out stalled SSE chunks", () =>
Effect.acquireUseRelease(
Effect.sync(() =>
Bun.serve({
port: 0,
fetch: () =>
new Response(
new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode(": connected\n\n"))
},
}),
{ headers: { "content-type": "text/event-stream" } },
),
}),
),
(server) =>
Effect.gen(function* () {
const aisdk = yield* AISDK.Service
let wrappedFetch: typeof fetch | undefined
yield* aisdk.hook.sdk((event) => {
wrappedFetch = event.options.fetch
event.sdk = {}
})
yield* aisdk.hook.language((event) => {
event.language = {
...failingLanguage(new Error("unused")),
doStream: async () => {
const fetcher = wrappedFetch
if (!fetcher) throw new Error("AI SDK fetch was not configured")
const response = await fetcher(server.url, { method: "POST" })
if (!response.body) throw new Error("AI SDK response body was missing")
return {
stream: response.body.pipeThrough(
new TransformStream<Uint8Array, LanguageModelV3StreamPart>({ transform() {} }),
),
request: { body: {} },
}
},
}
})
const resolved = yield* aisdk.model(model("@ai-sdk/openai", { chunkTimeout: 10 }))
const request = LLM.request({ model: resolved, prompt: "Hello" })
const prepared = yield* LLMClient.prepare<LanguageModelV3CallOptions>(request)
const error = yield* resolved.route
.streamPrepared(prepared.body, request, { http: { execute: () => Effect.die("unused") } })
.pipe(Stream.runDrain, Effect.flip)
expect(error).toMatchObject({ method: "readStream", reason: { _tag: "Transport", kind: "Timeout" } })
}),
(server) => Effect.promise(() => server.stop(true)),
),
)
it.effect("classifies missing AI SDK API keys", () =>
Effect.gen(function* () {
const error = yield* streamFailure(failingLanguage(new LoadAPIKeyError({ message: "API key is missing" })))
expect(error).toMatchObject({ reason: { _tag: "Authentication", kind: "missing" } })
}),
)
it.effect("classifies invalid AI SDK prompts", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(new InvalidPromptError({ prompt: [], message: "unsupported prompt" })),
)
expect(error).toMatchObject({ reason: { _tag: "InvalidRequest" } })
}),
)
it.effect("preserves existing LLM errors", () =>
Effect.gen(function* () {
const original = new LLMError({
module: "test",
method: "run",
reason: new InvalidRequestReason({ message: "invalid" }),
})
const error = yield* streamFailure(failingLanguage(original))
expect(error).toBe(original)
}),
)
it.effect("classifies malformed AI SDK response causes", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
failingLanguage(
new APICallError({
message: "Failed to process response",
url: "https://provider.test/v1",
requestBodyValues: {},
statusCode: 200,
cause: new InvalidResponseDataError({ data: { invalid: true } }),
}),
),
)
expect(error).toMatchObject({ reason: { _tag: "InvalidProviderOutput" } })
}),
)
+5 -16
View File
@@ -18,7 +18,7 @@ import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor"
import { ModelV2 } from "@opencode-ai/core/model"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Effect, Logger } from "effect"
import { Effect } from "effect"
import { Database } from "../../src/database/database"
import { tmpdir } from "../fixture/tmpdir"
import { testEffect } from "../lib/effect"
@@ -111,15 +111,8 @@ describe("PluginSupervisor config", () => {
),
)
it.live("logs invalid packages and continues loading", () => {
const output: string[] = []
const logger = Logger.map(Logger.formatStructured, (entry) => {
if (!Array.isArray(entry.message) || entry.message[0] !== "failed to load plugin") return
const details = entry.message[1]
if (typeof details !== "object" || details === null || !("target" in details)) return
if (typeof details.target === "string") output.push(details.target)
})
return withLocation(
it.live("ignores invalid packages and continues loading", () =>
withLocation(
{
plugins: [
"-*",
@@ -137,13 +130,9 @@ describe("PluginSupervisor config", () => {
expect(yield* agents.get(AgentV2.ID.make("configured"))).toMatchObject({
description: "Loaded after invalid plugins",
})
expect(output).toEqual([
path.join(import.meta.dir, "../plugin/fixtures/missing-plugin.ts"),
path.join(import.meta.dir, "../plugin/fixtures/invalid-plugin.ts"),
])
}),
).pipe(Effect.provide(Logger.layer([logger])))
})
),
)
it.live("loads auto-discovered plugin files", () =>
withLocation(
-1
View File
@@ -268,7 +268,6 @@ describe("MCP errors", () => {
})
test("MCP tool names match V1 sanitization", () => {
expect(McpTool.namespace("context 7")).toBe("context_7")
expect(McpTool.name("context 7", "resolve.library/id")).toBe("context_7_resolve_library_id")
})
+4 -4
View File
@@ -274,7 +274,7 @@ describe("PluginV2", () => {
}),
)
it.effect("namespaces tool names and routes codemode registrations through execute", () =>
it.effect("groups tool names and routes codemode registrations through execute", () =>
Effect.gen(function* () {
const plugins = yield* PluginV2.Service
const registry = yield* ToolRegistry.Service
@@ -291,8 +291,8 @@ describe("PluginV2", () => {
ctx.tool
.transform((draft) => {
draft.add("plain", tool("Plain"), { codemode: false })
draft.add("look/up", tool("Lookup"), { namespace: "context7", codemode: false })
draft.add("search", tool("Search"), { namespace: "context7" })
draft.add("look/up", tool("Lookup"), { group: "context 7", codemode: false })
draft.add("search", tool("Search"), { group: "context 7" })
})
.pipe(Effect.orDie),
})
@@ -301,7 +301,7 @@ describe("PluginV2", () => {
expect((yield* registry.materialize()).definitions.map((tool) => tool.name)).toEqual([
"plain",
"context7_look_up",
"context_7_look_up",
"execute",
])
}),
@@ -84,17 +84,6 @@ const constant = (text: string) =>
})
describe("ToolRegistry", () => {
it.effect("rejects invalid dotted namespaces", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
const error = yield* service.register({ echo: make() }, { namespace: "slack..admin" }).pipe(Effect.flip)
expect(error).toBeInstanceOf(Tool.RegistrationError)
expect(error.message).toBe('Invalid tool namespace: "slack..admin"')
expect((yield* service.materialize()).definitions).toEqual([])
}),
)
it.effect("filters disabled tools with edit aliases and ordered wildcard precedence", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
-47
View File
@@ -46,50 +46,3 @@ test("execute preserves successful results with visible unhandled rejections", a
},
])
})
test("execute supports callable namespace tools", async () => {
const callable = Tool.make({
description: "Administer Slack",
input: Schema.Struct({}),
output: Schema.String,
execute: () => Effect.succeed("admin"),
})
const child = Tool.make({
description: "Create a Slack resource",
input: Schema.Struct({}),
output: Schema.String,
execute: () => Effect.succeed("created"),
})
const execute = ExecuteTool.create(
new Map([
["slack_admin", { tool: callable, name: "admin", namespace: "slack" }],
["slack_admin_create", { tool: child, name: "create", namespace: "slack.admin" }],
]),
)
const result = await Effect.runPromise(
Tool.settle(
execute,
{
type: "tool-call",
id: "call_execute",
name: "execute",
input: { code: "return [await tools.slack.admin({}), await tools.slack.admin.create({})]" },
},
{
sessionID: Session.ID.make("ses_execute"),
agent: Agent.ID.make("build"),
messageID: SessionMessage.ID.make("msg_execute"),
callID: "call_execute",
progress: () => Effect.void,
},
),
)
expect(result.structured).toEqual({
toolCalls: [
{ tool: "slack.admin", status: "completed" },
{ tool: "slack.admin.create", status: "completed" },
],
})
expect(result.content).toEqual([{ type: "text", text: '[\n "admin",\n "created"\n]' }])
})
+5 -11
View File
@@ -150,24 +150,18 @@ export const validateName = (name: string) =>
? Effect.void
: Effect.fail(new RegistrationError({ name, message: `Invalid tool name: ${name}` }))
export const registrationEntries = (tools: Readonly<Record<string, AnyTool>>, namespace?: string) =>
export const registrationEntries = (tools: Readonly<Record<string, AnyTool>>, group?: string) =>
Object.entries(tools).map(([name, tool]) => {
const normalized = name.replace(/[^a-zA-Z0-9_-]/g, "_")
const parent = group?.replace(/[^a-zA-Z0-9_-]/g, "_")
return {
key: namespace === undefined ? normalized : `${namespace.replaceAll(".", "_")}_${normalized}`,
key: parent === undefined ? normalized : `${parent}_${normalized}`,
name: normalized,
namespace,
group: parent,
tool,
}
})
export const validateNamespace = (namespace: string) =>
namespace.split(".").every((segment) => /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(segment))
? Effect.void
: Effect.fail(
new RegistrationError({ name: namespace, message: `Invalid tool namespace: ${JSON.stringify(namespace)}` }),
)
export const withPermission = <T extends AnyTool>(
tool: T,
permission: string,
@@ -294,7 +288,7 @@ export interface ToolExecuteAfterEvent {
}
export interface RegisterOptions {
readonly namespace?: string
readonly group?: string
/** Defaults to true. False exposes the tool directly to the provider. */
readonly codemode?: boolean
}
+2 -2
View File
@@ -420,7 +420,7 @@ function App(props: { pair?: DialogPairCredentials; started: number }) {
const client = useClient()
const toast = useToast()
const themeState = useTheme()
const { themeV2, mode, setMode, locked, lock, unlock } = themeState
const { theme, mode, setMode, locked, lock, unlock } = themeState
const data = useData()
const location = useLocation()
const exit = useExit()
@@ -1087,7 +1087,7 @@ function App(props: { pair?: DialogPairCredentials; started: number }) {
width={dimensions().width}
height={dimensions().height}
flexDirection="column"
backgroundColor={themeV2.background()}
backgroundColor={theme.background}
onMouseDown={(evt) => {
if (!Flag.OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT) return
if (evt.button !== MouseButton.RIGHT) return
@@ -1,11 +1,10 @@
import { TextAttributes } from "@opentui/core"
import { createSignal, For } from "solid-js"
import { For } from "solid-js"
import { useTheme } from "../context/theme"
import { DevTools } from "../devtools"
export function DevToolsSidebar() {
const { themeV2, mode, setMode } = useTheme().contextual("elevated")
const [modeHovered, setModeHovered] = createSignal(false)
const { themeV2 } = useTheme().contextual("elevated")
return (
<box
@@ -17,27 +16,6 @@ export function DevToolsSidebar() {
paddingRight={2}
backgroundColor={themeV2.background()}
>
<box flexShrink={0} marginBottom={1}>
<box marginBottom={1}>
<text fg={themeV2.text.action()} attributes={TextAttributes.BOLD}>
Theme
</text>
</box>
<box flexDirection="row">
<text fg={themeV2.text.subdued()}>Mode</text>
<box flexGrow={1} />
<box
paddingLeft={1}
paddingRight={1}
backgroundColor={modeHovered() ? themeV2.background.action("hovered") : undefined}
onMouseOver={() => setModeHovered(true)}
onMouseOut={() => setModeHovered(false)}
onMouseUp={() => setMode(mode() === "dark" ? "light" : "dark")}
>
<text fg={themeV2.text()}>{mode()}</text>
</box>
</box>
</box>
<For each={DevTools.data()}>
{(group) => (
<box flexShrink={0} marginBottom={1}>
@@ -62,7 +62,7 @@ export function connectionSummary(integration: IntegrationInfo) {
export function DialogIntegration(props: { onConnected?: OnIntegrationConnected } = {}) {
const data = useData()
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const options = createMemo(() =>
integrationOptions(data.location.integration.list() ?? []).map((integration) => {
const methods = connectMethods(integration)
@@ -74,7 +74,7 @@ export function DialogIntegration(props: { onConnected?: OnIntegrationConnected
footer: connectionSummary(integration) || undefined,
category: integration.id in INTEGRATION_PRIORITY ? "Popular" : "Services",
disabled: methods.length === 0,
gutter: connected ? () => <text fg={themeV2.text.feedback.success()}>✓</text> : undefined,
gutter: connected ? () => <text fg={theme.success}>✓</text> : undefined,
onSelect: () =>
credentialConnections(integration).length
? manageConnections(integration, methods, dialog, props.onConnected)
@@ -89,12 +89,12 @@ export function DialogIntegration(props: { onConnected?: OnIntegrationConnected
options={options()}
emptyView={
<box paddingLeft={4} paddingRight={4} paddingTop={1}>
<text fg={themeV2.text.subdued()}>No integrations available</text>
<text fg={theme.textMuted}>No integrations available</text>
</box>
}
noMatchView={
<box paddingLeft={4} paddingRight={4} paddingTop={1}>
<text fg={themeV2.text.subdued()}>No integrations found</text>
<text fg={theme.textMuted}>No integrations found</text>
</box>
}
/>
@@ -289,30 +289,23 @@ function CommandPending(props: {
function CommandView(props: { title: string; output: string; message: string }) {
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { themeV2: overlayTheme } = useTheme().contextual("overlay")
const { theme } = useTheme()
onMount(() => dialog.setSize("large"))
return (
<box gap={1} paddingBottom={1}>
<box flexDirection="row" justifyContent="space-between" paddingLeft={2} paddingRight={2}>
<text attributes={TextAttributes.BOLD} fg={themeV2.text()}>
<text attributes={TextAttributes.BOLD} fg={theme.text}>
{props.title}
</text>
<text fg={themeV2.text.subdued()} onMouseUp={() => dialog.clear()}>
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
esc close
</text>
</box>
<box
backgroundColor={overlayTheme.background()}
paddingLeft={2}
paddingRight={2}
paddingTop={1}
paddingBottom={1}
>
<text fg={overlayTheme.text()}>{props.output.trim()}</text>
<box backgroundColor={theme.backgroundElement} paddingLeft={2} paddingRight={2} paddingTop={1} paddingBottom={1}>
<text fg={theme.text}>{props.output.trim()}</text>
</box>
<box paddingLeft={2} paddingRight={2}>
<text fg={themeV2.text.subdued()}>{props.message}</text>
<text fg={theme.textMuted}>{props.message}</text>
</box>
</box>
)
@@ -327,7 +320,7 @@ function KeyMethod(props: {
const dialog = useDialog()
const client = useClient()
const toast = useToast()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const [error, setError] = createSignal<string>()
return (
@@ -345,9 +338,7 @@ function KeyMethod(props: {
.then(() => connected(props.integration, data, dialog, toast, props.onConnected))
.catch((cause) => setError(message(cause)))
}}
description={() => (
<Show when={error()}>{(value) => <text fg={themeV2.text.feedback.error()}>{value()}</text>}</Show>
)}
description={() => <Show when={error()}>{(value) => <text fg={theme.error}>{value()}</text>}</Show>}
/>
)
}
@@ -502,7 +493,7 @@ function OAuthCode(props: {
const dialog = useDialog()
const client = useClient()
const toast = useToast()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const [error, setError] = createSignal<string>()
let settled = false
@@ -536,9 +527,9 @@ function OAuthCode(props: {
}}
description={() => (
<box gap={1}>
<text fg={themeV2.text.subdued()}>{props.attempt.instructions}</text>
<Link href={props.attempt.url} fg={themeV2.markdown.link()} />
<Show when={error()}>{(value) => <text fg={themeV2.text.feedback.error()}>{value()}</text>}</Show>
<text fg={theme.textMuted}>{props.attempt.instructions}</text>
<Link href={props.attempt.url} fg={theme.primary} />
<Show when={error()}>{(value) => <text fg={theme.error}>{value()}</text>}</Show>
</box>
)}
/>
@@ -547,31 +538,31 @@ function OAuthCode(props: {
function OAuthView(props: { title: string; url?: string; instructions?: string; message: string; copy?: boolean }) {
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
return (
<box paddingLeft={2} paddingRight={2} gap={1} paddingBottom={1}>
<box flexDirection="row" justifyContent="space-between">
<text attributes={TextAttributes.BOLD} fg={themeV2.text()}>
<text attributes={TextAttributes.BOLD} fg={theme.text}>
{props.title}
</text>
<text fg={themeV2.text.subdued()} onMouseUp={() => dialog.clear()}>
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
esc
</text>
</box>
<Show when={props.url}>
{(url) => (
<box gap={1}>
<Link href={url()} fg={themeV2.markdown.link()} />
<Link href={url()} fg={theme.primary} />
<Show when={props.instructions}>
{(instructions) => <text fg={themeV2.text.subdued()}>{instructions()}</text>}
{(instructions) => <text fg={theme.textMuted}>{instructions()}</text>}
</Show>
</box>
)}
</Show>
<text fg={themeV2.text.subdued()}>{props.message}</text>
<text fg={theme.textMuted}>{props.message}</text>
<Show when={props.copy}>
<text fg={themeV2.text()}>
c <span style={{ fg: themeV2.text.subdued() }}>copy</span>
<text fg={theme.text}>
c <span style={{ fg: theme.textMuted }}>copy</span>
</text>
</Show>
</box>
+23 -59
View File
@@ -4,7 +4,7 @@ import { Keymap } from "../context/keymap"
import { pipe, sortBy } from "remeda"
import { DialogSelect } from "../ui/dialog-select"
import { useDialog } from "../ui/dialog"
import { useTheme } from "../context/theme"
import { useTheme, type Theme } from "../context/theme"
import { TextAttributes, type ScrollBoxRenderable } from "@opentui/core"
import type { McpServer } from "@opencode-ai/client"
import { useClipboard } from "../context/clipboard"
@@ -12,59 +12,30 @@ import { useToast } from "../ui/toast"
import { useKeyboard, useTerminalDimensions } from "@opentui/solid"
import { useConfig } from "../config"
import { getScrollAcceleration } from "../util/scroll"
import type { ComponentTheme } from "../theme/v2/component"
// Sort by how much attention a server needs: auth prompts first, then failures,
// then healthy servers, and intentionally-off servers last.
function statusMeta(status: McpServer["status"], themeV2: ComponentTheme) {
function statusMeta(status: McpServer["status"], theme: Theme) {
switch (status.status) {
case "needs_auth":
return {
rank: 0,
icon: "!",
label: "Needs authentication",
color: themeV2.text.feedback.warning(),
error: undefined,
bold: false,
}
return { rank: 0, icon: "!", label: "Needs authentication", color: theme.warning, error: undefined, bold: false }
case "needs_client_registration":
return {
rank: 1,
icon: "✗",
label: "Needs registration",
color: themeV2.text.feedback.error(),
error: status.error,
bold: false,
}
return { rank: 1, icon: "✗", label: "Needs registration", color: theme.error, error: status.error, bold: false }
case "failed":
return {
rank: 2,
icon: "✗",
label: "Failed",
color: themeV2.text.feedback.error(),
error: status.error,
bold: false,
}
return { rank: 2, icon: "✗", label: "Failed", color: theme.error, error: status.error, bold: false }
case "connected":
return {
rank: 3,
icon: "✓",
label: "Connected",
color: themeV2.text.feedback.success(),
error: undefined,
bold: true,
}
return { rank: 3, icon: "✓", label: "Connected", color: theme.success, error: undefined, bold: true }
case "pending":
return { rank: 4, icon: "◌", label: "Pending", color: themeV2.text.subdued(), error: undefined, bold: false }
return { rank: 4, icon: "◌", label: "Pending", color: theme.textMuted, error: undefined, bold: false }
default:
return { rank: 5, icon: "○", label: "Disabled", color: themeV2.text.subdued(), error: undefined, bold: false }
return { rank: 5, icon: "○", label: "Disabled", color: theme.textMuted, error: undefined, bold: false }
}
}
export function DialogMcp() {
const data = useData()
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const [focused, setFocused] = createSignal<string>()
const [detail, setDetail] = createSignal<McpServer>()
@@ -76,7 +47,7 @@ export function DialogMcp() {
pipe(
data.location.mcp.server.list() ?? [],
sortBy(
(server) => statusMeta(server.status, themeV2).rank,
(server) => statusMeta(server.status, theme).rank,
(server) => server.name,
),
),
@@ -90,7 +61,7 @@ export function DialogMcp() {
const options = createMemo(() =>
servers().map((server) => {
const meta = statusMeta(server.status, themeV2)
const meta = statusMeta(server.status, theme)
return {
value: server.name,
title: server.name,
@@ -106,12 +77,12 @@ export function DialogMcp() {
const focusedError = createMemo(() => {
const name = focused()
const server = servers().find((entry) => entry.name === name)
return server ? statusMeta(server.status, themeV2).error : undefined
return server ? statusMeta(server.status, theme).error : undefined
})
const open = (name: string | undefined) => {
const server = servers().find((entry) => entry.name === name)
if (!server || !statusMeta(server.status, themeV2).error) return
if (!server || !statusMeta(server.status, theme).error) return
setDetail(server)
}
@@ -129,7 +100,7 @@ export function DialogMcp() {
onSelect={(option) => open(option.value as string)}
footer={
<Show when={focusedError()}>
<text fg={themeV2.text.subdued()}>enter to view error</text>
<text fg={theme.textMuted}>enter to view error</text>
</Show>
}
/>
@@ -145,12 +116,11 @@ function DialogMcpError(props: { server: McpServer; onBack: () => void }) {
const dialog = useDialog()
const clipboard = useClipboard()
const toast = useToast()
const { themeV2 } = useTheme().contextual("elevated")
const { themeV2: overlayTheme } = useTheme().contextual("overlay")
const { theme } = useTheme()
const dimensions = useTerminalDimensions()
const config = useConfig().data
const [copied, setCopied] = createSignal(false)
const error = () => statusMeta(props.server.status, themeV2).error ?? "Unknown MCP connection error"
const error = () => statusMeta(props.server.status, theme).error ?? "Unknown MCP connection error"
const height = createMemo(() => Math.max(3, Math.floor(dimensions().height / 2) - 5))
let scroll: ScrollBoxRenderable | undefined
@@ -182,35 +152,29 @@ function DialogMcpError(props: { server: McpServer; onBack: () => void }) {
return (
<box paddingLeft={4} paddingRight={4} paddingBottom={1} gap={1}>
<box flexDirection="row" justifyContent="space-between">
<text attributes={TextAttributes.BOLD} fg={themeV2.text()}>
<text attributes={TextAttributes.BOLD} fg={theme.text}>
MCP server: {props.server.name}
</text>
<text fg={themeV2.text.subdued()} onMouseUp={props.onBack}>
<text fg={theme.textMuted} onMouseUp={props.onBack}>
esc back
</text>
</box>
<text fg={themeV2.text.feedback.error()}>✗ Failed</text>
<box
backgroundColor={overlayTheme.background()}
paddingLeft={2}
paddingRight={2}
paddingTop={1}
paddingBottom={1}
>
<text fg={theme.error}>✗ Failed</text>
<box backgroundColor={theme.backgroundElement} paddingLeft={2} paddingRight={2} paddingTop={1} paddingBottom={1}>
<scrollbox
ref={(element: ScrollBoxRenderable) => (scroll = element)}
height={height()}
scrollbarOptions={{ visible: false }}
scrollAcceleration={getScrollAcceleration(config)}
>
<text fg={overlayTheme.text()} wrapMode="word">
<text fg={theme.text} wrapMode="word">
{error()}
</text>
</scrollbox>
</box>
<box flexDirection="row" justifyContent="space-between">
<text fg={themeV2.text.subdued()}>↑↓ scroll</text>
<text fg={themeV2.text.subdued()} onMouseUp={copy}>
<text fg={theme.textMuted}>↑↓ scroll</text>
<text fg={theme.textMuted} onMouseUp={copy}>
{copied() ? "✓ copied" : "c copy details"}
</text>
</box>
@@ -38,7 +38,7 @@ export function DialogMoveSession(props: DialogMoveSessionProps) {
const dialog = useDialog()
const client = useClient()
const dimensions = useTerminalDimensions()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const sessionData = useData()
const route = useRoute()
const toast = useToast()
@@ -172,18 +172,16 @@ export function DialogMoveSession(props: DialogMoveSessionProps) {
return {
title,
titleView: isRemoving ? (
<span style={{ fg: themeV2.text.feedback.error() }}>Deleting {item.location}</span>
<span style={{ fg: theme.error }}>Deleting {item.location}</span>
) : deleting ? (
<span style={{ fg: themeV2.text.action.destructive() }}>
Press {shortcuts.get("dialog.move_session.delete")} again to confirm
</span>
<span style={{ fg: theme.text }}>Press {shortcuts.get("dialog.move_session.delete")} again to confirm</span>
) : suffix ? (
<>
{visible.slice(0, split)}
<span style={{ fg: themeV2.text.subdued() }}>{visible.slice(split)}</span>
<span style={{ fg: theme.textMuted }}>{visible.slice(split)}</span>
</>
) : undefined,
bg: deleting ? themeV2.background.action.destructive() : undefined,
bg: deleting ? theme.error : undefined,
value: {
type: "directory",
directory: item.location,
@@ -316,7 +314,7 @@ export function DialogMoveSession(props: DialogMoveSessionProps) {
title="Move session"
titleView={
<box flexDirection="row" gap={1}>
<text fg={themeV2.text()} attributes={TextAttributes.BOLD}>
<text fg={theme.text} attributes={TextAttributes.BOLD}>
Move session
</text>
<Show when={working() || directories.loading || loadedProject.loading}>
@@ -329,25 +327,25 @@ export function DialogMoveSession(props: DialogMoveSessionProps) {
emptyView={
showError() ? (
<box paddingLeft={4} paddingRight={4} paddingTop={1}>
<text fg={themeV2.text.feedback.error()} attributes={TextAttributes.BOLD}>
<text fg={theme.error} attributes={TextAttributes.BOLD}>
Could not load project directories
</text>
<text fg={themeV2.text.subdued()}>{errorMessage(loadError())}</text>
<text fg={themeV2.text.subdued()}>Close and reopen Move session to try again.</text>
<text fg={theme.textMuted}>{errorMessage(loadError())}</text>
<text fg={theme.textMuted}>Close and reopen Move session to try again.</text>
</box>
) : directories.loading || loadedProject.loading ? (
<box paddingLeft={4} paddingRight={4} paddingTop={1}>
<text fg={themeV2.text.subdued()}>Loading project directories…</text>
<text fg={theme.textMuted}>Loading project directories…</text>
</box>
) : (
<box paddingLeft={4} paddingRight={4} paddingTop={1}>
<text fg={themeV2.text.subdued()}>No project directories available</text>
<text fg={theme.textMuted}>No project directories available</text>
</box>
)
}
noMatchView={
<box paddingLeft={4} paddingRight={4} paddingTop={1}>
<text fg={themeV2.text.subdued()}>No project directories found</text>
<text fg={theme.textMuted}>No project directories found</text>
</box>
}
locked={showError() || directories.loading || loadedProject.loading || Boolean(removing())}
@@ -2,7 +2,7 @@ import { RGBA, TextAttributes } from "@opentui/core"
import open from "open"
import { createSignal } from "solid-js"
import { Keymap } from "../context/keymap"
import { useTheme } from "../context/theme"
import { selectedForeground, useTheme } from "../context/theme"
import { useDialog, type DialogContext } from "../ui/dialog"
import { Link } from "../ui/link"
import { BgPulse } from "./bg-pulse"
@@ -38,9 +38,10 @@ function panelOverlay(color: RGBA) {
export function DialogRetryAction(props: DialogRetryActionProps) {
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const fg = selectedForeground(theme)
const showGoTreatment = () => props.link === GO_URL
const textBg = () => (showGoTreatment() ? panelOverlay(themeV2.background()) : undefined)
const textBg = () => (showGoTreatment() ? panelOverlay(theme.backgroundPanel) : undefined)
const [selected, setSelected] = createSignal<"dismiss" | "action">("action")
Keymap.createLayer(() => ({
@@ -85,26 +86,26 @@ export function DialogRetryAction(props: DialogRetryActionProps) {
) : null}
<box zIndex={1} paddingLeft={PAD_X} paddingRight={PAD_X} paddingBottom={1} gap={1}>
<box flexDirection="row" justifyContent="space-between">
<text attributes={TextAttributes.BOLD} fg={themeV2.text()} bg={textBg()}>
<text attributes={TextAttributes.BOLD} fg={theme.text} bg={textBg()}>
{props.title}
</text>
<text fg={themeV2.text.subdued()} bg={textBg()} onMouseUp={() => dialog.clear()}>
<text fg={theme.textMuted} bg={textBg()} onMouseUp={() => dialog.clear()}>
esc
</text>
</box>
<box gap={0}>
<text fg={themeV2.text.subdued()} bg={textBg()}>
<text fg={theme.textMuted} bg={textBg()}>
{props.message}
</text>
</box>
{props.link ? (
showGoTreatment() ? (
<box alignItems="center" justifyContent="flex-end" height={7} paddingBottom={1}>
<Link href={props.link} fg={themeV2.markdown.link()} bg={textBg()} wrapMode="none" />
<Link href={props.link} fg={theme.primary} bg={textBg()} wrapMode="none" />
</box>
) : (
<box width="100%" flexDirection="row" justifyContent="center" paddingBottom={1}>
<Link href={props.link} fg={themeV2.markdown.link()} wrapMode="none" />
<Link href={props.link} fg={theme.primary} wrapMode="none" />
</box>
)
) : (
@@ -114,14 +115,12 @@ export function DialogRetryAction(props: DialogRetryActionProps) {
<box
paddingLeft={2}
paddingRight={2}
backgroundColor={
selected() === "dismiss" ? themeV2.background.action("focused") : RGBA.fromInts(0, 0, 0, 0)
}
backgroundColor={selected() === "dismiss" ? theme.primary : RGBA.fromInts(0, 0, 0, 0)}
onMouseOver={() => setSelected("dismiss")}
onMouseUp={() => dismiss(props, dialog)}
>
<text
fg={selected() === "dismiss" ? themeV2.text.action("focused") : themeV2.text.subdued()}
fg={selected() === "dismiss" ? fg : theme.textMuted}
bg={selected() === "dismiss" ? undefined : textBg()}
attributes={selected() === "dismiss" ? TextAttributes.BOLD : undefined}
>
@@ -131,12 +130,12 @@ export function DialogRetryAction(props: DialogRetryActionProps) {
<box
paddingLeft={2}
paddingRight={2}
backgroundColor={selected() === "action" ? themeV2.background.action("focused") : RGBA.fromInts(0, 0, 0, 0)}
backgroundColor={selected() === "action" ? theme.primary : RGBA.fromInts(0, 0, 0, 0)}
onMouseOver={() => setSelected("action")}
onMouseUp={() => runAction(props, dialog)}
>
<text
fg={selected() === "action" ? themeV2.text.action("focused") : themeV2.text()}
fg={selected() === "action" ? fg : theme.text}
bg={selected() === "action" ? undefined : textBg()}
attributes={selected() === "action" ? TextAttributes.BOLD : undefined}
>
@@ -13,7 +13,7 @@ export function DialogSessionDeleteFailed(props: {
onDone?: () => void
}) {
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const [store, setStore] = createStore({
active: "delete" as "delete" | "restore",
})
@@ -64,17 +64,17 @@ export function DialogSessionDeleteFailed(props: {
return (
<box paddingLeft={2} paddingRight={2} gap={1}>
<box flexDirection="row" justifyContent="space-between">
<text attributes={TextAttributes.BOLD} fg={themeV2.text()}>
<text attributes={TextAttributes.BOLD} fg={theme.text}>
Failed to Delete Session
</text>
<text fg={themeV2.text.subdued()} onMouseUp={() => dialog.clear()}>
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
esc
</text>
</box>
<text fg={themeV2.text.subdued()} wrapMode="word">
<text fg={theme.textMuted} wrapMode="word">
{`The session "${props.session}" could not be deleted because the workspace "${props.workspace}" is not available.`}
</text>
<text fg={themeV2.text.subdued()} wrapMode="word">
<text fg={theme.textMuted} wrapMode="word">
Choose how you want to recover this broken workspace session.
</text>
<box flexDirection="column" paddingBottom={1} gap={1}>
@@ -86,7 +86,7 @@ export function DialogSessionDeleteFailed(props: {
paddingRight={1}
paddingTop={1}
paddingBottom={1}
backgroundColor={item.id === store.active ? themeV2.background.action("focused") : undefined}
backgroundColor={item.id === store.active ? theme.primary : undefined}
onMouseUp={() => {
setStore("active", item.id)
void confirm()
@@ -94,14 +94,11 @@ export function DialogSessionDeleteFailed(props: {
>
<text
attributes={TextAttributes.BOLD}
fg={item.id === store.active ? themeV2.text.action("focused") : themeV2.text()}
fg={item.id === store.active ? theme.selectedListItemText : theme.text}
>
{item.title}
</text>
<text
fg={item.id === store.active ? themeV2.text.action("focused") : themeV2.text.subdued()}
wrapMode="word"
>
<text fg={item.id === store.active ? theme.selectedListItemText : theme.textMuted} wrapMode="word">
{item.description}
</text>
</box>
@@ -31,15 +31,14 @@ export function DialogWorkspaceFileChanges(props: {
message?: string
}) {
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { themeV2: overlayTheme } = useTheme().contextual("overlay")
const { theme } = useTheme()
const config = useConfig().data
const dimensions = useTerminalDimensions()
const scrollAcceleration = createMemo(() => getScrollAcceleration(config))
const [store, setStore] = createStore({ active: "yes" as WorkspaceFileChangesChoice })
const height = createMemo(() => Math.min(props.files.length, 8))
const fileNameWidth = createMemo(() =>
Math.max(2, Math.min(60, dimensions().width - 2) - 6 - Math.max(7, ...props.files.map(changeCountWidth))),
const fileNameWidth = createMemo(
() => Math.max(2, Math.min(60, dimensions().width - 2) - 6 - Math.max(7, ...props.files.map(changeCountWidth))),
)
function confirm() {
@@ -72,21 +71,21 @@ export function DialogWorkspaceFileChanges(props: {
return (
<box gap={1}>
<box flexDirection="row" justifyContent="space-between" paddingLeft={2} paddingRight={2}>
<text attributes={TextAttributes.BOLD} fg={themeV2.text()}>
<text attributes={TextAttributes.BOLD} fg={theme.text}>
{props.title ?? "File Changes Found"}
</text>
<text fg={themeV2.text.subdued()} onMouseUp={() => dialog.clear()}>
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
esc
</text>
</box>
<box paddingLeft={2} paddingRight={2}>
<text fg={themeV2.text.subdued()} wrapMode="word">
<text fg={theme.textMuted} wrapMode="word">
{props.message ?? "Do you want to move these changes with the session?"}
</text>
</box>
<scrollbox
height={height()}
backgroundColor={overlayTheme.background()}
backgroundColor={theme.backgroundElement}
scrollbarOptions={{ visible: false }}
scrollAcceleration={scrollAcceleration()}
>
@@ -95,19 +94,15 @@ export function DialogWorkspaceFileChanges(props: {
<box flexDirection="row" justifyContent="space-between" paddingLeft={2} paddingRight={2}>
<box flexDirection="row" minWidth={0} flexShrink={1}>
<box width={2} flexShrink={0}>
<text fg={overlayTheme.text.subdued()}>{statusLabel(item.status)}</text>
<text fg={theme.textMuted}>{statusLabel(item.status)}</text>
</box>
<FilePath value={item.file} maxWidth={fileNameWidth()} fg={overlayTheme.text.subdued()} />
<FilePath value={item.file} maxWidth={fileNameWidth()} fg={theme.textMuted} />
</box>
<box flexDirection="row" gap={1} minWidth={7} flexShrink={0} justifyContent="flex-end">
<text>
{" "}
{item.additions ? (
<span style={{ fg: overlayTheme.diff.text.added() }}>+{item.additions}</span>
) : null}
{item.deletions ? (
<span style={{ fg: overlayTheme.diff.text.removed() }}> -{item.deletions}</span>
) : null}
{item.additions ? <span style={{ fg: theme.diffAdded }}>+{item.additions}</span> : null}
{item.deletions ? <span style={{ fg: theme.diffRemoved }}> -{item.deletions}</span> : null}
</text>
</box>
</box>
@@ -120,14 +115,14 @@ export function DialogWorkspaceFileChanges(props: {
<box
paddingLeft={2}
paddingRight={2}
backgroundColor={item === store.active ? themeV2.background.action("focused") : undefined}
backgroundColor={item === store.active ? theme.primary : undefined}
onMouseUp={() => {
setStore("active", item)
props.onSelect(item)
dialog.clear()
}}
>
<text fg={item === store.active ? themeV2.text.action("focused") : themeV2.text.subdued()}>{item}</text>
<text fg={item === store.active ? theme.selectedListItemText : theme.textMuted}>{item}</text>
</box>
)}
</For>
@@ -26,8 +26,7 @@ function Commands(props: { context: Plugin.Context }) {
function Scrap(props: { context: Plugin.Context }) {
const dimensions = useTerminalDimensions()
const { themeV2 } = useTheme()
const { themeV2: elevatedTheme } = useTheme().contextual("elevated")
const { theme } = useTheme()
Keymap.createLayer(() => ({
commands: [
@@ -43,19 +42,19 @@ function Scrap(props: { context: Plugin.Context }) {
}))
return (
<box width={dimensions().width} height={dimensions().height} backgroundColor={themeV2.background()}>
<box width={dimensions().width} height={dimensions().height} backgroundColor={theme.background}>
<box flexGrow={1} />
<box
height={1}
flexShrink={0}
backgroundColor={elevatedTheme.background()}
backgroundColor={theme.backgroundPanel}
paddingLeft={1}
paddingRight={1}
flexDirection="row"
>
<text fg={elevatedTheme.text.subdued()}>~/code/anomalyco/opencode</text>
<text fg={theme.textMuted}>~/code/anomalyco/opencode</text>
<box flexGrow={1} />
<text fg={elevatedTheme.text.subdued()}>esc home</text>
<text fg={theme.textMuted}>esc home</text>
</box>
</box>
)
+1 -1
View File
@@ -267,7 +267,7 @@ function neutralAnchors(theme: Theme, mode: "light" | "dark") {
const light: { step: HueStep; color: RGBA }[] = [
{ step: 100, color: theme.background },
{ step: 200, color: theme.backgroundPanel },
{ step: 300, color: theme.backgroundElement || theme.backgroundMenu },
{ step: 300, color: theme.backgroundMenu },
{ step: 700, color: theme.textMuted },
{ step: 900, color: theme.text },
]
+16 -42
View File
@@ -17,8 +17,7 @@ type Active = ExportFormat | "debug" | "thinking" | "copy" | "export"
export function DialogExportOptions(props: DialogExportOptionsProps) {
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { themeV2: overlayTheme } = useTheme().contextual("overlay")
const { theme } = useTheme()
const [store, setStore] = createStore({
format: "markdown" as ExportFormat,
debug: false,
@@ -76,33 +75,25 @@ export function DialogExportOptions(props: DialogExportOptionsProps) {
return (
<box paddingLeft={2} paddingRight={2} gap={1}>
<box flexDirection="row" justifyContent="space-between">
<text attributes={TextAttributes.BOLD} fg={themeV2.text()}>
<text attributes={TextAttributes.BOLD} fg={theme.text}>
Export session
</text>
<text fg={themeV2.text.subdued()} onMouseUp={() => dialog.clear()}>
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
esc
</text>
</box>
<box flexDirection="row" gap={1}>
<text fg={themeV2.text()}>Export as:</text>
<text fg={theme.text}>Export as:</text>
<box flexDirection="row" gap={1}>
<For each={["markdown", "json"] as const}>
{(format) => (
<box
paddingLeft={1}
paddingRight={1}
backgroundColor={themeV2.background.formfield({
focused: store.active === format,
selected: store.format === format,
})}
backgroundColor={store.format === format ? theme.backgroundElement : undefined}
onMouseUp={() => selectFormat(format)}
>
<text
fg={themeV2.text.formfield({
focused: store.active === format,
selected: store.format === format,
})}
>
<text fg={store.format === format ? theme.text : theme.textMuted}>
{store.format === format ? "◉" : "○"} {format === "markdown" ? "Markdown" : "JSON"}
</text>
</box>
@@ -114,60 +105,43 @@ export function DialogExportOptions(props: DialogExportOptionsProps) {
<box
flexDirection="row"
gap={1}
backgroundColor={themeV2.background.formfield({
focused: store.active === "thinking",
selected: store.thinking,
})}
backgroundColor={store.active === "thinking" ? theme.backgroundElement : undefined}
onMouseUp={() => {
setStore("active", "thinking")
setStore("thinking", !store.thinking)
}}
>
<text fg={themeV2.text.formfield({ focused: store.active === "thinking", selected: store.thinking })}>
<text fg={store.active === "thinking" ? theme.primary : theme.textMuted}>
{store.thinking ? "[x]" : "[ ]"}
</text>
<text fg={themeV2.text.formfield({ focused: store.active === "thinking", selected: store.thinking })}>
Include thinking
</text>
<text fg={store.active === "thinking" ? theme.primary : theme.text}>Include thinking</text>
</box>
</Show>
<Show when={store.format === "json"}>
<box
flexDirection="row"
gap={1}
backgroundColor={themeV2.background.formfield({
focused: store.active === "debug",
selected: store.debug,
})}
backgroundColor={store.active === "debug" ? theme.backgroundElement : undefined}
onMouseUp={() => {
setStore("active", "debug")
setStore("debug", !store.debug)
}}
>
<text fg={themeV2.text.formfield({ focused: store.active === "debug", selected: store.debug })}>
{store.debug ? "[x]" : "[ ]"}
</text>
<text fg={themeV2.text.formfield({ focused: store.active === "debug", selected: store.debug })}>
Events (debug)
</text>
<text fg={store.active === "debug" ? theme.primary : theme.textMuted}>{store.debug ? "[x]" : "[ ]"}</text>
<text fg={store.active === "debug" ? theme.primary : theme.text}>Events (debug)</text>
</box>
</Show>
<box flexDirection="row" justifyContent="flex-end" gap={1} paddingBottom={1}>
<box
paddingLeft={4}
paddingRight={4}
backgroundColor={overlayTheme.background()}
backgroundColor={theme.backgroundElement}
onMouseUp={() => confirm("copy")}
>
<text fg={overlayTheme.text()}>Copy</text>
<text fg={theme.text}>Copy</text>
</box>
<box
paddingLeft={4}
paddingRight={4}
backgroundColor={themeV2.background.action({ focused: store.active === "export" })}
onMouseUp={() => confirm("export")}
>
<text fg={themeV2.text.action({ focused: store.active === "export" })}>Export</text>
<box paddingLeft={4} paddingRight={4} backgroundColor={theme.primary} onMouseUp={() => confirm("export")}>
<text fg={theme.selectedListItemText}>Export</text>
</box>
</box>
</box>
+11 -11
View File
@@ -18,7 +18,7 @@ export type DialogPromptProps = {
export function DialogPrompt(props: DialogPromptProps) {
const dialog = useDialog()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const shortcuts = Keymap.useShortcuts()
const [textareaTarget, setTextareaTarget] = createSignal<TextareaRenderable>()
let textarea: TextareaRenderable
@@ -74,10 +74,10 @@ export function DialogPrompt(props: DialogPromptProps) {
return (
<box paddingLeft={2} paddingRight={2} gap={1}>
<box flexDirection="row" justifyContent="space-between">
<text attributes={TextAttributes.BOLD} fg={themeV2.text()}>
<text attributes={TextAttributes.BOLD} fg={theme.text}>
{props.title}
</text>
<text fg={themeV2.text.subdued()} onMouseUp={() => dialog.clear()}>
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
esc
</text>
</box>
@@ -91,20 +91,20 @@ export function DialogPrompt(props: DialogPromptProps) {
}}
initialValue={props.value}
placeholder={props.placeholder ?? "Enter text"}
placeholderColor={themeV2.text.subdued()}
textColor={themeV2.text.formfield({ disabled: props.busy })}
focusedTextColor={themeV2.text.formfield({ disabled: props.busy })}
cursorColor={props.busy ? themeV2.background.formfield("disabled") : themeV2.text()}
placeholderColor={theme.textMuted}
textColor={props.busy ? theme.textMuted : theme.text}
focusedTextColor={props.busy ? theme.textMuted : theme.text}
cursorColor={props.busy ? theme.backgroundElement : theme.text}
/>
<Show when={props.busy}>
<Spinner color={themeV2.text.subdued()}>{props.busyText ?? "Working..."}</Spinner>
<Spinner color={theme.textMuted}>{props.busyText ?? "Working..."}</Spinner>
</Show>
</box>
<box paddingBottom={1} gap={1} flexDirection="row">
<Show when={!props.busy} fallback={<text fg={themeV2.text.subdued()}>processing...</text>}>
<Show when={!props.busy} fallback={<text fg={theme.textMuted}>processing...</text>}>
<Show when={shortcuts.get("dialog.prompt.submit")}>
<text fg={themeV2.text()}>
{shortcuts.get("dialog.prompt.submit")} <span style={{ fg: themeV2.text.subdued() }}>submit</span>
<text fg={theme.text}>
{shortcuts.get("dialog.prompt.submit")} <span style={{ fg: theme.textMuted }}>submit</span>
</text>
</Show>
</Show>
+2 -2
View File
@@ -16,7 +16,7 @@ export function Dialog(
}>,
) {
const dimensions = useTerminalDimensions()
const { themeV2 } = useTheme().contextual("elevated")
const { theme } = useTheme()
const renderer = useRenderer()
let dismiss = false
@@ -59,7 +59,7 @@ export function Dialog(
}}
width={width()}
maxWidth={dimensions().width - 2}
backgroundColor={themeV2.background()}
backgroundColor={theme.backgroundPanel}
paddingTop={1}
>
{props.children}
+3 -3
View File
@@ -14,7 +14,7 @@ type ToastInput = Omit<ToastOptions, "duration"> & { duration?: number }
export function Toast() {
const toast = useToast()
const { themeV2 } = useTheme().contextual("overlay")
const { theme, themeV2 } = useTheme()
const dimensions = useTerminalDimensions()
return (
@@ -31,8 +31,8 @@ export function Toast() {
paddingRight={2}
paddingTop={1}
paddingBottom={1}
backgroundColor={themeV2.background()}
borderColor={themeV2.text.feedback[current().variant]()}
backgroundColor={theme.backgroundPanel}
borderColor={theme[current().variant]}
border={["left", "right"]}
customBorderChars={SplitBorder.customBorderChars}
>
@@ -85,7 +85,7 @@ test("infers chromatic hues, anchors light and dark colors, and aliases ambiguou
expect(() => resolveThemeFile(migrated, "dark")).not.toThrow()
})
test("builds gray from V1 surfaces and text without using menus or borders", () => {
test("builds gray from V1 surfaces and text without using borders", () => {
const source = structuredClone(DEFAULT_THEMES.opencode)
source.theme.backgroundMenu = { light: "#ededed", dark: "#252525" }
const light = resolveV1(source, "light")
@@ -97,12 +97,12 @@ test("builds gray from V1 surfaces and text without using menus or borders", ()
expect(lightGray[100]).toBe(hex(light.background))
expect(lightGray[200]).toBe(hex(light.backgroundPanel))
expect(lightGray[300]).toBe(hex(light.backgroundElement))
expect(lightGray[300]).toBe(hex(light.backgroundMenu))
expect(lightGray[700]).toBe(hex(light.textMuted))
expect(lightGray[900]).toBe(hex(light.text))
expect(darkGray[100]).toBe(hex(dark.text))
expect(darkGray[300]).toBe(hex(dark.textMuted))
expect(darkGray[700]).toBe(hex(dark.backgroundElement))
expect(darkGray[700]).toBe(hex(dark.backgroundMenu))
expect(darkGray[800]).toBe(hex(dark.backgroundPanel))
expect(darkGray[900]).toBe(hex(dark.background))