mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-16 01:19:19 -04:00
Compare commits
56 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c34e505026 | |||
| 16863ae97b | |||
| 314ca785df | |||
| a2697b9b08 | |||
| 5de3d73f24 | |||
| 4bf7210512 | |||
| 4e4729535e | |||
| 98bb5e3bb4 | |||
| 8eec2c6d57 | |||
| 6fb632eeb6 | |||
| 5452a13e07 | |||
| d881c1c476 | |||
| 364e2d9f03 | |||
| 35fcf1ed58 | |||
| e8b19afa8f | |||
| 3da0dea8e7 | |||
| c7aa47c144 | |||
| 7be95bcd6a | |||
| 3f4fb3f9db | |||
| 6702ce0d3f | |||
| a9895a1e8a | |||
| 75c7ac6a2c | |||
| 0eb71d0fc7 | |||
| deee40c572 | |||
| 8b5655ed53 | |||
| b9525b5878 | |||
| 2b8d1998d6 | |||
| 391cfbcfe7 | |||
| fe0c74f4df | |||
| 6d32bc9cb0 | |||
| 925c2423de | |||
| 71cb419570 | |||
| edc93ceff1 | |||
| 86a468c4d8 | |||
| f05d2ab551 | |||
| bef6cfbffe | |||
| fe9a936867 | |||
| d5669ca934 | |||
| 04f0a771a3 | |||
| c50554d907 | |||
| 3f5ad8441f | |||
| cf6e5b3604 | |||
| cbcf191fdb | |||
| ba0bbdafaa | |||
| a288cb5a0c | |||
| 57ff57595a | |||
| 584fdefe6f | |||
| c310ef82f4 | |||
| 4e85a37590 | |||
| fe9b051d1a | |||
| 33f1b269e9 | |||
| 0d68b0bb20 | |||
| 4e56998d3c | |||
| d625bc86fc | |||
| 5f437a09b0 | |||
| 7d4496eafc |
@@ -132,18 +132,14 @@
|
|||||||
"@opencode-ai/server": "workspace:*",
|
"@opencode-ai/server": "workspace:*",
|
||||||
"@opencode-ai/tui": "workspace:*",
|
"@opencode-ai/tui": "workspace:*",
|
||||||
"@opentui/core": "catalog:",
|
"@opentui/core": "catalog:",
|
||||||
"@opentui/keymap": "catalog:",
|
|
||||||
"@opentui/solid": "catalog:",
|
"@opentui/solid": "catalog:",
|
||||||
"@parcel/watcher": "2.5.1",
|
"@parcel/watcher": "2.5.1",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"fuzzysort": "catalog:",
|
|
||||||
"immer": "11.1.4",
|
"immer": "11.1.4",
|
||||||
"jsonc-parser": "3.3.1",
|
"jsonc-parser": "3.3.1",
|
||||||
"open": "10.1.2",
|
"open": "10.1.2",
|
||||||
"opentui-spinner": "catalog:",
|
|
||||||
"semver": "catalog:",
|
"semver": "catalog:",
|
||||||
"solid-js": "catalog:",
|
"solid-js": "catalog:",
|
||||||
"strip-ansi": "7.1.2",
|
|
||||||
"uqr": "0.1.3",
|
"uqr": "0.1.3",
|
||||||
"ws": "8.21.0",
|
"ws": "8.21.0",
|
||||||
},
|
},
|
||||||
@@ -900,9 +896,13 @@
|
|||||||
"version": "1.17.13",
|
"version": "1.17.13",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource/commit-mono": "5.2.5",
|
"@fontsource/commit-mono": "5.2.5",
|
||||||
|
"@fontsource/noto-sans-math": "5.2.5",
|
||||||
|
"@fontsource/noto-sans-symbols": "5.2.5",
|
||||||
|
"@fontsource/noto-sans-symbols-2": "5.2.5",
|
||||||
"@napi-rs/canvas": "1.0.2",
|
"@napi-rs/canvas": "1.0.2",
|
||||||
"@opencode-ai/ai": "workspace:*",
|
"@opencode-ai/ai": "workspace:*",
|
||||||
"@opencode-ai/core": "workspace:*",
|
"@opencode-ai/core": "workspace:*",
|
||||||
|
"@opencode-ai/plugin": "workspace:*",
|
||||||
"@opentui/core": "catalog:",
|
"@opentui/core": "catalog:",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
},
|
},
|
||||||
@@ -1026,6 +1026,7 @@
|
|||||||
"@opencode-ai/client": "workspace:*",
|
"@opencode-ai/client": "workspace:*",
|
||||||
"@opencode-ai/core": "workspace:*",
|
"@opencode-ai/core": "workspace:*",
|
||||||
"@opencode-ai/plugin": "workspace:*",
|
"@opencode-ai/plugin": "workspace:*",
|
||||||
|
"@opencode-ai/schema": "workspace:*",
|
||||||
"@opencode-ai/simulation": "workspace:*",
|
"@opencode-ai/simulation": "workspace:*",
|
||||||
"@opencode-ai/ui": "workspace:*",
|
"@opencode-ai/ui": "workspace:*",
|
||||||
"@opentui/core": "catalog:",
|
"@opentui/core": "catalog:",
|
||||||
@@ -1795,6 +1796,12 @@
|
|||||||
|
|
||||||
"@fontsource/inter": ["@fontsource/inter@5.2.8", "", {}, "sha512-P6r5WnJoKiNVV+zvW2xM13gNdFhAEpQ9dQJHt3naLvfg+LkF2ldgSLiF4T41lf1SQCM9QmkqPTn4TH568IRagg=="],
|
"@fontsource/inter": ["@fontsource/inter@5.2.8", "", {}, "sha512-P6r5WnJoKiNVV+zvW2xM13gNdFhAEpQ9dQJHt3naLvfg+LkF2ldgSLiF4T41lf1SQCM9QmkqPTn4TH568IRagg=="],
|
||||||
|
|
||||||
|
"@fontsource/noto-sans-math": ["@fontsource/noto-sans-math@5.2.5", "", {}, "sha512-1bxEvVlF51Vfgpju32mRZzI/CHvsfqjXjI2+sAuEyHYvXABUAIyj+93sCO3QZIoMG5drWyrzgoCqRQRaL6wQ8Q=="],
|
||||||
|
|
||||||
|
"@fontsource/noto-sans-symbols": ["@fontsource/noto-sans-symbols@5.2.5", "", {}, "sha512-mxoIRstsmZpZFzd/SRWiD+l6T7TGhpgCrGs7TEnnuGSQIfjVMrQT9Zej2enh9pkfmPNAFyeaGJkHkszJ1hH++w=="],
|
||||||
|
|
||||||
|
"@fontsource/noto-sans-symbols-2": ["@fontsource/noto-sans-symbols-2@5.2.5", "", {}, "sha512-F4O9WLifwoZS1quNzY1ebjMNo2cQPe/UP68Dmud0ONi2lOxaR6xp6fFPO2gG17MI7DwAnfMyQFl64A2tAd28hg=="],
|
||||||
|
|
||||||
"@fuma-translate/react": ["@fuma-translate/react@1.0.2", "", { "peerDependencies": { "@types/react": "*", "react": "^19.2.0", "react-dom": "^19.2.0" }, "optionalPeers": ["@types/react"] }, "sha512-uOiOtBx3nRXR8Nu1GzBf1tApgF1FErDBTHxRIAQeyQdyOoZbrNRN6H4kDCWObY4qyGeGbHydG0DHzgeUgFDMIw=="],
|
"@fuma-translate/react": ["@fuma-translate/react@1.0.2", "", { "peerDependencies": { "@types/react": "*", "react": "^19.2.0", "react-dom": "^19.2.0" }, "optionalPeers": ["@types/react"] }, "sha512-uOiOtBx3nRXR8Nu1GzBf1tApgF1FErDBTHxRIAQeyQdyOoZbrNRN6H4kDCWObY4qyGeGbHydG0DHzgeUgFDMIw=="],
|
||||||
|
|
||||||
"@fumadocs/tailwind": ["@fumadocs/tailwind@0.1.0", "", { "peerDependencies": { "tailwindcss": "^4.0.0" }, "optionalPeers": ["tailwindcss"] }, "sha512-nF/DCAwOR21HZ4AkjIOv3Iqwyqywzb6pdyeMcoa+aZzirXj5ntvNZbe3jJ0v3ehhtrRfYYeXBezvjn8ZmV+fuQ=="],
|
"@fumadocs/tailwind": ["@fumadocs/tailwind@0.1.0", "", { "peerDependencies": { "tailwindcss": "^4.0.0" }, "optionalPeers": ["tailwindcss"] }, "sha512-nF/DCAwOR21HZ4AkjIOv3Iqwyqywzb6pdyeMcoa+aZzirXj5ntvNZbe3jJ0v3ehhtrRfYYeXBezvjn8ZmV+fuQ=="],
|
||||||
|
|||||||
+43
-2
@@ -1,6 +1,6 @@
|
|||||||
# @opencode-ai/ai
|
# @opencode-ai/ai
|
||||||
|
|
||||||
Schema-first LLM core for opencode. One typed request, response, event, and tool language; provider quirks live in adapters, not in calling code.
|
Schema-first AI primitives for opencode. Provider quirks live in adapters, not in calling code.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
@@ -24,6 +24,45 @@ const program = Effect.gen(function* () {
|
|||||||
|
|
||||||
Run `LLMClient.stream(request)` instead of `generate` when you want incremental `LLMEvent`s. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses, Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
|
Run `LLMClient.stream(request)` instead of `generate` when you want incremental `LLMEvent`s. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses, Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
|
||||||
|
|
||||||
|
## Image generation
|
||||||
|
|
||||||
|
Use `Image.generate` with an image model for direct asset generation:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { Image } from "@opencode-ai/ai"
|
||||||
|
import { OpenAI } from "@opencode-ai/ai/providers"
|
||||||
|
|
||||||
|
const program = Effect.gen(function* () {
|
||||||
|
const response = yield* Image.generate({
|
||||||
|
model: OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }).image("gpt-image-2"),
|
||||||
|
prompt: "A robot tending a rooftop garden",
|
||||||
|
count: 2,
|
||||||
|
size: { width: 1024, height: 1024 },
|
||||||
|
providerOptions: { openai: { quality: "high", outputFormat: "webp" } },
|
||||||
|
})
|
||||||
|
|
||||||
|
return response.images // GeneratedImage[] with owned bytes or a provider URL
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Conversational image generation remains part of the LLM interaction. OpenAI Responses exposes it through its hosted image tool:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const program = Effect.gen(function* () {
|
||||||
|
const response = yield* LLM.generate(
|
||||||
|
LLM.request({
|
||||||
|
model: OpenAI.configure({ apiKey }).responses("gpt-5"),
|
||||||
|
prompt: "Design a solarpunk rooftop garden, then show me.",
|
||||||
|
tools: [OpenAI.imageGeneration({ quality: "high" })],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
return response.message
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
The hosted result is represented as a provider-executed tool call and tool result. Its image is a `file` content item with a data URI, so retaining `response.message` preserves the generated image for continuation.
|
||||||
|
|
||||||
## Public API
|
## Public API
|
||||||
|
|
||||||
- **`LLM.request({...})`** — build a provider-neutral `LLMRequest`. Accepts ergonomic inputs (`system: string`, `prompt: string`) that normalize into the canonical Schema classes.
|
- **`LLM.request({...})`** — build a provider-neutral `LLMRequest`. Accepts ergonomic inputs (`system: string`, `prompt: string`) that normalize into the canonical Schema classes.
|
||||||
@@ -32,6 +71,8 @@ Run `LLMClient.stream(request)` instead of `generate` when you want incremental
|
|||||||
- **`Model.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
|
- **`Model.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
|
||||||
- **`LLMClient.prepare(request)`** — compile a request through protocol body construction, validation, and HTTP preparation without sending. Useful for inspection and testing.
|
- **`LLMClient.prepare(request)`** — compile a request through protocol body construction, validation, and HTTP preparation without sending. Useful for inspection and testing.
|
||||||
- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
|
- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
|
||||||
|
- **`Image.generate({...})`** — generate images through a provider-neutral image request and response model.
|
||||||
|
- **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
|
||||||
|
|
||||||
## Caching
|
## Caching
|
||||||
|
|
||||||
@@ -182,7 +223,7 @@ Adding a new model or deployment is usually 5-15 lines using `Route.make({ proto
|
|||||||
|
|
||||||
## Effect
|
## Effect
|
||||||
|
|
||||||
This package is built on Effect. Public methods return `Effect` or `Stream`; provide `LLMClient.layer` for runtime dispatch and import the provider/protocol modules for the routes you use. The example at `example/tutorial.ts` is a runnable walkthrough.
|
This package is built on Effect. Public methods return `Effect` or `Stream`; provide `LLMClient.layer` for LLM dispatch and `ImageClient.layer` for image dispatch, then import the provider/protocol modules for the routes you use. The example at `example/tutorial.ts` is a runnable walkthrough.
|
||||||
|
|
||||||
## See also
|
## See also
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { Context, Effect, Layer } from "effect"
|
||||||
|
import { RequestExecutor } from "./route/executor"
|
||||||
|
import type { ImageRequest, ImageResponse } from "./image"
|
||||||
|
import type { LLMError } from "./schema"
|
||||||
|
|
||||||
|
export type Execute = RequestExecutor.Interface["execute"]
|
||||||
|
|
||||||
|
export interface Interface {
|
||||||
|
readonly generate: (request: ImageRequest) => Effect.Effect<ImageResponse, LLMError>
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Service extends Context.Service<Service, Interface>()("@opencode/ImageClient") {}
|
||||||
|
|
||||||
|
export const generate = (request: ImageRequest): Effect.Effect<ImageResponse, LLMError> =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const client = yield* Service
|
||||||
|
return yield* client.generate(request)
|
||||||
|
}) as Effect.Effect<ImageResponse, LLMError>
|
||||||
|
|
||||||
|
export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer.effect(
|
||||||
|
Service,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const executor = yield* RequestExecutor.Service
|
||||||
|
return Service.of({
|
||||||
|
generate: (request) => request.model.route.generate(request, executor.execute),
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const ImageClient = {
|
||||||
|
Service,
|
||||||
|
layer,
|
||||||
|
generate,
|
||||||
|
} as const
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { Effect, Schema } from "effect"
|
||||||
|
import { HttpOptions, InvalidRequestReason, LLMError, ModelID, ProviderID, ProviderMetadata, Usage } from "./schema"
|
||||||
|
import { ImageClient, type Execute as ImageExecute } from "./image-client"
|
||||||
|
|
||||||
|
export interface ImageRoute {
|
||||||
|
readonly id: string
|
||||||
|
readonly generate: (request: ImageRequest, execute: ImageExecute) => Effect.Effect<ImageResponse, LLMError>
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ImageModel {
|
||||||
|
readonly id: ModelID
|
||||||
|
readonly provider: ProviderID
|
||||||
|
readonly route: ImageRoute
|
||||||
|
readonly defaults?: ImageModelDefaults
|
||||||
|
|
||||||
|
constructor(input: ImageModel.Input) {
|
||||||
|
this.id = input.id
|
||||||
|
this.provider = input.provider
|
||||||
|
this.route = input.route
|
||||||
|
this.defaults = input.defaults
|
||||||
|
}
|
||||||
|
|
||||||
|
static make(input: ImageModel.MakeInput) {
|
||||||
|
return new ImageModel({
|
||||||
|
id: ModelID.make(input.id),
|
||||||
|
provider: ProviderID.make(input.provider),
|
||||||
|
route: input.route,
|
||||||
|
defaults: input.defaults,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export namespace ImageModel {
|
||||||
|
export interface Input {
|
||||||
|
readonly id: ModelID
|
||||||
|
readonly provider: ProviderID
|
||||||
|
readonly route: ImageRoute
|
||||||
|
readonly defaults?: ImageModelDefaults
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MakeInput extends Omit<Input, "id" | "provider"> {
|
||||||
|
readonly id: string | ModelID
|
||||||
|
readonly provider: string | ProviderID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageModelDefaults {
|
||||||
|
readonly providerOptions?: Record<string, Record<string, unknown>>
|
||||||
|
readonly http?: HttpOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ImageModelSchema = Schema.declare((value): value is ImageModel => value instanceof ImageModel, {
|
||||||
|
expected: "Image.Model",
|
||||||
|
})
|
||||||
|
|
||||||
|
export const ImageSize = Schema.Struct({
|
||||||
|
width: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
|
||||||
|
height: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
|
||||||
|
}).annotate({ identifier: "Image.Size" })
|
||||||
|
export type ImageSize = Schema.Schema.Type<typeof ImageSize>
|
||||||
|
|
||||||
|
export class ImageRequest extends Schema.Class<ImageRequest>("Image.Request")({
|
||||||
|
model: ImageModelSchema,
|
||||||
|
prompt: Schema.String,
|
||||||
|
count: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))),
|
||||||
|
size: Schema.optional(ImageSize),
|
||||||
|
aspectRatio: Schema.optional(Schema.String),
|
||||||
|
seed: Schema.optional(Schema.Number),
|
||||||
|
providerOptions: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown))),
|
||||||
|
http: Schema.optional(HttpOptions),
|
||||||
|
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||||
|
}) {}
|
||||||
|
|
||||||
|
export type ImageRequestInput = Omit<ConstructorParameters<typeof ImageRequest>[0], "http"> & {
|
||||||
|
readonly http?: HttpOptions.Input
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GeneratedImage extends Schema.Class<GeneratedImage>("Image.Generated")({
|
||||||
|
mediaType: Schema.String,
|
||||||
|
data: Schema.Union([Schema.String, Schema.Uint8Array]),
|
||||||
|
providerMetadata: Schema.optional(ProviderMetadata),
|
||||||
|
}) {}
|
||||||
|
|
||||||
|
export class ImageResponse extends Schema.Class<ImageResponse>("Image.Response")({
|
||||||
|
images: Schema.Array(GeneratedImage),
|
||||||
|
usage: Schema.optional(Usage),
|
||||||
|
providerMetadata: Schema.optional(ProviderMetadata),
|
||||||
|
}) {
|
||||||
|
get image() {
|
||||||
|
return this.images[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const request = (input: ImageRequest | ImageRequestInput) => {
|
||||||
|
if (input instanceof ImageRequest) return input
|
||||||
|
return new ImageRequest({
|
||||||
|
...input,
|
||||||
|
http: input.http === undefined ? undefined : HttpOptions.make(input.http),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const generate = (input: ImageRequest | ImageRequestInput) =>
|
||||||
|
Effect.try({
|
||||||
|
try: () => request(input),
|
||||||
|
catch: (error) =>
|
||||||
|
new LLMError({
|
||||||
|
module: "Image",
|
||||||
|
method: "generate",
|
||||||
|
reason: new InvalidRequestReason({ message: error instanceof Error ? error.message : String(error) }),
|
||||||
|
}),
|
||||||
|
}).pipe(Effect.flatMap(ImageClient.generate))
|
||||||
|
|
||||||
|
export const Image = {
|
||||||
|
request,
|
||||||
|
generate,
|
||||||
|
} as const
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
export { LLMClient } from "./route/client"
|
export { LLMClient } from "./route/client"
|
||||||
|
export { ImageClient } from "./image-client"
|
||||||
export { Auth } from "./route/auth"
|
export { Auth } from "./route/auth"
|
||||||
export { Provider } from "./provider"
|
export { Provider } from "./provider"
|
||||||
export { ProviderPackage } from "./provider-package"
|
export { ProviderPackage } from "./provider-package"
|
||||||
@@ -10,6 +11,9 @@ export type {
|
|||||||
Service as LLMClientService,
|
Service as LLMClientService,
|
||||||
} from "./route/client"
|
} from "./route/client"
|
||||||
export * from "./schema"
|
export * from "./schema"
|
||||||
|
export { GeneratedImage, ImageModel, ImageRequest, ImageResponse, ImageSize } from "./image"
|
||||||
|
export type { ImageModelDefaults, ImageRequestInput, ImageRoute } from "./image"
|
||||||
|
export { Image } from "./image"
|
||||||
export { Tool, ToolFailure, toDefinitions } from "./tool"
|
export { Tool, ToolFailure, toDefinitions } from "./tool"
|
||||||
export { ToolRuntime } from "./tool-runtime"
|
export { ToolRuntime } from "./tool-runtime"
|
||||||
export type { DispatchResult as ToolDispatchResult, ToolSettlement } from "./tool-runtime"
|
export type { DispatchResult as ToolDispatchResult, ToolSettlement } from "./tool-runtime"
|
||||||
|
|||||||
@@ -703,7 +703,14 @@ const onContentBlockStart = (state: ParserState, event: AnthropicEvent): StepRes
|
|||||||
providerExecuted: block.type === "server_tool_use",
|
providerExecuted: block.type === "server_tool_use",
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
[...events, LLMEvent.toolInputStart({ id: block.id ?? String(event.index), name: block.name ?? "" })],
|
[
|
||||||
|
...events,
|
||||||
|
LLMEvent.toolInputStart({
|
||||||
|
id: block.id ?? String(event.index),
|
||||||
|
name: block.name ?? "",
|
||||||
|
providerExecuted: block.type === "server_tool_use" ? true : undefined,
|
||||||
|
}),
|
||||||
|
],
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -561,7 +561,9 @@ const step = (state: ParserState, event: BedrockEvent) =>
|
|||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
...state,
|
...state,
|
||||||
hasToolCalls: resultEvents.some(LLMEvent.is.toolCall) ? true : state.hasToolCalls,
|
hasToolCalls:
|
||||||
|
resultEvents.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)) ||
|
||||||
|
state.hasToolCalls,
|
||||||
lifecycle,
|
lifecycle,
|
||||||
tools: result.tools,
|
tools: result.tools,
|
||||||
reasoningSignatures: Object.fromEntries(
|
reasoningSignatures: Object.fromEntries(
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ export * as AnthropicMessages from "./anthropic-messages"
|
|||||||
export * as BedrockConverse from "./bedrock-converse"
|
export * as BedrockConverse from "./bedrock-converse"
|
||||||
export * as Gemini from "./gemini"
|
export * as Gemini from "./gemini"
|
||||||
export * as OpenAIChat from "./openai-chat"
|
export * as OpenAIChat from "./openai-chat"
|
||||||
|
export * as OpenAIImages from "./openai-images"
|
||||||
export * as OpenAICompatibleChat from "./openai-compatible-chat"
|
export * as OpenAICompatibleChat from "./openai-compatible-chat"
|
||||||
export * as OpenAICompatibleResponses from "./openai-compatible-responses"
|
export * as OpenAICompatibleResponses from "./openai-compatible-responses"
|
||||||
export * as OpenAIResponses from "./openai-responses"
|
export * as OpenAIResponses from "./openai-responses"
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ const OpenAIChatMessage = Schema.Union([
|
|||||||
reasoning_content: Schema.optional(Schema.String),
|
reasoning_content: Schema.optional(Schema.String),
|
||||||
reasoning: Schema.optional(Schema.String),
|
reasoning: Schema.optional(Schema.String),
|
||||||
reasoning_text: Schema.optional(Schema.String),
|
reasoning_text: Schema.optional(Schema.String),
|
||||||
|
reasoning_details: optionalArray(Schema.Unknown),
|
||||||
}),
|
}),
|
||||||
Schema.Struct({ role: Schema.Literal("tool"), tool_call_id: Schema.String, content: Schema.String }),
|
Schema.Struct({ role: Schema.Literal("tool"), tool_call_id: Schema.String, content: Schema.String }),
|
||||||
]).pipe(Schema.toTaggedUnion("role"))
|
]).pipe(Schema.toTaggedUnion("role"))
|
||||||
@@ -149,6 +150,7 @@ const OpenAIChatDelta = Schema.Struct({
|
|||||||
reasoning_content: optionalNull(Schema.String),
|
reasoning_content: optionalNull(Schema.String),
|
||||||
reasoning: optionalNull(Schema.String),
|
reasoning: optionalNull(Schema.String),
|
||||||
reasoning_text: optionalNull(Schema.String),
|
reasoning_text: optionalNull(Schema.String),
|
||||||
|
reasoning_details: optionalNull(Schema.Array(Schema.Unknown)),
|
||||||
tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),
|
tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -164,13 +166,23 @@ export const OpenAIChatEvent = Schema.Struct({
|
|||||||
export type OpenAIChatEvent = Schema.Schema.Type<typeof OpenAIChatEvent>
|
export type OpenAIChatEvent = Schema.Schema.Type<typeof OpenAIChatEvent>
|
||||||
type OpenAIChatRequestMessage = LLMRequest["messages"][number]
|
type OpenAIChatRequestMessage = LLMRequest["messages"][number]
|
||||||
|
|
||||||
|
interface PendingToolDelta {
|
||||||
|
readonly id?: string
|
||||||
|
readonly name?: string
|
||||||
|
readonly input: string
|
||||||
|
}
|
||||||
|
|
||||||
export interface ParserState {
|
export interface ParserState {
|
||||||
readonly tools: ToolStream.State<number>
|
readonly tools: ToolStream.State<number>
|
||||||
|
readonly pendingTools: Partial<Record<number, PendingToolDelta>>
|
||||||
readonly toolCallEvents: ReadonlyArray<LLMEvent>
|
readonly toolCallEvents: ReadonlyArray<LLMEvent>
|
||||||
readonly usage?: Usage
|
readonly usage?: Usage
|
||||||
readonly finishReason?: FinishReason
|
readonly finishReason?: FinishReason
|
||||||
readonly lifecycle: Lifecycle.State
|
readonly lifecycle: Lifecycle.State
|
||||||
readonly reasoningField?: "reasoning" | "reasoning_content" | "reasoning_text"
|
readonly reasoningField?: "reasoning" | "reasoning_content" | "reasoning_text"
|
||||||
|
readonly reasoningDetails: Array<unknown>
|
||||||
|
readonly reasoningDetailsObserved: boolean
|
||||||
|
readonly reasoningEmitted: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
@@ -216,7 +228,15 @@ const openAICompatibleReasoningContent = (native: unknown) =>
|
|||||||
const reasoningField = (part: ReasoningPart) => {
|
const reasoningField = (part: ReasoningPart) => {
|
||||||
const field = part.providerMetadata?.openai?.reasoningField
|
const field = part.providerMetadata?.openai?.reasoningField
|
||||||
if (field === "reasoning" || field === "reasoning_content" || field === "reasoning_text") return field
|
if (field === "reasoning" || field === "reasoning_content" || field === "reasoning_text") return field
|
||||||
return "reasoning_content"
|
}
|
||||||
|
|
||||||
|
const reasoningDetails = (parts: ReadonlyArray<ReasoningPart>, native: unknown) => {
|
||||||
|
const observed = parts.flatMap((part) => {
|
||||||
|
const details = part.providerMetadata?.openai?.reasoningDetails
|
||||||
|
return Array.isArray(details) ? details : []
|
||||||
|
})
|
||||||
|
if (parts.some((part) => Array.isArray(part.providerMetadata?.openai?.reasoningDetails))) return observed
|
||||||
|
if (isRecord(native) && Array.isArray(native.reasoning_details)) return native.reasoning_details
|
||||||
}
|
}
|
||||||
|
|
||||||
const lowerUserMessage = Effect.fn("OpenAIChat.lowerUserMessage")(function* (message: OpenAIChatRequestMessage) {
|
const lowerUserMessage = Effect.fn("OpenAIChat.lowerUserMessage")(function* (message: OpenAIChatRequestMessage) {
|
||||||
@@ -260,19 +280,28 @@ const lowerAssistantMessage = Effect.fn("OpenAIChat.lowerAssistantMessage")(func
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const text = reasoning.map((part) => part.text).join("")
|
const text = reasoning.map((part) => part.text).join("")
|
||||||
const field = reasoning[0] ? reasoningField(reasoning[0]) : "reasoning_content"
|
const details = reasoningDetails(reasoning, message.native?.openaiCompatible)
|
||||||
|
const observedField = reasoning.map(reasoningField).find((value) => value !== undefined)
|
||||||
|
const nativeReasoning = openAICompatibleReasoningContent(message.native?.openaiCompatible)
|
||||||
|
const fullyStructured = reasoning.every((part) => Array.isArray(part.providerMetadata?.openai?.reasoningDetails))
|
||||||
|
const field = (() => {
|
||||||
|
if (reasoning.length === 0) return
|
||||||
|
if (observedField !== undefined) return observedField
|
||||||
|
if (nativeReasoning !== undefined) return "reasoning_content"
|
||||||
|
if (!fullyStructured) return "reasoning_content"
|
||||||
|
})()
|
||||||
|
const reasoningContent = (() => {
|
||||||
|
if (reasoning.length === 0) return nativeReasoning
|
||||||
|
if (field === "reasoning_content") return text
|
||||||
|
})()
|
||||||
return {
|
return {
|
||||||
role: "assistant" as const,
|
role: "assistant" as const,
|
||||||
content: content.length === 0 ? null : ProviderShared.joinText(content),
|
content: content.length === 0 ? null : ProviderShared.joinText(content),
|
||||||
tool_calls: toolCalls.length === 0 ? undefined : toolCalls,
|
tool_calls: toolCalls.length === 0 ? undefined : toolCalls,
|
||||||
reasoning_content:
|
reasoning_content: reasoningContent,
|
||||||
reasoning.length === 0
|
|
||||||
? openAICompatibleReasoningContent(message.native?.openaiCompatible)
|
|
||||||
: field === "reasoning_content"
|
|
||||||
? text
|
|
||||||
: undefined,
|
|
||||||
reasoning: reasoning.length > 0 && field === "reasoning" ? text : undefined,
|
reasoning: reasoning.length > 0 && field === "reasoning" ? text : undefined,
|
||||||
reasoning_text: reasoning.length > 0 && field === "reasoning_text" ? text : undefined,
|
reasoning_text: reasoning.length > 0 && field === "reasoning_text" ? text : undefined,
|
||||||
|
reasoning_details: details,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -423,6 +452,59 @@ const reasoningDelta = (delta: Schema.Schema.Type<typeof OpenAIChatDelta> | null
|
|||||||
if (delta?.reasoning_text) return { field: "reasoning_text", text: delta.reasoning_text } as const
|
if (delta?.reasoning_text) return { field: "reasoning_text", text: delta.reasoning_text } as const
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const detailText = (details: ReadonlyArray<unknown>) => {
|
||||||
|
const text = details.flatMap((detail) => {
|
||||||
|
if (!isRecord(detail)) return []
|
||||||
|
if (detail.type === "reasoning.text" && typeof detail.text === "string" && detail.text) return [detail.text]
|
||||||
|
if (detail.type === "reasoning.summary" && typeof detail.summary === "string" && detail.summary)
|
||||||
|
return [detail.summary]
|
||||||
|
return []
|
||||||
|
})
|
||||||
|
if (text.length > 0) return text.join("")
|
||||||
|
}
|
||||||
|
|
||||||
|
const appendReasoningDetails = (result: Array<unknown>, details: ReadonlyArray<unknown>) => {
|
||||||
|
for (const detail of details) {
|
||||||
|
const previous = result.at(-1)
|
||||||
|
if (
|
||||||
|
!isRecord(previous) ||
|
||||||
|
previous.type !== "reasoning.text" ||
|
||||||
|
!isRecord(detail) ||
|
||||||
|
detail.type !== "reasoning.text" ||
|
||||||
|
conflictingReasoningTextDetails(previous, detail)
|
||||||
|
) {
|
||||||
|
result.push(detail)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result[result.length - 1] = {
|
||||||
|
...previous,
|
||||||
|
...Object.fromEntries(Object.entries(detail).filter((entry) => entry[1] !== undefined)),
|
||||||
|
text: `${typeof previous.text === "string" ? previous.text : ""}${typeof detail.text === "string" ? detail.text : ""}`,
|
||||||
|
signature: mergeDetailValue(previous.signature, detail.signature),
|
||||||
|
format: mergeDetailValue(previous.format, detail.format),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const mergeDetailValue = (previous: unknown, current: unknown) =>
|
||||||
|
previous || current || (previous !== undefined ? previous : current)
|
||||||
|
|
||||||
|
const conflictingReasoningTextDetails = (previous: Record<string, unknown>, current: Record<string, unknown>) =>
|
||||||
|
conflictingDetailValue(previous.id, current.id) ||
|
||||||
|
conflictingDetailValue(previous.index, current.index) ||
|
||||||
|
conflictingDetailValue(previous.format, current.format) ||
|
||||||
|
(Boolean(previous.signature) && Boolean(current.signature) && previous.signature !== current.signature)
|
||||||
|
|
||||||
|
const conflictingDetailValue = (previous: unknown, current: unknown) =>
|
||||||
|
previous !== undefined && previous !== null && current !== undefined && current !== null && previous !== current
|
||||||
|
|
||||||
|
const reasoningMetadata = (field: ParserState["reasoningField"], details?: ReadonlyArray<unknown>) => ({
|
||||||
|
openai: {
|
||||||
|
...(field ? { reasoningField: field } : {}),
|
||||||
|
...(details ? { reasoningDetails: details } : {}),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const step = (state: ParserState, event: OpenAIChatEvent) =>
|
const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
@@ -432,29 +514,56 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|||||||
const delta = choice?.delta
|
const delta = choice?.delta
|
||||||
const toolDeltas = delta?.tool_calls ?? []
|
const toolDeltas = delta?.tool_calls ?? []
|
||||||
let tools = state.tools
|
let tools = state.tools
|
||||||
|
let pendingTools = state.pendingTools
|
||||||
|
|
||||||
let lifecycle = state.lifecycle
|
let lifecycle = state.lifecycle
|
||||||
|
|
||||||
const reasoning = reasoningDelta(delta)
|
const reasoning = reasoningDelta(delta)
|
||||||
const reasoningField = state.reasoningField ?? reasoning?.field
|
const reasoningField = state.reasoningField ?? (!state.lifecycle.text.has("text-0") ? reasoning?.field : undefined)
|
||||||
if (reasoning)
|
const detailDelta = Array.isArray(delta?.reasoning_details) ? delta.reasoning_details : undefined
|
||||||
lifecycle = Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", reasoning.text, {
|
if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)
|
||||||
openai: { reasoningField: reasoningField ?? reasoning.field },
|
const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined
|
||||||
})
|
const deltaMetadata = reasoningMetadata(reasoningField)
|
||||||
|
const text = detailDelta?.length ? (detailText(detailDelta) ?? reasoning?.text) : reasoning?.text
|
||||||
|
if (!state.lifecycle.text.has("text-0") && text !== undefined)
|
||||||
|
lifecycle = Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", text, deltaMetadata)
|
||||||
|
else if (
|
||||||
|
reasoningDetailsObserved &&
|
||||||
|
!lifecycle.reasoning.has("reasoning-0") &&
|
||||||
|
(Boolean(delta?.content) || toolDeltas.length > 0)
|
||||||
|
)
|
||||||
|
lifecycle = Lifecycle.reasoningStart(lifecycle, events, "reasoning-0", deltaMetadata)
|
||||||
|
const reasoningEmitted = state.reasoningEmitted || lifecycle.reasoning.has("reasoning-0")
|
||||||
|
|
||||||
if (delta?.content) {
|
if (delta?.content) {
|
||||||
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, "reasoning-0")
|
lifecycle = Lifecycle.reasoningEnd(
|
||||||
|
lifecycle,
|
||||||
|
events,
|
||||||
|
"reasoning-0",
|
||||||
|
reasoningMetadata(reasoningField, reasoningDetailsObserved ? state.reasoningDetails : undefined),
|
||||||
|
)
|
||||||
lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.content)
|
lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.content)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (toolDeltas.length) lifecycle = Lifecycle.reasoningEnd(lifecycle, events, "reasoning-0")
|
|
||||||
|
|
||||||
for (const tool of toolDeltas) {
|
for (const tool of toolDeltas) {
|
||||||
|
const current = tools[tool.index]
|
||||||
|
const pending = pendingTools[tool.index]
|
||||||
|
const id = current?.id ?? pending?.id ?? (tool.id || undefined)
|
||||||
|
const name = current?.name ?? pending?.name ?? (tool.function?.name || undefined)
|
||||||
|
const text = `${pending?.input ?? ""}${tool.function?.arguments ?? ""}`
|
||||||
|
if (!current && (!id || !name)) {
|
||||||
|
pendingTools = { ...pendingTools, [tool.index]: { id: id || undefined, name: name || undefined, input: text } }
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (pending) {
|
||||||
|
pendingTools = { ...pendingTools }
|
||||||
|
delete pendingTools[tool.index]
|
||||||
|
}
|
||||||
const result = ToolStream.appendOrStart(
|
const result = ToolStream.appendOrStart(
|
||||||
ADAPTER,
|
ADAPTER,
|
||||||
tools,
|
tools,
|
||||||
tool.index,
|
tool.index,
|
||||||
{ id: tool.id ?? undefined, name: tool.function?.name ?? undefined, text: tool.function?.arguments ?? "" },
|
{ id: id || undefined, name: name || undefined, text },
|
||||||
"OpenAI Chat tool call delta is missing id or name",
|
"OpenAI Chat tool call delta is missing id or name",
|
||||||
)
|
)
|
||||||
if (ToolStream.isError(result)) return yield* result
|
if (ToolStream.isError(result)) return yield* result
|
||||||
@@ -463,8 +572,11 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|||||||
events.push(...result.events)
|
events.push(...result.events)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (finishReason !== undefined && state.finishReason === undefined && Object.keys(pendingTools).length > 0)
|
||||||
|
return yield* ProviderShared.eventError(ADAPTER, "OpenAI Chat tool call delta is missing id or name")
|
||||||
|
|
||||||
// Finalize accumulated tool inputs eagerly when finish_reason arrives so
|
// Finalize accumulated tool inputs eagerly when finish_reason arrives so
|
||||||
// JSON parse failures fail the stream at the boundary rather than at halt.
|
// valid calls and malformed local calls settle independently.
|
||||||
const finished =
|
const finished =
|
||||||
finishReason !== undefined && state.finishReason === undefined && Object.keys(tools).length > 0
|
finishReason !== undefined && state.finishReason === undefined && Object.keys(tools).length > 0
|
||||||
? yield* ToolStream.finishAll(ADAPTER, tools)
|
? yield* ToolStream.finishAll(ADAPTER, tools)
|
||||||
@@ -473,11 +585,15 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
tools: finished?.tools ?? tools,
|
tools: finished?.tools ?? tools,
|
||||||
|
pendingTools,
|
||||||
toolCallEvents: finished?.events ?? state.toolCallEvents,
|
toolCallEvents: finished?.events ?? state.toolCallEvents,
|
||||||
usage,
|
usage,
|
||||||
finishReason,
|
finishReason,
|
||||||
lifecycle,
|
lifecycle,
|
||||||
reasoningField,
|
reasoningField,
|
||||||
|
reasoningDetails: state.reasoningDetails,
|
||||||
|
reasoningDetailsObserved,
|
||||||
|
reasoningEmitted,
|
||||||
},
|
},
|
||||||
events,
|
events,
|
||||||
] as const
|
] as const
|
||||||
@@ -487,7 +603,16 @@ const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
|
|||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
const hasToolCalls = state.toolCallEvents.length > 0
|
const hasToolCalls = state.toolCallEvents.length > 0
|
||||||
const reason = state.finishReason === "stop" && hasToolCalls ? "tool-calls" : state.finishReason
|
const reason = state.finishReason === "stop" && hasToolCalls ? "tool-calls" : state.finishReason
|
||||||
const lifecycle = state.toolCallEvents.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
|
const metadata = reasoningMetadata(
|
||||||
|
state.reasoningField,
|
||||||
|
state.reasoningDetailsObserved ? state.reasoningDetails : undefined,
|
||||||
|
)
|
||||||
|
const started =
|
||||||
|
state.reasoningDetailsObserved && !state.reasoningEmitted
|
||||||
|
? Lifecycle.reasoningStart(state.lifecycle, events, "reasoning-0", reasoningMetadata(state.reasoningField))
|
||||||
|
: state.lifecycle
|
||||||
|
const ended = Lifecycle.reasoningEnd(started, events, "reasoning-0", metadata)
|
||||||
|
const lifecycle = state.toolCallEvents.length ? Lifecycle.stepStart(ended, events) : ended
|
||||||
events.push(...state.toolCallEvents)
|
events.push(...state.toolCallEvents)
|
||||||
if (reason) Lifecycle.finish(lifecycle, events, { reason, usage: state.usage })
|
if (reason) Lifecycle.finish(lifecycle, events, { reason, usage: state.usage })
|
||||||
return events
|
return events
|
||||||
@@ -512,9 +637,13 @@ export const protocol = Protocol.make({
|
|||||||
event: Protocol.jsonEvent(OpenAIChatEvent),
|
event: Protocol.jsonEvent(OpenAIChatEvent),
|
||||||
initial: () => ({
|
initial: () => ({
|
||||||
tools: ToolStream.empty<number>(),
|
tools: ToolStream.empty<number>(),
|
||||||
|
pendingTools: {},
|
||||||
toolCallEvents: [],
|
toolCallEvents: [],
|
||||||
lifecycle: Lifecycle.initial(),
|
lifecycle: Lifecycle.initial(),
|
||||||
reasoningField: undefined,
|
reasoningField: undefined,
|
||||||
|
reasoningDetails: [],
|
||||||
|
reasoningDetailsObserved: false,
|
||||||
|
reasoningEmitted: false,
|
||||||
}),
|
}),
|
||||||
step,
|
step,
|
||||||
onHalt: finishEvents,
|
onHalt: finishEvents,
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
import { Effect, Encoding, Schema } from "effect"
|
||||||
|
import { Headers, HttpClientRequest } from "effect/unstable/http"
|
||||||
|
import {
|
||||||
|
ImageModel,
|
||||||
|
GeneratedImage,
|
||||||
|
ImageResponse,
|
||||||
|
type ImageRequest,
|
||||||
|
type ImageModelDefaults,
|
||||||
|
type ImageRoute,
|
||||||
|
} from "../image"
|
||||||
|
import { Auth, type Definition as AuthDefinition } from "../route/auth"
|
||||||
|
import { InvalidProviderOutputReason, LLMError, Usage, mergeHttpOptions, mergeJsonRecords } from "../schema"
|
||||||
|
import { ProviderShared } from "./shared"
|
||||||
|
import { OpenAIImage } from "./utils/openai-image"
|
||||||
|
|
||||||
|
const ADAPTER = "openai-images"
|
||||||
|
export const DEFAULT_BASE_URL = "https://api.openai.com/v1"
|
||||||
|
export const PATH = "/images/generations"
|
||||||
|
|
||||||
|
export interface OpenAIImageOptions {
|
||||||
|
readonly quality?: "auto" | "low" | "medium" | "high"
|
||||||
|
readonly background?: "auto" | "opaque" | "transparent"
|
||||||
|
readonly moderation?: "auto" | "low"
|
||||||
|
readonly outputFormat?: "png" | "jpeg" | "webp"
|
||||||
|
readonly outputCompression?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const OpenAIImageBody = Schema.Struct({
|
||||||
|
model: Schema.String,
|
||||||
|
prompt: Schema.String,
|
||||||
|
n: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))),
|
||||||
|
size: Schema.optional(Schema.String),
|
||||||
|
quality: Schema.optional(Schema.Literals(["auto", "low", "medium", "high"])),
|
||||||
|
background: Schema.optional(Schema.Literals(["auto", "opaque", "transparent"])),
|
||||||
|
moderation: Schema.optional(Schema.Literals(["auto", "low"])),
|
||||||
|
output_format: Schema.optional(Schema.Literals(["png", "jpeg", "webp"])),
|
||||||
|
output_compression: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 100 }))),
|
||||||
|
})
|
||||||
|
export type OpenAIImageBody = Schema.Schema.Type<typeof OpenAIImageBody>
|
||||||
|
|
||||||
|
const OpenAIImageResponse = Schema.Struct({
|
||||||
|
data: Schema.Array(
|
||||||
|
Schema.Struct({
|
||||||
|
b64_json: Schema.optional(Schema.String),
|
||||||
|
url: Schema.optional(Schema.String),
|
||||||
|
revised_prompt: Schema.optional(Schema.String),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
output_format: Schema.optional(Schema.String),
|
||||||
|
usage: Schema.optional(
|
||||||
|
Schema.Struct({
|
||||||
|
input_tokens: Schema.optional(Schema.Number),
|
||||||
|
output_tokens: Schema.optional(Schema.Number),
|
||||||
|
total_tokens: Schema.optional(Schema.Number),
|
||||||
|
input_tokens_details: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||||
|
output_tokens_details: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
export interface ModelInput {
|
||||||
|
readonly id: string
|
||||||
|
readonly auth: AuthDefinition
|
||||||
|
readonly baseURL?: string
|
||||||
|
readonly headers?: Record<string, string>
|
||||||
|
readonly defaults?: ImageModelDefaults
|
||||||
|
}
|
||||||
|
|
||||||
|
const providerOptions = (request: ImageRequest): OpenAIImageOptions => ({
|
||||||
|
...request.model.defaults?.providerOptions?.openai,
|
||||||
|
...request.providerOptions?.openai,
|
||||||
|
})
|
||||||
|
|
||||||
|
const body = (request: ImageRequest): OpenAIImageBody => {
|
||||||
|
const options = providerOptions(request)
|
||||||
|
return {
|
||||||
|
model: request.model.id,
|
||||||
|
prompt: request.prompt,
|
||||||
|
n: request.count,
|
||||||
|
size: request.size === undefined ? undefined : `${request.size.width}x${request.size.height}`,
|
||||||
|
quality: options.quality,
|
||||||
|
background: options.background,
|
||||||
|
moderation: options.moderation,
|
||||||
|
output_format: options.outputFormat,
|
||||||
|
output_compression: options.outputCompression,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const invalidOutput = (message: string) =>
|
||||||
|
new LLMError({
|
||||||
|
module: ADAPTER,
|
||||||
|
method: "generate",
|
||||||
|
reason: new InvalidProviderOutputReason({ message, route: ADAPTER }),
|
||||||
|
})
|
||||||
|
|
||||||
|
const applyQuery = (url: string, query: Record<string, string> | undefined) => {
|
||||||
|
if (!query) return url
|
||||||
|
const next = new URL(url)
|
||||||
|
Object.entries(query).forEach(([key, value]) => next.searchParams.set(key, value))
|
||||||
|
return next.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
const PROTOCOL_BODY_FIELDS = new Set([
|
||||||
|
"model",
|
||||||
|
"prompt",
|
||||||
|
"n",
|
||||||
|
"size",
|
||||||
|
"quality",
|
||||||
|
"background",
|
||||||
|
"moderation",
|
||||||
|
"output_format",
|
||||||
|
"output_compression",
|
||||||
|
])
|
||||||
|
|
||||||
|
const bodyWithOverlay = Effect.fn("OpenAIImages.bodyWithOverlay")(function* (
|
||||||
|
imageBody: OpenAIImageBody,
|
||||||
|
overlay: Record<string, unknown> | undefined,
|
||||||
|
) {
|
||||||
|
if (!overlay) return imageBody
|
||||||
|
const reserved = Object.keys(overlay).filter((key) => PROTOCOL_BODY_FIELDS.has(key))
|
||||||
|
if (reserved.length > 0)
|
||||||
|
return yield* ProviderShared.invalidRequest(
|
||||||
|
`http.body cannot overlay protocol-owned field(s): ${reserved.join(", ")}`,
|
||||||
|
)
|
||||||
|
return mergeJsonRecords(imageBody, overlay) ?? imageBody
|
||||||
|
})
|
||||||
|
|
||||||
|
export const model = (input: ModelInput) => {
|
||||||
|
const route: ImageRoute = {
|
||||||
|
id: ADAPTER,
|
||||||
|
generate: Effect.fn("OpenAIImages.generate")(function* (request: ImageRequest, execute) {
|
||||||
|
if (request.aspectRatio !== undefined)
|
||||||
|
return yield* ProviderShared.invalidRequest("OpenAI Images does not support the common aspectRatio option")
|
||||||
|
if (request.seed !== undefined)
|
||||||
|
return yield* ProviderShared.invalidRequest("OpenAI Images does not support the common seed option")
|
||||||
|
|
||||||
|
const requestBody = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(OpenAIImageBody))(body(request))
|
||||||
|
const http = mergeHttpOptions(request.model.defaults?.http, request.http)
|
||||||
|
const overlaidBody = yield* bodyWithOverlay(requestBody, http?.body)
|
||||||
|
const text = ProviderShared.encodeJson(overlaidBody)
|
||||||
|
const url = applyQuery(`${(input.baseURL ?? DEFAULT_BASE_URL).replace(/\/$/, "")}${PATH}`, http?.query)
|
||||||
|
const headers = yield* Auth.toEffect(input.auth)({
|
||||||
|
request,
|
||||||
|
method: "POST",
|
||||||
|
url,
|
||||||
|
body: text,
|
||||||
|
headers: Headers.fromInput({ ...input.headers, ...http?.headers }),
|
||||||
|
})
|
||||||
|
const response = yield* execute(
|
||||||
|
HttpClientRequest.post(url).pipe(
|
||||||
|
HttpClientRequest.setHeaders(headers),
|
||||||
|
HttpClientRequest.bodyText(text, "application/json"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
const payload = yield* response.json.pipe(
|
||||||
|
Effect.mapError(() => invalidOutput("Failed to read the OpenAI Images response")),
|
||||||
|
)
|
||||||
|
const decoded = yield* Schema.decodeUnknownEffect(OpenAIImageResponse)(payload).pipe(
|
||||||
|
Effect.mapError(() => invalidOutput("OpenAI Images returned an invalid response")),
|
||||||
|
)
|
||||||
|
const format = decoded.output_format ?? providerOptions(request).outputFormat ?? "png"
|
||||||
|
const images = yield* Effect.forEach(decoded.data, (item, index) => {
|
||||||
|
if (item.b64_json)
|
||||||
|
return Effect.fromResult(Encoding.decodeBase64(item.b64_json)).pipe(
|
||||||
|
Effect.mapError(() => invalidOutput(`OpenAI Images result ${index} contains invalid base64 data`)),
|
||||||
|
Effect.map(
|
||||||
|
(data) =>
|
||||||
|
new GeneratedImage({
|
||||||
|
mediaType: `image/${format}`,
|
||||||
|
data,
|
||||||
|
providerMetadata:
|
||||||
|
item.revised_prompt === undefined ? undefined : { openai: { revisedPrompt: item.revised_prompt } },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if (item.url)
|
||||||
|
return Effect.succeed(
|
||||||
|
new GeneratedImage({
|
||||||
|
mediaType: `image/${format}`,
|
||||||
|
data: item.url,
|
||||||
|
providerMetadata:
|
||||||
|
item.revised_prompt === undefined ? undefined : { openai: { revisedPrompt: item.revised_prompt } },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
return Effect.fail(invalidOutput(`OpenAI Images result ${index} has neither image data nor a URL`))
|
||||||
|
})
|
||||||
|
if (images.length === 0) return yield* invalidOutput("OpenAI Images returned no images")
|
||||||
|
return new ImageResponse({
|
||||||
|
images,
|
||||||
|
usage:
|
||||||
|
decoded.usage === undefined
|
||||||
|
? undefined
|
||||||
|
: new Usage({
|
||||||
|
inputTokens: decoded.usage.input_tokens,
|
||||||
|
outputTokens: decoded.usage.output_tokens,
|
||||||
|
totalTokens: decoded.usage.total_tokens,
|
||||||
|
providerMetadata: { openai: decoded.usage },
|
||||||
|
}),
|
||||||
|
providerMetadata: { openai: { outputFormat: format } },
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
return ImageModel.make({ id: input.id, provider: "openai", route, defaults: input.defaults })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const OpenAIImages = {
|
||||||
|
model,
|
||||||
|
} as const
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Effect, Schema } from "effect"
|
import { Effect, Encoding, Schema } from "effect"
|
||||||
import { Route } from "../route/client"
|
import { Route } from "../route/client"
|
||||||
import { Auth } from "../route/auth"
|
import { Auth } from "../route/auth"
|
||||||
import { Endpoint } from "../route/endpoint"
|
import { Endpoint } from "../route/endpoint"
|
||||||
@@ -25,6 +25,7 @@ import { OpenAIOptions } from "./utils/openai-options"
|
|||||||
import { Lifecycle } from "./utils/lifecycle"
|
import { Lifecycle } from "./utils/lifecycle"
|
||||||
import { ToolSchemaProjection } from "./utils/tool-schema"
|
import { ToolSchemaProjection } from "./utils/tool-schema"
|
||||||
import { ToolStream } from "./utils/tool-stream"
|
import { ToolStream } from "./utils/tool-stream"
|
||||||
|
import { OpenAIImage } from "./utils/openai-image"
|
||||||
|
|
||||||
const ADAPTER = "openai-responses"
|
const ADAPTER = "openai-responses"
|
||||||
export const DEFAULT_BASE_URL = "https://api.openai.com/v1"
|
export const DEFAULT_BASE_URL = "https://api.openai.com/v1"
|
||||||
@@ -113,11 +114,24 @@ const OpenAIResponsesTool = Schema.Struct({
|
|||||||
parameters: JsonObject,
|
parameters: JsonObject,
|
||||||
strict: Schema.optional(Schema.Boolean),
|
strict: Schema.optional(Schema.Boolean),
|
||||||
})
|
})
|
||||||
type OpenAIResponsesTool = Schema.Schema.Type<typeof OpenAIResponsesTool>
|
const OpenAIResponsesImageGenerationTool = Schema.Struct({
|
||||||
|
type: Schema.tag("image_generation"),
|
||||||
|
action: Schema.optional(Schema.Literals(["auto", "generate", "edit"])),
|
||||||
|
background: Schema.optional(Schema.Literals(["auto", "opaque", "transparent"])),
|
||||||
|
input_fidelity: Schema.optional(Schema.Literals(["low", "high"])),
|
||||||
|
output_compression: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 100 }))),
|
||||||
|
output_format: Schema.optional(Schema.Literals(["png", "jpeg", "webp"])),
|
||||||
|
partial_images: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
|
||||||
|
quality: Schema.optional(Schema.Literals(["auto", "low", "medium", "high"])),
|
||||||
|
size: Schema.optional(OpenAIImage.Size),
|
||||||
|
})
|
||||||
|
const OpenAIResponsesTools = Schema.Union([OpenAIResponsesTool, OpenAIResponsesImageGenerationTool])
|
||||||
|
type OpenAIResponsesTool = Schema.Schema.Type<typeof OpenAIResponsesTools>
|
||||||
|
|
||||||
const OpenAIResponsesToolChoice = Schema.Union([
|
const OpenAIResponsesToolChoice = Schema.Union([
|
||||||
Schema.Literals(["auto", "none", "required"]),
|
Schema.Literals(["auto", "none", "required"]),
|
||||||
Schema.Struct({ type: Schema.tag("function"), name: Schema.String }),
|
Schema.Struct({ type: Schema.tag("function"), name: Schema.String }),
|
||||||
|
Schema.Struct({ type: Schema.tag("image_generation") }),
|
||||||
])
|
])
|
||||||
|
|
||||||
// Fields shared between the HTTP body and the WebSocket `response.create`
|
// Fields shared between the HTTP body and the WebSocket `response.create`
|
||||||
@@ -128,7 +142,7 @@ const OpenAIResponsesCoreFields = {
|
|||||||
model: Schema.String,
|
model: Schema.String,
|
||||||
input: Schema.Array(OpenAIResponsesInputItem),
|
input: Schema.Array(OpenAIResponsesInputItem),
|
||||||
instructions: Schema.optional(Schema.String),
|
instructions: Schema.optional(Schema.String),
|
||||||
tools: optionalArray(OpenAIResponsesTool),
|
tools: optionalArray(OpenAIResponsesTools),
|
||||||
tool_choice: Schema.optional(OpenAIResponsesToolChoice),
|
tool_choice: Schema.optional(OpenAIResponsesToolChoice),
|
||||||
store: Schema.optional(Schema.Boolean),
|
store: Schema.optional(Schema.Boolean),
|
||||||
service_tier: Schema.optional(OpenAIOptions.OpenAIServiceTier),
|
service_tier: Schema.optional(OpenAIOptions.OpenAIServiceTier),
|
||||||
@@ -194,6 +208,8 @@ const OpenAIResponsesStreamItem = Schema.Struct({
|
|||||||
outputs: Schema.optional(Schema.Unknown),
|
outputs: Schema.optional(Schema.Unknown),
|
||||||
server_label: Schema.optional(Schema.String),
|
server_label: Schema.optional(Schema.String),
|
||||||
output: Schema.optional(Schema.Unknown),
|
output: Schema.optional(Schema.Unknown),
|
||||||
|
result: Schema.optional(Schema.String),
|
||||||
|
output_format: Schema.optional(Schema.Literals(["png", "jpeg", "webp"])),
|
||||||
error: Schema.optional(Schema.Unknown),
|
error: Schema.optional(Schema.Unknown),
|
||||||
encrypted_content: optionalNull(Schema.String),
|
encrypted_content: optionalNull(Schema.String),
|
||||||
})
|
})
|
||||||
@@ -258,21 +274,41 @@ const invalid = ProviderShared.invalidRequest
|
|||||||
// =============================================================================
|
// =============================================================================
|
||||||
// Request Lowering
|
// Request Lowering
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
const lowerTool = (tool: ToolDefinition, inputSchema: JsonSchema): OpenAIResponsesTool => ({
|
const nativeImageToolInput = (tool: ToolDefinition) => {
|
||||||
type: "function",
|
const native = tool.native?.openai
|
||||||
name: tool.name,
|
return ProviderShared.isRecord(native) && native.type === "image_generation" ? native : undefined
|
||||||
description: tool.description,
|
}
|
||||||
parameters: ToolSchemaProjection.openAI(inputSchema),
|
|
||||||
// TODO: Read this from OpenAI-specific tool options so direct LLM callers can opt into strict schemas.
|
const nativeImageTool = (tool: ToolDefinition) => {
|
||||||
strict: false,
|
const native = nativeImageToolInput(tool)
|
||||||
|
return Schema.is(OpenAIResponsesImageGenerationTool)(native) ? native : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const lowerTool = Effect.fn("OpenAIResponses.lowerTool")(function* (tool: ToolDefinition, inputSchema: JsonSchema) {
|
||||||
|
const native = nativeImageToolInput(tool)
|
||||||
|
if (native !== undefined) {
|
||||||
|
if (Schema.is(OpenAIResponsesImageGenerationTool)(native)) return native
|
||||||
|
return yield* invalid("OpenAI Responses image generation tool options are invalid")
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
type: "function" as const,
|
||||||
|
name: tool.name,
|
||||||
|
description: tool.description,
|
||||||
|
parameters: ToolSchemaProjection.openAI(inputSchema),
|
||||||
|
// TODO: Read this from OpenAI-specific tool options so direct LLM callers can opt into strict schemas.
|
||||||
|
strict: false,
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
const lowerToolChoice = (toolChoice: NonNullable<LLMRequest["toolChoice"]>) =>
|
const lowerToolChoice = (toolChoice: NonNullable<LLMRequest["toolChoice"]>, tools: ReadonlyArray<ToolDefinition>) =>
|
||||||
ProviderShared.matchToolChoice("OpenAI Responses", toolChoice, {
|
ProviderShared.matchToolChoice("OpenAI Responses", toolChoice, {
|
||||||
auto: () => "auto" as const,
|
auto: () => "auto" as const,
|
||||||
none: () => "none" as const,
|
none: () => "none" as const,
|
||||||
required: () => "required" as const,
|
required: () => "required" as const,
|
||||||
tool: (name) => ({ type: "function" as const, name }),
|
tool: (name) =>
|
||||||
|
tools.some((tool) => tool.name === name && nativeImageTool(tool) !== undefined)
|
||||||
|
? ({ type: "image_generation" } as const)
|
||||||
|
: { type: "function" as const, name },
|
||||||
})
|
})
|
||||||
|
|
||||||
const lowerToolCall = (part: ToolCallPart): OpenAIResponsesInputItem => ({
|
const lowerToolCall = (part: ToolCallPart): OpenAIResponsesInputItem => ({
|
||||||
@@ -420,6 +456,13 @@ const lowerMessages = Effect.fn("OpenAIResponses.lowerMessages")(function* (requ
|
|||||||
const itemID = hostedToolItemID(part)
|
const itemID = hostedToolItemID(part)
|
||||||
if (store !== false && itemID && !hostedToolReferences.has(itemID))
|
if (store !== false && itemID && !hostedToolReferences.has(itemID))
|
||||||
input.push({ type: "item_reference", id: itemID })
|
input.push({ type: "item_reference", id: itemID })
|
||||||
|
if (store === false && part.name === "image_generation" && part.result.type === "content") {
|
||||||
|
const content: ReadonlyArray<ToolContent> = part.result.value
|
||||||
|
input.push({
|
||||||
|
role: "user",
|
||||||
|
content: yield* Effect.forEach(content, lowerToolResultContentItem),
|
||||||
|
})
|
||||||
|
}
|
||||||
if (itemID) hostedToolReferences.add(itemID)
|
if (itemID) hostedToolReferences.add(itemID)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -485,10 +528,10 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request:
|
|||||||
tools:
|
tools:
|
||||||
request.tools.length === 0
|
request.tools.length === 0
|
||||||
? undefined
|
? undefined
|
||||||
: request.tools.map((tool) =>
|
: yield* Effect.forEach(request.tools, (tool) =>
|
||||||
lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),
|
lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),
|
||||||
),
|
),
|
||||||
tool_choice: request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,
|
tool_choice: request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools) : undefined,
|
||||||
stream: true as const,
|
stream: true as const,
|
||||||
max_output_tokens: generation?.maxTokens,
|
max_output_tokens: generation?.maxTokens,
|
||||||
temperature: generation?.temperature,
|
temperature: generation?.temperature,
|
||||||
@@ -574,14 +617,29 @@ const isReasoningItem = (
|
|||||||
|
|
||||||
// Round-trip the full item as the structured result so consumers can extract
|
// Round-trip the full item as the structured result so consumers can extract
|
||||||
// outputs / sources / status without re-decoding.
|
// outputs / sources / status without re-decoding.
|
||||||
const hostedToolResult = (item: OpenAIResponsesStreamItem) => {
|
const hostedToolResult = Effect.fn("OpenAIResponses.hostedToolResult")(function* (item: OpenAIResponsesStreamItem) {
|
||||||
const isError = typeof item.error !== "undefined" && item.error !== null
|
const isError = typeof item.error !== "undefined" && item.error !== null
|
||||||
|
if (item.type === "image_generation_call" && item.result) {
|
||||||
|
yield* Effect.fromResult(Encoding.decodeBase64(item.result)).pipe(
|
||||||
|
Effect.mapError(() => ProviderShared.eventError(ADAPTER, "OpenAI Responses returned invalid image base64")),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
type: "content" as const,
|
||||||
|
value: [
|
||||||
|
{
|
||||||
|
type: "file" as const,
|
||||||
|
uri: `data:image/${item.output_format ?? "png"};base64,${item.result}`,
|
||||||
|
mime: `image/${item.output_format ?? "png"}`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
return isError ? { type: "error" as const, value: item.error } : { type: "json" as const, value: item }
|
return isError ? { type: "error" as const, value: item.error } : { type: "json" as const, value: item }
|
||||||
}
|
})
|
||||||
|
|
||||||
const hostedToolEvents = (
|
const hostedToolEvents = Effect.fn("OpenAIResponses.hostedToolEvents")(function* (
|
||||||
item: OpenAIResponsesStreamItem & { type: HostedToolType; id: string },
|
item: OpenAIResponsesStreamItem & { type: HostedToolType; id: string },
|
||||||
): ReadonlyArray<LLMEvent> => {
|
) {
|
||||||
const tool = HOSTED_TOOLS[item.type]
|
const tool = HOSTED_TOOLS[item.type]
|
||||||
const providerMetadata = openaiMetadata({ itemId: item.id })
|
const providerMetadata = openaiMetadata({ itemId: item.id })
|
||||||
return [
|
return [
|
||||||
@@ -595,12 +653,12 @@ const hostedToolEvents = (
|
|||||||
LLMEvent.toolResult({
|
LLMEvent.toolResult({
|
||||||
id: item.id,
|
id: item.id,
|
||||||
name: tool.name,
|
name: tool.name,
|
||||||
result: hostedToolResult(item),
|
result: yield* hostedToolResult(item),
|
||||||
providerExecuted: true,
|
providerExecuted: true,
|
||||||
providerMetadata,
|
providerMetadata,
|
||||||
}),
|
}),
|
||||||
]
|
]
|
||||||
}
|
})
|
||||||
|
|
||||||
type StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]
|
type StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]
|
||||||
|
|
||||||
@@ -835,7 +893,9 @@ const onOutputItemDone = Effect.fn("OpenAIResponses.onOutputItemDone")(function*
|
|||||||
{
|
{
|
||||||
...state,
|
...state,
|
||||||
lifecycle,
|
lifecycle,
|
||||||
hasFunctionCall: resultEvents.some(LLMEvent.is.toolCall) ? true : state.hasFunctionCall,
|
hasFunctionCall:
|
||||||
|
resultEvents.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)) ||
|
||||||
|
state.hasFunctionCall,
|
||||||
tools: result.tools,
|
tools: result.tools,
|
||||||
},
|
},
|
||||||
events,
|
events,
|
||||||
@@ -845,7 +905,7 @@ const onOutputItemDone = Effect.fn("OpenAIResponses.onOutputItemDone")(function*
|
|||||||
if (isHostedToolItem(item)) {
|
if (isHostedToolItem(item)) {
|
||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
||||||
events.push(...hostedToolEvents(item))
|
events.push(...(yield* hostedToolEvents(item)))
|
||||||
return [{ ...state, lifecycle }, events] satisfies StepResult
|
return [{ ...state, lifecycle }, events] satisfies StepResult
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ export const reasoningDelta = (
|
|||||||
providerMetadata?: ProviderMetadata,
|
providerMetadata?: ProviderMetadata,
|
||||||
): State => {
|
): State => {
|
||||||
const started = reasoningStart(state, events, id, providerMetadata)
|
const started = reasoningStart(state, events, id, providerMetadata)
|
||||||
events.push(LLMEvent.reasoningDelta({ id, text }))
|
events.push(LLMEvent.reasoningDelta({ id, text, providerMetadata }))
|
||||||
return started
|
return started
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Schema } from "effect"
|
||||||
|
|
||||||
|
const dimensions = (value: string) => {
|
||||||
|
const match = /^(\d+)x(\d+)$/.exec(value)
|
||||||
|
if (!match) return undefined
|
||||||
|
return { width: Number(match[1]), height: Number(match[2]) }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Size = Schema.String.check(
|
||||||
|
Schema.makeFilter((value) => {
|
||||||
|
if (value === "auto") return undefined
|
||||||
|
const parsed = dimensions(value)
|
||||||
|
if (!parsed) return "image size must be `auto` or `{width}x{height}`"
|
||||||
|
return parsed.width > 0 && parsed.height > 0 ? undefined : "image dimensions must be positive integers"
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const OpenAIImage = {
|
||||||
|
Size,
|
||||||
|
} as const
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
import { LLMError, LLMEvent, type ProviderMetadata, type ToolCall } from "../../schema"
|
import { LLMError, LLMEvent, type ProviderMetadata, type ToolCall, type ToolInputError } from "../../schema"
|
||||||
import { eventError, parseToolInput, type ToolAccumulator } from "../shared"
|
import { eventError, parseToolInput, type ToolAccumulator } from "../shared"
|
||||||
|
|
||||||
type StreamKey = string | number
|
type StreamKey = string | number
|
||||||
@@ -53,6 +53,7 @@ const inputStart = (tool: PendingTool) =>
|
|||||||
LLMEvent.toolInputStart({
|
LLMEvent.toolInputStart({
|
||||||
id: tool.id,
|
id: tool.id,
|
||||||
name: tool.name,
|
name: tool.name,
|
||||||
|
providerExecuted: tool.providerExecuted ? true : undefined,
|
||||||
providerMetadata: tool.providerMetadata,
|
providerMetadata: tool.providerMetadata,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -63,19 +64,36 @@ const inputDelta = (tool: PendingTool, text: string) =>
|
|||||||
text,
|
text,
|
||||||
})
|
})
|
||||||
|
|
||||||
const toolCall = (route: string, tool: PendingTool, inputOverride?: string) =>
|
const toolCall = (route: string, tool: PendingTool, inputOverride?: string) => {
|
||||||
parseToolInput(route, tool.name, inputOverride ?? tool.input).pipe(
|
const raw = inputOverride ?? tool.input
|
||||||
Effect.map(
|
return parseToolInput(route, tool.name, raw).pipe(
|
||||||
(input): ToolCall =>
|
Effect.map((input): ToolCall | ToolInputError =>
|
||||||
LLMEvent.toolCall({
|
LLMEvent.toolCall({
|
||||||
id: tool.id,
|
id: tool.id,
|
||||||
name: tool.name,
|
name: tool.name,
|
||||||
input,
|
input,
|
||||||
providerExecuted: tool.providerExecuted ? true : undefined,
|
providerExecuted: tool.providerExecuted ? true : undefined,
|
||||||
providerMetadata: tool.providerMetadata,
|
providerMetadata: tool.providerMetadata,
|
||||||
}),
|
}),
|
||||||
|
),
|
||||||
|
Effect.catch((error) =>
|
||||||
|
tool.providerExecuted
|
||||||
|
? Effect.fail(error)
|
||||||
|
: Effect.succeed(
|
||||||
|
LLMEvent.toolInputError({
|
||||||
|
id: tool.id,
|
||||||
|
name: tool.name,
|
||||||
|
raw,
|
||||||
|
}),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const finishEvents = (tool: PendingTool, event: ToolCall | ToolInputError): ReadonlyArray<LLMEvent> =>
|
||||||
|
event.type === "tool-input-error"
|
||||||
|
? [event]
|
||||||
|
: [LLMEvent.toolInputEnd({ id: tool.id, name: tool.name, providerMetadata: tool.providerMetadata }), event]
|
||||||
|
|
||||||
/** Store the updated tool and produce the optional public delta event. */
|
/** Store the updated tool and produce the optional public delta event. */
|
||||||
const appendTool = <K extends StreamKey>(
|
const appendTool = <K extends StreamKey>(
|
||||||
@@ -122,8 +140,8 @@ export const appendOrStart = <K extends StreamKey>(
|
|||||||
missingToolMessage: string,
|
missingToolMessage: string,
|
||||||
): AppendOutcome<K> | LLMError => {
|
): AppendOutcome<K> | LLMError => {
|
||||||
const current = tools[key]
|
const current = tools[key]
|
||||||
const id = delta.id ?? current?.id
|
const id = current?.id ?? delta.id
|
||||||
const name = delta.name ?? current?.name
|
const name = current?.name ?? delta.name
|
||||||
if (!id || !name) return eventError(route, missingToolMessage)
|
if (!id || !name) return eventError(route, missingToolMessage)
|
||||||
|
|
||||||
const tool = {
|
const tool = {
|
||||||
@@ -158,8 +176,9 @@ export const appendExisting = <K extends StreamKey>(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Finalize one pending tool call: parse the accumulated raw JSON, remove it
|
* Finalize one pending tool call: parse the accumulated raw JSON, remove it
|
||||||
* from state, and return the optional public `tool-call` event. Missing keys are
|
* from state, and return either a call or a non-executable local input error.
|
||||||
* a no-op because some providers emit stop events for non-tool content blocks.
|
* Missing keys are a no-op because some providers emit stop events for
|
||||||
|
* non-tool content blocks.
|
||||||
*/
|
*/
|
||||||
export const finish = <K extends StreamKey>(route: string, tools: State<K>, key: K) =>
|
export const finish = <K extends StreamKey>(route: string, tools: State<K>, key: K) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -167,10 +186,7 @@ export const finish = <K extends StreamKey>(route: string, tools: State<K>, key:
|
|||||||
if (!tool) return { tools }
|
if (!tool) return { tools }
|
||||||
return {
|
return {
|
||||||
tools: withoutTool(tools, key),
|
tools: withoutTool(tools, key),
|
||||||
events: [
|
events: finishEvents(tool, yield* toolCall(route, tool)),
|
||||||
LLMEvent.toolInputEnd({ id: tool.id, name: tool.name, providerMetadata: tool.providerMetadata }),
|
|
||||||
yield* toolCall(route, tool),
|
|
||||||
],
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -185,17 +201,14 @@ export const finishWithInput = <K extends StreamKey>(route: string, tools: State
|
|||||||
if (!tool) return { tools }
|
if (!tool) return { tools }
|
||||||
return {
|
return {
|
||||||
tools: withoutTool(tools, key),
|
tools: withoutTool(tools, key),
|
||||||
events: [
|
events: finishEvents(tool, yield* toolCall(route, tool, input)),
|
||||||
LLMEvent.toolInputEnd({ id: tool.id, name: tool.name, providerMetadata: tool.providerMetadata }),
|
|
||||||
yield* toolCall(route, tool, input),
|
|
||||||
],
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Finalize every pending tool call at once. OpenAI Chat has this shape: it does
|
* Finalize every pending tool call at once. OpenAI Chat has this shape: it does
|
||||||
* not emit per-tool stop events, so all accumulated calls finish when the choice
|
* not emit per-tool stop events, so all accumulated calls finish independently
|
||||||
* receives a terminal `finish_reason`.
|
* when the choice receives a terminal `finish_reason`.
|
||||||
*/
|
*/
|
||||||
export const finishAll = <K extends StreamKey>(route: string, tools: State<K>) =>
|
export const finishAll = <K extends StreamKey>(route: string, tools: State<K>) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -205,12 +218,7 @@ export const finishAll = <K extends StreamKey>(route: string, tools: State<K>) =
|
|||||||
return {
|
return {
|
||||||
tools: empty<K>(),
|
tools: empty<K>(),
|
||||||
events: yield* Effect.forEach(pending, (tool) =>
|
events: yield* Effect.forEach(pending, (tool) =>
|
||||||
toolCall(route, tool).pipe(
|
toolCall(route, tool).pipe(Effect.map((event) => finishEvents(tool, event))),
|
||||||
Effect.map((call) => [
|
|
||||||
LLMEvent.toolInputEnd({ id: tool.id, name: tool.name, providerMetadata: tool.providerMetadata }),
|
|
||||||
call,
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
).pipe(Effect.map((events) => events.flat())),
|
).pipe(Effect.map((events) => events.flat())),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -16,13 +16,17 @@ import {
|
|||||||
|
|
||||||
const patterns = [
|
const patterns = [
|
||||||
/prompt is too long/i,
|
/prompt is too long/i,
|
||||||
|
/request_too_large/i,
|
||||||
/input is too long for requested model/i,
|
/input is too long for requested model/i,
|
||||||
/exceeds the context window/i,
|
/exceeds the context window/i,
|
||||||
|
/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,
|
||||||
/input token count.*exceeds the maximum/i,
|
/input token count.*exceeds the maximum/i,
|
||||||
/tokens in request more than max tokens allowed/i,
|
/tokens in request more than max tokens allowed/i,
|
||||||
/maximum prompt length is \d+/i,
|
/maximum prompt length is \d+/i,
|
||||||
/reduce the length of the messages/i,
|
/reduce the length of the messages/i,
|
||||||
/maximum context length is \d+ tokens/i,
|
/maximum context length is \d+ tokens/i,
|
||||||
|
/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,
|
||||||
|
/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,
|
||||||
/exceeds the limit of \d+/i,
|
/exceeds the limit of \d+/i,
|
||||||
/exceeds the available context size/i,
|
/exceeds the available context size/i,
|
||||||
/greater than the context length/i,
|
/greater than the context length/i,
|
||||||
@@ -34,11 +38,17 @@ const patterns = [
|
|||||||
/input length.*exceeds.*context length/i,
|
/input length.*exceeds.*context length/i,
|
||||||
/prompt too long; exceeded (?:max )?context length/i,
|
/prompt too long; exceeded (?:max )?context length/i,
|
||||||
/too large for model with \d+ maximum context length/i,
|
/too large for model with \d+ maximum context length/i,
|
||||||
|
/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,
|
||||||
/model_context_window_exceeded/i,
|
/model_context_window_exceeded/i,
|
||||||
|
/too many tokens/i,
|
||||||
|
/token limit exceeded/i,
|
||||||
]
|
]
|
||||||
|
|
||||||
|
const exclusions = [/^(throttling error|service unavailable):/i, /rate limit/i, /too many requests/i]
|
||||||
|
|
||||||
export const isContextOverflow = (message: string) =>
|
export const isContextOverflow = (message: string) =>
|
||||||
patterns.some((pattern) => pattern.test(message)) || /^4(00|13)\s*(status code)?\s*\(no body\)/i.test(message)
|
!exclusions.some((pattern) => pattern.test(message)) &&
|
||||||
|
(patterns.some((pattern) => pattern.test(message)) || /^4(00|13)\s*(status code)?\s*\(no body\)/i.test(message))
|
||||||
|
|
||||||
export const isContextOverflowFailure = (failure: unknown) =>
|
export const isContextOverflowFailure = (failure: unknown) =>
|
||||||
failure instanceof LLMError
|
failure instanceof LLMError
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options"
|
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options"
|
||||||
import type { Route, RouteDefaultsInput } from "../route/client"
|
import type { Route, RouteDefaultsInput } from "../route/client"
|
||||||
import type { ProviderPackage } from "../provider-package"
|
import type { ProviderPackage } from "../provider-package"
|
||||||
import { ProviderID, type ModelID } from "../schema"
|
import { HttpOptions, ProviderID, ToolDefinition, mergeHttpOptions, type ModelID } from "../schema"
|
||||||
import * as OpenAIChat from "../protocols/openai-chat"
|
import * as OpenAIChat from "../protocols/openai-chat"
|
||||||
import * as OpenAIResponses from "../protocols/openai-responses"
|
import * as OpenAIResponses from "../protocols/openai-responses"
|
||||||
import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options"
|
import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options"
|
||||||
|
import { OpenAIImages, type OpenAIImageOptions } from "../protocols/openai-images"
|
||||||
|
|
||||||
export type { OpenAIOptionsInput, OpenAIResponseIncludable } from "./openai-options"
|
export type { OpenAIOptionsInput, OpenAIResponseIncludable } from "./openai-options"
|
||||||
|
export type { OpenAIImageOptions } from "../protocols/openai-images"
|
||||||
|
|
||||||
export const id = ProviderID.make("openai")
|
export const id = ProviderID.make("openai")
|
||||||
|
|
||||||
@@ -20,8 +22,44 @@ export type Config = RouteDefaultsInput &
|
|||||||
readonly baseURL?: string
|
readonly baseURL?: string
|
||||||
readonly queryParams?: Record<string, string>
|
readonly queryParams?: Record<string, string>
|
||||||
readonly providerOptions?: OpenAIProviderOptionsInput
|
readonly providerOptions?: OpenAIProviderOptionsInput
|
||||||
|
readonly image?: ImageConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ImageConfig {
|
||||||
|
readonly providerOptions?: OpenAIImageOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageGenerationOptions {
|
||||||
|
readonly action?: "auto" | "generate" | "edit"
|
||||||
|
readonly background?: "auto" | "opaque" | "transparent"
|
||||||
|
readonly inputFidelity?: "low" | "high"
|
||||||
|
readonly outputCompression?: number
|
||||||
|
readonly outputFormat?: "png" | "jpeg" | "webp"
|
||||||
|
readonly partialImages?: number
|
||||||
|
readonly quality?: "auto" | "low" | "medium" | "high"
|
||||||
|
readonly size?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const imageGeneration = (options: ImageGenerationOptions = {}) =>
|
||||||
|
ToolDefinition.make({
|
||||||
|
name: "image_generation",
|
||||||
|
description: "Generate or edit an image using OpenAI's hosted image generation tool.",
|
||||||
|
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||||
|
native: {
|
||||||
|
openai: {
|
||||||
|
type: "image_generation",
|
||||||
|
action: options.action,
|
||||||
|
background: options.background,
|
||||||
|
input_fidelity: options.inputFidelity,
|
||||||
|
output_compression: options.outputCompression,
|
||||||
|
output_format: options.outputFormat,
|
||||||
|
partial_images: options.partialImages,
|
||||||
|
quality: options.quality,
|
||||||
|
size: options.size,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
export interface Settings extends ProviderPackage.Settings {
|
export interface Settings extends ProviderPackage.Settings {
|
||||||
readonly apiKey?: string
|
readonly apiKey?: string
|
||||||
readonly baseURL?: string
|
readonly baseURL?: string
|
||||||
@@ -35,7 +73,7 @@ export interface Settings extends ProviderPackage.Settings {
|
|||||||
const auth = (options: ProviderAuthOption<"optional">) => AuthOptions.bearer(options, "OPENAI_API_KEY")
|
const auth = (options: ProviderAuthOption<"optional">) => AuthOptions.bearer(options, "OPENAI_API_KEY")
|
||||||
|
|
||||||
const defaults = (input: Config) => {
|
const defaults = (input: Config) => {
|
||||||
const { apiKey: _, auth: _auth, baseURL: _baseURL, queryParams: _queryParams, ...rest } = input
|
const { apiKey: _, auth: _auth, baseURL: _baseURL, queryParams: _queryParams, image: _image, ...rest } = input
|
||||||
return rest
|
return rest
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,6 +93,21 @@ export const configure = (input: Config = {}) => {
|
|||||||
const responsesWebSocket = (id: string | ModelID) =>
|
const responsesWebSocket = (id: string | ModelID) =>
|
||||||
responsesWebSocketRoute.with(withOpenAIOptions(id, modelDefaults, { textVerbosity: true })).model({ id })
|
responsesWebSocketRoute.with(withOpenAIOptions(id, modelDefaults, { textVerbosity: true })).model({ id })
|
||||||
const chat = (id: string | ModelID) => chatRoute.with(withOpenAIOptions(id, modelDefaults)).model({ id })
|
const chat = (id: string | ModelID) => chatRoute.with(withOpenAIOptions(id, modelDefaults)).model({ id })
|
||||||
|
const image = (modelID: string | ModelID) =>
|
||||||
|
OpenAIImages.model({
|
||||||
|
id: modelID,
|
||||||
|
auth: auth(input),
|
||||||
|
baseURL: input.baseURL,
|
||||||
|
headers: input.headers,
|
||||||
|
defaults: {
|
||||||
|
providerOptions:
|
||||||
|
input.image?.providerOptions === undefined ? undefined : { openai: { ...input.image.providerOptions } },
|
||||||
|
http: mergeHttpOptions(
|
||||||
|
input.http === undefined ? undefined : HttpOptions.make(input.http),
|
||||||
|
input.queryParams === undefined ? undefined : new HttpOptions({ query: input.queryParams }),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -62,6 +115,7 @@ export const configure = (input: Config = {}) => {
|
|||||||
responses,
|
responses,
|
||||||
responsesWebSocket,
|
responsesWebSocket,
|
||||||
chat,
|
chat,
|
||||||
|
image,
|
||||||
configure,
|
configure,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -97,3 +151,4 @@ export const chatModel: ProviderPackage.Definition<Settings>["model"] = (modelID
|
|||||||
export const responses = provider.responses
|
export const responses = provider.responses
|
||||||
export const responsesWebSocket = provider.responsesWebSocket
|
export const responsesWebSocket = provider.responsesWebSocket
|
||||||
export const chat = provider.chat
|
export const chat = provider.chat
|
||||||
|
export const image = provider.image
|
||||||
|
|||||||
@@ -41,13 +41,31 @@ export const protocol = Protocol.make({
|
|||||||
schema: OpenRouterBody,
|
schema: OpenRouterBody,
|
||||||
from: (request) =>
|
from: (request) =>
|
||||||
OpenAIChat.protocol.body.from(request).pipe(
|
OpenAIChat.protocol.body.from(request).pipe(
|
||||||
Effect.map(
|
Effect.map((body) => {
|
||||||
(body) =>
|
const sourceAssistants = request.messages.filter((message) => message.role === "assistant")
|
||||||
({
|
let assistantIndex = 0
|
||||||
...body,
|
const messages = body.messages.map((message) => {
|
||||||
...bodyOptions(request.providerOptions?.openrouter),
|
if (message.role !== "assistant") return message
|
||||||
}) as OpenRouterBody,
|
const source = sourceAssistants[assistantIndex++]
|
||||||
),
|
const reasoning = source?.content
|
||||||
|
.filter((part) => part.type === "reasoning")
|
||||||
|
.map((part) => part.text)
|
||||||
|
.join("")
|
||||||
|
const reasoningDetails = Array.isArray(message.reasoning_details) ? message.reasoning_details : undefined
|
||||||
|
return {
|
||||||
|
...message,
|
||||||
|
reasoning_content: undefined,
|
||||||
|
reasoning_text: undefined,
|
||||||
|
reasoning: reasoning && reasoningDetails && reasoningDetails.length > 0 ? reasoning : undefined,
|
||||||
|
reasoning_details: reasoningDetails,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
...body,
|
||||||
|
messages,
|
||||||
|
...bodyOptions(request.providerOptions?.openrouter),
|
||||||
|
} as OpenRouterBody
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
stream: OpenAIChat.protocol.stream,
|
stream: OpenAIChat.protocol.stream,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Config, Effect, Redacted } from "effect"
|
import { Config, Effect, Redacted } from "effect"
|
||||||
import { Headers } from "effect/unstable/http"
|
import { Headers } from "effect/unstable/http"
|
||||||
import { AuthenticationReason, InvalidRequestReason, LLMError, type LLMRequest } from "../schema"
|
import { AuthenticationReason, InvalidRequestReason, LLMError, type HttpOptions } from "../schema"
|
||||||
|
|
||||||
export class MissingCredentialError extends Error {
|
export class MissingCredentialError extends Error {
|
||||||
readonly _tag = "MissingCredentialError"
|
readonly _tag = "MissingCredentialError"
|
||||||
@@ -15,7 +15,7 @@ export type AuthError = CredentialError | LLMError
|
|||||||
type Secret = string | Redacted.Redacted | Config.Config<string | Redacted.Redacted>
|
type Secret = string | Redacted.Redacted | Config.Config<string | Redacted.Redacted>
|
||||||
|
|
||||||
export interface AuthInput {
|
export interface AuthInput {
|
||||||
readonly request: LLMRequest
|
readonly request: { readonly http?: HttpOptions }
|
||||||
readonly method: "POST" | "GET"
|
readonly method: "POST" | "GET"
|
||||||
readonly url: string
|
readonly url: string
|
||||||
readonly body: string
|
readonly body: string
|
||||||
|
|||||||
@@ -129,6 +129,7 @@ export const ToolInputStart = Schema.Struct({
|
|||||||
type: Schema.tag("tool-input-start"),
|
type: Schema.tag("tool-input-start"),
|
||||||
id: ToolCallID,
|
id: ToolCallID,
|
||||||
name: Schema.String,
|
name: Schema.String,
|
||||||
|
providerExecuted: Schema.optional(Schema.Boolean),
|
||||||
providerMetadata: Schema.optional(ProviderMetadata),
|
providerMetadata: Schema.optional(ProviderMetadata),
|
||||||
}).annotate({ identifier: "LLM.Event.ToolInputStart" })
|
}).annotate({ identifier: "LLM.Event.ToolInputStart" })
|
||||||
export type ToolInputStart = Schema.Schema.Type<typeof ToolInputStart>
|
export type ToolInputStart = Schema.Schema.Type<typeof ToolInputStart>
|
||||||
@@ -149,6 +150,15 @@ export const ToolInputEnd = Schema.Struct({
|
|||||||
}).annotate({ identifier: "LLM.Event.ToolInputEnd" })
|
}).annotate({ identifier: "LLM.Event.ToolInputEnd" })
|
||||||
export type ToolInputEnd = Schema.Schema.Type<typeof ToolInputEnd>
|
export type ToolInputEnd = Schema.Schema.Type<typeof ToolInputEnd>
|
||||||
|
|
||||||
|
/** A local tool call whose final input could not be decoded. */
|
||||||
|
export const ToolInputError = Schema.Struct({
|
||||||
|
type: Schema.tag("tool-input-error"),
|
||||||
|
id: ToolCallID,
|
||||||
|
name: Schema.String,
|
||||||
|
raw: Schema.String,
|
||||||
|
}).annotate({ identifier: "LLM.Event.ToolInputError" })
|
||||||
|
export type ToolInputError = Schema.Schema.Type<typeof ToolInputError>
|
||||||
|
|
||||||
export const ToolCall = Schema.Struct({
|
export const ToolCall = Schema.Struct({
|
||||||
type: Schema.tag("tool-call"),
|
type: Schema.tag("tool-call"),
|
||||||
id: ToolCallID,
|
id: ToolCallID,
|
||||||
@@ -216,6 +226,7 @@ const llmEventTagged = Schema.Union([
|
|||||||
ToolInputStart,
|
ToolInputStart,
|
||||||
ToolInputDelta,
|
ToolInputDelta,
|
||||||
ToolInputEnd,
|
ToolInputEnd,
|
||||||
|
ToolInputError,
|
||||||
ToolCall,
|
ToolCall,
|
||||||
ToolResult,
|
ToolResult,
|
||||||
ToolError,
|
ToolError,
|
||||||
@@ -253,6 +264,8 @@ export const LLMEvent = Object.assign(llmEventTagged, {
|
|||||||
toolInputDelta: (input: WithID<ToolInputDelta, ToolCallID>) =>
|
toolInputDelta: (input: WithID<ToolInputDelta, ToolCallID>) =>
|
||||||
ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
|
ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
|
||||||
toolInputEnd: (input: WithID<ToolInputEnd, ToolCallID>) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
|
toolInputEnd: (input: WithID<ToolInputEnd, ToolCallID>) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
|
||||||
|
toolInputError: (input: WithID<ToolInputError, ToolCallID>) =>
|
||||||
|
ToolInputError.make({ ...input, id: toolCallID(input.id) }),
|
||||||
toolCall: (input: WithID<ToolCall, ToolCallID>) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
|
toolCall: (input: WithID<ToolCall, ToolCallID>) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
|
||||||
toolResult: (input: WithID<ToolResult, ToolCallID>) =>
|
toolResult: (input: WithID<ToolResult, ToolCallID>) =>
|
||||||
ToolResult.make({
|
ToolResult.make({
|
||||||
@@ -283,6 +296,7 @@ export const LLMEvent = Object.assign(llmEventTagged, {
|
|||||||
toolInputStart: llmEventTagged.guards["tool-input-start"],
|
toolInputStart: llmEventTagged.guards["tool-input-start"],
|
||||||
toolInputDelta: llmEventTagged.guards["tool-input-delta"],
|
toolInputDelta: llmEventTagged.guards["tool-input-delta"],
|
||||||
toolInputEnd: llmEventTagged.guards["tool-input-end"],
|
toolInputEnd: llmEventTagged.guards["tool-input-end"],
|
||||||
|
toolInputError: llmEventTagged.guards["tool-input-error"],
|
||||||
toolCall: llmEventTagged.guards["tool-call"],
|
toolCall: llmEventTagged.guards["tool-call"],
|
||||||
toolResult: llmEventTagged.guards["tool-result"],
|
toolResult: llmEventTagged.guards["tool-result"],
|
||||||
toolError: llmEventTagged.guards["tool-error"],
|
toolError: llmEventTagged.guards["tool-error"],
|
||||||
@@ -548,6 +562,10 @@ const reduceResponseState = (state: ResponseState, event: LLMEvent): ResponseSta
|
|||||||
return reduceToolInputDelta(next, event)
|
return reduceToolInputDelta(next, event)
|
||||||
case "tool-input-end":
|
case "tool-input-end":
|
||||||
return reduceToolInputEnd(next, event)
|
return reduceToolInputEnd(next, event)
|
||||||
|
case "tool-input-error": {
|
||||||
|
const { [event.id]: _finished, ...toolInputs } = next.toolInputs
|
||||||
|
return { ...next, toolInputs }
|
||||||
|
}
|
||||||
case "tool-call":
|
case "tool-call":
|
||||||
return reduceToolCall(next, event)
|
return reduceToolCall(next, event)
|
||||||
case "tool-result":
|
case "tool-result":
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
+50
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+55
File diff suppressed because one or more lines are too long
@@ -0,0 +1,95 @@
|
|||||||
|
import { describe, expect } from "bun:test"
|
||||||
|
import { Effect, Layer } from "effect"
|
||||||
|
import { HttpClientRequest } from "effect/unstable/http"
|
||||||
|
import { Image, ImageClient } from "../src"
|
||||||
|
import { OpenAI } from "../src/providers"
|
||||||
|
import { it } from "./lib/effect"
|
||||||
|
import { dynamicResponse } from "./lib/http"
|
||||||
|
|
||||||
|
describe("Image", () => {
|
||||||
|
it.effect("generates images through the OpenAI Images API", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const response = yield* Image.generate({
|
||||||
|
model: OpenAI.configure({
|
||||||
|
apiKey: "test",
|
||||||
|
baseURL: "https://api.openai.test/v1",
|
||||||
|
queryParams: { "api-version": "v1" },
|
||||||
|
http: { body: { deployment: "test" }, headers: { "x-default": "yes" } },
|
||||||
|
}).image("gpt-image-2"),
|
||||||
|
prompt: "A robot tending a rooftop garden",
|
||||||
|
count: 2,
|
||||||
|
size: { width: 1024, height: 1024 },
|
||||||
|
providerOptions: {
|
||||||
|
openai: { quality: "high", outputFormat: "webp" },
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
body: { request_metadata: "value" },
|
||||||
|
headers: { "x-request": "yes" },
|
||||||
|
query: { trace: "1" },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(response.images).toHaveLength(2)
|
||||||
|
expect(response.image?.mediaType).toBe("image/webp")
|
||||||
|
expect(response.image?.data).toEqual(Uint8Array.from([1, 2, 3]))
|
||||||
|
expect(response.image?.providerMetadata).toEqual({ openai: { revisedPrompt: "A precise robot" } })
|
||||||
|
expect(response.usage?.totalTokens).toBe(12)
|
||||||
|
}).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
ImageClient.layer.pipe(
|
||||||
|
Layer.provide(
|
||||||
|
dynamicResponse((input) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const request = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
|
||||||
|
expect(request.url).toBe("https://api.openai.test/v1/images/generations?api-version=v1&trace=1")
|
||||||
|
expect(request.headers.get("authorization")).toBe("Bearer test")
|
||||||
|
expect(request.headers.get("x-default")).toBe("yes")
|
||||||
|
expect(request.headers.get("x-request")).toBe("yes")
|
||||||
|
expect(JSON.parse(input.text)).toEqual({
|
||||||
|
model: "gpt-image-2",
|
||||||
|
prompt: "A robot tending a rooftop garden",
|
||||||
|
n: 2,
|
||||||
|
size: "1024x1024",
|
||||||
|
quality: "high",
|
||||||
|
output_format: "webp",
|
||||||
|
deployment: "test",
|
||||||
|
request_metadata: "value",
|
||||||
|
})
|
||||||
|
return input.respond(
|
||||||
|
JSON.stringify({
|
||||||
|
data: [{ b64_json: "AQID", revised_prompt: "A precise robot" }, { b64_json: "BAUG" }],
|
||||||
|
output_format: "webp",
|
||||||
|
usage: { input_tokens: 4, output_tokens: 8, total_tokens: 12 },
|
||||||
|
}),
|
||||||
|
{ headers: { "content-type": "application/json" } },
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("rejects invalid common and OpenAI image options locally", () =>
|
||||||
|
Image.generate({
|
||||||
|
model: OpenAI.configure({ apiKey: "test", baseURL: "https://api.openai.test/v1" }).image("gpt-image-2"),
|
||||||
|
prompt: "A robot tending a rooftop garden",
|
||||||
|
count: -1,
|
||||||
|
size: { width: -1, height: 0.5 },
|
||||||
|
providerOptions: { openai: { outputCompression: 101 } },
|
||||||
|
}).pipe(
|
||||||
|
Effect.flip,
|
||||||
|
Effect.tap((error) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
expect(error.reason._tag).toBe("InvalidRequest")
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Effect.provide(
|
||||||
|
ImageClient.layer.pipe(
|
||||||
|
Layer.provide(dynamicResponse(() => Effect.die("invalid request should not reach the provider"))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
})
|
||||||
@@ -3,8 +3,30 @@ import { isContextOverflow } from "../src"
|
|||||||
import { classifyProviderFailure } from "../src/provider-error"
|
import { classifyProviderFailure } from "../src/provider-error"
|
||||||
|
|
||||||
describe("provider error classification", () => {
|
describe("provider error classification", () => {
|
||||||
test("classifies Z.AI GLM token limit messages as context overflow", () => {
|
test("classifies provider token limit messages as context overflow", () => {
|
||||||
expect(isContextOverflow("tokens in request more than max tokens allowed")).toBe(true)
|
const messages = [
|
||||||
|
"tokens in request more than max tokens allowed",
|
||||||
|
'{"error":{"type":"request_too_large","message":"Request exceeds the maximum size"}}',
|
||||||
|
"Requested token count exceeds the model's maximum context length of 131072 tokens.",
|
||||||
|
"Input length (265330) exceeds model's maximum context length (262144).",
|
||||||
|
"Input length 131393 exceeds the maximum allowed input length of 131040 tokens.",
|
||||||
|
"The input (516368 tokens) is longer than the model's context length (262144 tokens).",
|
||||||
|
"Prompt has 5,958,968 tokens, but the configured context size is 256,000 tokens",
|
||||||
|
"Too many tokens",
|
||||||
|
"Token limit exceeded",
|
||||||
|
]
|
||||||
|
|
||||||
|
expect(messages.every(isContextOverflow)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("does not classify rate limits as context overflow", () => {
|
||||||
|
const messages = [
|
||||||
|
"Throttling error: Too many tokens, please wait before trying again.",
|
||||||
|
"Rate limit exceeded, please retry after 30 seconds.",
|
||||||
|
"Too many requests. Please slow down.",
|
||||||
|
]
|
||||||
|
|
||||||
|
expect(messages.some(isContextOverflow)).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("classifies V1 plain-text rate limit fallbacks", () => {
|
test("classifies V1 plain-text rate limit fallbacks", () => {
|
||||||
|
|||||||
@@ -484,6 +484,30 @@ describe("Anthropic Messages route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("keeps malformed server tool input terminal", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const body = sseEvents(
|
||||||
|
{ type: "message_start", message: { usage: { input_tokens: 5 } } },
|
||||||
|
{
|
||||||
|
type: "content_block_start",
|
||||||
|
index: 0,
|
||||||
|
content_block: { type: "server_tool_use", id: "call_1", name: "web_search" },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "content_block_delta",
|
||||||
|
index: 0,
|
||||||
|
delta: { type: "input_json_delta", partial_json: '{"query":"partial' },
|
||||||
|
},
|
||||||
|
{ type: "content_block_stop", index: 0 },
|
||||||
|
)
|
||||||
|
|
||||||
|
const error = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
|
||||||
|
|
||||||
|
expect(error).toBeInstanceOf(LLMError)
|
||||||
|
expect(error.message).toContain("Invalid JSON input for anthropic-messages tool call web_search")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("fails with a typed provider error for stream error frames", () =>
|
it.effect("fails with a typed provider error for stream error frames", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const error = yield* LLMClient.generate(request).pipe(
|
const error = yield* LLMClient.generate(request).pipe(
|
||||||
|
|||||||
@@ -303,6 +303,32 @@ describe("Bedrock Converse route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("emits malformed tool input as an unexecuted tool error", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const body = eventStreamBody(
|
||||||
|
["messageStart", { role: "assistant" }],
|
||||||
|
[
|
||||||
|
"contentBlockStart",
|
||||||
|
{
|
||||||
|
contentBlockIndex: 0,
|
||||||
|
start: { toolUse: { toolUseId: "tool_1", name: "lookup" } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
["contentBlockDelta", { contentBlockIndex: 0, delta: { toolUse: { input: '{"query":"partial' } } }],
|
||||||
|
["contentBlockStop", { contentBlockIndex: 0 }],
|
||||||
|
["messageStop", { stopReason: "end_turn" }],
|
||||||
|
)
|
||||||
|
const response = yield* LLMClient.generate(baseRequest).pipe(Effect.provide(fixedBytes(body)))
|
||||||
|
|
||||||
|
expect(response.events.find((event) => event.type === "tool-input-error")).toMatchObject({
|
||||||
|
id: "tool_1",
|
||||||
|
name: "lookup",
|
||||||
|
raw: '{"query":"partial',
|
||||||
|
})
|
||||||
|
expect(response.finishReason).toBe("tool-calls")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("decodes reasoning deltas", () =>
|
it.effect("decodes reasoning deltas", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const body = eventStreamBody(
|
const body = eventStreamBody(
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { describe, expect } from "bun:test"
|
import { describe, expect } from "bun:test"
|
||||||
import { ConfigProvider, Effect, Schema } from "effect"
|
import { ConfigProvider, Effect, Schema } from "effect"
|
||||||
import { HttpClientRequest } from "effect/unstable/http"
|
import { HttpClientRequest } from "effect/unstable/http"
|
||||||
import { LLM } from "../../src"
|
import { LLM, LLMEvent } from "../../src"
|
||||||
import { CloudflareAIGateway, CloudflareWorkersAI } from "../../src/providers/cloudflare"
|
import { CloudflareAIGateway, CloudflareWorkersAI } from "../../src/providers/cloudflare"
|
||||||
import { LLMClient } from "../../src/route"
|
import { LLMClient } from "../../src/route"
|
||||||
import { it } from "../lib/effect"
|
import { it } from "../lib/effect"
|
||||||
@@ -83,6 +83,59 @@ describe("Cloudflare", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("preserves reasoning details for AI Gateway continuation", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const model = CloudflareAIGateway.configure({
|
||||||
|
accountId: "test-account",
|
||||||
|
gatewayId: "test-gateway",
|
||||||
|
apiKey: "test-token",
|
||||||
|
}).model("anthropic/claude-sonnet-4.6")
|
||||||
|
const details = [
|
||||||
|
{ type: "reasoning.text", text: "Think", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
{ type: "reasoning.text", text: "ing", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
{ type: "reasoning.text", signature: "signed", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
]
|
||||||
|
const merged = [
|
||||||
|
{
|
||||||
|
type: "reasoning.text",
|
||||||
|
text: "Thinking",
|
||||||
|
signature: "signed",
|
||||||
|
format: "anthropic-claude-v1",
|
||||||
|
index: 0,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const response = yield* LLM.generate(LLM.request({ model, prompt: "Say hello." })).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
dynamicResponse((input) =>
|
||||||
|
Effect.succeed(
|
||||||
|
input.respond(
|
||||||
|
sseEvents(
|
||||||
|
deltaChunk({ reasoning: "Think", reasoning_details: [details[0]] }),
|
||||||
|
deltaChunk({ reasoning: "ing", reasoning_details: [details[1]] }),
|
||||||
|
deltaChunk({ reasoning_details: [details[2]] }),
|
||||||
|
deltaChunk({ content: "Hello" }),
|
||||||
|
deltaChunk({}, "stop"),
|
||||||
|
),
|
||||||
|
{ headers: { "content-type": "text/event-stream" } },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("Thinking")
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningDelta)).toHaveLength(2)
|
||||||
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningField: "reasoning", reasoningDetails: merged },
|
||||||
|
})
|
||||||
|
|
||||||
|
const replay = yield* LLMClient.prepare(LLM.request({ model, messages: [response.message] }))
|
||||||
|
expect(replay.body.messages).toEqual([
|
||||||
|
{ role: "assistant", content: "Hello", reasoning: "Thinking", reasoning_details: merged },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("defaults AI Gateway id to default when omitted or blank", () =>
|
it.effect("defaults AI Gateway id to default when omitted or blank", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { describe, expect } from "bun:test"
|
import { describe, expect } from "bun:test"
|
||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
import { LLM, LLMEvent } from "../../src"
|
import { LLM, LLMEvent, LLMResponse } from "../../src"
|
||||||
|
import { OpenAIChat } from "../../src/protocols/openai-chat"
|
||||||
import * as OpenAICompatible from "../../src/providers/openai-compatible"
|
import * as OpenAICompatible from "../../src/providers/openai-compatible"
|
||||||
import * as OpenRouter from "../../src/providers/openrouter"
|
import * as OpenRouter from "../../src/providers/openrouter"
|
||||||
import { LLMClient } from "../../src/route"
|
import { LLMClient } from "../../src/route"
|
||||||
import { recordedTests } from "../recorded-test"
|
import { recordedTests } from "../recorded-test"
|
||||||
|
import { expectWeatherToolLoop, goldenWeatherToolLoopRequest, runWeatherToolLoop } from "../recorded-scenarios"
|
||||||
|
|
||||||
const cases = [
|
const cases = [
|
||||||
{
|
{
|
||||||
@@ -15,6 +17,7 @@ const cases = [
|
|||||||
}).model("anthropic/claude-sonnet-4.6"),
|
}).model("anthropic/claude-sonnet-4.6"),
|
||||||
requires: ["OPENROUTER_API_KEY"],
|
requires: ["OPENROUTER_API_KEY"],
|
||||||
cassette: "openrouter-reasoning",
|
cassette: "openrouter-reasoning",
|
||||||
|
structured: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Vercel AI Gateway",
|
name: "Vercel AI Gateway",
|
||||||
@@ -26,6 +29,7 @@ const cases = [
|
|||||||
}).model("anthropic/claude-sonnet-4.6"),
|
}).model("anthropic/claude-sonnet-4.6"),
|
||||||
requires: ["AI_GATEWAY_API_KEY"],
|
requires: ["AI_GATEWAY_API_KEY"],
|
||||||
cassette: "vercel-ai-gateway-reasoning",
|
cassette: "vercel-ai-gateway-reasoning",
|
||||||
|
structured: true,
|
||||||
},
|
},
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
@@ -57,11 +61,82 @@ for (const item of cases) {
|
|||||||
expect(response.text.replaceAll(",", "").trim()).toBe("37887")
|
expect(response.text.replaceAll(",", "").trim()).toBe("37887")
|
||||||
expect(response.reasoning.length).toBeGreaterThan(0)
|
expect(response.reasoning.length).toBeGreaterThan(0)
|
||||||
expect(response.events.some(LLMEvent.is.reasoningDelta)).toBe(true)
|
expect(response.events.some(LLMEvent.is.reasoningDelta)).toBe(true)
|
||||||
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
const metadata = response.message.content.find((part) => part.type === "reasoning")?.providerMetadata
|
||||||
openai: { reasoningField: "reasoning" },
|
expect(metadata?.openai?.reasoningField).toBe(item.structured ? "reasoning" : "reasoning_content")
|
||||||
|
expect(Array.isArray(metadata?.openai?.reasoningDetails)).toBe(item.structured)
|
||||||
|
if (!item.structured) return
|
||||||
|
const details = metadata?.openai?.reasoningDetails
|
||||||
|
if (!Array.isArray(details)) return
|
||||||
|
expect(
|
||||||
|
details.some(
|
||||||
|
(detail) =>
|
||||||
|
typeof detail === "object" &&
|
||||||
|
detail !== null &&
|
||||||
|
"signature" in detail &&
|
||||||
|
typeof detail.signature === "string" &&
|
||||||
|
detail.signature.length > 0,
|
||||||
|
),
|
||||||
|
).toBe(true)
|
||||||
|
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({ model: item.model, messages: [response.message] }),
|
||||||
|
)
|
||||||
|
expect(replay.body.messages).toMatchObject([
|
||||||
|
{ role: "assistant", content: response.text, reasoning: response.reasoning },
|
||||||
|
])
|
||||||
|
const replayDetails =
|
||||||
|
replay.body.messages[0]?.role === "assistant" ? replay.body.messages[0].reasoning_details : undefined
|
||||||
|
expect(Array.isArray(replayDetails)).toBe(true)
|
||||||
|
if (!Array.isArray(replayDetails)) return
|
||||||
|
expect(replayDetails).toEqual(details)
|
||||||
|
expect(replayDetails).toHaveLength(1)
|
||||||
|
expect(replayDetails[0]).toMatchObject({
|
||||||
|
type: "reasoning.text",
|
||||||
|
text: response.reasoning,
|
||||||
|
signature: expect.any(String),
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
30_000,
|
30_000,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
recorded.effect.with(
|
||||||
|
"continues signed reasoning through a tool loop",
|
||||||
|
{ cassette: `${item.cassette}-tool-loop`, tags: ["continuation", "tool", "tool-loop"] },
|
||||||
|
() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const events = yield* runWeatherToolLoop(
|
||||||
|
goldenWeatherToolLoopRequest({
|
||||||
|
id: `${item.cassette}-tool-loop`,
|
||||||
|
model: item.model,
|
||||||
|
maxTokens: 1536,
|
||||||
|
temperature: false,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expectWeatherToolLoop(events)
|
||||||
|
expect(
|
||||||
|
LLMResponse.text({
|
||||||
|
events: events.slice(events.findIndex(LLMEvent.is.stepFinish) + 1),
|
||||||
|
}).trim(),
|
||||||
|
).toMatch(/^Paris is sunny\.?$/)
|
||||||
|
const details = events
|
||||||
|
.filter(LLMEvent.is.reasoningEnd)
|
||||||
|
.map((event) => event.providerMetadata?.openai?.reasoningDetails)
|
||||||
|
.find(Array.isArray)
|
||||||
|
expect(Array.isArray(details)).toBe(item.structured)
|
||||||
|
if (!item.structured || !Array.isArray(details)) return
|
||||||
|
expect(
|
||||||
|
details.some(
|
||||||
|
(detail) =>
|
||||||
|
typeof detail === "object" &&
|
||||||
|
detail !== null &&
|
||||||
|
"signature" in detail &&
|
||||||
|
typeof detail.signature === "string" &&
|
||||||
|
detail.signature.length > 0,
|
||||||
|
),
|
||||||
|
).toBe(true)
|
||||||
|
}),
|
||||||
|
60_000,
|
||||||
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -570,6 +570,375 @@ describe("OpenAI Chat route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("preserves and replays reasoning details alongside scalar reasoning", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [
|
||||||
|
{ type: "reasoning.text", text: "thinking", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
{ type: "reasoning.encrypted", data: "opaque", format: "anthropic-claude-v1", index: 1 },
|
||||||
|
]
|
||||||
|
const response = yield* LLMClient.generate(
|
||||||
|
LLM.updateRequest(request, {
|
||||||
|
tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
|
||||||
|
}),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning: "thinking", reasoning_details: [details[0]] } }] },
|
||||||
|
{ choices: [{ delta: { reasoning_details: [details[1]] } }] },
|
||||||
|
{
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
delta: {
|
||||||
|
tool_calls: [
|
||||||
|
{ index: 0, id: "call_1", function: { name: "lookup", arguments: '{"query":"weather"}' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
finish_reason: "tool_calls",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("thinking")
|
||||||
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningField: "reasoning", reasoningDetails: details },
|
||||||
|
})
|
||||||
|
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({ model, messages: [response.message] }),
|
||||||
|
)
|
||||||
|
expect(replay.body.messages).toEqual([
|
||||||
|
{
|
||||||
|
role: "assistant",
|
||||||
|
content: null,
|
||||||
|
reasoning: "thinking",
|
||||||
|
reasoning_details: details,
|
||||||
|
tool_calls: [
|
||||||
|
{
|
||||||
|
id: "call_1",
|
||||||
|
type: "function",
|
||||||
|
function: { name: "lookup", arguments: '{"query":"weather"}' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("uses reasoning details as display fallback without inventing a scalar replay field", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [
|
||||||
|
{ type: "reasoning.summary", summary: "thinking", format: "openai-responses-v1", index: 0 },
|
||||||
|
{ type: "reasoning.encrypted", data: "opaque", format: "openai-responses-v1", index: 1 },
|
||||||
|
]
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning_details: [details[0]] } }] },
|
||||||
|
{ choices: [{ delta: { reasoning_details: [details[1]] } }] },
|
||||||
|
{ choices: [{ delta: { content: "Hello" } }] },
|
||||||
|
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("thinking")
|
||||||
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningDetails: details },
|
||||||
|
})
|
||||||
|
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({ model, messages: [response.message] }),
|
||||||
|
)
|
||||||
|
expect(replay.body.messages).toEqual([{ role: "assistant", content: "Hello", reasoning_details: details }])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("preserves unknown reasoning details while using scalar display text", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [{ type: "reasoning.future", format: "provider-v2", state: { opaque: true } }]
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning: "thinking", reasoning_details: details } }] },
|
||||||
|
{ choices: [{ delta: { content: "Hello" } }] },
|
||||||
|
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("thinking")
|
||||||
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningField: "reasoning", reasoningDetails: details },
|
||||||
|
})
|
||||||
|
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({ model, messages: [response.message] }),
|
||||||
|
)
|
||||||
|
expect(replay.body.messages).toEqual([
|
||||||
|
{ role: "assistant", content: "Hello", reasoning: "thinking", reasoning_details: details },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("uses scalar display text for signature-only reasoning details", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [{ type: "reasoning.text", signature: "signed", format: "provider-v2", index: 0 }]
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning: "thinking", reasoning_details: details } }] },
|
||||||
|
{ choices: [{ delta: { content: "Hello" } }] },
|
||||||
|
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("thinking")
|
||||||
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningField: "reasoning", reasoningDetails: details },
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("ignores scalar reasoning after content starts", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [{ type: "reasoning.text", text: "detail", format: "unknown", index: 0 }]
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning_details: details } }] },
|
||||||
|
{ choices: [{ delta: { content: "Hello" } }] },
|
||||||
|
{ choices: [{ delta: { reasoning: "scalar" } }] },
|
||||||
|
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("detail")
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningStart)).toHaveLength(1)
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(1)
|
||||||
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningDetails: details },
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("preserves an explicitly empty reasoning details array", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning_details: [] } }] },
|
||||||
|
{ choices: [{ delta: { content: "Hello" } }] },
|
||||||
|
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("")
|
||||||
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningDetails: [] },
|
||||||
|
})
|
||||||
|
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({ model, messages: [response.message] }),
|
||||||
|
)
|
||||||
|
expect(replay.body.messages).toEqual([{ role: "assistant", content: "Hello", reasoning_details: [] }])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("attaches signature-only details that arrive after content", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [
|
||||||
|
{ type: "reasoning.text", text: "thinking", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
{ type: "reasoning.text", signature: "signed", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
]
|
||||||
|
const merged = [
|
||||||
|
{
|
||||||
|
type: "reasoning.text",
|
||||||
|
text: "thinking",
|
||||||
|
signature: "signed",
|
||||||
|
format: "anthropic-claude-v1",
|
||||||
|
index: 0,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning: "thinking", reasoning_details: [details[0]] } }] },
|
||||||
|
{ choices: [{ delta: { content: "Hello" } }] },
|
||||||
|
{ choices: [{ delta: { reasoning_details: [details[1]] } }] },
|
||||||
|
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("thinking")
|
||||||
|
expect(response.message.content.filter((part) => part.type === "reasoning")).toHaveLength(1)
|
||||||
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningField: "reasoning", reasoningDetails: merged },
|
||||||
|
})
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningStart)).toHaveLength(1)
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningDelta)).toHaveLength(1)
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(1)
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningEnd).at(-1)?.providerMetadata).toEqual({
|
||||||
|
openai: { reasoningField: "reasoning", reasoningDetails: merged },
|
||||||
|
})
|
||||||
|
expect(response.events.findIndex(LLMEvent.is.reasoningEnd)).toBeLessThan(
|
||||||
|
response.events.findIndex(LLMEvent.is.textStart),
|
||||||
|
)
|
||||||
|
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({ model, messages: [response.message] }),
|
||||||
|
)
|
||||||
|
expect(replay.body.messages).toEqual([
|
||||||
|
{ role: "assistant", content: "Hello", reasoning: "thinking", reasoning_details: merged },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("preserves metadata-only reasoning when the stream ends", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [{ type: "reasoning.encrypted", data: "opaque", format: "openai-responses-v1", index: 0 }]
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning_details: details } }] },
|
||||||
|
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.message.content).toEqual([
|
||||||
|
{ type: "reasoning", text: "", providerMetadata: { openai: { reasoningDetails: details } } },
|
||||||
|
])
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningStart)).toHaveLength(1)
|
||||||
|
expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(1)
|
||||||
|
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({ model, messages: [response.message] }),
|
||||||
|
)
|
||||||
|
expect(replay.body.messages).toEqual([{ role: "assistant", content: null, reasoning_details: details }])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("flushes details-only display reasoning when the stream ends", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [{ type: "reasoning.summary", summary: "summary", format: "openai-responses-v1", index: 0 }]
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ choices: [{ delta: { reasoning_details: details } }] },
|
||||||
|
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.reasoning).toBe("summary")
|
||||||
|
expect(response.message.content).toEqual([
|
||||||
|
{ type: "reasoning", text: "summary", providerMetadata: { openai: { reasoningDetails: details } } },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("replays details from multiple reasoning parts in order", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const first = { type: "reasoning.text", text: "first", signature: "signed-0", index: 0 }
|
||||||
|
const second = { type: "reasoning.text", text: "second", signature: "signed-1", index: 1 }
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({
|
||||||
|
model,
|
||||||
|
messages: [
|
||||||
|
Message.assistant([
|
||||||
|
{
|
||||||
|
type: "reasoning",
|
||||||
|
text: "first",
|
||||||
|
providerMetadata: { openai: { reasoningDetails: [first] } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "reasoning",
|
||||||
|
text: "second",
|
||||||
|
providerMetadata: { openai: { reasoningField: "reasoning", reasoningDetails: [second] } },
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(replay.body.messages).toEqual([
|
||||||
|
{ role: "assistant", content: null, reasoning: "firstsecond", reasoning_details: [first, second] },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("retains scalar replay for mixed structured reasoning parts", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const detail = { type: "reasoning.encrypted", data: "opaque", index: 0 }
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({
|
||||||
|
model,
|
||||||
|
messages: [
|
||||||
|
Message.assistant([
|
||||||
|
{
|
||||||
|
type: "reasoning",
|
||||||
|
text: "A",
|
||||||
|
providerMetadata: { openai: { reasoningDetails: [detail] } },
|
||||||
|
},
|
||||||
|
{ type: "reasoning", text: "B" },
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(replay.body.messages).toEqual([
|
||||||
|
{ role: "assistant", content: null, reasoning_content: "AB", reasoning_details: [detail] },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("replays native scalar reasoning alongside native details", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [{ type: "reasoning.encrypted", data: "opaque", index: 0 }]
|
||||||
|
const replay = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
|
||||||
|
LLM.request({
|
||||||
|
model,
|
||||||
|
messages: [
|
||||||
|
Message.make({
|
||||||
|
role: "assistant",
|
||||||
|
content: [{ type: "reasoning", text: "thinking" }],
|
||||||
|
native: { openaiCompatible: { reasoning_content: "thinking", reasoning_details: details } },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(replay.body.messages).toEqual([
|
||||||
|
{ role: "assistant", content: null, reasoning_content: "thinking", reasoning_details: details },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("assembles streamed tool call input", () =>
|
it.effect("assembles streamed tool call input", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const body = sseEvents(
|
const body = sseEvents(
|
||||||
@@ -606,6 +975,67 @@ describe("OpenAI Chat route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("ignores empty identity fields on later tool call deltas", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const body = sseEvents(
|
||||||
|
deltaChunk({
|
||||||
|
tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: "{" } }],
|
||||||
|
}),
|
||||||
|
deltaChunk({
|
||||||
|
tool_calls: [{ index: 0, id: "", function: { name: "", arguments: '\"query\":\"weather\"}' } }],
|
||||||
|
}),
|
||||||
|
deltaChunk({}, "tool_calls"),
|
||||||
|
)
|
||||||
|
const response = yield* LLMClient.generate(
|
||||||
|
LLM.updateRequest(request, {
|
||||||
|
tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
|
||||||
|
}),
|
||||||
|
).pipe(Effect.provide(fixedResponse(body)))
|
||||||
|
|
||||||
|
expect(response.toolCalls).toMatchObject([{ id: "call_1", name: "lookup", input: { query: "weather" } }])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("buffers tool call deltas until the function name arrives", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const body = sseEvents(
|
||||||
|
deltaChunk({
|
||||||
|
tool_calls: [{ index: 0, id: "call_1", function: { arguments: "{" } }],
|
||||||
|
}),
|
||||||
|
deltaChunk({
|
||||||
|
tool_calls: [{ index: 0, function: { name: "lookup", arguments: '\"query\":' } }],
|
||||||
|
}),
|
||||||
|
deltaChunk({ tool_calls: [{ index: 0, function: { arguments: '\"weather\"}' } }] }),
|
||||||
|
deltaChunk({}, "tool_calls"),
|
||||||
|
)
|
||||||
|
const response = yield* LLMClient.generate(
|
||||||
|
LLM.updateRequest(request, {
|
||||||
|
tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
|
||||||
|
}),
|
||||||
|
).pipe(Effect.provide(fixedResponse(body)))
|
||||||
|
|
||||||
|
expect(response.toolCalls).toMatchObject([{ id: "call_1", name: "lookup", input: { query: "weather" } }])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("fails when a buffered tool call never receives a function name", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const body = sseEvents(
|
||||||
|
deltaChunk({
|
||||||
|
tool_calls: [{ index: 0, id: "call_1", function: { arguments: "{}" } }],
|
||||||
|
}),
|
||||||
|
deltaChunk({}, "tool_calls"),
|
||||||
|
)
|
||||||
|
const error = yield* LLMClient.generate(
|
||||||
|
LLM.updateRequest(request, {
|
||||||
|
tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
|
||||||
|
}),
|
||||||
|
).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
|
||||||
|
|
||||||
|
expect(error.message).toContain("OpenAI Chat tool call delta is missing id or name")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("fails a streamed tool call when the provider ends without a finish reason", () =>
|
it.effect("fails a streamed tool call when the provider ends without a finish reason", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const body = sseEvents(
|
const body = sseEvents(
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, expect } from "bun:test"
|
||||||
|
import { Effect } from "effect"
|
||||||
|
import { Image } from "../../src"
|
||||||
|
import { OpenAI } from "../../src/providers"
|
||||||
|
import { recordedTests } from "../recorded-test"
|
||||||
|
|
||||||
|
const model = OpenAI.configure({
|
||||||
|
apiKey: process.env.OPENAI_API_KEY ?? "fixture",
|
||||||
|
image: {
|
||||||
|
providerOptions: {
|
||||||
|
quality: "low",
|
||||||
|
outputFormat: "jpeg",
|
||||||
|
outputCompression: 10,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}).image("gpt-image-1-mini")
|
||||||
|
|
||||||
|
const recorded = recordedTests({
|
||||||
|
prefix: "openai-images",
|
||||||
|
provider: "openai",
|
||||||
|
protocol: "openai-images",
|
||||||
|
requires: ["OPENAI_API_KEY"],
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("OpenAI Images recorded", () => {
|
||||||
|
recorded.effect("generates an image", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const response = yield* Image.generate({
|
||||||
|
model,
|
||||||
|
prompt: "A simple flat black circle centered on a plain white background.",
|
||||||
|
size: { width: 1024, height: 1024 },
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(response.images).toHaveLength(1)
|
||||||
|
expect(response.image?.mediaType).toBe("image/jpeg")
|
||||||
|
expect(response.image?.data).toBeInstanceOf(Uint8Array)
|
||||||
|
expect(response.image?.data.length).toBeGreaterThan(0)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { describe, expect } from "bun:test"
|
||||||
|
import { Effect } from "effect"
|
||||||
|
import { LLM, LLMEvent, Message } from "../../src"
|
||||||
|
import { OpenAI } from "../../src/providers"
|
||||||
|
import { recordedTests } from "../recorded-test"
|
||||||
|
|
||||||
|
const openai = OpenAI.configure({
|
||||||
|
apiKey: process.env.OPENAI_API_KEY ?? "fixture",
|
||||||
|
})
|
||||||
|
|
||||||
|
const recorded = recordedTests({
|
||||||
|
prefix: "openai-responses-images",
|
||||||
|
provider: "openai",
|
||||||
|
protocol: "openai-responses",
|
||||||
|
requires: ["OPENAI_API_KEY"],
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("OpenAI Responses image generation recorded", () => {
|
||||||
|
recorded.effect("generates and edits an image with the hosted tool", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const initial = Message.user("Generate a simple flat black triangle centered on a plain white background.")
|
||||||
|
const tools = [
|
||||||
|
OpenAI.imageGeneration({
|
||||||
|
action: "auto",
|
||||||
|
quality: "low",
|
||||||
|
size: "1024x1024",
|
||||||
|
outputFormat: "jpeg",
|
||||||
|
outputCompression: 10,
|
||||||
|
partialImages: 0,
|
||||||
|
}),
|
||||||
|
]
|
||||||
|
const response = yield* LLM.generate(
|
||||||
|
LLM.request({
|
||||||
|
model: openai.responses("gpt-5-mini"),
|
||||||
|
messages: [initial],
|
||||||
|
tools,
|
||||||
|
toolChoice: "image_generation",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const result = response.events.find(LLMEvent.is.toolResult)
|
||||||
|
expect(result).toBeDefined()
|
||||||
|
expect(result?.providerExecuted).toBe(true)
|
||||||
|
expect(result?.result.type).toBe("content")
|
||||||
|
if (result?.result.type !== "content") return
|
||||||
|
expect(result.result.value).toHaveLength(1)
|
||||||
|
expect(result.result.value[0]?.type).toBe("file")
|
||||||
|
if (result.result.value[0]?.type !== "file") return
|
||||||
|
expect(result.result.value[0].mime).toBe("image/jpeg")
|
||||||
|
expect(result.result.value[0].uri.startsWith("data:image/jpeg;base64,")).toBe(true)
|
||||||
|
|
||||||
|
const edited = yield* LLM.generate(
|
||||||
|
LLM.request({
|
||||||
|
model: openai.responses("gpt-5-mini"),
|
||||||
|
messages: [initial, response.message, Message.user("Now make the triangle blue.")],
|
||||||
|
tools,
|
||||||
|
toolChoice: "image_generation",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const editedResult = edited.events.find(LLMEvent.is.toolResult)
|
||||||
|
expect(editedResult?.result.type).toBe("content")
|
||||||
|
if (editedResult?.result.type !== "content") return
|
||||||
|
expect(editedResult.result.value[0]?.type).toBe("file")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { describe, expect } from "bun:test"
|
import { describe, expect } from "bun:test"
|
||||||
import { ConfigProvider, Effect, Layer, Stream } from "effect"
|
import { ConfigProvider, Effect, Layer, Stream } from "effect"
|
||||||
import { Headers, HttpClientRequest } from "effect/unstable/http"
|
import { Headers, HttpClientRequest } from "effect/unstable/http"
|
||||||
import { LLM, LLMError, Message, Model, ToolCallPart, Usage } from "../../src"
|
import { LLM, LLMError, LLMEvent, Message, Model, ToolCallPart, ToolResultPart, Usage } from "../../src"
|
||||||
import { Auth, LLMClient, RequestExecutor, WebSocketExecutor } from "../../src/route"
|
import { Auth, LLMClient, RequestExecutor, WebSocketExecutor } from "../../src/route"
|
||||||
import * as Azure from "../../src/providers/azure"
|
import * as Azure from "../../src/providers/azure"
|
||||||
import * as OpenAI from "../../src/providers/openai"
|
import * as OpenAI from "../../src/providers/openai"
|
||||||
@@ -58,6 +58,39 @@ describe("OpenAI Responses route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("lowers the hosted OpenAI image generation tool", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
|
||||||
|
LLM.request({
|
||||||
|
model,
|
||||||
|
prompt: "Show me a rooftop garden.",
|
||||||
|
tools: [OpenAI.imageGeneration({ action: "generate", quality: "high", size: "1024x1024" })],
|
||||||
|
toolChoice: "image_generation",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(prepared.body.tools).toEqual([
|
||||||
|
{ type: "image_generation", action: "generate", quality: "high", size: "1024x1024" },
|
||||||
|
])
|
||||||
|
expect(prepared.body.tool_choice).toEqual({ type: "image_generation" })
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("rejects invalid hosted image generation options locally", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const error = yield* LLMClient.prepare(
|
||||||
|
LLM.request({
|
||||||
|
model,
|
||||||
|
prompt: "Show me a rooftop garden.",
|
||||||
|
tools: [OpenAI.imageGeneration({ outputCompression: -1, partialImages: 4, size: "bogus" })],
|
||||||
|
}),
|
||||||
|
).pipe(Effect.flip)
|
||||||
|
|
||||||
|
expect(error.reason._tag).toBe("InvalidRequest")
|
||||||
|
expect(error.message).toContain("image generation tool options are invalid")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("lowers semantic service tier options", () =>
|
it.effect("lowers semantic service tier options", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const input = LLM.updateRequest(request, { providerOptions: { openai: { serviceTier: "priority" } } })
|
const input = LLM.updateRequest(request, { providerOptions: { openai: { serviceTier: "priority" } } })
|
||||||
@@ -1103,6 +1136,48 @@ describe("OpenAI Responses route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("continues stateless hosted image generation with the generated image", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const imageTool = OpenAI.imageGeneration({ action: "edit" })
|
||||||
|
const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
|
||||||
|
LLM.request({
|
||||||
|
model,
|
||||||
|
messages: [
|
||||||
|
Message.user("Generate a black triangle."),
|
||||||
|
Message.assistant([
|
||||||
|
ToolCallPart.make({
|
||||||
|
id: "ig_1",
|
||||||
|
name: "image_generation",
|
||||||
|
input: {},
|
||||||
|
providerExecuted: true,
|
||||||
|
providerMetadata: { openai: { itemId: "ig_1" } },
|
||||||
|
}),
|
||||||
|
ToolResultPart.make({
|
||||||
|
id: "ig_1",
|
||||||
|
name: "image_generation",
|
||||||
|
result: {
|
||||||
|
type: "content",
|
||||||
|
value: [{ type: "file", uri: "data:image/png;base64,AQID", mime: "image/png" }],
|
||||||
|
},
|
||||||
|
providerExecuted: true,
|
||||||
|
providerMetadata: { openai: { itemId: "ig_1" } },
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
Message.user("Make it blue."),
|
||||||
|
],
|
||||||
|
tools: [imageTool],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(prepared.body.store).toBe(false)
|
||||||
|
expect(prepared.body.input).toEqual([
|
||||||
|
{ role: "user", content: [{ type: "input_text", text: "Generate a black triangle." }] },
|
||||||
|
{ role: "user", content: [{ type: "input_image", image_url: "data:image/png;base64,AQID" }] },
|
||||||
|
{ role: "user", content: [{ type: "input_text", text: "Make it blue." }] },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("joins streamed summary blocks into one continuation reasoning item", () =>
|
it.effect("joins streamed summary blocks into one continuation reasoning item", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
|
const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
|
||||||
@@ -1259,6 +1334,69 @@ describe("OpenAI Responses route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("emits malformed final function arguments as an unexecuted tool error", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const body = sseEvents(
|
||||||
|
{
|
||||||
|
type: "response.output_item.added",
|
||||||
|
item: { type: "function_call", id: "item_1", call_id: "call_1", name: "lookup", arguments: "" },
|
||||||
|
},
|
||||||
|
{ type: "response.function_call_arguments.delta", item_id: "item_1", delta: '{"query":"streamed"}' },
|
||||||
|
{
|
||||||
|
type: "response.output_item.done",
|
||||||
|
item: {
|
||||||
|
type: "function_call",
|
||||||
|
id: "item_1",
|
||||||
|
call_id: "call_1",
|
||||||
|
name: "lookup",
|
||||||
|
arguments: '{"query":"partial',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: "response.completed", response: { usage: { input_tokens: 5, output_tokens: 1 } } },
|
||||||
|
)
|
||||||
|
const response = yield* LLMClient.generate(
|
||||||
|
LLM.updateRequest(request, {
|
||||||
|
tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
|
||||||
|
}),
|
||||||
|
).pipe(Effect.provide(fixedResponse(body)))
|
||||||
|
|
||||||
|
expect(response.events.find(LLMEvent.is.toolInputError)).toEqual({
|
||||||
|
type: "tool-input-error",
|
||||||
|
id: "call_1",
|
||||||
|
name: "lookup",
|
||||||
|
raw: '{"query":"partial',
|
||||||
|
})
|
||||||
|
expect(response.finishReason).toBe("tool-calls")
|
||||||
|
expect(response.events.some(LLMEvent.is.toolCall)).toBeFalse()
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("settles malformed function arguments when output_item.added is absent", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const body = sseEvents(
|
||||||
|
{
|
||||||
|
type: "response.output_item.done",
|
||||||
|
item: {
|
||||||
|
type: "function_call",
|
||||||
|
id: "item_1",
|
||||||
|
call_id: "call_1",
|
||||||
|
name: "lookup",
|
||||||
|
arguments: '{"query":"partial',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: "response.completed", response: { usage: { input_tokens: 5, output_tokens: 1 } } },
|
||||||
|
)
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
|
||||||
|
|
||||||
|
expect(response.events.find(LLMEvent.is.toolInputError)).toMatchObject({
|
||||||
|
id: "call_1",
|
||||||
|
name: "lookup",
|
||||||
|
raw: '{"query":"partial',
|
||||||
|
})
|
||||||
|
expect(response.finishReason).toBe("tool-calls")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("decodes web_search_call as provider-executed tool-call + tool-result", () =>
|
it.effect("decodes web_search_call as provider-executed tool-call + tool-result", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const item = {
|
const item = {
|
||||||
@@ -1298,6 +1436,59 @@ describe("OpenAI Responses route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("decodes image generation output as image content", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const item = {
|
||||||
|
type: "image_generation_call",
|
||||||
|
id: "ig_1",
|
||||||
|
status: "completed",
|
||||||
|
result: "AQID",
|
||||||
|
}
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{ type: "response.output_item.done", item },
|
||||||
|
{ type: "response.completed", response: { usage: { input_tokens: 5, output_tokens: 1 } } },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.events.find(LLMEvent.is.toolResult)).toMatchObject({
|
||||||
|
id: "ig_1",
|
||||||
|
name: "image_generation",
|
||||||
|
providerExecuted: true,
|
||||||
|
result: {
|
||||||
|
type: "content",
|
||||||
|
value: [{ type: "file", uri: "data:image/png;base64,AQID", mime: "image/png" }],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("rejects malformed image generation base64", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const error = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
{
|
||||||
|
type: "response.output_item.done",
|
||||||
|
item: { type: "image_generation_call", id: "ig_bad", status: "completed", result: "%%%" },
|
||||||
|
},
|
||||||
|
{ type: "response.completed", response: {} },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.flip,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(error.reason._tag).toBe("InvalidProviderOutput")
|
||||||
|
expect(error.message).toContain("invalid image base64")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("decodes code_interpreter_call as provider-executed events with code input", () =>
|
it.effect("decodes code_interpreter_call as provider-executed events with code input", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const item = {
|
const item = {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect } from "bun:test"
|
import { describe, expect } from "bun:test"
|
||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
import { LLM } from "../../src"
|
import { LLM, Message } from "../../src"
|
||||||
import { LLMClient } from "../../src/route"
|
import { LLMClient } from "../../src/route"
|
||||||
import * as OpenRouter from "../../src/providers/openrouter"
|
import * as OpenRouter from "../../src/providers/openrouter"
|
||||||
import { it } from "../lib/effect"
|
import { it } from "../lib/effect"
|
||||||
@@ -53,4 +53,102 @@ describe("OpenRouter", () => {
|
|||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("preserves manually supplied reasoning details", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [
|
||||||
|
{ type: "reasoning.text", text: "Think", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
{ type: "reasoning.text", text: "ing", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
{ type: "reasoning.text", signature: "signed", format: "anthropic-claude-v1", index: 0 },
|
||||||
|
{ type: "reasoning.encrypted", data: "opaque", format: "openai-responses-v1", index: 1 },
|
||||||
|
]
|
||||||
|
const prepared = yield* LLMClient.prepare<OpenRouter.OpenRouterBody>(
|
||||||
|
LLM.request({
|
||||||
|
model: OpenRouter.configure({ apiKey: "test-key" }).model("anthropic/claude-sonnet-4.6"),
|
||||||
|
messages: [
|
||||||
|
Message.assistant([
|
||||||
|
{
|
||||||
|
type: "reasoning",
|
||||||
|
text: "Thinking",
|
||||||
|
providerMetadata: { openai: { reasoningField: "reasoning", reasoningDetails: details } },
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(prepared.body.messages).toEqual([
|
||||||
|
{
|
||||||
|
role: "assistant",
|
||||||
|
content: null,
|
||||||
|
reasoning: "Thinking",
|
||||||
|
reasoning_details: details,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("preserves opaque and duplicate continuation details", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [
|
||||||
|
{ type: "reasoning.future", format: "provider-v2", state: { opaque: true } },
|
||||||
|
{ type: "reasoning.encrypted", id: "state", data: "opaque" },
|
||||||
|
{ type: "reasoning.encrypted", id: "state", data: "opaque" },
|
||||||
|
]
|
||||||
|
const prepared = yield* LLMClient.prepare<OpenRouter.OpenRouterBody>(
|
||||||
|
LLM.request({
|
||||||
|
model: OpenRouter.configure({ apiKey: "test-key" }).model("anthropic/claude-sonnet-4.6"),
|
||||||
|
messages: [
|
||||||
|
Message.assistant({
|
||||||
|
type: "reasoning",
|
||||||
|
text: "Thinking",
|
||||||
|
providerMetadata: { openai: { reasoningField: "reasoning", reasoningDetails: details } },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(prepared.body.messages).toEqual([
|
||||||
|
{ role: "assistant", content: null, reasoning: "Thinking", reasoning_details: details },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("does not merge distinct adjacent reasoning text blocks", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const details = [
|
||||||
|
{ type: "reasoning.text", id: "first", index: 0, text: "A", opaque: "first" },
|
||||||
|
{ type: "reasoning.text", id: "second", index: 1, text: "B", opaque: "second" },
|
||||||
|
]
|
||||||
|
const prepared = yield* LLMClient.prepare<OpenRouter.OpenRouterBody>(
|
||||||
|
LLM.request({
|
||||||
|
model: OpenRouter.configure({ apiKey: "test-key" }).model("anthropic/claude-sonnet-4.6"),
|
||||||
|
messages: [
|
||||||
|
Message.assistant({
|
||||||
|
type: "reasoning",
|
||||||
|
text: "AB",
|
||||||
|
providerMetadata: { openai: { reasoningField: "reasoning", reasoningDetails: details } },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(prepared.body.messages).toEqual([
|
||||||
|
{ role: "assistant", content: null, reasoning: "AB", reasoning_details: details },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("omits scalar reasoning without continuation details", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const prepared = yield* LLMClient.prepare<OpenRouter.OpenRouterBody>(
|
||||||
|
LLM.request({
|
||||||
|
model: OpenRouter.configure({ apiKey: "test-key" }).model("anthropic/claude-sonnet-4.6"),
|
||||||
|
messages: [Message.assistant({ type: "reasoning", text: "Thinking" })],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(prepared.body.messages).toEqual([{ role: "assistant", content: null }])
|
||||||
|
}),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -120,29 +120,8 @@ export const runWeatherToolLoop = (request: LLMRequest) =>
|
|||||||
throw new Error("Weather tool loop exceeded 10 steps")
|
throw new Error("Weather tool loop exceeded 10 steps")
|
||||||
})
|
})
|
||||||
|
|
||||||
const assistantContent = (events: ReadonlyArray<LLMEvent>) => {
|
const assistantContent = (events: ReadonlyArray<LLMEvent>) =>
|
||||||
const content: ContentPart[] = []
|
events.reduce(LLMResponse.reduce, LLMResponse.empty()).message.content
|
||||||
for (const event of events) {
|
|
||||||
if (event.type === "text-delta" || event.type === "reasoning-delta") {
|
|
||||||
const type = event.type === "text-delta" ? "text" : "reasoning"
|
|
||||||
const last = content.at(-1)
|
|
||||||
if (last?.type === type) {
|
|
||||||
content[content.length - 1] = { ...last, text: `${last.text}${event.text}` }
|
|
||||||
} else {
|
|
||||||
content.push({ type, text: event.text })
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (event.type === "text-end" || event.type === "reasoning-end") {
|
|
||||||
const type = event.type === "text-end" ? "text" : "reasoning"
|
|
||||||
const last = content.at(-1)
|
|
||||||
if (last?.type === type) content[content.length - 1] = { ...last, providerMetadata: event.providerMetadata }
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (event.type === "tool-call") content.push(event)
|
|
||||||
}
|
|
||||||
return content
|
|
||||||
}
|
|
||||||
|
|
||||||
export const expectFinish = (
|
export const expectFinish = (
|
||||||
events: ReadonlyArray<LLMEvent>,
|
events: ReadonlyArray<LLMEvent>,
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { Layer } from "effect"
|
|||||||
import * as path from "node:path"
|
import * as path from "node:path"
|
||||||
import { fileURLToPath } from "node:url"
|
import { fileURLToPath } from "node:url"
|
||||||
import { LLMClient, RequestExecutor, WebSocketExecutor } from "../src/route"
|
import { LLMClient, RequestExecutor, WebSocketExecutor } from "../src/route"
|
||||||
|
import { ImageClient } from "../src/image-client"
|
||||||
|
import type { Service as ImageClientService } from "../src/image-client"
|
||||||
import type { Service as LLMClientService } from "../src/route/client"
|
import type { Service as LLMClientService } from "../src/route/client"
|
||||||
import type { Service as RequestExecutorService } from "../src/route/executor"
|
import type { Service as RequestExecutorService } from "../src/route/executor"
|
||||||
import type { Service as WebSocketExecutorService } from "../src/route/transport/websocket"
|
import type { Service as WebSocketExecutorService } from "../src/route/transport/websocket"
|
||||||
@@ -15,7 +17,7 @@ import {
|
|||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||||
const FIXTURES_DIR = path.resolve(__dirname, "fixtures", "recordings")
|
const FIXTURES_DIR = path.resolve(__dirname, "fixtures", "recordings")
|
||||||
|
|
||||||
type RecordedEnv = RequestExecutorService | WebSocketExecutorService | LLMClientService
|
type RecordedEnv = RequestExecutorService | WebSocketExecutorService | LLMClientService | ImageClientService
|
||||||
|
|
||||||
type RecordedTestsOptions = RecordedGroupOptions & {
|
type RecordedTestsOptions = RecordedGroupOptions & {
|
||||||
readonly options?: HttpRecorder.RecorderOptions
|
readonly options?: HttpRecorder.RecorderOptions
|
||||||
@@ -81,6 +83,10 @@ export const recordedTests = (options: RecordedTestsOptions) =>
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
const deps = Layer.mergeAll(requestExecutor, WebSocketExecutor.layer)
|
const deps = Layer.mergeAll(requestExecutor, WebSocketExecutor.layer)
|
||||||
return Layer.mergeAll(deps, LLMClient.layer.pipe(Layer.provide(deps)))
|
return Layer.mergeAll(
|
||||||
|
deps,
|
||||||
|
LLMClient.layer.pipe(Layer.provide(deps)),
|
||||||
|
ImageClient.layer.pipe(Layer.provide(deps)),
|
||||||
|
)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -95,4 +95,19 @@ describe("LLMResponse reducer", () => {
|
|||||||
{ type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" } },
|
{ type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" } },
|
||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("clears malformed tool input without appending an executable call", () => {
|
||||||
|
const state = reduce([
|
||||||
|
LLMEvent.toolInputStart({ id: "call_1", name: "lookup" }),
|
||||||
|
LLMEvent.toolInputDelta({ id: "call_1", name: "lookup", text: '{"query":"partial' }),
|
||||||
|
LLMEvent.toolInputError({
|
||||||
|
id: "call_1",
|
||||||
|
name: "lookup",
|
||||||
|
raw: '{"query":"partial',
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
expect(state.toolInputs).toEqual({})
|
||||||
|
expect(state.message.content).toEqual([])
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -36,6 +36,33 @@ describe("ToolStream", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("keeps accumulated identity when later deltas contain empty strings", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const first = ToolStream.appendOrStart(
|
||||||
|
ADAPTER,
|
||||||
|
ToolStream.empty<number>(),
|
||||||
|
0,
|
||||||
|
{ id: "call_1", name: "lookup", text: '{"query"' },
|
||||||
|
"missing tool",
|
||||||
|
)
|
||||||
|
if (ToolStream.isError(first)) return yield* first
|
||||||
|
const second = ToolStream.appendOrStart(
|
||||||
|
ADAPTER,
|
||||||
|
first.tools,
|
||||||
|
0,
|
||||||
|
{ id: "", name: "", text: ':"weather"}' },
|
||||||
|
"missing tool",
|
||||||
|
)
|
||||||
|
if (ToolStream.isError(second)) return yield* second
|
||||||
|
const finished = yield* ToolStream.finish(ADAPTER, second.tools, 0)
|
||||||
|
|
||||||
|
expect(finished.events).toEqual([
|
||||||
|
{ type: "tool-input-end", id: "call_1", name: "lookup" },
|
||||||
|
{ type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" } },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("fails appendExisting when the provider skipped the tool start", () =>
|
it.effect("fails appendExisting when the provider skipped the tool start", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const error = ToolStream.appendExisting(ADAPTER, ToolStream.empty<number>(), 0, "{}", "missing tool")
|
const error = ToolStream.appendExisting(ADAPTER, ToolStream.empty<number>(), 0, "{}", "missing tool")
|
||||||
@@ -64,6 +91,73 @@ describe("ToolStream", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("finalizes malformed local input as a non-executable tool error", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tools = ToolStream.start(ToolStream.empty<string>(), "item_1", {
|
||||||
|
id: "call_1",
|
||||||
|
name: "lookup",
|
||||||
|
input: '{"query":"partial',
|
||||||
|
})
|
||||||
|
const finished = yield* ToolStream.finish(ADAPTER, tools, "item_1")
|
||||||
|
|
||||||
|
expect(finished).toEqual({
|
||||||
|
tools: {},
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: "tool-input-error",
|
||||||
|
id: "call_1",
|
||||||
|
name: "lookup",
|
||||||
|
raw: '{"query":"partial',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("preserves valid siblings when one parallel input is malformed", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const valid = ToolStream.start(ToolStream.empty<number>(), 0, {
|
||||||
|
id: "call_valid",
|
||||||
|
name: "lookup",
|
||||||
|
input: '{"query":"weather"}',
|
||||||
|
})
|
||||||
|
const tools = ToolStream.start(valid, 1, {
|
||||||
|
id: "call_invalid",
|
||||||
|
name: "lookup",
|
||||||
|
input: '{"query":"partial',
|
||||||
|
})
|
||||||
|
const finished = yield* ToolStream.finishAll(ADAPTER, tools)
|
||||||
|
|
||||||
|
expect(finished).toEqual({
|
||||||
|
tools: {},
|
||||||
|
events: [
|
||||||
|
{ type: "tool-input-end", id: "call_valid", name: "lookup" },
|
||||||
|
{ type: "tool-call", id: "call_valid", name: "lookup", input: { query: "weather" } },
|
||||||
|
{
|
||||||
|
type: "tool-input-error",
|
||||||
|
id: "call_invalid",
|
||||||
|
name: "lookup",
|
||||||
|
raw: '{"query":"partial',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("keeps malformed provider-executed input terminal", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tools = ToolStream.start(ToolStream.empty<string>(), "item_1", {
|
||||||
|
id: "call_1",
|
||||||
|
name: "web_search",
|
||||||
|
input: '{"query":"partial',
|
||||||
|
providerExecuted: true,
|
||||||
|
})
|
||||||
|
const result = yield* Effect.exit(ToolStream.finish(ADAPTER, tools, "item_1"))
|
||||||
|
|
||||||
|
expect(result._tag).toBe("Failure")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("preserves providerExecuted and clears all tools", () =>
|
it.effect("preserves providerExecuted and clears all tools", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const first: ToolStream.State<number> = ToolStream.start(ToolStream.empty<number>(), 0, {
|
const first: ToolStream.State<number> = ToolStream.start(ToolStream.empty<number>(), 0, {
|
||||||
|
|||||||
@@ -1615,6 +1615,7 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
|
|||||||
<div class="flex flex-col gap-3">
|
<div class="flex flex-col gap-3">
|
||||||
<DockShellForm
|
<DockShellForm
|
||||||
data-component={newSession() ? "session-new-composer" : "session-composer"}
|
data-component={newSession() ? "session-new-composer" : "session-composer"}
|
||||||
|
data-background-surface="prompt"
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
classList={{
|
classList={{
|
||||||
"group/prompt-input min-h-[96px] w-full rounded-xl bg-v2-background-bg-base shadow-[var(--v2-elevation-raised)]": true,
|
"group/prompt-input min-h-[96px] w-full rounded-xl bg-v2-background-bg-base shadow-[var(--v2-elevation-raised)]": true,
|
||||||
|
|||||||
@@ -446,6 +446,7 @@ export function PromptProjectAddButton(props: { controller: PromptProjectControl
|
|||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
data-action="prompt-project"
|
data-action="prompt-project"
|
||||||
|
data-background-surface="project-selector"
|
||||||
type="button"
|
type="button"
|
||||||
class="flex h-7 min-w-0 max-w-[160px] items-center gap-1.5 rounded-sm px-2 text-[13px] font-[440] leading-5 tracking-[-0.04px] text-v2-text-text-faint transition-colors hover:bg-v2-overlay-simple-overlay-hover focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:outline-none"
|
class="flex h-7 min-w-0 max-w-[160px] items-center gap-1.5 rounded-sm px-2 text-[13px] font-[440] leading-5 tracking-[-0.04px] text-v2-text-text-faint transition-colors hover:bg-v2-overlay-simple-overlay-hover focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:outline-none"
|
||||||
onClick={() => props.controller.add()}
|
onClick={() => props.controller.add()}
|
||||||
@@ -464,6 +465,7 @@ function ProjectTrigger(props: ComponentProps<"button"> & { controller: PromptPr
|
|||||||
<button
|
<button
|
||||||
{...rest}
|
{...rest}
|
||||||
data-action="prompt-project"
|
data-action="prompt-project"
|
||||||
|
data-background-surface="project-selector"
|
||||||
type="button"
|
type="button"
|
||||||
class="flex h-7 min-w-0 max-w-[203px] items-center gap-1.5 rounded-sm px-1.5 transition-colors focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:outline-none"
|
class="flex h-7 min-w-0 max-w-[203px] items-center gap-1.5 rounded-sm px-1.5 transition-colors focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:outline-none"
|
||||||
classList={{
|
classList={{
|
||||||
|
|||||||
@@ -4,10 +4,14 @@ import { NEW_SESSION_CONTENT_WIDTH } from "@/pages/session/new-session-layout"
|
|||||||
|
|
||||||
export function NewSessionDesignView(props: { children: JSX.Element }) {
|
export function NewSessionDesignView(props: { children: JSX.Element }) {
|
||||||
return (
|
return (
|
||||||
<div data-component="session-new-design" class="relative size-full overflow-hidden bg-v2-background-bg-deep ">
|
<div
|
||||||
|
data-component="session-new-design"
|
||||||
|
data-background-surface="shell"
|
||||||
|
class="relative size-full overflow-hidden bg-v2-background-bg-deep "
|
||||||
|
>
|
||||||
<div class="absolute inset-x-0 top-[25.375%] flex justify-center px-6">
|
<div class="absolute inset-x-0 top-[25.375%] flex justify-center px-6">
|
||||||
<div class={NEW_SESSION_CONTENT_WIDTH}>
|
<div class={NEW_SESSION_CONTENT_WIDTH}>
|
||||||
<WordmarkV2 class="h-auto w-full text-v2-background-bg-inverse" />
|
<WordmarkV2 class="h-auto w-full text-v2-background-bg-inverse [&>g>g>g]:!opacity-[0.45]" />
|
||||||
<div class="mt-8">{props.children}</div>
|
<div class="mt-8">{props.children}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { createStore } from "solid-js/store"
|
||||||
|
import { useLanguage } from "@/context/language"
|
||||||
|
import { usePlatform } from "@/context/platform"
|
||||||
|
import { showToast } from "@/utils/toast"
|
||||||
|
|
||||||
|
export function useSettingsBackgroundImage() {
|
||||||
|
const platform = usePlatform()
|
||||||
|
const language = useLanguage()
|
||||||
|
const [state, setState] = createStore({ busy: false })
|
||||||
|
|
||||||
|
const run = async (action: (() => Promise<unknown>) | undefined) => {
|
||||||
|
if (!action || state.busy) return
|
||||||
|
setState("busy", true)
|
||||||
|
try {
|
||||||
|
await action()
|
||||||
|
} catch (error) {
|
||||||
|
showToast({
|
||||||
|
variant: "error",
|
||||||
|
title: language.t("common.requestFailed"),
|
||||||
|
description: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
setState("busy", false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
available: !!platform.selectBackgroundImage,
|
||||||
|
active: () => platform.backgroundImage?.() ?? false,
|
||||||
|
get busy() {
|
||||||
|
return state.busy
|
||||||
|
},
|
||||||
|
select: () => run(platform.selectBackgroundImage),
|
||||||
|
clear: () => run(platform.clearBackgroundImage),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,7 @@ import { decode64 } from "@/utils/base64"
|
|||||||
import { playSoundById, SOUND_OPTIONS } from "@/utils/sound"
|
import { playSoundById, SOUND_OPTIONS } from "@/utils/sound"
|
||||||
import { Link } from "./link"
|
import { Link } from "./link"
|
||||||
import { SettingsList } from "./settings-list"
|
import { SettingsList } from "./settings-list"
|
||||||
|
import { useSettingsBackgroundImage } from "./settings-background-image"
|
||||||
|
|
||||||
let demoSoundState = {
|
let demoSoundState = {
|
||||||
cleanup: undefined as (() => void) | undefined,
|
cleanup: undefined as (() => void) | undefined,
|
||||||
@@ -87,6 +88,7 @@ export const SettingsGeneral: Component = () => {
|
|||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const permission = usePermission()
|
const permission = usePermission()
|
||||||
const platform = usePlatform()
|
const platform = usePlatform()
|
||||||
|
const backgroundImage = useSettingsBackgroundImage()
|
||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
const params = useParams()
|
const params = useParams()
|
||||||
const settings = useSettings()
|
const settings = useSettings()
|
||||||
@@ -499,6 +501,24 @@ export const SettingsGeneral: Component = () => {
|
|||||||
/>
|
/>
|
||||||
</SettingsRow>
|
</SettingsRow>
|
||||||
|
|
||||||
|
<Show when={backgroundImage.available}>
|
||||||
|
<SettingsRow
|
||||||
|
title={language.t("settings.general.row.backgroundImage.title")}
|
||||||
|
description={language.t("settings.general.row.backgroundImage.description")}
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Button size="small" variant="secondary" disabled={backgroundImage.busy} onClick={backgroundImage.select}>
|
||||||
|
{language.t("settings.general.row.backgroundImage.choose")}
|
||||||
|
</Button>
|
||||||
|
<Show when={backgroundImage.active()}>
|
||||||
|
<Button size="small" variant="ghost" disabled={backgroundImage.busy} onClick={backgroundImage.clear}>
|
||||||
|
{language.t("settings.general.row.backgroundImage.remove")}
|
||||||
|
</Button>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</SettingsRow>
|
||||||
|
</Show>
|
||||||
|
|
||||||
<SettingsRow
|
<SettingsRow
|
||||||
title={language.t("settings.general.row.uiFont.title")}
|
title={language.t("settings.general.row.uiFont.title")}
|
||||||
description={language.t("settings.general.row.uiFont.description")}
|
description={language.t("settings.general.row.uiFont.description")}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { Link } from "../link"
|
|||||||
import { SettingsListV2 } from "./parts/list"
|
import { SettingsListV2 } from "./parts/list"
|
||||||
import { SettingsRowV2 } from "./parts/row"
|
import { SettingsRowV2 } from "./parts/row"
|
||||||
import { LayoutRetirementNotice, LayoutTransitionToggle } from "./interface-transition"
|
import { LayoutRetirementNotice, LayoutTransitionToggle } from "./interface-transition"
|
||||||
|
import { useSettingsBackgroundImage } from "../settings-background-image"
|
||||||
import "./settings-v2.css"
|
import "./settings-v2.css"
|
||||||
|
|
||||||
let demoSoundState = {
|
let demoSoundState = {
|
||||||
@@ -88,6 +89,7 @@ export const SettingsGeneralV2: Component<{
|
|||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const permission = usePermission()
|
const permission = usePermission()
|
||||||
const platform = usePlatform()
|
const platform = usePlatform()
|
||||||
|
const backgroundImage = useSettingsBackgroundImage()
|
||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
const settings = useSettings()
|
const settings = useSettings()
|
||||||
const serverSync = useServerSync()
|
const serverSync = useServerSync()
|
||||||
@@ -460,6 +462,29 @@ export const SettingsGeneralV2: Component<{
|
|||||||
/>
|
/>
|
||||||
</SettingsRowV2>
|
</SettingsRowV2>
|
||||||
|
|
||||||
|
<Show when={backgroundImage.available}>
|
||||||
|
<SettingsRowV2
|
||||||
|
title={language.t("settings.general.row.backgroundImage.title")}
|
||||||
|
description={language.t("settings.general.row.backgroundImage.description")}
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<ButtonV2
|
||||||
|
size="normal"
|
||||||
|
variant="neutral"
|
||||||
|
disabled={backgroundImage.busy}
|
||||||
|
onClick={backgroundImage.select}
|
||||||
|
>
|
||||||
|
{language.t("settings.general.row.backgroundImage.choose")}
|
||||||
|
</ButtonV2>
|
||||||
|
<Show when={backgroundImage.active()}>
|
||||||
|
<ButtonV2 size="normal" variant="ghost" disabled={backgroundImage.busy} onClick={backgroundImage.clear}>
|
||||||
|
{language.t("settings.general.row.backgroundImage.remove")}
|
||||||
|
</ButtonV2>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</SettingsRowV2>
|
||||||
|
</Show>
|
||||||
|
|
||||||
<SettingsRowV2
|
<SettingsRowV2
|
||||||
title={language.t("settings.general.row.uiFont.title")}
|
title={language.t("settings.general.row.uiFont.title")}
|
||||||
description={language.t("settings.general.row.uiFont.description")}
|
description={language.t("settings.general.row.uiFont.description")}
|
||||||
|
|||||||
@@ -227,6 +227,7 @@ export function Titlebar(props: { update?: TitlebarUpdate }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<header
|
<header
|
||||||
|
data-background-surface="shell"
|
||||||
data-slot={useV2Titlebar() ? "titlebar-v2" : undefined}
|
data-slot={useV2Titlebar() ? "titlebar-v2" : undefined}
|
||||||
classList={{
|
classList={{
|
||||||
"shrink-0 relative flex flex-row": true,
|
"shrink-0 relative flex flex-row": true,
|
||||||
|
|||||||
@@ -112,6 +112,18 @@ type PlatformBase = {
|
|||||||
/** Read image from clipboard (desktop only) */
|
/** Read image from clipboard (desktop only) */
|
||||||
readClipboardImage?(): Promise<File | null>
|
readClipboardImage?(): Promise<File | null>
|
||||||
|
|
||||||
|
/** Load and apply the saved app background image. */
|
||||||
|
loadBackgroundImage?(): Promise<boolean>
|
||||||
|
|
||||||
|
/** Whether the app currently has a background image. */
|
||||||
|
backgroundImage?: Accessor<boolean>
|
||||||
|
|
||||||
|
/** Select and apply an app background image. */
|
||||||
|
selectBackgroundImage?(): Promise<boolean>
|
||||||
|
|
||||||
|
/** Clear the saved app background image. */
|
||||||
|
clearBackgroundImage?(): Promise<void>
|
||||||
|
|
||||||
/** Export collected diagnostic logs (desktop only) */
|
/** Export collected diagnostic logs (desktop only) */
|
||||||
exportDebugLogs?(): Promise<string>
|
exportDebugLogs?(): Promise<string>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// @refresh reload
|
// @refresh reload
|
||||||
|
|
||||||
import * as Sentry from "@sentry/solid"
|
import * as Sentry from "@sentry/solid"
|
||||||
|
import { createSignal } from "solid-js"
|
||||||
import { render } from "solid-js/web"
|
import { render } from "solid-js/web"
|
||||||
import { AppBaseProviders, AppInterface } from "@/app"
|
import { AppBaseProviders, AppInterface } from "@/app"
|
||||||
import { type Platform, PlatformProvider } from "@/context/platform"
|
import { type Platform, PlatformProvider } from "@/context/platform"
|
||||||
@@ -8,6 +9,12 @@ import { dict as en } from "@/i18n/en"
|
|||||||
import { dict as zh } from "@/i18n/zh"
|
import { dict as zh } from "@/i18n/zh"
|
||||||
import { handleNotificationClick } from "@/utils/notification-click"
|
import { handleNotificationClick } from "@/utils/notification-click"
|
||||||
import { authFromToken } from "@/utils/server"
|
import { authFromToken } from "@/utils/server"
|
||||||
|
import {
|
||||||
|
clearWebBackgroundImage,
|
||||||
|
loadWebBackgroundImage,
|
||||||
|
saveWebBackgroundImage,
|
||||||
|
selectWebBackgroundImage,
|
||||||
|
} from "@/utils/web-background-image"
|
||||||
import pkg from "../package.json"
|
import pkg from "../package.json"
|
||||||
import { ServerConnection } from "./context/server"
|
import { ServerConnection } from "./context/server"
|
||||||
|
|
||||||
@@ -119,6 +126,21 @@ const clearAuthToken = () => {
|
|||||||
history.replaceState(null, "", location.pathname + (params.size ? `?${params}` : "") + location.hash)
|
history.replaceState(null, "", location.pathname + (params.size ? `?${params}` : "") + location.hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const [backgroundImage, setBackgroundImage] = createSignal(false)
|
||||||
|
let backgroundImageUrl: string | undefined
|
||||||
|
const applyBackgroundImage = (image: Blob | null) => {
|
||||||
|
if (backgroundImageUrl) URL.revokeObjectURL(backgroundImageUrl)
|
||||||
|
backgroundImageUrl = image ? URL.createObjectURL(image) : undefined
|
||||||
|
setBackgroundImage(!!backgroundImageUrl)
|
||||||
|
document.documentElement.toggleAttribute("data-background-image", !!backgroundImageUrl)
|
||||||
|
if (backgroundImageUrl) {
|
||||||
|
document.documentElement.style.setProperty("--app-background-image", `url("${backgroundImageUrl}")`)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
document.documentElement.style.removeProperty("--app-background-image")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
const platform: Platform = {
|
const platform: Platform = {
|
||||||
platform: "web",
|
platform: "web",
|
||||||
version: pkg.version,
|
version: pkg.version,
|
||||||
@@ -132,8 +154,23 @@ const platform: Platform = {
|
|||||||
return stored ? ServerConnection.Key.make(stored) : null
|
return stored ? ServerConnection.Key.make(stored) : null
|
||||||
},
|
},
|
||||||
setDefaultServer: writeDefaultServerUrl,
|
setDefaultServer: writeDefaultServerUrl,
|
||||||
|
backgroundImage,
|
||||||
|
async loadBackgroundImage() {
|
||||||
|
return applyBackgroundImage(await loadWebBackgroundImage())
|
||||||
|
},
|
||||||
|
async selectBackgroundImage() {
|
||||||
|
const file = await selectWebBackgroundImage()
|
||||||
|
if (!file) return backgroundImage()
|
||||||
|
return applyBackgroundImage(await saveWebBackgroundImage(file))
|
||||||
|
},
|
||||||
|
async clearBackgroundImage() {
|
||||||
|
await clearWebBackgroundImage()
|
||||||
|
applyBackgroundImage(null)
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void platform.loadBackgroundImage?.()
|
||||||
|
|
||||||
if (import.meta.env.VITE_SENTRY_DSN) {
|
if (import.meta.env.VITE_SENTRY_DSN) {
|
||||||
Sentry.init({
|
Sentry.init({
|
||||||
dsn: import.meta.env.VITE_SENTRY_DSN,
|
dsn: import.meta.env.VITE_SENTRY_DSN,
|
||||||
|
|||||||
@@ -704,6 +704,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "خصّص الخط المستخدم في كتل التعليمات البرمجية",
|
"settings.general.row.font.description": "خصّص الخط المستخدم في كتل التعليمات البرمجية",
|
||||||
"settings.general.row.terminalFont.title": "خط الطرفية",
|
"settings.general.row.terminalFont.title": "خط الطرفية",
|
||||||
"settings.general.row.terminalFont.description": "خصّص الخط المستخدم في الطرفية",
|
"settings.general.row.terminalFont.description": "خصّص الخط المستخدم في الطرفية",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "خط الواجهة",
|
"settings.general.row.uiFont.title": "خط الواجهة",
|
||||||
"settings.general.row.uiFont.description": "خصّص الخط المستخدم في الواجهة بأكملها",
|
"settings.general.row.uiFont.description": "خصّص الخط المستخدم في الواجهة بأكملها",
|
||||||
"settings.general.row.followup.title": "سلوك المتابعة",
|
"settings.general.row.followup.title": "سلوك المتابعة",
|
||||||
|
|||||||
@@ -713,6 +713,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Personalize a fonte usada em blocos de código",
|
"settings.general.row.font.description": "Personalize a fonte usada em blocos de código",
|
||||||
"settings.general.row.terminalFont.title": "Fonte do terminal",
|
"settings.general.row.terminalFont.title": "Fonte do terminal",
|
||||||
"settings.general.row.terminalFont.description": "Personalize a fonte usada no terminal",
|
"settings.general.row.terminalFont.description": "Personalize a fonte usada no terminal",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "Fonte da interface",
|
"settings.general.row.uiFont.title": "Fonte da interface",
|
||||||
"settings.general.row.uiFont.description": "Personalize a fonte usada em toda a interface",
|
"settings.general.row.uiFont.description": "Personalize a fonte usada em toda a interface",
|
||||||
"settings.general.row.followup.title": "Comportamento de acompanhamento",
|
"settings.general.row.followup.title": "Comportamento de acompanhamento",
|
||||||
|
|||||||
@@ -778,6 +778,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Prilagodi font koji se koristi u blokovima koda",
|
"settings.general.row.font.description": "Prilagodi font koji se koristi u blokovima koda",
|
||||||
"settings.general.row.terminalFont.title": "Font terminala",
|
"settings.general.row.terminalFont.title": "Font terminala",
|
||||||
"settings.general.row.terminalFont.description": "Prilagodite font koji se koristi u terminalu",
|
"settings.general.row.terminalFont.description": "Prilagodite font koji se koristi u terminalu",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "UI font",
|
"settings.general.row.uiFont.title": "UI font",
|
||||||
"settings.general.row.uiFont.description": "Prilagodi font koji se koristi u cijelom interfejsu",
|
"settings.general.row.uiFont.description": "Prilagodi font koji se koristi u cijelom interfejsu",
|
||||||
"settings.general.row.followup.title": "Ponašanje nadovezivanja",
|
"settings.general.row.followup.title": "Ponašanje nadovezivanja",
|
||||||
|
|||||||
@@ -773,6 +773,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Tilpas skrifttypen, der bruges i kodeblokke",
|
"settings.general.row.font.description": "Tilpas skrifttypen, der bruges i kodeblokke",
|
||||||
"settings.general.row.terminalFont.title": "Terminalskrifttype",
|
"settings.general.row.terminalFont.title": "Terminalskrifttype",
|
||||||
"settings.general.row.terminalFont.description": "Tilpas den skrifttype, der bruges i terminalen",
|
"settings.general.row.terminalFont.description": "Tilpas den skrifttype, der bruges i terminalen",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "UI-skrifttype",
|
"settings.general.row.uiFont.title": "UI-skrifttype",
|
||||||
"settings.general.row.uiFont.description": "Tilpas skrifttypen, der bruges i hele brugerfladen",
|
"settings.general.row.uiFont.description": "Tilpas skrifttypen, der bruges i hele brugerfladen",
|
||||||
"settings.general.row.followup.title": "Opfølgningsadfærd",
|
"settings.general.row.followup.title": "Opfølgningsadfærd",
|
||||||
|
|||||||
@@ -724,6 +724,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Die in Codeblöcken verwendete Schriftart anpassen",
|
"settings.general.row.font.description": "Die in Codeblöcken verwendete Schriftart anpassen",
|
||||||
"settings.general.row.terminalFont.title": "Terminalschriftart",
|
"settings.general.row.terminalFont.title": "Terminalschriftart",
|
||||||
"settings.general.row.terminalFont.description": "Passe die im Terminal verwendete Schriftart an",
|
"settings.general.row.terminalFont.description": "Passe die im Terminal verwendete Schriftart an",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "UI-Schriftart",
|
"settings.general.row.uiFont.title": "UI-Schriftart",
|
||||||
"settings.general.row.uiFont.description": "Die im gesamten Interface verwendete Schriftart anpassen",
|
"settings.general.row.uiFont.description": "Die im gesamten Interface verwendete Schriftart anpassen",
|
||||||
"settings.general.row.followup.title": "Verhalten bei Folgefragen",
|
"settings.general.row.followup.title": "Verhalten bei Folgefragen",
|
||||||
|
|||||||
@@ -862,6 +862,10 @@ export const dict = {
|
|||||||
"settings.general.row.colorScheme.description": "Choose whether OpenCode follows the system, light, or dark theme",
|
"settings.general.row.colorScheme.description": "Choose whether OpenCode follows the system, light, or dark theme",
|
||||||
"settings.general.row.theme.title": "Theme",
|
"settings.general.row.theme.title": "Theme",
|
||||||
"settings.general.row.theme.description": "Customise how OpenCode is themed.",
|
"settings.general.row.theme.description": "Customise how OpenCode is themed.",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.font.title": "Code Font",
|
"settings.general.row.font.title": "Code Font",
|
||||||
"settings.general.row.font.description": "Customise the font used in code blocks",
|
"settings.general.row.font.description": "Customise the font used in code blocks",
|
||||||
"settings.general.row.terminalFont.title": "Terminal Font",
|
"settings.general.row.terminalFont.title": "Terminal Font",
|
||||||
|
|||||||
@@ -781,6 +781,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Personaliza la fuente usada en bloques de código",
|
"settings.general.row.font.description": "Personaliza la fuente usada en bloques de código",
|
||||||
"settings.general.row.terminalFont.title": "Fuente del terminal",
|
"settings.general.row.terminalFont.title": "Fuente del terminal",
|
||||||
"settings.general.row.terminalFont.description": "Personaliza la fuente utilizada en el terminal",
|
"settings.general.row.terminalFont.description": "Personaliza la fuente utilizada en el terminal",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "Fuente de la interfaz",
|
"settings.general.row.uiFont.title": "Fuente de la interfaz",
|
||||||
"settings.general.row.uiFont.description": "Personaliza la fuente usada en toda la interfaz",
|
"settings.general.row.uiFont.description": "Personaliza la fuente usada en toda la interfaz",
|
||||||
"settings.general.row.followup.title": "Comportamiento de seguimiento",
|
"settings.general.row.followup.title": "Comportamiento de seguimiento",
|
||||||
|
|||||||
@@ -720,6 +720,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Personnaliser la police utilisée dans les blocs de code",
|
"settings.general.row.font.description": "Personnaliser la police utilisée dans les blocs de code",
|
||||||
"settings.general.row.terminalFont.title": "Police du terminal",
|
"settings.general.row.terminalFont.title": "Police du terminal",
|
||||||
"settings.general.row.terminalFont.description": "Personnalisez la police utilisée dans le terminal",
|
"settings.general.row.terminalFont.description": "Personnalisez la police utilisée dans le terminal",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "Police de l'interface",
|
"settings.general.row.uiFont.title": "Police de l'interface",
|
||||||
"settings.general.row.uiFont.description": "Personnaliser la police utilisée dans toute l'interface",
|
"settings.general.row.uiFont.description": "Personnaliser la police utilisée dans toute l'interface",
|
||||||
"settings.general.row.followup.title": "Comportement de suivi",
|
"settings.general.row.followup.title": "Comportement de suivi",
|
||||||
|
|||||||
@@ -709,6 +709,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "コードブロックで使用するフォントをカスタマイズします",
|
"settings.general.row.font.description": "コードブロックで使用するフォントをカスタマイズします",
|
||||||
"settings.general.row.terminalFont.title": "ターミナルのフォント",
|
"settings.general.row.terminalFont.title": "ターミナルのフォント",
|
||||||
"settings.general.row.terminalFont.description": "ターミナルで使用するフォントをカスタマイズ",
|
"settings.general.row.terminalFont.description": "ターミナルで使用するフォントをカスタマイズ",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "UIフォント",
|
"settings.general.row.uiFont.title": "UIフォント",
|
||||||
"settings.general.row.uiFont.description": "インターフェース全体で使用するフォントをカスタマイズします",
|
"settings.general.row.uiFont.description": "インターフェース全体で使用するフォントをカスタマイズします",
|
||||||
"settings.general.row.followup.title": "フォローアップの動作",
|
"settings.general.row.followup.title": "フォローアップの動作",
|
||||||
|
|||||||
@@ -580,6 +580,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "코드 블록에 사용되는 글꼴을 사용자 지정",
|
"settings.general.row.font.description": "코드 블록에 사용되는 글꼴을 사용자 지정",
|
||||||
"settings.general.row.terminalFont.title": "터미널 글꼴",
|
"settings.general.row.terminalFont.title": "터미널 글꼴",
|
||||||
"settings.general.row.terminalFont.description": "터미널에서 사용할 글꼴을 설정합니다",
|
"settings.general.row.terminalFont.description": "터미널에서 사용할 글꼴을 설정합니다",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "UI 글꼴",
|
"settings.general.row.uiFont.title": "UI 글꼴",
|
||||||
"settings.general.row.uiFont.description": "인터페이스 전반에 사용되는 글꼴을 사용자 지정",
|
"settings.general.row.uiFont.description": "인터페이스 전반에 사용되는 글꼴을 사용자 지정",
|
||||||
"settings.general.row.followup.title": "후속 조치 동작",
|
"settings.general.row.followup.title": "후속 조치 동작",
|
||||||
|
|||||||
@@ -654,6 +654,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Tilpass skrifttypen som brukes i kodeblokker",
|
"settings.general.row.font.description": "Tilpass skrifttypen som brukes i kodeblokker",
|
||||||
"settings.general.row.terminalFont.title": "Terminalskrift",
|
"settings.general.row.terminalFont.title": "Terminalskrift",
|
||||||
"settings.general.row.terminalFont.description": "Tilpass skrifttypen som brukes i terminalen",
|
"settings.general.row.terminalFont.description": "Tilpass skrifttypen som brukes i terminalen",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "UI-skrift",
|
"settings.general.row.uiFont.title": "UI-skrift",
|
||||||
"settings.general.row.uiFont.description": "Tilpass skrifttypen som brukes i hele grensesnittet",
|
"settings.general.row.uiFont.description": "Tilpass skrifttypen som brukes i hele grensesnittet",
|
||||||
"settings.general.row.followup.title": "Oppfølgingsadferd",
|
"settings.general.row.followup.title": "Oppfølgingsadferd",
|
||||||
|
|||||||
@@ -714,6 +714,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Dostosuj czcionkę używaną w blokach kodu",
|
"settings.general.row.font.description": "Dostosuj czcionkę używaną w blokach kodu",
|
||||||
"settings.general.row.terminalFont.title": "Czcionka terminala",
|
"settings.general.row.terminalFont.title": "Czcionka terminala",
|
||||||
"settings.general.row.terminalFont.description": "Dostosuj czcionkę używaną w terminalu",
|
"settings.general.row.terminalFont.description": "Dostosuj czcionkę używaną w terminalu",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "Czcionka interfejsu",
|
"settings.general.row.uiFont.title": "Czcionka interfejsu",
|
||||||
"settings.general.row.uiFont.description": "Dostosuj czcionkę używaną w całym interfejsie",
|
"settings.general.row.uiFont.description": "Dostosuj czcionkę używaną w całym interfejsie",
|
||||||
"settings.general.row.followup.title": "Zachowanie kontynuacji",
|
"settings.general.row.followup.title": "Zachowanie kontynuacji",
|
||||||
|
|||||||
@@ -778,6 +778,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Настройте шрифт, используемый в блоках кода",
|
"settings.general.row.font.description": "Настройте шрифт, используемый в блоках кода",
|
||||||
"settings.general.row.terminalFont.title": "Шрифт терминала",
|
"settings.general.row.terminalFont.title": "Шрифт терминала",
|
||||||
"settings.general.row.terminalFont.description": "Настройте шрифт, используемый в терминале",
|
"settings.general.row.terminalFont.description": "Настройте шрифт, используемый в терминале",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "Шрифт интерфейса",
|
"settings.general.row.uiFont.title": "Шрифт интерфейса",
|
||||||
"settings.general.row.uiFont.description": "Настройте шрифт, используемый во всем интерфейсе",
|
"settings.general.row.uiFont.description": "Настройте шрифт, используемый во всем интерфейсе",
|
||||||
"settings.general.row.followup.title": "Поведение уточняющих вопросов",
|
"settings.general.row.followup.title": "Поведение уточняющих вопросов",
|
||||||
|
|||||||
@@ -771,6 +771,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "ปรับแต่งฟอนต์ที่ใช้ในบล็อกโค้ด",
|
"settings.general.row.font.description": "ปรับแต่งฟอนต์ที่ใช้ในบล็อกโค้ด",
|
||||||
"settings.general.row.terminalFont.title": "ฟอนต์เทอร์มินัล",
|
"settings.general.row.terminalFont.title": "ฟอนต์เทอร์มินัล",
|
||||||
"settings.general.row.terminalFont.description": "ปรับแต่งฟอนต์ที่ใช้ในเทอร์มินัล",
|
"settings.general.row.terminalFont.description": "ปรับแต่งฟอนต์ที่ใช้ในเทอร์มินัล",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "ฟอนต์ UI",
|
"settings.general.row.uiFont.title": "ฟอนต์ UI",
|
||||||
"settings.general.row.uiFont.description": "ปรับแต่งฟอนต์ที่ใช้ทั่วทั้งอินเทอร์เฟซ",
|
"settings.general.row.uiFont.description": "ปรับแต่งฟอนต์ที่ใช้ทั่วทั้งอินเทอร์เฟซ",
|
||||||
"settings.general.row.followup.title": "พฤติกรรมการติดตามผล",
|
"settings.general.row.followup.title": "พฤติกรรมการติดตามผล",
|
||||||
|
|||||||
@@ -784,6 +784,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Kod bloklarında kullanılan yazı tipini özelleştirin",
|
"settings.general.row.font.description": "Kod bloklarında kullanılan yazı tipini özelleştirin",
|
||||||
"settings.general.row.terminalFont.title": "Terminal yazı tipi",
|
"settings.general.row.terminalFont.title": "Terminal yazı tipi",
|
||||||
"settings.general.row.terminalFont.description": "Terminalde kullanılan yazı tipini özelleştirin",
|
"settings.general.row.terminalFont.description": "Terminalde kullanılan yazı tipini özelleştirin",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "Arayüz Yazı Tipi",
|
"settings.general.row.uiFont.title": "Arayüz Yazı Tipi",
|
||||||
"settings.general.row.uiFont.description": "Arayüz genelinde kullanılan yazı tipini özelleştirin",
|
"settings.general.row.uiFont.description": "Arayüz genelinde kullanılan yazı tipini özelleştirin",
|
||||||
"settings.general.row.followup.title": "Takip davranışı",
|
"settings.general.row.followup.title": "Takip davranışı",
|
||||||
|
|||||||
@@ -870,6 +870,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "Налаштуйте шрифт, який використовується в блоках коду",
|
"settings.general.row.font.description": "Налаштуйте шрифт, який використовується в блоках коду",
|
||||||
"settings.general.row.terminalFont.title": "Шрифт термінала",
|
"settings.general.row.terminalFont.title": "Шрифт термінала",
|
||||||
"settings.general.row.terminalFont.description": "Налаштуйте шрифт, який використовується в терміналі",
|
"settings.general.row.terminalFont.description": "Налаштуйте шрифт, який використовується в терміналі",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "Шрифт інтерфейсу",
|
"settings.general.row.uiFont.title": "Шрифт інтерфейсу",
|
||||||
"settings.general.row.uiFont.description": "Налаштуйте шрифт, який використовується в інтерфейсі",
|
"settings.general.row.uiFont.description": "Налаштуйте шрифт, який використовується в інтерфейсі",
|
||||||
"settings.general.row.followup.title": "Поведінка продовження",
|
"settings.general.row.followup.title": "Поведінка продовження",
|
||||||
|
|||||||
@@ -768,6 +768,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "自定义代码块使用的字体",
|
"settings.general.row.font.description": "自定义代码块使用的字体",
|
||||||
"settings.general.row.terminalFont.title": "终端字体",
|
"settings.general.row.terminalFont.title": "终端字体",
|
||||||
"settings.general.row.terminalFont.description": "自定义终端使用的字体",
|
"settings.general.row.terminalFont.description": "自定义终端使用的字体",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "界面字体",
|
"settings.general.row.uiFont.title": "界面字体",
|
||||||
"settings.general.row.uiFont.description": "自定义整个界面使用的字体",
|
"settings.general.row.uiFont.description": "自定义整个界面使用的字体",
|
||||||
"settings.general.row.followup.title": "跟进消息行为",
|
"settings.general.row.followup.title": "跟进消息行为",
|
||||||
|
|||||||
@@ -763,6 +763,10 @@ export const dict = {
|
|||||||
"settings.general.row.font.description": "自訂程式碼區塊使用的字型",
|
"settings.general.row.font.description": "自訂程式碼區塊使用的字型",
|
||||||
"settings.general.row.terminalFont.title": "終端機字型",
|
"settings.general.row.terminalFont.title": "終端機字型",
|
||||||
"settings.general.row.terminalFont.description": "自訂終端機使用的字型",
|
"settings.general.row.terminalFont.description": "自訂終端機使用的字型",
|
||||||
|
"settings.general.row.backgroundImage.title": "Background image",
|
||||||
|
"settings.general.row.backgroundImage.description": "Choose an image for the app background.",
|
||||||
|
"settings.general.row.backgroundImage.choose": "Choose image",
|
||||||
|
"settings.general.row.backgroundImage.remove": "Remove",
|
||||||
"settings.general.row.uiFont.title": "介面字型",
|
"settings.general.row.uiFont.title": "介面字型",
|
||||||
"settings.general.row.uiFont.description": "自訂整個介面使用的字型",
|
"settings.general.row.uiFont.description": "自訂整個介面使用的字型",
|
||||||
"settings.general.row.followup.title": "後續追問行為",
|
"settings.general.row.followup.title": "後續追問行為",
|
||||||
|
|||||||
@@ -3,6 +3,62 @@
|
|||||||
@import "@opencode-ai/ui/v2/styles/tailwind.css";
|
@import "@opencode-ai/ui/v2/styles/tailwind.css";
|
||||||
@import "tw-animate-css";
|
@import "tw-animate-css";
|
||||||
|
|
||||||
|
html[data-background-image] body {
|
||||||
|
background-image: linear-gradient(rgb(0 0 0 / 30%), rgb(0 0 0 / 30%)), var(--app-background-image);
|
||||||
|
background-color: transparent !important;
|
||||||
|
background-position: center;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-size: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] #root {
|
||||||
|
background-color: transparent !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] [data-background-surface="shell"] {
|
||||||
|
background-color: transparent !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] [data-background-surface="content"] {
|
||||||
|
background-color: color-mix(in srgb, var(--background-base) 68%, transparent) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] [data-background-surface="panel"] {
|
||||||
|
background-color: color-mix(in srgb, var(--v2-background-bg-base) 56%, transparent) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] [data-background-surface="prompt"] {
|
||||||
|
background-color: color-mix(in srgb, var(--v2-background-bg-base) 68%, transparent) !important;
|
||||||
|
backdrop-filter: blur(16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] [data-background-surface="project-selector"] {
|
||||||
|
background-color: color-mix(in srgb, var(--v2-background-bg-base) 68%, transparent) !important;
|
||||||
|
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--v2-border-border-base) 70%, transparent);
|
||||||
|
backdrop-filter: blur(16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] [data-background-surface="prompt"] [data-background-surface="project-selector"] {
|
||||||
|
background-color: transparent !important;
|
||||||
|
box-shadow: none;
|
||||||
|
backdrop-filter: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] [data-background-surface="workspace-bar"] {
|
||||||
|
padding-inline: 6px;
|
||||||
|
padding-block: 2px;
|
||||||
|
border-radius: 6px;
|
||||||
|
background-color: color-mix(in srgb, var(--v2-background-bg-base) 68%, transparent) !important;
|
||||||
|
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--v2-border-border-base) 70%, transparent);
|
||||||
|
backdrop-filter: blur(16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-background-image] [data-background-surface="workspace-bar"] [data-background-surface="project-selector"] {
|
||||||
|
background-color: transparent !important;
|
||||||
|
box-shadow: none;
|
||||||
|
backdrop-filter: none;
|
||||||
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "JetBrainsMono Nerd Font Mono";
|
font-family: "JetBrainsMono Nerd Font Mono";
|
||||||
src: url("/assets/JetBrainsMonoNerdFontMono-Regular.woff2") format("woff2");
|
src: url("/assets/JetBrainsMonoNerdFontMono-Regular.woff2") format("woff2");
|
||||||
|
|||||||
@@ -598,7 +598,10 @@ export function NewHome() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class="rounded-[10px] shadow-[var(--v2-elevation-raised)] m-2 min-h-0 overflow-hidden bg-v2-background-bg-base self-stretch flex-1">
|
<div
|
||||||
|
data-background-surface="panel"
|
||||||
|
class="rounded-[10px] shadow-[var(--v2-elevation-raised)] m-2 min-h-0 overflow-hidden bg-v2-background-bg-base self-stretch flex-1"
|
||||||
|
>
|
||||||
<ScrollView
|
<ScrollView
|
||||||
class="h-full [container-type:size]"
|
class="h-full [container-type:size]"
|
||||||
thumbContainer={sessionThumbTrack}
|
thumbContainer={sessionThumbTrack}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ export default function NewLayout(props: ParentProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
data-background-surface="shell"
|
||||||
class="relative bg-v2-background-bg-deep flex-1 min-h-0 min-w-0 flex flex-col select-none [&_input]:select-text [&_textarea]:select-text [&_[contenteditable]]:select-text"
|
class="relative bg-v2-background-bg-deep flex-1 min-h-0 min-w-0 flex flex-col select-none [&_input]:select-text [&_textarea]:select-text [&_[contenteditable]]:select-text"
|
||||||
style={{
|
style={{
|
||||||
"padding-top": "env(safe-area-inset-top, 0px)",
|
"padding-top": "env(safe-area-inset-top, 0px)",
|
||||||
|
|||||||
@@ -2246,7 +2246,10 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class="relative bg-background-base flex-1 min-h-0 min-w-0 flex flex-col select-none [&_input]:select-text [&_textarea]:select-text [&_[contenteditable]]:select-text">
|
<div
|
||||||
|
data-background-surface="shell"
|
||||||
|
class="relative bg-background-base flex-1 min-h-0 min-w-0 flex flex-col select-none [&_input]:select-text [&_textarea]:select-text [&_[contenteditable]]:select-text"
|
||||||
|
>
|
||||||
{autoselecting() ?? ""}
|
{autoselecting() ?? ""}
|
||||||
<Titlebar update={titlebarUpdate} />
|
<Titlebar update={titlebarUpdate} />
|
||||||
<Show when={updateVersion() !== undefined}>
|
<Show when={updateVersion() !== undefined}>
|
||||||
@@ -2344,6 +2347,7 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<main
|
<main
|
||||||
|
data-background-surface="content"
|
||||||
classList={{
|
classList={{
|
||||||
"size-full overflow-x-hidden flex flex-col items-start contain-strict border-t border-border-weak-base bg-background-base xl:border-l xl:rounded-tl-[12px]": true,
|
"size-full overflow-x-hidden flex flex-col items-start contain-strict border-t border-border-weak-base bg-background-base xl:border-l xl:rounded-tl-[12px]": true,
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -180,9 +180,11 @@ export default function NewSessionPage() {
|
|||||||
/>
|
/>
|
||||||
<Show when={projectController.selected()}>
|
<Show when={projectController.selected()}>
|
||||||
<div
|
<div
|
||||||
|
data-background-surface={showWorkspaceBar() ? "workspace-bar" : undefined}
|
||||||
class="flex min-h-7 min-w-0 items-center gap-0 text-v2-text-text-faint"
|
class="flex min-h-7 min-w-0 items-center gap-0 text-v2-text-text-faint"
|
||||||
classList={{
|
classList={{
|
||||||
"flex-col justify-center sm:flex-row": showWorkspaceBar(),
|
"flex-col justify-center sm:flex-row": showWorkspaceBar(),
|
||||||
|
"w-fit max-w-full self-center": showWorkspaceBar(),
|
||||||
"justify-start": !showWorkspaceBar(),
|
"justify-start": !showWorkspaceBar(),
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -335,6 +335,7 @@ function SessionRouteFrame(props: ParentProps<{ padded?: boolean }>) {
|
|||||||
function SessionPanelFrame(props: ParentProps<{ newLayout: boolean; raised?: boolean }>) {
|
function SessionPanelFrame(props: ParentProps<{ newLayout: boolean; raised?: boolean }>) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
data-background-surface={props.newLayout ? "panel" : undefined}
|
||||||
classList={{
|
classList={{
|
||||||
"flex-1 min-h-0 flex flex-col": true,
|
"flex-1 min-h-0 flex flex-col": true,
|
||||||
"bg-v2-background-bg-base": props.newLayout,
|
"bg-v2-background-bg-base": props.newLayout,
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
const cacheName = "opencode-background-image-v1"
|
||||||
|
const maxBytes = 20 * 1024 * 1024
|
||||||
|
|
||||||
|
function key() {
|
||||||
|
return new URL("/__opencode/background-image", location.origin).toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadWebBackgroundImage() {
|
||||||
|
const response = await (await caches.open(cacheName)).match(key())
|
||||||
|
return response?.blob() ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveWebBackgroundImage(file: File) {
|
||||||
|
if (!file.type.startsWith("image/")) throw new Error("Unsupported background image format")
|
||||||
|
if (file.size > maxBytes) throw new Error("Background images must be 20 MB or smaller")
|
||||||
|
await (await caches.open(cacheName)).put(key(), new Response(file, { headers: { "Content-Type": file.type } }))
|
||||||
|
return file
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearWebBackgroundImage() {
|
||||||
|
await (await caches.open(cacheName)).delete(key())
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectWebBackgroundImage() {
|
||||||
|
return new Promise<File | null>((resolve) => {
|
||||||
|
const input = document.createElement("input")
|
||||||
|
input.type = "file"
|
||||||
|
input.accept = "image/avif,image/bmp,image/gif,image/jpeg,image/png,image/webp"
|
||||||
|
input.onchange = () => resolve(input.files?.[0] ?? null)
|
||||||
|
input.oncancel = () => resolve(null)
|
||||||
|
input.click()
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -12,16 +12,7 @@
|
|||||||
],
|
],
|
||||||
"exports": {
|
"exports": {
|
||||||
"./daemon": "./src/daemon.ts",
|
"./daemon": "./src/daemon.ts",
|
||||||
"./mini": "./src/mini/index.ts",
|
"./run": "./src/run/index.ts",
|
||||||
"./mini/footer.command": "./src/mini/footer.command.tsx",
|
|
||||||
"./mini/footer.menu": "./src/mini/footer.menu.tsx",
|
|
||||||
"./mini/footer.permission": "./src/mini/footer.permission.tsx",
|
|
||||||
"./mini/footer.prompt": "./src/mini/footer.prompt.tsx",
|
|
||||||
"./mini/footer.question": "./src/mini/footer.question.tsx",
|
|
||||||
"./mini/footer.subagent": "./src/mini/footer.subagent.tsx",
|
|
||||||
"./mini/footer.view": "./src/mini/footer.view.tsx",
|
|
||||||
"./mini/scrollback.writer": "./src/mini/scrollback.writer.tsx",
|
|
||||||
"./mini/*": "./src/mini/*.ts",
|
|
||||||
"./server-process": "./src/server-process.ts"
|
"./server-process": "./src/server-process.ts"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -40,18 +31,14 @@
|
|||||||
"@opencode-ai/server": "workspace:*",
|
"@opencode-ai/server": "workspace:*",
|
||||||
"@opencode-ai/tui": "workspace:*",
|
"@opencode-ai/tui": "workspace:*",
|
||||||
"@opentui/core": "catalog:",
|
"@opentui/core": "catalog:",
|
||||||
"@opentui/keymap": "catalog:",
|
|
||||||
"@opentui/solid": "catalog:",
|
"@opentui/solid": "catalog:",
|
||||||
"@parcel/watcher": "2.5.1",
|
"@parcel/watcher": "2.5.1",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"fuzzysort": "catalog:",
|
|
||||||
"immer": "11.1.4",
|
"immer": "11.1.4",
|
||||||
"jsonc-parser": "3.3.1",
|
"jsonc-parser": "3.3.1",
|
||||||
"open": "10.1.2",
|
"open": "10.1.2",
|
||||||
"opentui-spinner": "catalog:",
|
|
||||||
"semver": "catalog:",
|
"semver": "catalog:",
|
||||||
"solid-js": "catalog:",
|
"solid-js": "catalog:",
|
||||||
"strip-ansi": "7.1.2",
|
|
||||||
"uqr": "0.1.3",
|
"uqr": "0.1.3",
|
||||||
"ws": "8.21.0"
|
"ws": "8.21.0"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { Effect, Option } from "effect"
|
import { Context, Effect, FileSystem, Option } from "effect"
|
||||||
import { Commands } from "../commands"
|
import { Commands } from "../commands"
|
||||||
import { Runtime } from "../../framework/runtime"
|
import { Runtime } from "../../framework/runtime"
|
||||||
import { ServerConnection } from "../../services/server-connection"
|
import { ServerConnection } from "../../services/server-connection"
|
||||||
|
import { Config } from "../../config"
|
||||||
|
import { resolve } from "@opencode-ai/tui/config"
|
||||||
|
|
||||||
export default Runtime.handler(Commands.commands.mini, (input) =>
|
export default Runtime.handler(Commands.commands.mini, (input) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -9,9 +11,17 @@ export default Runtime.handler(Commands.commands.mini, (input) =>
|
|||||||
yield* Effect.promise(async () => validateMiniTerminal())
|
yield* Effect.promise(async () => validateMiniTerminal())
|
||||||
const serverURL = Option.getOrUndefined(input.server)
|
const serverURL = Option.getOrUndefined(input.server)
|
||||||
const server = yield* ServerConnection.resolve({ server: serverURL, standalone: input.standalone })
|
const server = yield* ServerConnection.resolve({ server: serverURL, standalone: input.standalone })
|
||||||
|
const config = yield* Config.Service
|
||||||
|
const resolved = resolve(yield* config.get(), { terminalSuspend: process.platform !== "win32" })
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem
|
||||||
|
const runServicePromise = Effect.runPromiseWith(Context.make(FileSystem.FileSystem, fileSystem))
|
||||||
|
const service = server.service
|
||||||
yield* Effect.promise(() =>
|
yield* Effect.promise(() =>
|
||||||
runMini({
|
runMini({
|
||||||
server,
|
server: {
|
||||||
|
endpoint: server.endpoint,
|
||||||
|
reconnect: service ? (signal) => runServicePromise(service.reconnect(), { signal }) : undefined,
|
||||||
|
},
|
||||||
continue: input.continue,
|
continue: input.continue,
|
||||||
session: Option.getOrUndefined(input.session),
|
session: Option.getOrUndefined(input.session),
|
||||||
fork: input.fork,
|
fork: input.fork,
|
||||||
@@ -21,6 +31,7 @@ export default Runtime.handler(Commands.commands.mini, (input) =>
|
|||||||
replay: input.replay,
|
replay: input.replay,
|
||||||
replayLimit: Option.getOrUndefined(input.replayLimit),
|
replayLimit: Option.getOrUndefined(input.replayLimit),
|
||||||
demo: input.demo,
|
demo: input.demo,
|
||||||
|
tuiConfig: resolved,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { ServerConnection } from "../../services/server-connection"
|
|||||||
|
|
||||||
export default Runtime.handler(Commands.commands.run, (input) =>
|
export default Runtime.handler(Commands.commands.run, (input) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const { runNonInteractive } = yield* Effect.promise(() => import("../../mini"))
|
const { runNonInteractive } = yield* Effect.promise(() => import("../../run/run"))
|
||||||
const separator = process.argv.indexOf("--", 2)
|
const separator = process.argv.indexOf("--", 2)
|
||||||
const server = yield* ServerConnection.resolve({
|
const server = yield* ServerConnection.resolve({
|
||||||
server: Option.getOrUndefined(input.server),
|
server: Option.getOrUndefined(input.server),
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
import type { MiniFrontendInput } from "@opencode-ai/tui/mini"
|
||||||
|
import { createModelPreferenceRepository } from "@opencode-ai/tui/model-preference"
|
||||||
|
import { Flag } from "@opencode-ai/core/flag/flag"
|
||||||
|
import { Global } from "@opencode-ai/core/global"
|
||||||
|
import fs from "node:fs"
|
||||||
|
import { readFile } from "node:fs/promises"
|
||||||
|
import path from "node:path"
|
||||||
|
import { ReadStream } from "node:tty"
|
||||||
|
|
||||||
|
export const INTERACTIVE_INPUT_ERROR = "opencode mini requires a controlling terminal for input"
|
||||||
|
|
||||||
|
export type InteractiveStdin = {
|
||||||
|
stdin: NodeJS.ReadStream
|
||||||
|
cleanup(): void
|
||||||
|
}
|
||||||
|
|
||||||
|
type MiniHost = MiniFrontendInput["host"]
|
||||||
|
|
||||||
|
function preferences(statePath: string): MiniHost["preferences"] {
|
||||||
|
const repository = createModelPreferenceRepository(path.join(statePath, "model.json"))
|
||||||
|
return {
|
||||||
|
async resolveVariant(model) {
|
||||||
|
if (!model) return
|
||||||
|
return repository.resolveVariant(model)
|
||||||
|
},
|
||||||
|
async saveVariant(model, variant) {
|
||||||
|
if (!model) return
|
||||||
|
await repository.saveVariant(model, variant).catch(() => undefined)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function signal(name: "SIGINT" | "SIGUSR2"): MiniHost["signals"]["sigint"] {
|
||||||
|
return {
|
||||||
|
subscribe(listener) {
|
||||||
|
let subscribed = true
|
||||||
|
process.on(name, listener)
|
||||||
|
return () => {
|
||||||
|
if (!subscribed) return
|
||||||
|
subscribed = false
|
||||||
|
process.off(name, listener)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTrace(
|
||||||
|
logPath: string,
|
||||||
|
diagnostics: { pid: number; cwd: string; argv: string[] },
|
||||||
|
): MiniHost["diagnostics"]["trace"] {
|
||||||
|
if (!process.env.OPENCODE_DIRECT_TRACE) return
|
||||||
|
const stamp = new Date()
|
||||||
|
.toISOString()
|
||||||
|
.replace(/[-:]/g, "")
|
||||||
|
.replace(/\.\d+Z$/, "Z")
|
||||||
|
const target = path.join(logPath, "direct", `${stamp}-${diagnostics.pid}.jsonl`)
|
||||||
|
const text = (data: unknown) =>
|
||||||
|
JSON.stringify(data, (_key, value) => (typeof value === "bigint" ? String(value) : value), 0)
|
||||||
|
fs.mkdirSync(path.dirname(target), { recursive: true })
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(logPath, "direct", "latest.json"),
|
||||||
|
text({
|
||||||
|
time: new Date().toISOString(),
|
||||||
|
...diagnostics,
|
||||||
|
path: target,
|
||||||
|
}) + "\n",
|
||||||
|
)
|
||||||
|
const trace = {
|
||||||
|
write(type: string, data?: unknown) {
|
||||||
|
fs.appendFileSync(
|
||||||
|
target,
|
||||||
|
text({
|
||||||
|
time: new Date().toISOString(),
|
||||||
|
pid: diagnostics.pid,
|
||||||
|
type,
|
||||||
|
data,
|
||||||
|
}) + "\n",
|
||||||
|
)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
trace.write("trace.start", {
|
||||||
|
argv: diagnostics.argv,
|
||||||
|
cwd: diagnostics.cwd,
|
||||||
|
path: target,
|
||||||
|
})
|
||||||
|
return trace
|
||||||
|
}
|
||||||
|
|
||||||
|
function openTerminalStdin(target: string): NodeJS.ReadStream {
|
||||||
|
return new ReadStream(fs.openSync(target, "r"))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveInteractiveStdin(
|
||||||
|
stdin: NodeJS.ReadStream = process.stdin,
|
||||||
|
open: (target: string) => NodeJS.ReadStream = openTerminalStdin,
|
||||||
|
platform: NodeJS.Platform = process.platform,
|
||||||
|
): InteractiveStdin {
|
||||||
|
if (stdin.isTTY) return { stdin, cleanup() {} }
|
||||||
|
const target = platform === "win32" ? "CONIN$" : "/dev/tty"
|
||||||
|
try {
|
||||||
|
const source = open(target)
|
||||||
|
let cleaned = false
|
||||||
|
return {
|
||||||
|
stdin: source,
|
||||||
|
cleanup() {
|
||||||
|
if (cleaned) return
|
||||||
|
cleaned = true
|
||||||
|
source.destroy()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(INTERACTIVE_INPUT_ERROR, { cause: error })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal Exported for owner-local resource cleanup tests. */
|
||||||
|
export async function usingInteractiveStdin<T>(
|
||||||
|
run: (terminal: InteractiveStdin) => Promise<T>,
|
||||||
|
resolve: () => InteractiveStdin = resolveInteractiveStdin,
|
||||||
|
) {
|
||||||
|
const terminal = resolve()
|
||||||
|
try {
|
||||||
|
return await run(terminal)
|
||||||
|
} finally {
|
||||||
|
terminal.cleanup()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal Exported for owner-local host capability tests. */
|
||||||
|
export function createMiniHost(input: {
|
||||||
|
terminal: InteractiveStdin
|
||||||
|
directory: string
|
||||||
|
paths?: { home: string; state: string; log: string }
|
||||||
|
}): MiniHost {
|
||||||
|
const paths = input.paths ?? {
|
||||||
|
home: Global.Path.home,
|
||||||
|
state: Global.Path.state,
|
||||||
|
log: Global.Path.log,
|
||||||
|
}
|
||||||
|
const diagnostics = {
|
||||||
|
pid: process.pid,
|
||||||
|
cwd: input.directory,
|
||||||
|
argv: process.argv.slice(2),
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
terminal: { stdin: input.terminal.stdin },
|
||||||
|
platform: process.platform,
|
||||||
|
stdout: {
|
||||||
|
write(value) {
|
||||||
|
process.stdout.write(value)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
files: {
|
||||||
|
readText: (url) => readFile(new URL(url), "utf8"),
|
||||||
|
},
|
||||||
|
editor: {
|
||||||
|
async open(options) {
|
||||||
|
const { openEditor } = await import("@opencode-ai/tui/editor")
|
||||||
|
return openEditor(options)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
paths: { home: paths.home },
|
||||||
|
signals: {
|
||||||
|
sigint: signal("SIGINT"),
|
||||||
|
sigusr2: signal("SIGUSR2"),
|
||||||
|
},
|
||||||
|
startup: {
|
||||||
|
showTiming: Flag.OPENCODE_SHOW_TTFD,
|
||||||
|
now: () => performance.now(),
|
||||||
|
},
|
||||||
|
diagnostics: {
|
||||||
|
trace: createTrace(paths.log, diagnostics),
|
||||||
|
},
|
||||||
|
preferences: preferences(paths.state),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
import { Service, type Endpoint } from "@opencode-ai/client/effect/service"
|
||||||
|
import { ClientError, OpenCode, type OpenCodeClient } from "@opencode-ai/client/promise"
|
||||||
|
import type { MiniFrontendInput } from "@opencode-ai/tui/mini"
|
||||||
|
import { setTimeout } from "node:timers/promises"
|
||||||
|
import { waitForCatalogReady } from "./services/catalog"
|
||||||
|
import { readStdin } from "./util/io"
|
||||||
|
import { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from "./mini-host"
|
||||||
|
import { parseSessionTargetModel, resolveSessionTarget, type SessionTargetPreparation } from "./session-target"
|
||||||
|
|
||||||
|
export type MiniCommandInput = {
|
||||||
|
server: {
|
||||||
|
endpoint: Endpoint
|
||||||
|
reconnect?: (signal: AbortSignal) => Promise<Endpoint>
|
||||||
|
}
|
||||||
|
continue?: boolean
|
||||||
|
session?: string
|
||||||
|
fork?: boolean
|
||||||
|
model?: string
|
||||||
|
agent?: string
|
||||||
|
prompt?: string
|
||||||
|
replay?: boolean
|
||||||
|
replayLimit?: number
|
||||||
|
demo?: boolean
|
||||||
|
tuiConfig?: MiniFrontendInput["tuiConfig"]
|
||||||
|
}
|
||||||
|
|
||||||
|
type Model = MiniFrontendInput["model"]
|
||||||
|
|
||||||
|
class MiniInputError extends Error {}
|
||||||
|
|
||||||
|
export async function runMini(input: MiniCommandInput) {
|
||||||
|
try {
|
||||||
|
validate(input)
|
||||||
|
const result = await usingInteractiveStdin(async (terminal) => {
|
||||||
|
const initialInput = mergeInput(process.stdin.isTTY ? undefined : await readStdin(), input.prompt)
|
||||||
|
const frontendTask = import("@opencode-ai/tui/mini")
|
||||||
|
const directory = localDirectory()
|
||||||
|
const connection = createMiniConnection(input.server)
|
||||||
|
const sdk = connection.sdk
|
||||||
|
const requested = parseModel(input.model)
|
||||||
|
const model = requested ? { providerID: requested.providerID, modelID: requested.id } : undefined
|
||||||
|
const prepare = prepareTarget(input.agent)
|
||||||
|
const resolveTarget = async (initial: OpenCodeClient, signal: AbortSignal) => {
|
||||||
|
const resolved = await resolveMiniTarget({
|
||||||
|
sdk: initial,
|
||||||
|
reconnect: connection.reconnect,
|
||||||
|
signal,
|
||||||
|
resolve: (client) =>
|
||||||
|
resolveSessionTarget({
|
||||||
|
client,
|
||||||
|
location: { directory },
|
||||||
|
continue: input.continue,
|
||||||
|
session: input.session,
|
||||||
|
fork: input.fork,
|
||||||
|
model: requested,
|
||||||
|
agent: input.agent,
|
||||||
|
prepare,
|
||||||
|
signal,
|
||||||
|
}).catch((error) => {
|
||||||
|
if (error instanceof Error && error.message === "Session not found")
|
||||||
|
throw new MiniInputError(error.message)
|
||||||
|
throw error
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
const target = resolved.value
|
||||||
|
return {
|
||||||
|
sdk: resolved.sdk,
|
||||||
|
sessionID: target.session.id,
|
||||||
|
sessionTitle: target.session.title,
|
||||||
|
location: target.location,
|
||||||
|
model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,
|
||||||
|
variant: target.model?.variant,
|
||||||
|
agent: target.agent,
|
||||||
|
resume: target.resume,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const create = (
|
||||||
|
client: OpenCodeClient,
|
||||||
|
next: {
|
||||||
|
location: { directory: string; workspaceID?: string }
|
||||||
|
agent: string | undefined
|
||||||
|
model: Model
|
||||||
|
variant: string | undefined
|
||||||
|
},
|
||||||
|
signal?: AbortSignal,
|
||||||
|
) =>
|
||||||
|
resolveSessionTarget({
|
||||||
|
client,
|
||||||
|
location: { directory: next.location.directory, workspace: next.location.workspaceID },
|
||||||
|
agent: next.agent,
|
||||||
|
model: next.model
|
||||||
|
? { providerID: next.model.providerID, id: next.model.modelID, variant: next.variant }
|
||||||
|
: undefined,
|
||||||
|
prepare,
|
||||||
|
signal,
|
||||||
|
}).then((target) => ({
|
||||||
|
sessionID: target.session.id,
|
||||||
|
sessionTitle: target.session.title,
|
||||||
|
location: target.location,
|
||||||
|
model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,
|
||||||
|
variant: target.model?.variant,
|
||||||
|
agent: target.agent,
|
||||||
|
resume: false,
|
||||||
|
}))
|
||||||
|
const frontend = await frontendTask
|
||||||
|
return frontend.runMiniFrontend({
|
||||||
|
host: createMiniHost({ terminal, directory }),
|
||||||
|
sdk,
|
||||||
|
directory,
|
||||||
|
target: resolveTarget,
|
||||||
|
reconnect: connection.reconnect,
|
||||||
|
createSession: create,
|
||||||
|
agent: input.agent,
|
||||||
|
model,
|
||||||
|
variant: requested?.variant,
|
||||||
|
files: [],
|
||||||
|
initialInput,
|
||||||
|
replay: input.replay ?? true,
|
||||||
|
replayLimit: input.replayLimit,
|
||||||
|
demo: input.demo,
|
||||||
|
tuiConfig: input.tuiConfig,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
if (result.exitCode !== 0) process.exit(result.exitCode)
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof MiniInputError || (error instanceof Error && error.message === INTERACTIVE_INPUT_ERROR))
|
||||||
|
fail(error.message)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal Exported for CLI boundary tests. */
|
||||||
|
export function createMiniConnection(input: MiniCommandInput["server"]) {
|
||||||
|
const make = (endpoint: Endpoint) =>
|
||||||
|
OpenCode.make({
|
||||||
|
baseUrl: endpoint.url,
|
||||||
|
headers: Service.headers(endpoint),
|
||||||
|
})
|
||||||
|
const reconnect = input.reconnect
|
||||||
|
return {
|
||||||
|
sdk: make(input.endpoint),
|
||||||
|
reconnect: reconnect
|
||||||
|
? async (signal: AbortSignal) => {
|
||||||
|
const endpoint = await reconnect(signal)
|
||||||
|
return make(endpoint)
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal Exported for reconnect lifecycle tests. */
|
||||||
|
export async function resolveMiniTarget<A>(input: {
|
||||||
|
sdk: OpenCodeClient
|
||||||
|
reconnect?: (signal: AbortSignal) => Promise<OpenCodeClient>
|
||||||
|
signal: AbortSignal
|
||||||
|
resolve: (sdk: OpenCodeClient) => Promise<A>
|
||||||
|
}) {
|
||||||
|
let sdk = input.sdk
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
return { sdk, value: await input.resolve(sdk) }
|
||||||
|
} catch (error) {
|
||||||
|
if (!input.reconnect || !(error instanceof ClientError) || error.reason !== "Transport") throw error
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
sdk = await input.reconnect(input.signal)
|
||||||
|
break
|
||||||
|
} catch (resolveError) {
|
||||||
|
if (input.signal.aborted) throw resolveError
|
||||||
|
await setTimeout(250, undefined, { signal: input.signal })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateMiniTerminal() {
|
||||||
|
if (!process.stdout.isTTY) fail("opencode mini requires a TTY stdout")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal Exported for testing. */
|
||||||
|
export function mergeInput(piped: string | undefined, prompt: string | undefined) {
|
||||||
|
if (!prompt) return piped || undefined
|
||||||
|
if (!piped) return prompt
|
||||||
|
return piped + "\n" + prompt
|
||||||
|
}
|
||||||
|
|
||||||
|
function validate(input: MiniCommandInput) {
|
||||||
|
validateMiniTerminal()
|
||||||
|
if (input.replayLimit !== undefined && (!Number.isInteger(input.replayLimit) || input.replayLimit <= 0)) {
|
||||||
|
fail("--replay-limit must be a positive integer")
|
||||||
|
}
|
||||||
|
if (input.fork && !input.continue && !input.session) fail("--fork requires --continue or --session")
|
||||||
|
}
|
||||||
|
|
||||||
|
function localDirectory(): string {
|
||||||
|
const root = process.env.PWD ?? process.cwd()
|
||||||
|
try {
|
||||||
|
process.chdir(root)
|
||||||
|
return process.cwd()
|
||||||
|
} catch {
|
||||||
|
throw new MiniInputError(`Failed to change directory to ${root}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseModel(value?: string) {
|
||||||
|
try {
|
||||||
|
return parseSessionTargetModel(value)
|
||||||
|
} catch {
|
||||||
|
throw new MiniInputError("--model must use the format provider/model[#variant]")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function prepareTarget(requestedAgent?: string): SessionTargetPreparation {
|
||||||
|
return async (input) => {
|
||||||
|
if (input.model)
|
||||||
|
await waitForCatalogReady({
|
||||||
|
sdk: input.client,
|
||||||
|
directory: input.location.directory,
|
||||||
|
workspace: input.location.workspaceID,
|
||||||
|
model: { providerID: input.model.providerID, modelID: input.model.id },
|
||||||
|
signal: input.signal,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
model: input.model,
|
||||||
|
agent: requestedAgent
|
||||||
|
? await validateAgent(
|
||||||
|
input.client,
|
||||||
|
input.location.directory,
|
||||||
|
input.location.workspaceID,
|
||||||
|
requestedAgent,
|
||||||
|
input.signal,
|
||||||
|
)
|
||||||
|
: input.agent,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function validateAgent(
|
||||||
|
sdk: OpenCodeClient,
|
||||||
|
directory: string,
|
||||||
|
workspace: string | undefined,
|
||||||
|
name?: string,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
) {
|
||||||
|
if (!name) return
|
||||||
|
const deadline = Date.now() + 5_000
|
||||||
|
let agents: Awaited<ReturnType<OpenCodeClient["agent"]["list"]>> | undefined
|
||||||
|
while (Date.now() < deadline && !signal?.aborted) {
|
||||||
|
agents = await sdk.agent.list({ location: { directory, workspace } }, { signal }).catch((error) => {
|
||||||
|
if (signal && error instanceof ClientError && error.reason === "Transport") throw error
|
||||||
|
return undefined
|
||||||
|
})
|
||||||
|
const agent = agents?.data.find((item) => item.id === name)
|
||||||
|
if (agent?.mode === "subagent") {
|
||||||
|
warning(`agent "${name}" is a subagent, not a primary agent. Falling back to default agent`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (agent) return name
|
||||||
|
await setTimeout(25, undefined, { signal }).catch(() => {})
|
||||||
|
}
|
||||||
|
if (signal?.aborted) return
|
||||||
|
if (!agents) {
|
||||||
|
warning("failed to list agents. Falling back to default agent")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
warning(`agent "${name}" not found. Falling back to default agent`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function warning(message: string) {
|
||||||
|
process.stderr.write(`\x1b[93m\x1b[1m!\x1b[0m ${message}\n`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function fail(message: string): never {
|
||||||
|
process.stderr.write(`\x1b[91m\x1b[1mError: \x1b[0m${message}\n`)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
@@ -1,159 +0,0 @@
|
|||||||
import type {
|
|
||||||
AgentListOutput,
|
|
||||||
CommandListOutput,
|
|
||||||
ModelListOutput,
|
|
||||||
OpenCodeClient,
|
|
||||||
ProviderListOutput,
|
|
||||||
SkillListOutput,
|
|
||||||
} from "@opencode-ai/client/promise"
|
|
||||||
import type { RunAgent, RunCommand, RunProvider, RunReference } from "./types"
|
|
||||||
|
|
||||||
type CurrentAgent = AgentListOutput["data"][number]
|
|
||||||
type CurrentCommand = CommandListOutput["data"][number]
|
|
||||||
type CurrentSkill = SkillListOutput["data"][number]
|
|
||||||
type CurrentProvider = ProviderListOutput["data"][number]
|
|
||||||
type CurrentModel = ModelListOutput["data"][number]
|
|
||||||
|
|
||||||
function location(directory: string, workspace?: string) {
|
|
||||||
return {
|
|
||||||
location: {
|
|
||||||
directory,
|
|
||||||
workspace,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function defaultCost(model: CurrentModel) {
|
|
||||||
const picked = model.cost.find((cost) => cost.tier === undefined) ?? model.cost[0]
|
|
||||||
if (!picked) {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...picked,
|
|
||||||
input: model.cost.every((cost) => cost.input === 0) ? 0 : picked.input,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function runAgent(input: CurrentAgent): RunAgent {
|
|
||||||
return {
|
|
||||||
id: input.id,
|
|
||||||
name: input.name,
|
|
||||||
description: input.description,
|
|
||||||
mode: input.mode,
|
|
||||||
hidden: input.hidden,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function runCommand(input: CurrentCommand): RunCommand {
|
|
||||||
return {
|
|
||||||
name: input.name,
|
|
||||||
description: input.description,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function runSkill(input: CurrentSkill): RunCommand {
|
|
||||||
return {
|
|
||||||
name: input.id,
|
|
||||||
description: input.description,
|
|
||||||
source: "skill",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function runProviders(providers: CurrentProvider[], models: CurrentModel[]): RunProvider[] {
|
|
||||||
const grouped = new Map<string, RunProvider>()
|
|
||||||
|
|
||||||
for (const provider of providers) {
|
|
||||||
grouped.set(provider.id, {
|
|
||||||
id: provider.id,
|
|
||||||
name: provider.name,
|
|
||||||
models: {},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const model of models) {
|
|
||||||
const provider = grouped.get(model.providerID) ?? {
|
|
||||||
id: model.providerID,
|
|
||||||
name: model.providerID,
|
|
||||||
models: {},
|
|
||||||
}
|
|
||||||
provider.models[model.id] = {
|
|
||||||
id: model.id,
|
|
||||||
providerID: model.providerID,
|
|
||||||
name: model.name,
|
|
||||||
capabilities: model.capabilities,
|
|
||||||
cost: defaultCost(model),
|
|
||||||
limit: model.limit,
|
|
||||||
status: model.status,
|
|
||||||
variants: Object.fromEntries((model.variants ?? []).map((variant) => [variant.id, {}])),
|
|
||||||
}
|
|
||||||
grouped.set(provider.id, provider)
|
|
||||||
}
|
|
||||||
|
|
||||||
return [...grouped.values()]
|
|
||||||
}
|
|
||||||
|
|
||||||
// A location boots its plugins in a deferred background batch after the layer
|
|
||||||
// is built, so first-turn model resolution can observe empty catalog state.
|
|
||||||
// For explicit --model flows, wait for that exact ref to appear before prompt
|
|
||||||
// admission. On timeout, return and let the real execution error surface.
|
|
||||||
export async function waitForCatalogReady(input: {
|
|
||||||
sdk: OpenCodeClient
|
|
||||||
directory: string
|
|
||||||
workspace?: string
|
|
||||||
model: { providerID: string; modelID: string }
|
|
||||||
timeoutMs?: number
|
|
||||||
}) {
|
|
||||||
const deadline = Date.now() + (input.timeoutMs ?? 5_000)
|
|
||||||
while (Date.now() < deadline) {
|
|
||||||
const models = await input.sdk.model
|
|
||||||
.list(location(input.directory, input.workspace))
|
|
||||||
.then((result) => result.data)
|
|
||||||
.catch(() => undefined)
|
|
||||||
if (models?.some((model) => model.providerID === input.model.providerID && model.id === input.model.modelID)) return
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 25))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function waitForDefaultModel(input: {
|
|
||||||
sdk: OpenCodeClient
|
|
||||||
directory: string
|
|
||||||
timeoutMs?: number
|
|
||||||
active?: () => boolean
|
|
||||||
}): Promise<{ providerID: string; modelID: string } | undefined> {
|
|
||||||
const deadline = Date.now() + (input.timeoutMs ?? 5_000)
|
|
||||||
while (Date.now() < deadline && (input.active?.() ?? true)) {
|
|
||||||
const model = await input.sdk.model
|
|
||||||
.default(location(input.directory))
|
|
||||||
.then((result) => result.data)
|
|
||||||
.catch(() => undefined)
|
|
||||||
if (model) return { providerID: model.providerID, modelID: model.id }
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 25))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadRunAgents(sdk: OpenCodeClient, directory: string): Promise<RunAgent[]> {
|
|
||||||
const result = await sdk.agent.list(location(directory))
|
|
||||||
return result.data.map(runAgent)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadRunCommands(sdk: OpenCodeClient, directory: string): Promise<RunCommand[]> {
|
|
||||||
const [commands, skills] = await Promise.all([
|
|
||||||
sdk.command.list(location(directory)),
|
|
||||||
sdk.skill.list(location(directory)),
|
|
||||||
])
|
|
||||||
return [...commands.data.map(runCommand), ...skills.data.filter((skill) => skill.slash !== false).map(runSkill)]
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadRunReferences(sdk: OpenCodeClient, directory: string): Promise<RunReference[]> {
|
|
||||||
const result = await sdk.reference.list(location(directory))
|
|
||||||
return result.data.filter((reference) => !reference.hidden)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadRunProviders(sdk: OpenCodeClient, directory: string): Promise<RunProvider[]> {
|
|
||||||
const [providers, models] = await Promise.all([
|
|
||||||
sdk.provider.list(location(directory)),
|
|
||||||
sdk.model.list(location(directory)),
|
|
||||||
])
|
|
||||||
return runProviders([...providers.data], [...models.data])
|
|
||||||
}
|
|
||||||
@@ -1,573 +0,0 @@
|
|||||||
// Question UI body for the direct-mode footer.
|
|
||||||
//
|
|
||||||
// Renders inside the footer when the reducer pushes a FooterView of type
|
|
||||||
// "question". Supports single-question and multi-question flows:
|
|
||||||
//
|
|
||||||
// Single question: options list with up/down selection, digit shortcuts,
|
|
||||||
// and optional custom text input.
|
|
||||||
//
|
|
||||||
// Multi-question: tabbed interface where each question is a tab, plus a
|
|
||||||
// final "Confirm" tab that shows all answers for review. Tab/shift-tab
|
|
||||||
// or left/right to navigate between questions.
|
|
||||||
//
|
|
||||||
// All state logic lives in question.shared.ts as a pure state machine.
|
|
||||||
// This component just renders it and dispatches keyboard events.
|
|
||||||
/** @jsxImportSource @opentui/solid */
|
|
||||||
import type { TextareaRenderable } from "@opentui/core"
|
|
||||||
import { useKeyboard, useTerminalDimensions } from "@opentui/solid"
|
|
||||||
import { For, Show, createEffect, createMemo, createSignal } from "solid-js"
|
|
||||||
import type { QuestionV2Request } from "@opencode-ai/client/promise"
|
|
||||||
import {
|
|
||||||
createQuestionBodyState,
|
|
||||||
questionConfirm,
|
|
||||||
questionCustom,
|
|
||||||
questionInfo,
|
|
||||||
questionInput,
|
|
||||||
questionMove,
|
|
||||||
questionOther,
|
|
||||||
questionPicked,
|
|
||||||
questionReject,
|
|
||||||
questionSave,
|
|
||||||
questionSelect,
|
|
||||||
questionSetEditing,
|
|
||||||
questionSetSelected,
|
|
||||||
questionSetSubmitting,
|
|
||||||
questionSetTab,
|
|
||||||
questionSingle,
|
|
||||||
questionStoreCustom,
|
|
||||||
questionSubmit,
|
|
||||||
questionSync,
|
|
||||||
questionTabs,
|
|
||||||
questionTotal,
|
|
||||||
} from "./question.shared"
|
|
||||||
import { footerWidthPolicy } from "./footer.width"
|
|
||||||
import type { RunFooterTheme } from "./theme"
|
|
||||||
import type { QuestionReject, QuestionReply } from "./types"
|
|
||||||
|
|
||||||
export function RunQuestionBody(props: {
|
|
||||||
request: QuestionV2Request
|
|
||||||
theme: RunFooterTheme
|
|
||||||
onReply: (input: QuestionReply) => void | Promise<void>
|
|
||||||
onReject: (input: QuestionReject) => void | Promise<void>
|
|
||||||
}) {
|
|
||||||
const dims = useTerminalDimensions()
|
|
||||||
const [state, setState] = createSignal(createQuestionBodyState(props.request.id))
|
|
||||||
const single = createMemo(() => questionSingle(props.request))
|
|
||||||
const confirm = createMemo(() => questionConfirm(props.request, state()))
|
|
||||||
const info = createMemo(() => questionInfo(props.request, state()))
|
|
||||||
const input = createMemo(() => questionInput(state()))
|
|
||||||
const other = createMemo(() => questionOther(props.request, state()))
|
|
||||||
const picked = createMemo(() => questionPicked(state()))
|
|
||||||
const disabled = createMemo(() => state().submitting)
|
|
||||||
const narrow = createMemo(() => footerWidthPolicy(dims().width).dialog.narrow)
|
|
||||||
const verb = createMemo(() => {
|
|
||||||
if (confirm()) {
|
|
||||||
return "submit"
|
|
||||||
}
|
|
||||||
|
|
||||||
if (info()?.multiple) {
|
|
||||||
return "toggle"
|
|
||||||
}
|
|
||||||
|
|
||||||
if (single()) {
|
|
||||||
return "submit"
|
|
||||||
}
|
|
||||||
|
|
||||||
return "confirm"
|
|
||||||
})
|
|
||||||
let area: TextareaRenderable | undefined
|
|
||||||
|
|
||||||
createEffect(() => {
|
|
||||||
setState((prev) => questionSync(prev, props.request.id))
|
|
||||||
})
|
|
||||||
|
|
||||||
const setTab = (tab: number) => {
|
|
||||||
setState((prev) => questionSetTab(prev, tab))
|
|
||||||
}
|
|
||||||
|
|
||||||
const move = (dir: -1 | 1) => {
|
|
||||||
setState((prev) => questionMove(prev, props.request, dir))
|
|
||||||
}
|
|
||||||
|
|
||||||
const beginReply = async (input: QuestionReply) => {
|
|
||||||
setState((prev) => questionSetSubmitting(prev, true))
|
|
||||||
|
|
||||||
try {
|
|
||||||
await props.onReply(input)
|
|
||||||
} catch {
|
|
||||||
setState((prev) => questionSetSubmitting(prev, false))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const beginReject = async (input: QuestionReject) => {
|
|
||||||
setState((prev) => questionSetSubmitting(prev, true))
|
|
||||||
|
|
||||||
try {
|
|
||||||
await props.onReject(input)
|
|
||||||
} catch {
|
|
||||||
setState((prev) => questionSetSubmitting(prev, false))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const saveCustom = () => {
|
|
||||||
const cur = state()
|
|
||||||
const next = questionSave(cur, props.request)
|
|
||||||
if (next.state !== cur) {
|
|
||||||
setState(next.state)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!next.reply) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
void beginReply(next.reply)
|
|
||||||
}
|
|
||||||
|
|
||||||
const choose = (selected: number) => {
|
|
||||||
const base = state()
|
|
||||||
const cur = questionSetSelected(base, selected)
|
|
||||||
const next = questionSelect(cur, props.request)
|
|
||||||
if (next.state !== base) {
|
|
||||||
setState(next.state)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!next.reply) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
void beginReply(next.reply)
|
|
||||||
}
|
|
||||||
|
|
||||||
const mark = (selected: number) => {
|
|
||||||
setState((prev) => questionSetSelected(prev, selected))
|
|
||||||
}
|
|
||||||
|
|
||||||
const select = () => {
|
|
||||||
const cur = state()
|
|
||||||
const next = questionSelect(cur, props.request)
|
|
||||||
if (next.state !== cur) {
|
|
||||||
setState(next.state)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!next.reply) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
void beginReply(next.reply)
|
|
||||||
}
|
|
||||||
|
|
||||||
const submit = () => {
|
|
||||||
void beginReply(questionSubmit(props.request, state()))
|
|
||||||
}
|
|
||||||
|
|
||||||
const reject = () => {
|
|
||||||
void beginReject(questionReject(props.request))
|
|
||||||
}
|
|
||||||
|
|
||||||
useKeyboard((event) => {
|
|
||||||
const cur = state()
|
|
||||||
if (cur.submitting) {
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cur.editing) {
|
|
||||||
if (event.name === "escape") {
|
|
||||||
setState((prev) => questionSetEditing(prev, false))
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!single() && (event.name === "left" || event.name === "h")) {
|
|
||||||
setTab((cur.tab - 1 + questionTabs(props.request)) % questionTabs(props.request))
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!single() && (event.name === "right" || event.name === "l")) {
|
|
||||||
setTab((cur.tab + 1) % questionTabs(props.request))
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!single() && event.name === "tab") {
|
|
||||||
const dir = event.shift ? -1 : 1
|
|
||||||
setTab((cur.tab + dir + questionTabs(props.request)) % questionTabs(props.request))
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (questionConfirm(props.request, cur)) {
|
|
||||||
if (event.name === "return") {
|
|
||||||
submit()
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.name === "escape") {
|
|
||||||
reject()
|
|
||||||
event.preventDefault()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const total = questionTotal(props.request, cur)
|
|
||||||
const max = Math.min(total, 9)
|
|
||||||
const digit = Number(event.name)
|
|
||||||
if (!Number.isNaN(digit) && digit >= 1 && digit <= max) {
|
|
||||||
choose(digit - 1)
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.name === "up" || event.name === "k") {
|
|
||||||
move(-1)
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.name === "down" || event.name === "j") {
|
|
||||||
move(1)
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.name === "return") {
|
|
||||||
select()
|
|
||||||
event.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.name === "escape") {
|
|
||||||
reject()
|
|
||||||
event.preventDefault()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
createEffect(() => {
|
|
||||||
if (!state().editing || !area || area.isDestroyed) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (area.plainText !== input()) {
|
|
||||||
area.setText(input())
|
|
||||||
area.cursorOffset = input().length
|
|
||||||
}
|
|
||||||
|
|
||||||
queueMicrotask(() => {
|
|
||||||
if (!area || area.isDestroyed || !state().editing) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
area.focus()
|
|
||||||
area.cursorOffset = area.plainText.length
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<box width="100%" height="100%" flexDirection="column">
|
|
||||||
<box
|
|
||||||
flexDirection="column"
|
|
||||||
gap={1}
|
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={3}
|
|
||||||
paddingTop={1}
|
|
||||||
flexGrow={1}
|
|
||||||
flexShrink={1}
|
|
||||||
backgroundColor={props.theme.surface}
|
|
||||||
>
|
|
||||||
<Show when={!single()}>
|
|
||||||
<box flexDirection="row" gap={1} paddingLeft={1} flexShrink={0}>
|
|
||||||
<For each={props.request.questions}>
|
|
||||||
{(item, index) => {
|
|
||||||
const active = () => state().tab === index()
|
|
||||||
const answered = () => (state().answers[index()]?.length ?? 0) > 0
|
|
||||||
return (
|
|
||||||
<box
|
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
|
||||||
backgroundColor={active() ? props.theme.highlight : props.theme.surface}
|
|
||||||
onMouseUp={() => {
|
|
||||||
if (!disabled()) setTab(index())
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<text fg={active() ? props.theme.surface : answered() ? props.theme.text : props.theme.muted}>
|
|
||||||
{item.header}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
</For>
|
|
||||||
<box
|
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
|
||||||
backgroundColor={confirm() ? props.theme.highlight : props.theme.surface}
|
|
||||||
onMouseUp={() => {
|
|
||||||
if (!disabled()) setTab(props.request.questions.length)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<text fg={confirm() ? props.theme.surface : props.theme.muted}>Confirm</text>
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
</Show>
|
|
||||||
|
|
||||||
<Show
|
|
||||||
when={!confirm()}
|
|
||||||
fallback={
|
|
||||||
<box width="100%" flexGrow={1} flexShrink={1} paddingLeft={1}>
|
|
||||||
<scrollbox
|
|
||||||
width="100%"
|
|
||||||
height="100%"
|
|
||||||
verticalScrollbarOptions={{
|
|
||||||
trackOptions: {
|
|
||||||
backgroundColor: props.theme.surface,
|
|
||||||
foregroundColor: props.theme.line,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<box width="100%" flexDirection="column" gap={1}>
|
|
||||||
<box paddingLeft={1}>
|
|
||||||
<text fg={props.theme.text}>Review</text>
|
|
||||||
</box>
|
|
||||||
<For each={props.request.questions}>
|
|
||||||
{(item, index) => {
|
|
||||||
const value = () => state().answers[index()]?.join(", ") ?? ""
|
|
||||||
const answered = () => Boolean(value())
|
|
||||||
return (
|
|
||||||
<box paddingLeft={1}>
|
|
||||||
<text wrapMode="word">
|
|
||||||
<span style={{ fg: props.theme.muted }}>{item.header}:</span>{" "}
|
|
||||||
<span style={{ fg: answered() ? props.theme.text : props.theme.error }}>
|
|
||||||
{answered() ? value() : "(not answered)"}
|
|
||||||
</span>
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
</For>
|
|
||||||
</box>
|
|
||||||
</scrollbox>
|
|
||||||
</box>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<box width="100%" flexGrow={1} flexShrink={1} paddingLeft={1} gap={1}>
|
|
||||||
<box>
|
|
||||||
<text fg={props.theme.text} wrapMode="word">
|
|
||||||
{info()?.question}
|
|
||||||
{info()?.multiple ? " (select all that apply)" : ""}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
|
|
||||||
<box flexGrow={1} flexShrink={1}>
|
|
||||||
<scrollbox
|
|
||||||
width="100%"
|
|
||||||
height="100%"
|
|
||||||
verticalScrollbarOptions={{
|
|
||||||
trackOptions: {
|
|
||||||
backgroundColor: props.theme.surface,
|
|
||||||
foregroundColor: props.theme.line,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<box width="100%" flexDirection="column">
|
|
||||||
<For each={info()?.options ?? []}>
|
|
||||||
{(item, index) => {
|
|
||||||
const active = () => state().selected === index()
|
|
||||||
const hit = () => state().answers[state().tab]?.includes(item.label) ?? false
|
|
||||||
return (
|
|
||||||
<box
|
|
||||||
flexDirection="column"
|
|
||||||
gap={0}
|
|
||||||
onMouseOver={() => {
|
|
||||||
if (!disabled()) {
|
|
||||||
mark(index())
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onMouseDown={() => {
|
|
||||||
if (!disabled()) {
|
|
||||||
mark(index())
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onMouseUp={() => {
|
|
||||||
if (!disabled()) {
|
|
||||||
choose(index())
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<box flexDirection="row">
|
|
||||||
<box backgroundColor={active() ? props.theme.line : undefined} paddingRight={1}>
|
|
||||||
<text fg={active() ? props.theme.highlight : props.theme.muted}>{`${index() + 1}.`}</text>
|
|
||||||
</box>
|
|
||||||
<box backgroundColor={active() ? props.theme.line : undefined}>
|
|
||||||
<text
|
|
||||||
fg={active() ? props.theme.highlight : hit() ? props.theme.success : props.theme.text}
|
|
||||||
>
|
|
||||||
{info()?.multiple ? `[${hit() ? "✓" : " "}] ${item.label}` : item.label}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
<Show when={!info()?.multiple}>
|
|
||||||
<text fg={props.theme.success}>{hit() ? " ✓" : ""}</text>
|
|
||||||
</Show>
|
|
||||||
</box>
|
|
||||||
<box paddingLeft={3}>
|
|
||||||
<text fg={props.theme.muted} wrapMode="word">
|
|
||||||
{item.description}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
</For>
|
|
||||||
|
|
||||||
<Show when={questionCustom(props.request, state())}>
|
|
||||||
<box
|
|
||||||
flexDirection="column"
|
|
||||||
gap={0}
|
|
||||||
onMouseOver={() => {
|
|
||||||
if (!disabled()) {
|
|
||||||
mark(info()?.options.length ?? 0)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onMouseDown={() => {
|
|
||||||
if (!disabled()) {
|
|
||||||
mark(info()?.options.length ?? 0)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onMouseUp={() => {
|
|
||||||
if (!disabled()) {
|
|
||||||
choose(info()?.options.length ?? 0)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<box flexDirection="row">
|
|
||||||
<box backgroundColor={other() ? props.theme.line : undefined} paddingRight={1}>
|
|
||||||
<text
|
|
||||||
fg={other() ? props.theme.highlight : props.theme.muted}
|
|
||||||
>{`${(info()?.options.length ?? 0) + 1}.`}</text>
|
|
||||||
</box>
|
|
||||||
<box backgroundColor={other() ? props.theme.line : undefined}>
|
|
||||||
<text
|
|
||||||
fg={other() ? props.theme.highlight : picked() ? props.theme.success : props.theme.text}
|
|
||||||
>
|
|
||||||
{info()?.multiple
|
|
||||||
? `[${picked() ? "✓" : " "}] Type your own answer`
|
|
||||||
: "Type your own answer"}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
<Show when={!info()?.multiple}>
|
|
||||||
<text fg={props.theme.success}>{picked() ? " ✓" : ""}</text>
|
|
||||||
</Show>
|
|
||||||
</box>
|
|
||||||
<Show
|
|
||||||
when={state().editing}
|
|
||||||
fallback={
|
|
||||||
<Show when={input()}>
|
|
||||||
<box paddingLeft={3}>
|
|
||||||
<text fg={props.theme.muted} wrapMode="word">
|
|
||||||
{input()}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
</Show>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<box paddingLeft={3}>
|
|
||||||
<textarea
|
|
||||||
width="100%"
|
|
||||||
minHeight={1}
|
|
||||||
maxHeight={4}
|
|
||||||
wrapMode="word"
|
|
||||||
placeholder="Type your own answer"
|
|
||||||
placeholderColor={props.theme.muted}
|
|
||||||
textColor={props.theme.text}
|
|
||||||
focusedTextColor={props.theme.text}
|
|
||||||
backgroundColor={props.theme.surface}
|
|
||||||
focusedBackgroundColor={props.theme.surface}
|
|
||||||
cursorColor={props.theme.text}
|
|
||||||
focused={!disabled()}
|
|
||||||
onSubmit={saveCustom}
|
|
||||||
onContentChange={() => {
|
|
||||||
if (!area || area.isDestroyed || disabled()) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const text = area.plainText
|
|
||||||
setState((prev) => questionStoreCustom(prev, prev.tab, text))
|
|
||||||
}}
|
|
||||||
ref={(item) => {
|
|
||||||
area = item
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</box>
|
|
||||||
</Show>
|
|
||||||
</box>
|
|
||||||
</Show>
|
|
||||||
</box>
|
|
||||||
</scrollbox>
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
</Show>
|
|
||||||
</box>
|
|
||||||
|
|
||||||
<box
|
|
||||||
flexDirection={narrow() ? "column" : "row"}
|
|
||||||
flexShrink={0}
|
|
||||||
gap={1}
|
|
||||||
paddingLeft={2}
|
|
||||||
paddingRight={3}
|
|
||||||
paddingBottom={1}
|
|
||||||
justifyContent={narrow() ? "flex-start" : "space-between"}
|
|
||||||
alignItems={narrow() ? "flex-start" : "center"}
|
|
||||||
>
|
|
||||||
<Show
|
|
||||||
when={!disabled()}
|
|
||||||
fallback={
|
|
||||||
<text fg={props.theme.muted} wrapMode="word">
|
|
||||||
Waiting for question event...
|
|
||||||
</text>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<box
|
|
||||||
flexDirection={narrow() ? "column" : "row"}
|
|
||||||
gap={narrow() ? 1 : 2}
|
|
||||||
flexShrink={0}
|
|
||||||
width={narrow() ? "100%" : undefined}
|
|
||||||
>
|
|
||||||
<Show
|
|
||||||
when={!state().editing}
|
|
||||||
fallback={
|
|
||||||
<>
|
|
||||||
<text fg={props.theme.text}>
|
|
||||||
enter <span style={{ fg: props.theme.muted }}>save</span>
|
|
||||||
</text>
|
|
||||||
<text fg={props.theme.text}>
|
|
||||||
esc <span style={{ fg: props.theme.muted }}>cancel</span>
|
|
||||||
</text>
|
|
||||||
</>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Show when={!single()}>
|
|
||||||
<text fg={props.theme.text}>
|
|
||||||
{"⇆"} <span style={{ fg: props.theme.muted }}>tab</span>
|
|
||||||
</text>
|
|
||||||
</Show>
|
|
||||||
<Show when={!confirm()}>
|
|
||||||
<text fg={props.theme.text}>
|
|
||||||
{"↑↓"} <span style={{ fg: props.theme.muted }}>select</span>
|
|
||||||
</text>
|
|
||||||
</Show>
|
|
||||||
<text fg={props.theme.text}>
|
|
||||||
enter <span style={{ fg: props.theme.muted }}>{verb()}</span>
|
|
||||||
</text>
|
|
||||||
<text fg={props.theme.text}>
|
|
||||||
esc <span style={{ fg: props.theme.muted }}>dismiss</span>
|
|
||||||
</text>
|
|
||||||
</Show>
|
|
||||||
</box>
|
|
||||||
</Show>
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
export { runMini, validateMiniTerminal, mergeInput as mergeInteractiveInput, type MiniCommandInput } from "./mini"
|
|
||||||
export {
|
|
||||||
runNonInteractive,
|
|
||||||
mergeInput as mergeNonInteractiveInput,
|
|
||||||
pickRunModel,
|
|
||||||
parseRunModel,
|
|
||||||
type RunCommandInput,
|
|
||||||
} from "./run"
|
|
||||||
@@ -1,175 +0,0 @@
|
|||||||
import { Service } from "@opencode-ai/client/effect/service"
|
|
||||||
import { OpenCode, type OpenCodeClient } from "@opencode-ai/client/promise"
|
|
||||||
import { ServerConnection } from "../services/server-connection"
|
|
||||||
import { waitForCatalogReady } from "./catalog.shared"
|
|
||||||
import { INTERACTIVE_INPUT_ERROR, resolveInteractiveStdin } from "./runtime.stdin"
|
|
||||||
import type { RunInput, RunTuiConfig } from "./types"
|
|
||||||
import { readStdin } from "../util/io"
|
|
||||||
import { setTimeout } from "node:timers/promises"
|
|
||||||
|
|
||||||
export type MiniCommandInput = {
|
|
||||||
server: ServerConnection.Resolved
|
|
||||||
continue?: boolean
|
|
||||||
session?: string
|
|
||||||
fork?: boolean
|
|
||||||
model?: string
|
|
||||||
agent?: string
|
|
||||||
prompt?: string
|
|
||||||
replay?: boolean
|
|
||||||
replayLimit?: number
|
|
||||||
demo?: boolean
|
|
||||||
tuiConfig?: RunTuiConfig | Promise<RunTuiConfig>
|
|
||||||
}
|
|
||||||
|
|
||||||
type Session = Awaited<ReturnType<OpenCodeClient["session"]["get"]>>
|
|
||||||
export async function runMini(input: MiniCommandInput) {
|
|
||||||
validate(input)
|
|
||||||
const initialInput = mergeInput(process.stdin.isTTY ? undefined : await readStdin(), input.prompt)
|
|
||||||
const runtimeTask = import("./runtime")
|
|
||||||
const directory = localDirectory()
|
|
||||||
|
|
||||||
try {
|
|
||||||
const sdk = OpenCode.make({
|
|
||||||
baseUrl: input.server.endpoint.url,
|
|
||||||
headers: Service.headers(input.server.endpoint),
|
|
||||||
})
|
|
||||||
const model = parseModel(input.model)
|
|
||||||
let agentTask: Promise<string | undefined> | undefined
|
|
||||||
const resolveAgent = () => {
|
|
||||||
agentTask ??= validateAgent(sdk, directory, input.agent)
|
|
||||||
return agentTask
|
|
||||||
}
|
|
||||||
const resolveSession = async () => {
|
|
||||||
const [agent, selected] = await Promise.all([resolveAgent(), selectSession(sdk, directory, input)])
|
|
||||||
const readyModel =
|
|
||||||
model ?? (selected?.model ? { providerID: selected.model.providerID, modelID: selected.model.id } : undefined)
|
|
||||||
if (readyModel) await waitForCatalogReady({ sdk, directory, model: readyModel })
|
|
||||||
const session = selected ?? (await createSession(sdk, directory, agent, model))
|
|
||||||
return { id: session.id, title: session.title, resume: selected !== undefined }
|
|
||||||
}
|
|
||||||
const create = (
|
|
||||||
_sdk: OpenCodeClient,
|
|
||||||
next: { agent: string | undefined; model: RunInput["model"]; variant: string | undefined },
|
|
||||||
) => createSession(sdk, directory, next.agent, next.model, next.variant)
|
|
||||||
const runtime = await runtimeTask
|
|
||||||
await runtime.runInteractiveDeferredMode({
|
|
||||||
sdk,
|
|
||||||
directory,
|
|
||||||
resolveAgent,
|
|
||||||
session: resolveSession,
|
|
||||||
createSession: create,
|
|
||||||
agent: input.agent,
|
|
||||||
model,
|
|
||||||
variant: undefined,
|
|
||||||
files: [],
|
|
||||||
initialInput,
|
|
||||||
thinking: true,
|
|
||||||
replay: input.replay ?? true,
|
|
||||||
replayLimit: input.replayLimit,
|
|
||||||
demo: input.demo,
|
|
||||||
tuiConfig: input.tuiConfig,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof Error && error.message === INTERACTIVE_INPUT_ERROR) fail(error.message)
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function validateMiniTerminal() {
|
|
||||||
if (!process.stdout.isTTY) fail("opencode mini requires a TTY stdout")
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @internal Exported for testing. */
|
|
||||||
export function mergeInput(piped: string | undefined, prompt: string | undefined) {
|
|
||||||
if (!prompt) return piped || undefined
|
|
||||||
if (!piped) return prompt
|
|
||||||
return piped + "\n" + prompt
|
|
||||||
}
|
|
||||||
|
|
||||||
function validate(input: MiniCommandInput) {
|
|
||||||
validateMiniTerminal()
|
|
||||||
if (input.replayLimit !== undefined && (!Number.isInteger(input.replayLimit) || input.replayLimit <= 0)) {
|
|
||||||
fail("--replay-limit must be a positive integer")
|
|
||||||
}
|
|
||||||
if (input.fork && !input.continue && !input.session) fail("--fork requires --continue or --session")
|
|
||||||
resolveInteractiveStdin().cleanup?.()
|
|
||||||
}
|
|
||||||
|
|
||||||
function localDirectory(): string {
|
|
||||||
const root = process.env.PWD ?? process.cwd()
|
|
||||||
try {
|
|
||||||
process.chdir(root)
|
|
||||||
return process.cwd()
|
|
||||||
} catch {
|
|
||||||
fail(`Failed to change directory to ${root}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseModel(value?: string): RunInput["model"] {
|
|
||||||
if (!value) return
|
|
||||||
const [providerID, ...rest] = value.split("/")
|
|
||||||
const modelID = rest.join("/")
|
|
||||||
if (!providerID || !modelID) fail("--model must use the format provider/model")
|
|
||||||
return { providerID, modelID }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function validateAgent(sdk: OpenCodeClient, directory: string, name?: string) {
|
|
||||||
if (!name) return
|
|
||||||
const deadline = Date.now() + 5_000
|
|
||||||
let agents: Awaited<ReturnType<OpenCodeClient["agent"]["list"]>> | undefined
|
|
||||||
while (Date.now() < deadline) {
|
|
||||||
agents = await sdk.agent.list({ location: { directory } }).catch(() => undefined)
|
|
||||||
const agent = agents?.data.find((item) => item.id === name)
|
|
||||||
if (agent?.mode === "subagent") {
|
|
||||||
warning(`agent "${name}" is a subagent, not a primary agent. Falling back to default agent`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (agent) return name
|
|
||||||
await setTimeout(25)
|
|
||||||
}
|
|
||||||
if (!agents) {
|
|
||||||
warning("failed to list agents. Falling back to default agent")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
warning(`agent "${name}" not found. Falling back to default agent`)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function selectSession(sdk: OpenCodeClient, directory: string, input: MiniCommandInput, preselected?: Session) {
|
|
||||||
const selected =
|
|
||||||
preselected ??
|
|
||||||
(input.session
|
|
||||||
? await sdk.session.get({ sessionID: input.session }).catch(() => undefined)
|
|
||||||
: input.continue
|
|
||||||
? await sdk.session
|
|
||||||
.list({ directory, parentID: null, limit: 1, order: "desc" })
|
|
||||||
.then((result) => result.data[0])
|
|
||||||
: undefined)
|
|
||||||
if (input.session && !selected) fail("Session not found")
|
|
||||||
if (!selected) return
|
|
||||||
if (!input.fork) return selected
|
|
||||||
return sdk.session.fork({ sessionID: selected.id })
|
|
||||||
}
|
|
||||||
|
|
||||||
async function createSession(
|
|
||||||
sdk: OpenCodeClient,
|
|
||||||
directory: string,
|
|
||||||
agent: string | undefined,
|
|
||||||
model: RunInput["model"],
|
|
||||||
variant?: string,
|
|
||||||
): Promise<Session> {
|
|
||||||
if (model) await waitForCatalogReady({ sdk, directory, model })
|
|
||||||
return sdk.session.create({
|
|
||||||
agent,
|
|
||||||
model: model ? { providerID: model.providerID, id: model.modelID, variant } : undefined,
|
|
||||||
location: { directory },
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function warning(message: string) {
|
|
||||||
process.stderr.write(`\x1b[93m\x1b[1m!\x1b[0m ${message}\n`)
|
|
||||||
}
|
|
||||||
|
|
||||||
function fail(message: string): never {
|
|
||||||
process.stderr.write(`\x1b[91m\x1b[1mError: \x1b[0m${message}\n`)
|
|
||||||
process.exit(1)
|
|
||||||
}
|
|
||||||
@@ -1,260 +0,0 @@
|
|||||||
// Pure state machine for the permission UI.
|
|
||||||
//
|
|
||||||
// Lives outside the JSX component so it can be tested independently. The
|
|
||||||
// machine has three stages:
|
|
||||||
//
|
|
||||||
// permission → initial view with Allow once / Always / Reject options
|
|
||||||
// always → confirmation step (Confirm / Cancel)
|
|
||||||
// reject → text input for rejection message
|
|
||||||
//
|
|
||||||
// permissionRun() is the main transition: given the current state and the
|
|
||||||
// selected option, it returns a new state and optionally a PermissionReply
|
|
||||||
// to send to the SDK. The component calls this on enter/click.
|
|
||||||
//
|
|
||||||
// permissionInfo() extracts display info (icon, title, lines, diff) from
|
|
||||||
// the request, delegating to tool.ts for tool-specific formatting.
|
|
||||||
import type { PermissionV2Request } from "@opencode-ai/client/promise"
|
|
||||||
import type { PermissionReply } from "./types"
|
|
||||||
import { toolPath, toolPermissionInfo } from "./tool"
|
|
||||||
|
|
||||||
type Dict = Record<string, unknown>
|
|
||||||
|
|
||||||
export type PermissionStage = "permission" | "always" | "reject"
|
|
||||||
export type PermissionOption = "once" | "always" | "reject" | "confirm" | "cancel"
|
|
||||||
|
|
||||||
export type PermissionBodyState = {
|
|
||||||
requestID: string
|
|
||||||
stage: PermissionStage
|
|
||||||
selected: PermissionOption
|
|
||||||
message: string
|
|
||||||
submitting: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PermissionInfo = {
|
|
||||||
icon: string
|
|
||||||
title: string
|
|
||||||
lines: string[]
|
|
||||||
diff?: string
|
|
||||||
file?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PermissionStep = {
|
|
||||||
state: PermissionBodyState
|
|
||||||
reply?: PermissionReply
|
|
||||||
}
|
|
||||||
|
|
||||||
function dict(v: unknown): Dict {
|
|
||||||
if (!v || typeof v !== "object" || Array.isArray(v)) {
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ...v }
|
|
||||||
}
|
|
||||||
|
|
||||||
function text(v: unknown): string {
|
|
||||||
return typeof v === "string" ? v : ""
|
|
||||||
}
|
|
||||||
|
|
||||||
function data(request: PermissionV2Request): Dict {
|
|
||||||
const meta = dict(request.metadata)
|
|
||||||
return {
|
|
||||||
...meta,
|
|
||||||
...dict(meta.input),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function patterns(request: PermissionV2Request): string[] {
|
|
||||||
return request.resources.filter((item): item is string => typeof item === "string")
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createPermissionBodyState(requestID: string): PermissionBodyState {
|
|
||||||
return {
|
|
||||||
requestID,
|
|
||||||
stage: "permission",
|
|
||||||
selected: "once",
|
|
||||||
message: "",
|
|
||||||
submitting: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionOptions(stage: PermissionStage): PermissionOption[] {
|
|
||||||
if (stage === "permission") {
|
|
||||||
return ["once", "always", "reject"]
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stage === "always") {
|
|
||||||
return ["confirm", "cancel"]
|
|
||||||
}
|
|
||||||
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionInfo(request: PermissionV2Request): PermissionInfo {
|
|
||||||
const pats = patterns(request)
|
|
||||||
const input = data(request)
|
|
||||||
const info = toolPermissionInfo(request.action, input, dict(request.metadata), pats)
|
|
||||||
if (info) {
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
if (request.action === "external_directory") {
|
|
||||||
const meta = dict(request.metadata)
|
|
||||||
const raw = text(meta.parentDir) || text(meta.filepath) || pats[0] || ""
|
|
||||||
const dir = raw.includes("*") ? raw.slice(0, raw.indexOf("*")).replace(/[\\/]+$/, "") : raw
|
|
||||||
return {
|
|
||||||
icon: "←",
|
|
||||||
title: `Access external directory ${toolPath(dir, { home: true })}`,
|
|
||||||
lines: pats.map((item) => `- ${item}`),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (request.action === "doom_loop") {
|
|
||||||
return {
|
|
||||||
icon: "⟳",
|
|
||||||
title: "Continue after repeated failures",
|
|
||||||
lines: ["This keeps the session running despite repeated failures."],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
icon: "⚙",
|
|
||||||
title: `Call tool ${request.action}`,
|
|
||||||
lines: [`Tool: ${request.action}`],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionAlwaysLines(request: PermissionV2Request): string[] {
|
|
||||||
const save = request.save ?? []
|
|
||||||
if (save.length === 1 && save[0] === "*") {
|
|
||||||
return [`This will allow ${request.action} until OpenCode is restarted.`]
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
"This will allow the following patterns until OpenCode is restarted.",
|
|
||||||
...save.map((item) => `- ${item}`),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionLabel(option: PermissionOption): string {
|
|
||||||
if (option === "once") return "Allow once"
|
|
||||||
if (option === "always") return "Allow always"
|
|
||||||
if (option === "reject") return "Reject"
|
|
||||||
if (option === "confirm") return "Confirm"
|
|
||||||
return "Cancel"
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionReply(requestID: string, reply: PermissionReply["reply"], message?: string): PermissionReply {
|
|
||||||
return {
|
|
||||||
requestID,
|
|
||||||
reply,
|
|
||||||
...(message && message.trim() ? { message: message.trim() } : {}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionShift(
|
|
||||||
state: PermissionBodyState,
|
|
||||||
dir: -1 | 1,
|
|
||||||
list = permissionOptions(state.stage),
|
|
||||||
): PermissionBodyState {
|
|
||||||
if (list.length === 0) {
|
|
||||||
return state
|
|
||||||
}
|
|
||||||
|
|
||||||
const idx = Math.max(0, list.indexOf(state.selected))
|
|
||||||
const selected = list[(idx + dir + list.length) % list.length]
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
selected,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionHover(state: PermissionBodyState, option: PermissionOption): PermissionBodyState {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
selected: option,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionRun(state: PermissionBodyState, requestID: string, option: PermissionOption): PermissionStep {
|
|
||||||
if (state.submitting) {
|
|
||||||
return { state }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state.stage === "permission") {
|
|
||||||
if (option === "always") {
|
|
||||||
return {
|
|
||||||
state: {
|
|
||||||
...state,
|
|
||||||
stage: "always",
|
|
||||||
selected: "confirm",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (option === "reject") {
|
|
||||||
return {
|
|
||||||
state: {
|
|
||||||
...state,
|
|
||||||
stage: "reject",
|
|
||||||
selected: "reject",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
state,
|
|
||||||
reply: permissionReply(requestID, "once"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state.stage !== "always") {
|
|
||||||
return { state }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (option === "cancel") {
|
|
||||||
return {
|
|
||||||
state: {
|
|
||||||
...state,
|
|
||||||
stage: "permission",
|
|
||||||
selected: "always",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
state,
|
|
||||||
reply: permissionReply(requestID, "always"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionReject(state: PermissionBodyState, requestID: string): PermissionReply | undefined {
|
|
||||||
if (state.submitting) {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
return permissionReply(requestID, "reject", state.message)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionCancel(state: PermissionBodyState): PermissionBodyState {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
stage: "permission",
|
|
||||||
selected: "reject",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function permissionEscape(state: PermissionBodyState): PermissionBodyState {
|
|
||||||
if (state.stage === "always") {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
stage: "permission",
|
|
||||||
selected: "always",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
stage: "reject",
|
|
||||||
selected: "reject",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
import type { RunPromptPart } from "./types"
|
|
||||||
|
|
||||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
|
|
||||||
|
|
||||||
export function resolveEditorSlashValue(text: string) {
|
|
||||||
const head = slashHead(text)
|
|
||||||
if (!head || head.name.toLowerCase() !== "editor") {
|
|
||||||
return text
|
|
||||||
}
|
|
||||||
|
|
||||||
return head.arguments
|
|
||||||
}
|
|
||||||
|
|
||||||
export function realignEditorPromptParts(content: string, parts: RunPromptPart[]): RunPromptPart[] {
|
|
||||||
const matches = new Map<number, Mention | undefined>()
|
|
||||||
const used: Array<{ start: number; end: number }> = []
|
|
||||||
|
|
||||||
for (const [index, part] of parts.entries()) {
|
|
||||||
if (part.type !== "file" && part.type !== "agent") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
const text = promptPartText(part)
|
|
||||||
if (!text) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
const start = findPromptPartIndex(content, text, used, promptPartStart(part))
|
|
||||||
if (start === -1) {
|
|
||||||
matches.set(index, undefined)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
const end = start + text.length
|
|
||||||
used.push({ start, end })
|
|
||||||
matches.set(index, updatePromptPart(part, start, end, text))
|
|
||||||
}
|
|
||||||
|
|
||||||
const next: RunPromptPart[] = []
|
|
||||||
for (const [index, part] of parts.entries()) {
|
|
||||||
if (part.type !== "file" && part.type !== "agent") {
|
|
||||||
next.push(part)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!promptPartText(part)) {
|
|
||||||
next.push(part)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
const match = matches.get(index)
|
|
||||||
if (match) {
|
|
||||||
next.push(match)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return next
|
|
||||||
}
|
|
||||||
|
|
||||||
function slashHead(text: string) {
|
|
||||||
if (!text.startsWith("/")) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = 1; i < text.length; i++) {
|
|
||||||
switch (text[i]) {
|
|
||||||
case " ":
|
|
||||||
case "\t":
|
|
||||||
case "\n":
|
|
||||||
return {
|
|
||||||
name: text.slice(1, i),
|
|
||||||
arguments: text.slice(i + 1),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: text.slice(1),
|
|
||||||
arguments: "",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function promptPartText(part: Mention) {
|
|
||||||
if (part.type === "agent") {
|
|
||||||
return part.source?.value
|
|
||||||
}
|
|
||||||
|
|
||||||
return part.source?.text.value
|
|
||||||
}
|
|
||||||
|
|
||||||
function promptPartStart(part: Mention) {
|
|
||||||
if (part.type === "agent") {
|
|
||||||
return part.source?.start ?? Number.POSITIVE_INFINITY
|
|
||||||
}
|
|
||||||
|
|
||||||
return part.source?.text.start ?? Number.POSITIVE_INFINITY
|
|
||||||
}
|
|
||||||
|
|
||||||
function findPromptPartIndex(content: string, text: string, used: Array<{ start: number; end: number }>, hint: number) {
|
|
||||||
let searchFrom = 0
|
|
||||||
let best = -1
|
|
||||||
let distance = Number.POSITIVE_INFINITY
|
|
||||||
const hinted = Number.isFinite(hint)
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const start = content.indexOf(text, searchFrom)
|
|
||||||
if (start === -1) {
|
|
||||||
return best
|
|
||||||
}
|
|
||||||
|
|
||||||
const end = start + text.length
|
|
||||||
searchFrom = start + 1
|
|
||||||
if (used.some((range) => start < range.end && end > range.start)) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!hinted) {
|
|
||||||
return start
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextDistance = Math.abs(start - hint)
|
|
||||||
if (nextDistance < distance) {
|
|
||||||
best = start
|
|
||||||
distance = nextDistance
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function updatePromptPart(part: Mention, start: number, end: number, text: string): Mention {
|
|
||||||
if (part.type === "agent") {
|
|
||||||
return {
|
|
||||||
...part,
|
|
||||||
source: {
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
value: text,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!part.source?.text) {
|
|
||||||
return part
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...part,
|
|
||||||
source: {
|
|
||||||
...part.source,
|
|
||||||
text: {
|
|
||||||
...part.source.text,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
value: text,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,340 +0,0 @@
|
|||||||
// Pure state machine for the question UI.
|
|
||||||
//
|
|
||||||
// Supports both single-question and multi-question flows. Single questions
|
|
||||||
// submit immediately on selection. Multi-question flows use tabs and a
|
|
||||||
// final confirmation step.
|
|
||||||
//
|
|
||||||
// State transitions:
|
|
||||||
// questionSelect → picks an option (single: submits, multi: toggles/advances)
|
|
||||||
// questionSave → saves custom text input
|
|
||||||
// questionMove → arrow key navigation through options
|
|
||||||
// questionSetTab → tab navigation between questions
|
|
||||||
// questionSubmit → builds the final QuestionReply with all answers
|
|
||||||
//
|
|
||||||
// Custom answers: if a question has custom=true, an extra "Type your own
|
|
||||||
// answer" option appears. Selecting it enters editing mode with a text field.
|
|
||||||
import type { QuestionV2Info, QuestionV2Request } from "@opencode-ai/client/promise"
|
|
||||||
import type { QuestionReject, QuestionReply } from "./types"
|
|
||||||
|
|
||||||
export type QuestionBodyState = {
|
|
||||||
requestID: string
|
|
||||||
tab: number
|
|
||||||
answers: string[][]
|
|
||||||
custom: string[]
|
|
||||||
selected: number
|
|
||||||
editing: boolean
|
|
||||||
submitting: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export type QuestionStep = {
|
|
||||||
state: QuestionBodyState
|
|
||||||
reply?: QuestionReply
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createQuestionBodyState(requestID: string): QuestionBodyState {
|
|
||||||
return {
|
|
||||||
requestID,
|
|
||||||
tab: 0,
|
|
||||||
answers: [],
|
|
||||||
custom: [],
|
|
||||||
selected: 0,
|
|
||||||
editing: false,
|
|
||||||
submitting: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSync(state: QuestionBodyState, requestID: string): QuestionBodyState {
|
|
||||||
if (state.requestID === requestID) {
|
|
||||||
return state
|
|
||||||
}
|
|
||||||
|
|
||||||
return createQuestionBodyState(requestID)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSingle(request: QuestionV2Request): boolean {
|
|
||||||
return request.questions.length === 1 && request.questions[0]?.multiple !== true
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionTabs(request: QuestionV2Request): number {
|
|
||||||
return questionSingle(request) ? 1 : request.questions.length + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionConfirm(request: QuestionV2Request, state: QuestionBodyState): boolean {
|
|
||||||
return !questionSingle(request) && state.tab === request.questions.length
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionInfo(request: QuestionV2Request, state: QuestionBodyState): QuestionV2Info | undefined {
|
|
||||||
return request.questions[state.tab]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionCustom(request: QuestionV2Request, state: QuestionBodyState): boolean {
|
|
||||||
return questionInfo(request, state)?.custom !== false
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionInput(state: QuestionBodyState): string {
|
|
||||||
return state.custom[state.tab] ?? ""
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionPicked(state: QuestionBodyState): boolean {
|
|
||||||
const value = questionInput(state)
|
|
||||||
if (!value) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return state.answers[state.tab]?.includes(value) ?? false
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionOther(request: QuestionV2Request, state: QuestionBodyState): boolean {
|
|
||||||
const info = questionInfo(request, state)
|
|
||||||
if (!info || info.custom === false) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return state.selected === info.options.length
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionTotal(request: QuestionV2Request, state: QuestionBodyState): number {
|
|
||||||
const info = questionInfo(request, state)
|
|
||||||
if (!info) {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
return info.options.length + (questionCustom(request, state) ? 1 : 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionAnswers(state: QuestionBodyState, count: number): string[][] {
|
|
||||||
return Array.from({ length: count }, (_, idx) => state.answers[idx] ?? [])
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSetTab(state: QuestionBodyState, tab: number): QuestionBodyState {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
tab,
|
|
||||||
selected: 0,
|
|
||||||
editing: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSetSelected(state: QuestionBodyState, selected: number): QuestionBodyState {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
selected,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSetEditing(state: QuestionBodyState, editing: boolean): QuestionBodyState {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
editing,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSetSubmitting(state: QuestionBodyState, submitting: boolean): QuestionBodyState {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
submitting,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function storeAnswers(state: QuestionBodyState, tab: number, list: string[]): QuestionBodyState {
|
|
||||||
const answers = [...state.answers]
|
|
||||||
answers[tab] = list
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
answers,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionStoreCustom(state: QuestionBodyState, tab: number, text: string): QuestionBodyState {
|
|
||||||
const custom = [...state.custom]
|
|
||||||
custom[tab] = text
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
custom,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function questionPick(
|
|
||||||
state: QuestionBodyState,
|
|
||||||
request: QuestionV2Request,
|
|
||||||
answer: string,
|
|
||||||
custom = false,
|
|
||||||
): QuestionStep {
|
|
||||||
const answers = [...state.answers]
|
|
||||||
answers[state.tab] = [answer]
|
|
||||||
let next: QuestionBodyState = {
|
|
||||||
...state,
|
|
||||||
answers,
|
|
||||||
editing: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
if (custom) {
|
|
||||||
const list = [...state.custom]
|
|
||||||
list[state.tab] = answer
|
|
||||||
next = {
|
|
||||||
...next,
|
|
||||||
custom: list,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (questionSingle(request)) {
|
|
||||||
return {
|
|
||||||
state: next,
|
|
||||||
reply: {
|
|
||||||
requestID: request.id,
|
|
||||||
answers: [[answer]],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
state: questionSetTab(next, state.tab + 1),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function questionToggle(state: QuestionBodyState, answer: string): QuestionBodyState {
|
|
||||||
const list = [...(state.answers[state.tab] ?? [])]
|
|
||||||
const idx = list.indexOf(answer)
|
|
||||||
if (idx === -1) {
|
|
||||||
list.push(answer)
|
|
||||||
} else {
|
|
||||||
list.splice(idx, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
return storeAnswers(state, state.tab, list)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionMove(state: QuestionBodyState, request: QuestionV2Request, dir: -1 | 1): QuestionBodyState {
|
|
||||||
const total = questionTotal(request, state)
|
|
||||||
if (total === 0) {
|
|
||||||
return state
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
selected: (state.selected + dir + total) % total,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSelect(state: QuestionBodyState, request: QuestionV2Request): QuestionStep {
|
|
||||||
const info = questionInfo(request, state)
|
|
||||||
if (!info) {
|
|
||||||
return { state }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (questionOther(request, state)) {
|
|
||||||
if (!info.multiple) {
|
|
||||||
return {
|
|
||||||
state: questionSetEditing(state, true),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const value = questionInput(state)
|
|
||||||
if (value && questionPicked(state)) {
|
|
||||||
return {
|
|
||||||
state: questionToggle(state, value),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
state: questionSetEditing(state, true),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const option = info.options[state.selected]
|
|
||||||
if (!option) {
|
|
||||||
return { state }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (info.multiple) {
|
|
||||||
return {
|
|
||||||
state: questionToggle(state, option.label),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return questionPick(state, request, option.label)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSave(state: QuestionBodyState, request: QuestionV2Request): QuestionStep {
|
|
||||||
const info = questionInfo(request, state)
|
|
||||||
if (!info) {
|
|
||||||
return { state }
|
|
||||||
}
|
|
||||||
|
|
||||||
const value = questionInput(state).trim()
|
|
||||||
const prev = state.custom[state.tab]
|
|
||||||
if (!value) {
|
|
||||||
if (!prev) {
|
|
||||||
return {
|
|
||||||
state: questionSetEditing(state, false),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const next = questionStoreCustom(state, state.tab, "")
|
|
||||||
return {
|
|
||||||
state: questionSetEditing(
|
|
||||||
storeAnswers(
|
|
||||||
next,
|
|
||||||
state.tab,
|
|
||||||
(state.answers[state.tab] ?? []).filter((item) => item !== prev),
|
|
||||||
),
|
|
||||||
false,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (info.multiple) {
|
|
||||||
const answers = [...(state.answers[state.tab] ?? [])]
|
|
||||||
if (prev) {
|
|
||||||
const idx = answers.indexOf(prev)
|
|
||||||
if (idx !== -1) {
|
|
||||||
answers.splice(idx, 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!answers.includes(value)) {
|
|
||||||
answers.push(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
const next = questionStoreCustom(state, state.tab, value)
|
|
||||||
return {
|
|
||||||
state: questionSetEditing(storeAnswers(next, state.tab, answers), false),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return questionPick(state, request, value, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionSubmit(request: QuestionV2Request, state: QuestionBodyState): QuestionReply {
|
|
||||||
return {
|
|
||||||
requestID: request.id,
|
|
||||||
answers: questionAnswers(state, request.questions.length),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionReject(request: QuestionV2Request): QuestionReject {
|
|
||||||
return {
|
|
||||||
requestID: request.id,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function questionHint(request: QuestionV2Request, state: QuestionBodyState): string {
|
|
||||||
if (state.submitting) {
|
|
||||||
return "Waiting for question event..."
|
|
||||||
}
|
|
||||||
|
|
||||||
if (questionConfirm(request, state)) {
|
|
||||||
return "enter submit esc dismiss"
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state.editing) {
|
|
||||||
return "enter save esc cancel"
|
|
||||||
}
|
|
||||||
|
|
||||||
const info = questionInfo(request, state)
|
|
||||||
if (questionSingle(request)) {
|
|
||||||
return `↑↓ select enter ${info?.multiple ? "toggle" : "submit"} esc dismiss`
|
|
||||||
}
|
|
||||||
|
|
||||||
return `⇆ tab ↑↓ select enter ${info?.multiple ? "toggle" : "confirm"} esc dismiss`
|
|
||||||
}
|
|
||||||
@@ -1,166 +0,0 @@
|
|||||||
// Boot-time resolution for direct interactive mode.
|
|
||||||
//
|
|
||||||
// These functions run concurrently at startup to gather everything the runtime
|
|
||||||
// needs before the first frame: TUI keymap config, diff display style,
|
|
||||||
// model variant list with context limits, and session history for the prompt
|
|
||||||
// history ring. All are async because they read config or hit the SDK, but
|
|
||||||
// none block each other.
|
|
||||||
import { Context, Effect, Layer } from "effect"
|
|
||||||
import { resolve } from "@opencode-ai/tui/config/v1"
|
|
||||||
import { makeGlobalNode } from "@opencode-ai/core/effect/app-node"
|
|
||||||
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
|
|
||||||
import { makeRuntime } from "@opencode-ai/core/effect/runtime"
|
|
||||||
import { loadRunProviders } from "./catalog.shared"
|
|
||||||
import { resolveCurrentSession, sessionHistory } from "./session.shared"
|
|
||||||
import type { RunDiffStyle, RunInput, RunPrompt, RunProvider, RunTuiConfig } from "./types"
|
|
||||||
import { pickVariant } from "./variant.shared"
|
|
||||||
|
|
||||||
export type ModelInfo = {
|
|
||||||
providers: RunProvider[]
|
|
||||||
variants: string[]
|
|
||||||
limits: Record<string, number>
|
|
||||||
}
|
|
||||||
|
|
||||||
export type SessionInfo = {
|
|
||||||
first: boolean
|
|
||||||
history: RunPrompt[]
|
|
||||||
model?: NonNullable<RunInput["model"]>
|
|
||||||
variant: string | undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
type BootService = {
|
|
||||||
readonly resolveModelInfo: (
|
|
||||||
sdk: RunInput["sdk"],
|
|
||||||
directory: string,
|
|
||||||
model: RunInput["model"],
|
|
||||||
) => Effect.Effect<ModelInfo>
|
|
||||||
readonly resolveSessionInfo: (
|
|
||||||
sdk: RunInput["sdk"],
|
|
||||||
sessionID: string,
|
|
||||||
model: RunInput["model"],
|
|
||||||
) => Effect.Effect<SessionInfo>
|
|
||||||
}
|
|
||||||
|
|
||||||
class Service extends Context.Service<Service, BootService>()("@opencode/RunBoot") {}
|
|
||||||
|
|
||||||
function emptyModelInfo(): ModelInfo {
|
|
||||||
return {
|
|
||||||
providers: [],
|
|
||||||
variants: [],
|
|
||||||
limits: {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function emptySessionInfo(): SessionInfo {
|
|
||||||
return {
|
|
||||||
first: true,
|
|
||||||
history: [],
|
|
||||||
variant: undefined,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function defaultRunTuiConfig(): RunTuiConfig {
|
|
||||||
return {
|
|
||||||
...resolve({}, { terminalSuspend: process.platform !== "win32" }),
|
|
||||||
diff_style: "auto",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const layer = Layer.effect(
|
|
||||||
Service,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const resolveModelInfo = Effect.fn("RunBoot.resolveModelInfo")(function* (
|
|
||||||
sdk: RunInput["sdk"],
|
|
||||||
directory: string,
|
|
||||||
model: RunInput["model"],
|
|
||||||
) {
|
|
||||||
const providers = yield* Effect.promise(() => loadRunProviders(sdk, directory))
|
|
||||||
const limits = Object.fromEntries(
|
|
||||||
providers.flatMap((provider) =>
|
|
||||||
Object.entries(provider.models ?? {}).flatMap(([modelID, info]) => {
|
|
||||||
const limit = info?.limit?.context
|
|
||||||
if (typeof limit !== "number" || limit <= 0) {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
return [[`${provider.id}/${modelID}`, limit] as const]
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
if (!model) {
|
|
||||||
return {
|
|
||||||
providers,
|
|
||||||
variants: [],
|
|
||||||
limits,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const info = providers.find((item) => item.id === model.providerID)?.models?.[model.modelID]
|
|
||||||
return {
|
|
||||||
providers,
|
|
||||||
variants: Object.keys(info?.variants ?? {}),
|
|
||||||
limits,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const resolveSessionInfo = Effect.fn("RunBoot.resolveSessionInfo")(function* (
|
|
||||||
sdk: RunInput["sdk"],
|
|
||||||
sessionID: string,
|
|
||||||
model: RunInput["model"],
|
|
||||||
) {
|
|
||||||
const session = yield* Effect.promise(() => resolveCurrentSession(sdk, sessionID).catch(() => undefined))
|
|
||||||
if (!session) {
|
|
||||||
return emptySessionInfo()
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
first: session.first,
|
|
||||||
history: sessionHistory(session),
|
|
||||||
model: session.model,
|
|
||||||
variant: pickVariant(model ?? session.model, session),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return Service.of({
|
|
||||||
resolveModelInfo,
|
|
||||||
resolveSessionInfo,
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
const node = makeGlobalNode({ service: Service, layer, deps: [] })
|
|
||||||
const runtime = makeRuntime(Service, LayerNode.compile(node))
|
|
||||||
|
|
||||||
// Fetches available variants and context limits for every provider/model pair.
|
|
||||||
export async function resolveModelInfo(
|
|
||||||
sdk: RunInput["sdk"],
|
|
||||||
directory: string,
|
|
||||||
model: RunInput["model"],
|
|
||||||
): Promise<ModelInfo> {
|
|
||||||
return runtime.runPromise((svc) => svc.resolveModelInfo(sdk, directory, model)).catch(() => emptyModelInfo())
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveModelInfoStrict(sdk: RunInput["sdk"], directory: string, model: RunInput["model"]) {
|
|
||||||
return runtime.runPromise((svc) => svc.resolveModelInfo(sdk, directory, model))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetches session messages to determine if this is the first turn and build prompt history.
|
|
||||||
export async function resolveSessionInfo(
|
|
||||||
sdk: RunInput["sdk"],
|
|
||||||
sessionID: string,
|
|
||||||
model: RunInput["model"],
|
|
||||||
): Promise<SessionInfo> {
|
|
||||||
return runtime.runPromise((svc) => svc.resolveSessionInfo(sdk, sessionID, model)).catch(() => emptySessionInfo())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reads TUI config once for direct mode keymap setup and display preferences.
|
|
||||||
export async function resolveRunTuiConfig(
|
|
||||||
config?: RunTuiConfig | Promise<RunTuiConfig>,
|
|
||||||
): Promise<RunTuiConfig> {
|
|
||||||
return Promise.resolve(config).then((value) => value ?? defaultRunTuiConfig()).catch(() => defaultRunTuiConfig())
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function resolveDiffStyle(config?: RunTuiConfig | Promise<RunTuiConfig>): Promise<RunDiffStyle> {
|
|
||||||
return resolveRunTuiConfig(config).then((value) => value.diff_style ?? "auto")
|
|
||||||
}
|
|
||||||
@@ -1,389 +0,0 @@
|
|||||||
// Lifecycle management for the split-footer renderer.
|
|
||||||
//
|
|
||||||
// Creates the OpenTUI CliRenderer in split-footer mode, resolves the theme
|
|
||||||
// from the terminal palette, writes the entry splash to scrollback, and
|
|
||||||
// constructs the RunFooter. Returns a Lifecycle handle whose close() writes
|
|
||||||
// the exit splash and tears everything down in the right order:
|
|
||||||
// footer.close → footer.destroy → renderer shutdown.
|
|
||||||
//
|
|
||||||
// Also wires SIGINT so Ctrl-c clears a live prompt draft first, then falls
|
|
||||||
// back to the usual two-press exit sequence through RunFooter.requestExit().
|
|
||||||
import path from "path"
|
|
||||||
import { CliRenderEvents, createCliRenderer, type CliRenderer, type ScrollbackWriter } from "@opentui/core"
|
|
||||||
import { Global } from "@opencode-ai/core/global"
|
|
||||||
import { isDefaultTitle } from "@opencode-ai/tui/util/session"
|
|
||||||
import { Locale } from "@opencode-ai/tui/util/locale"
|
|
||||||
import { resolveInteractiveStdin } from "./runtime.stdin"
|
|
||||||
import { entrySplash, exitSplash, splashMeta } from "./splash"
|
|
||||||
import { resolveRunTheme } from "./theme"
|
|
||||||
import type {
|
|
||||||
FooterApi,
|
|
||||||
PermissionReply,
|
|
||||||
QuestionReject,
|
|
||||||
QuestionReply,
|
|
||||||
RunAgent,
|
|
||||||
RunInput,
|
|
||||||
RunPrompt,
|
|
||||||
RunReference,
|
|
||||||
RunTuiConfig,
|
|
||||||
} from "./types"
|
|
||||||
import { formatModelLabel } from "./variant.shared"
|
|
||||||
|
|
||||||
const FOOTER_HEIGHT = 4
|
|
||||||
|
|
||||||
type SplashState = {
|
|
||||||
entry: boolean
|
|
||||||
exit: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
type CycleResult = {
|
|
||||||
modelLabel?: string
|
|
||||||
status?: string
|
|
||||||
variant?: string | undefined
|
|
||||||
variants?: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
type FooterLabels = {
|
|
||||||
agentLabel: string
|
|
||||||
modelLabel: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type LifecycleInput = {
|
|
||||||
directory: string
|
|
||||||
findFiles: (query: string) => Promise<string[]>
|
|
||||||
agents: RunAgent[]
|
|
||||||
references: RunReference[]
|
|
||||||
sessionID: string
|
|
||||||
sessionTitle?: string
|
|
||||||
getSessionID?: () => string | undefined
|
|
||||||
first: boolean
|
|
||||||
history: RunPrompt[]
|
|
||||||
agent: string | undefined
|
|
||||||
model: RunInput["model"]
|
|
||||||
variant: string | undefined
|
|
||||||
tuiConfig: RunTuiConfig | Promise<RunTuiConfig>
|
|
||||||
onPermissionReply: (input: PermissionReply) => void | Promise<void>
|
|
||||||
onQuestionReply: (input: QuestionReply) => void | Promise<void>
|
|
||||||
onQuestionReject: (input: QuestionReject) => void | Promise<void>
|
|
||||||
onCycleVariant?: () => CycleResult | void
|
|
||||||
onModelSelect?: (model: NonNullable<RunInput["model"]>) => CycleResult | void | Promise<CycleResult | void>
|
|
||||||
onVariantSelect?: (variant: string | undefined) => CycleResult | void | Promise<CycleResult | void>
|
|
||||||
onInterrupt?: () => void
|
|
||||||
onBackground?: () => void
|
|
||||||
onSubagentSelect?: (sessionID: string | undefined) => void
|
|
||||||
onSubagentInterrupt?: (sessionID: string) => void
|
|
||||||
}
|
|
||||||
|
|
||||||
export type Lifecycle = {
|
|
||||||
footer: FooterApi
|
|
||||||
onResize(fn: () => void): () => void
|
|
||||||
refreshTheme(): void
|
|
||||||
resetForReplay(input: { sessionTitle?: string; sessionID?: string; history: RunPrompt[] }): Promise<void>
|
|
||||||
close(input: { showExit: boolean; sessionTitle?: string; sessionID?: string; history?: RunPrompt[] }): Promise<void>
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gracefully tears down the renderer. Order matters: switch external output
|
|
||||||
// back to passthrough before leaving split-footer mode, so pending stdout
|
|
||||||
// doesn't get captured into the now-dead scrollback pipeline.
|
|
||||||
function shutdown(renderer: CliRenderer): void {
|
|
||||||
if (renderer.isDestroyed) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (renderer.externalOutputMode === "capture-stdout") {
|
|
||||||
renderer.externalOutputMode = "passthrough"
|
|
||||||
}
|
|
||||||
|
|
||||||
if (renderer.screenMode === "split-footer") {
|
|
||||||
renderer.screenMode = "main-screen"
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!renderer.isDestroyed) {
|
|
||||||
renderer.destroy()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function splashInfo(title: string | undefined, history: RunPrompt[]) {
|
|
||||||
if (title && !isDefaultTitle(title)) {
|
|
||||||
return {
|
|
||||||
title,
|
|
||||||
showSession: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const next = history.find((item) => item.text.trim().length > 0)
|
|
||||||
return {
|
|
||||||
title: next?.text ?? title,
|
|
||||||
showSession: !!next,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function footerLabels(input: Pick<RunInput, "agent" | "model" | "variant">): FooterLabels {
|
|
||||||
const agentLabel = Locale.titlecase(input.agent ?? "build")
|
|
||||||
return {
|
|
||||||
agentLabel,
|
|
||||||
modelLabel: input.model ? formatModelLabel(input.model, input.variant) : "",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function directoryLabel(directory: string) {
|
|
||||||
const resolved = path.resolve(directory)
|
|
||||||
const display =
|
|
||||||
resolved === Global.Path.home
|
|
||||||
? "~"
|
|
||||||
: resolved.startsWith(`${Global.Path.home}${path.sep}`)
|
|
||||||
? resolved.replace(Global.Path.home, "~")
|
|
||||||
: resolved
|
|
||||||
return display.replaceAll("\\", "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
function queueSplash(
|
|
||||||
renderer: Pick<CliRenderer, "writeToScrollback" | "requestRender">,
|
|
||||||
state: SplashState,
|
|
||||||
phase: keyof SplashState,
|
|
||||||
write: ScrollbackWriter | undefined,
|
|
||||||
): boolean {
|
|
||||||
if (state[phase]) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!write) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
state[phase] = true
|
|
||||||
renderer.writeToScrollback(write)
|
|
||||||
renderer.requestRender()
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Boots the split-footer renderer and constructs the RunFooter.
|
|
||||||
//
|
|
||||||
// The renderer starts in split-footer mode with captured stdout so that
|
|
||||||
// scrollback commits and footer repaints happen in the same frame. After
|
|
||||||
// the entry splash, RunFooter takes over the footer region.
|
|
||||||
export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lifecycle> {
|
|
||||||
const source = resolveInteractiveStdin()
|
|
||||||
const footerTask = import("./footer")
|
|
||||||
try {
|
|
||||||
const renderer = await createCliRenderer({
|
|
||||||
stdin: source.stdin,
|
|
||||||
targetFps: 30,
|
|
||||||
maxFps: 60,
|
|
||||||
useMouse: false,
|
|
||||||
autoFocus: false,
|
|
||||||
openConsoleOnError: false,
|
|
||||||
exitOnCtrlC: false,
|
|
||||||
useKittyKeyboard: { events: process.platform === "win32" },
|
|
||||||
screenMode: "split-footer",
|
|
||||||
footerHeight: FOOTER_HEIGHT,
|
|
||||||
externalOutputMode: "capture-stdout",
|
|
||||||
consoleMode: "disabled",
|
|
||||||
clearOnShutdown: false,
|
|
||||||
})
|
|
||||||
const [theme, tuiConfig] = await Promise.all([resolveRunTheme(renderer), input.tuiConfig])
|
|
||||||
renderer.setBackgroundColor(theme.background)
|
|
||||||
const state: SplashState = {
|
|
||||||
entry: false,
|
|
||||||
exit: false,
|
|
||||||
}
|
|
||||||
const splash = splashInfo(input.sessionTitle, input.history)
|
|
||||||
const meta = splashMeta({
|
|
||||||
title: splash.title,
|
|
||||||
session_id: input.sessionID,
|
|
||||||
})
|
|
||||||
const labels = footerLabels({
|
|
||||||
agent: input.agent,
|
|
||||||
model: input.model,
|
|
||||||
variant: input.variant,
|
|
||||||
})
|
|
||||||
const wrote = queueSplash(
|
|
||||||
renderer,
|
|
||||||
state,
|
|
||||||
"entry",
|
|
||||||
entrySplash({
|
|
||||||
...meta,
|
|
||||||
theme: theme.splash,
|
|
||||||
showSession: splash.showSession,
|
|
||||||
detail: directoryLabel(input.directory),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
await renderer.idle().catch(() => {})
|
|
||||||
|
|
||||||
const { RunFooter } = await footerTask
|
|
||||||
let closed = false
|
|
||||||
let sigintRegistered = false
|
|
||||||
|
|
||||||
const footer = new RunFooter(renderer, {
|
|
||||||
directory: input.directory,
|
|
||||||
findFiles: input.findFiles,
|
|
||||||
agents: input.agents,
|
|
||||||
references: input.references,
|
|
||||||
sessionID: input.getSessionID ?? (() => input.sessionID),
|
|
||||||
...labels,
|
|
||||||
model: input.model,
|
|
||||||
variant: input.variant,
|
|
||||||
first: input.first,
|
|
||||||
history: input.history,
|
|
||||||
theme,
|
|
||||||
wrote,
|
|
||||||
tuiConfig,
|
|
||||||
diffStyle: tuiConfig.diff_style ?? "auto",
|
|
||||||
onPermissionReply: input.onPermissionReply,
|
|
||||||
onQuestionReply: input.onQuestionReply,
|
|
||||||
onQuestionReject: input.onQuestionReject,
|
|
||||||
onCycleVariant: input.onCycleVariant,
|
|
||||||
onModelSelect: input.onModelSelect,
|
|
||||||
onVariantSelect: input.onVariantSelect,
|
|
||||||
onInterrupt: input.onInterrupt,
|
|
||||||
onBackground: input.onBackground,
|
|
||||||
onEditorOpen: async ({ value }) => {
|
|
||||||
if (closed || renderer.isDestroyed) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const { openEditor } = await import("@opencode-ai/tui/editor")
|
|
||||||
await renderer.idle().catch(() => {})
|
|
||||||
const ignore = () => {}
|
|
||||||
detachSigint()
|
|
||||||
process.on("SIGINT", ignore)
|
|
||||||
try {
|
|
||||||
return await openEditor({
|
|
||||||
value,
|
|
||||||
cwd: input.directory,
|
|
||||||
renderer,
|
|
||||||
stdin: source.stdin,
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
process.off("SIGINT", ignore)
|
|
||||||
attachSigint()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onSubagentSelect: input.onSubagentSelect,
|
|
||||||
onSubagentInterrupt: input.onSubagentInterrupt,
|
|
||||||
})
|
|
||||||
|
|
||||||
const sigint = () => {
|
|
||||||
footer.requestExit()
|
|
||||||
}
|
|
||||||
|
|
||||||
const attachSigint = () => {
|
|
||||||
if (closed || sigintRegistered) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
process.on("SIGINT", sigint)
|
|
||||||
sigintRegistered = true
|
|
||||||
}
|
|
||||||
|
|
||||||
const detachSigint = () => {
|
|
||||||
if (!sigintRegistered) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
process.off("SIGINT", sigint)
|
|
||||||
sigintRegistered = false
|
|
||||||
}
|
|
||||||
|
|
||||||
attachSigint()
|
|
||||||
|
|
||||||
const close = async (next: {
|
|
||||||
showExit: boolean
|
|
||||||
sessionTitle?: string
|
|
||||||
sessionID?: string
|
|
||||||
history?: RunPrompt[]
|
|
||||||
}) => {
|
|
||||||
if (closed) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
closed = true
|
|
||||||
detachSigint()
|
|
||||||
let wroteExit = false
|
|
||||||
|
|
||||||
try {
|
|
||||||
await footer.idle().catch(() => {})
|
|
||||||
|
|
||||||
const show = renderer.isDestroyed ? false : next.showExit
|
|
||||||
if (!renderer.isDestroyed && show) {
|
|
||||||
const sessionID = next.sessionID || input.getSessionID?.() || input.sessionID
|
|
||||||
const splash = splashInfo(next.sessionTitle ?? input.sessionTitle, next.history ?? input.history)
|
|
||||||
wroteExit = queueSplash(
|
|
||||||
renderer,
|
|
||||||
state,
|
|
||||||
"exit",
|
|
||||||
exitSplash({
|
|
||||||
...splashMeta({
|
|
||||||
title: splash.title,
|
|
||||||
session_id: sessionID,
|
|
||||||
}),
|
|
||||||
theme: footer.currentTheme().splash,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
await renderer.idle().catch(() => {})
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
footer.close()
|
|
||||||
await footer.idle().catch(() => {})
|
|
||||||
footer.destroy()
|
|
||||||
shutdown(renderer)
|
|
||||||
if (!wroteExit) {
|
|
||||||
process.stdout.write("\n")
|
|
||||||
}
|
|
||||||
source.cleanup?.()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
footer,
|
|
||||||
refreshTheme() {
|
|
||||||
footer.refreshTheme()
|
|
||||||
},
|
|
||||||
onResize(fn) {
|
|
||||||
let width = renderer.terminalWidth
|
|
||||||
let height = renderer.terminalHeight
|
|
||||||
const resize = () => {
|
|
||||||
if (width === renderer.terminalWidth && height === renderer.terminalHeight) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
width = renderer.terminalWidth
|
|
||||||
height = renderer.terminalHeight
|
|
||||||
fn()
|
|
||||||
}
|
|
||||||
renderer.on(CliRenderEvents.RESIZE, resize)
|
|
||||||
return () => renderer.off(CliRenderEvents.RESIZE, resize)
|
|
||||||
},
|
|
||||||
async resetForReplay(next) {
|
|
||||||
if (closed || renderer.isDestroyed || footer.isClosed) {
|
|
||||||
throw new Error("runtime closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
await footer.idle()
|
|
||||||
if (closed || renderer.isDestroyed || footer.isClosed) {
|
|
||||||
throw new Error("runtime closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
footer.resetForReplay(true)
|
|
||||||
renderer.resetSplitFooterForReplay({ clearSavedLines: true })
|
|
||||||
const splash = splashInfo(next.sessionTitle ?? input.sessionTitle, next.history)
|
|
||||||
renderer.writeToScrollback(
|
|
||||||
entrySplash({
|
|
||||||
...splashMeta({
|
|
||||||
title: splash.title,
|
|
||||||
session_id: next.sessionID ?? input.getSessionID?.() ?? input.sessionID,
|
|
||||||
}),
|
|
||||||
theme: footer.currentTheme().splash,
|
|
||||||
showSession: splash.showSession,
|
|
||||||
detail: directoryLabel(input.directory),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
renderer.requestRender()
|
|
||||||
},
|
|
||||||
close,
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
source.cleanup?.()
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
type PendingTask<T> = {
|
|
||||||
current?: Promise<T>
|
|
||||||
}
|
|
||||||
|
|
||||||
export function reusePendingTask<T>(slot: PendingTask<T>, run: () => Promise<T>) {
|
|
||||||
if (slot.current) {
|
|
||||||
return slot.current
|
|
||||||
}
|
|
||||||
|
|
||||||
const task = run().finally(() => {
|
|
||||||
if (slot.current === task) {
|
|
||||||
slot.current = undefined
|
|
||||||
}
|
|
||||||
})
|
|
||||||
slot.current = task
|
|
||||||
return task
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import fs from "fs"
|
|
||||||
import * as tty from "node:tty"
|
|
||||||
|
|
||||||
export const INTERACTIVE_INPUT_ERROR = "opencode mini requires a controlling terminal for input"
|
|
||||||
|
|
||||||
type InteractiveStdin = {
|
|
||||||
stdin: NodeJS.ReadStream
|
|
||||||
cleanup?: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
function openTerminalStdin(path: string): NodeJS.ReadStream {
|
|
||||||
return new tty.ReadStream(fs.openSync(path, "r"))
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveInteractiveStdin(
|
|
||||||
stdin: NodeJS.ReadStream = process.stdin,
|
|
||||||
open: (path: string) => NodeJS.ReadStream = openTerminalStdin,
|
|
||||||
platform = process.platform,
|
|
||||||
): InteractiveStdin {
|
|
||||||
if (stdin.isTTY) {
|
|
||||||
return { stdin }
|
|
||||||
}
|
|
||||||
|
|
||||||
const file = platform === "win32" ? "CONIN$" : "/dev/tty"
|
|
||||||
|
|
||||||
try {
|
|
||||||
const stream = open(file)
|
|
||||||
return {
|
|
||||||
stdin: stream,
|
|
||||||
cleanup: () => {
|
|
||||||
stream.destroy()
|
|
||||||
},
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(INTERACTIVE_INPUT_ERROR, { cause: error })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import type { PermissionV2Request, QuestionV2Request } from "@opencode-ai/client/promise"
|
|
||||||
import type { FooterView } from "./types"
|
|
||||||
|
|
||||||
export function pickBlockerView(input: {
|
|
||||||
permission?: PermissionV2Request
|
|
||||||
question?: QuestionV2Request
|
|
||||||
}): FooterView {
|
|
||||||
if (input.permission) return { type: "permission", request: input.permission }
|
|
||||||
if (input.question) return { type: "question", request: input.question }
|
|
||||||
return { type: "prompt" }
|
|
||||||
}
|
|
||||||
|
|
||||||
export function blockerStatus(view: FooterView) {
|
|
||||||
if (view.type === "permission") return "awaiting permission"
|
|
||||||
if (view.type === "question") return "awaiting answer"
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
@@ -1,786 +0,0 @@
|
|||||||
// Current-native subagent (child Session) tracking for the mini transport.
|
|
||||||
//
|
|
||||||
// Discovers child Sessions of the active parent from four current sources:
|
|
||||||
// 1. projected subagent tool output (`structured.sessionID`) during hydration
|
|
||||||
// 2. the current session list filtered by `parentID` during hydration
|
|
||||||
// 3. the process-local active-session map during hydration
|
|
||||||
// 4. live events from unknown sessions whose `parentID` matches the parent
|
|
||||||
//
|
|
||||||
// Tracks one footer tab per child and a detail transcript for the selected
|
|
||||||
// child, reduced from the same current live event stream the parent uses.
|
|
||||||
// Detail transcripts rebuild from projected messages on discovery, selection,
|
|
||||||
// and reconnect, then continue from live deltas using the same
|
|
||||||
// projected-prefix dedup the parent transport uses.
|
|
||||||
//
|
|
||||||
// Per-child interruption uses `v2.session.interrupt(childID)`. Per-child
|
|
||||||
// backgrounding is intentionally absent: subagent jobs block the parent
|
|
||||||
// session, so only whole-session `v2.session.background(parentID)` exists.
|
|
||||||
import type {
|
|
||||||
EventSubscribeOutput,
|
|
||||||
OpenCodeClient,
|
|
||||||
SessionMessageAssistantTool,
|
|
||||||
SessionMessageInfo,
|
|
||||||
} from "@opencode-ai/client/promise"
|
|
||||||
import { Locale } from "@opencode-ai/tui/util/locale"
|
|
||||||
import type { FooterSubagentDetail, FooterSubagentState, FooterSubagentTab, MiniToolPart, StreamCommit } from "./types"
|
|
||||||
|
|
||||||
const CHILD_MESSAGE_LIMIT = 80
|
|
||||||
const CHILD_FRAME_LIMIT = 80
|
|
||||||
const CHILD_EVENT_BUFFER_LIMIT = 64
|
|
||||||
const FAMILY_LIST_LIMIT = 100
|
|
||||||
const FALLBACK_LABEL = "Subagent"
|
|
||||||
|
|
||||||
type V2Event = EventSubscribeOutput
|
|
||||||
|
|
||||||
export function outputText(content: ReadonlyArray<{ type: string; text?: string }>) {
|
|
||||||
return content.flatMap((item) => (item.type === "text" && item.text ? [item.text] : [])).join("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
export function miniTool(input: {
|
|
||||||
sessionID: string
|
|
||||||
messageID: string
|
|
||||||
tool: SessionMessageAssistantTool
|
|
||||||
}): MiniToolPart {
|
|
||||||
const tool = input.tool
|
|
||||||
const providerCall =
|
|
||||||
tool.executed === undefined && tool.providerState === undefined
|
|
||||||
? undefined
|
|
||||||
: { executed: tool.executed, state: tool.providerState }
|
|
||||||
const providerResult =
|
|
||||||
tool.executed === undefined && tool.providerResultState === undefined
|
|
||||||
? undefined
|
|
||||||
: { executed: tool.executed, state: tool.providerResultState }
|
|
||||||
const base = {
|
|
||||||
id: `prt_${tool.id}`,
|
|
||||||
sessionID: input.sessionID,
|
|
||||||
messageID: input.messageID,
|
|
||||||
type: "tool" as const,
|
|
||||||
callID: tool.id,
|
|
||||||
tool: tool.name,
|
|
||||||
}
|
|
||||||
if (tool.state.status === "streaming") {
|
|
||||||
return {
|
|
||||||
...base,
|
|
||||||
state: { status: "pending", input: {}, raw: tool.state.input },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (tool.state.status === "running") {
|
|
||||||
return {
|
|
||||||
...base,
|
|
||||||
state: {
|
|
||||||
status: "running",
|
|
||||||
input: tool.state.input,
|
|
||||||
title: tool.name,
|
|
||||||
metadata: { structured: tool.state.structured, content: tool.state.content, providerCall },
|
|
||||||
time: { start: tool.time.ran ?? tool.time.created },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (tool.state.status === "completed") {
|
|
||||||
return {
|
|
||||||
...base,
|
|
||||||
state: {
|
|
||||||
status: "completed",
|
|
||||||
input: tool.state.input,
|
|
||||||
output: outputText(tool.state.content),
|
|
||||||
title: tool.name,
|
|
||||||
metadata: {
|
|
||||||
structured: tool.state.structured,
|
|
||||||
content: tool.state.content,
|
|
||||||
result: tool.state.result,
|
|
||||||
providerCall,
|
|
||||||
providerResult,
|
|
||||||
},
|
|
||||||
time: { start: tool.time.ran ?? tool.time.created, end: tool.time.completed ?? tool.time.created },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...base,
|
|
||||||
state: {
|
|
||||||
status: "error",
|
|
||||||
input: tool.state.input,
|
|
||||||
error: tool.state.error.message,
|
|
||||||
metadata: {
|
|
||||||
structured: tool.state.structured,
|
|
||||||
content: tool.state.content,
|
|
||||||
result: tool.state.result,
|
|
||||||
providerCall,
|
|
||||||
providerResult,
|
|
||||||
},
|
|
||||||
time: { start: tool.time.ran ?? tool.time.created, end: tool.time.completed ?? tool.time.created },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function toolCommit(part: MiniToolPart, phase: "start" | "progress" | "final"): StreamCommit {
|
|
||||||
const status = part.state.status
|
|
||||||
const text =
|
|
||||||
status === "running"
|
|
||||||
? part.tool === "task"
|
|
||||||
? "running task"
|
|
||||||
: `running ${part.tool}`
|
|
||||||
: status === "completed"
|
|
||||||
? part.state.output
|
|
||||||
: status === "error"
|
|
||||||
? part.state.error
|
|
||||||
: ""
|
|
||||||
return {
|
|
||||||
kind: "tool",
|
|
||||||
source: "tool",
|
|
||||||
text,
|
|
||||||
phase,
|
|
||||||
messageID: part.messageID,
|
|
||||||
partID: part.id,
|
|
||||||
tool: part.tool,
|
|
||||||
part,
|
|
||||||
toolState: status === "error" ? "error" : status === "completed" ? "completed" : "running",
|
|
||||||
toolError: status === "error" ? part.state.error : undefined,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Frame = {
|
|
||||||
key: string
|
|
||||||
commit: StreamCommit
|
|
||||||
}
|
|
||||||
|
|
||||||
type ToolTrack = {
|
|
||||||
name: string
|
|
||||||
input: Record<string, unknown>
|
|
||||||
started: number
|
|
||||||
providerState?: Record<string, unknown>
|
|
||||||
}
|
|
||||||
|
|
||||||
type ChildState = {
|
|
||||||
sessionID: string
|
|
||||||
label: string
|
|
||||||
description: string
|
|
||||||
status: FooterSubagentTab["status"]
|
|
||||||
background: boolean
|
|
||||||
title?: string
|
|
||||||
callIDs: Set<string>
|
|
||||||
lastUpdatedAt: number
|
|
||||||
frames: Frame[]
|
|
||||||
text: Map<string, string>
|
|
||||||
projectedText: Map<string, string>
|
|
||||||
reasoning: Map<string, string>
|
|
||||||
projectedReasoning: Map<string, string>
|
|
||||||
tools: Map<string, ToolTrack>
|
|
||||||
finishedTools: Set<string>
|
|
||||||
messageIDs: Set<string>
|
|
||||||
prompts: Map<string, string>
|
|
||||||
hydrated: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export type SubagentTrackerInput = {
|
|
||||||
sdk: OpenCodeClient
|
|
||||||
sessionID: string
|
|
||||||
thinking: boolean
|
|
||||||
emit: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
export type SubagentTracker = {
|
|
||||||
main(event: V2Event): void
|
|
||||||
foreign(sessionID: string, event: V2Event): void
|
|
||||||
hydrate(next: { messages: SessionMessageInfo[]; active: Record<string, unknown> }): Promise<void>
|
|
||||||
select(sessionID: string | undefined): void
|
|
||||||
snapshot(): FooterSubagentState
|
|
||||||
}
|
|
||||||
|
|
||||||
function record(value: unknown): Record<string, unknown> | undefined {
|
|
||||||
if (typeof value === "object" && value !== null && !Array.isArray(value)) return value as Record<string, unknown>
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
function text(value: unknown): string | undefined {
|
|
||||||
if (typeof value !== "string") return undefined
|
|
||||||
const next = value.trim()
|
|
||||||
return next || undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
function childSessionID(structured: Record<string, unknown> | undefined) {
|
|
||||||
const sessionID = text(structured?.sessionID)
|
|
||||||
if (!sessionID || !sessionID.startsWith("ses")) return undefined
|
|
||||||
const status = structured?.status
|
|
||||||
if (status !== "running" && status !== "completed") return undefined
|
|
||||||
return { sessionID, running: status === "running" }
|
|
||||||
}
|
|
||||||
|
|
||||||
function tab(child: ChildState): FooterSubagentTab {
|
|
||||||
return {
|
|
||||||
sessionID: child.sessionID,
|
|
||||||
partID: `subagent:${child.sessionID}`,
|
|
||||||
callID: `subagent:${child.sessionID}`,
|
|
||||||
label: child.label,
|
|
||||||
description: child.description || child.title || "",
|
|
||||||
status: child.status,
|
|
||||||
background: child.background ? true : undefined,
|
|
||||||
title: child.title,
|
|
||||||
toolCalls: child.callIDs.size > 0 ? child.callIDs.size : undefined,
|
|
||||||
lastUpdatedAt: child.lastUpdatedAt,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createSubagentTracker(input: SubagentTrackerInput): SubagentTracker {
|
|
||||||
const children = new Map<string, ChildState>()
|
|
||||||
// Live subagent tool calls in the parent, so tool.success structured output
|
|
||||||
// can be joined with the call's input metadata.
|
|
||||||
const pendingCalls = new Map<string, Record<string, unknown>>()
|
|
||||||
// Foreign sessions already resolved through session.get. Non-children stay
|
|
||||||
// cached so unrelated concurrent sessions are checked at most once.
|
|
||||||
const checked = new Set<string>()
|
|
||||||
// Foreign events buffered while a session.get discovery is in flight, so a
|
|
||||||
// fast child (including its settled event) is not lost mid-discovery.
|
|
||||||
const pendingEvents = new Map<string, V2Event[]>()
|
|
||||||
const hydrationEvents = new Map<string, V2Event[]>()
|
|
||||||
const hydrationOverflow = new Set<string>()
|
|
||||||
const hydrations = new Map<string, Promise<void>>()
|
|
||||||
let selected: string | undefined
|
|
||||||
const fragmentKey = (messageID: string, partID: string) => `${messageID}\u0000${partID}`
|
|
||||||
|
|
||||||
const ensureChild = (sessionID: string): ChildState => {
|
|
||||||
const existing = children.get(sessionID)
|
|
||||||
const child: ChildState = existing ?? {
|
|
||||||
sessionID,
|
|
||||||
label: FALLBACK_LABEL,
|
|
||||||
description: "",
|
|
||||||
status: "running",
|
|
||||||
background: false,
|
|
||||||
callIDs: new Set(),
|
|
||||||
lastUpdatedAt: Date.now(),
|
|
||||||
frames: [],
|
|
||||||
text: new Map(),
|
|
||||||
projectedText: new Map(),
|
|
||||||
reasoning: new Map(),
|
|
||||||
projectedReasoning: new Map(),
|
|
||||||
tools: new Map(),
|
|
||||||
finishedTools: new Set(),
|
|
||||||
messageIDs: new Set(),
|
|
||||||
prompts: new Map(),
|
|
||||||
hydrated: false,
|
|
||||||
}
|
|
||||||
if (!existing) children.set(sessionID, child)
|
|
||||||
// Adopting a child while its session.get discovery is still in flight:
|
|
||||||
// drain the buffered events now. They arrived before whatever the caller
|
|
||||||
// applies next, so replaying them first preserves bus order, and the
|
|
||||||
// resolved discovery can no longer replay stale events (e.g. step.started)
|
|
||||||
// after a terminal settled event was applied directly.
|
|
||||||
const buffered = pendingEvents.get(sessionID)
|
|
||||||
if (buffered) {
|
|
||||||
pendingEvents.delete(sessionID)
|
|
||||||
for (const event of buffered) reduce(child, event)
|
|
||||||
}
|
|
||||||
return child
|
|
||||||
}
|
|
||||||
|
|
||||||
const touch = (child: ChildState, timestamp?: number) => {
|
|
||||||
child.lastUpdatedAt = Math.max(child.lastUpdatedAt, timestamp ?? Date.now())
|
|
||||||
}
|
|
||||||
|
|
||||||
const notifyDetail = (child: ChildState) => {
|
|
||||||
if (child.sessionID === selected) input.emit()
|
|
||||||
}
|
|
||||||
|
|
||||||
const setFrame = (child: ChildState, key: string, commit: StreamCommit) => {
|
|
||||||
const index = child.frames.findIndex((item) => item.key === key)
|
|
||||||
if (index === -1) {
|
|
||||||
child.frames.push({ key, commit })
|
|
||||||
if (child.frames.length > CHILD_FRAME_LIMIT) child.frames.splice(0, child.frames.length - CHILD_FRAME_LIMIT)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
child.frames[index] = { key, commit }
|
|
||||||
}
|
|
||||||
|
|
||||||
const applyMeta = (child: ChildState, meta: Record<string, unknown> | undefined) => {
|
|
||||||
if (!meta) return
|
|
||||||
const agent = text(meta.agent)
|
|
||||||
if (agent) child.label = Locale.titlecase(agent)
|
|
||||||
const description = text(meta.description)
|
|
||||||
if (description) child.description = description
|
|
||||||
if (meta.background === true) child.background = true
|
|
||||||
}
|
|
||||||
|
|
||||||
const userFrame = (child: ChildState, messageID: string, value: string) => {
|
|
||||||
if (child.messageIDs.has(messageID)) return false
|
|
||||||
child.messageIDs.add(messageID)
|
|
||||||
setFrame(child, `user:${messageID}`, {
|
|
||||||
kind: "user",
|
|
||||||
source: "system",
|
|
||||||
text: value,
|
|
||||||
phase: "start",
|
|
||||||
messageID,
|
|
||||||
})
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
const childTool = (child: ChildState, item: SessionMessageAssistantTool, messageID: string) => {
|
|
||||||
const part = miniTool({
|
|
||||||
sessionID: child.sessionID,
|
|
||||||
messageID,
|
|
||||||
tool: item,
|
|
||||||
})
|
|
||||||
if (item.state.status === "streaming") return
|
|
||||||
child.callIDs.add(item.id)
|
|
||||||
if (item.state.status === "running") {
|
|
||||||
setFrame(child, `tool:${item.id}`, toolCommit(part, "start"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
child.finishedTools.add(item.id)
|
|
||||||
child.tools.delete(item.id)
|
|
||||||
setFrame(child, `tool:${item.id}`, toolCommit(part, "final"))
|
|
||||||
}
|
|
||||||
|
|
||||||
const rebuild = (child: ChildState, messages: SessionMessageInfo[]) => {
|
|
||||||
child.frames = []
|
|
||||||
child.text.clear()
|
|
||||||
child.projectedText.clear()
|
|
||||||
child.reasoning.clear()
|
|
||||||
child.projectedReasoning.clear()
|
|
||||||
child.finishedTools.clear()
|
|
||||||
child.messageIDs.clear()
|
|
||||||
child.callIDs.clear()
|
|
||||||
for (const message of messages) {
|
|
||||||
if (message.type === "user") {
|
|
||||||
child.prompts.delete(message.id)
|
|
||||||
userFrame(child, message.id, message.text)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (message.type !== "assistant") continue
|
|
||||||
child.messageIDs.add(message.id)
|
|
||||||
let textOrdinal = 0
|
|
||||||
let reasoningOrdinal = 0
|
|
||||||
for (const item of message.content) {
|
|
||||||
if (item.type === "text") {
|
|
||||||
const id = `text:${textOrdinal++}`
|
|
||||||
const key = fragmentKey(message.id, id)
|
|
||||||
child.text.set(key, item.text)
|
|
||||||
child.projectedText.set(key, item.text)
|
|
||||||
setFrame(child, key, {
|
|
||||||
kind: "assistant",
|
|
||||||
source: "assistant",
|
|
||||||
text: item.text,
|
|
||||||
phase: "progress",
|
|
||||||
messageID: message.id,
|
|
||||||
partID: id,
|
|
||||||
})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (item.type === "reasoning") {
|
|
||||||
const id = `reasoning:${reasoningOrdinal++}`
|
|
||||||
const key = fragmentKey(message.id, id)
|
|
||||||
child.reasoning.set(key, item.text)
|
|
||||||
child.projectedReasoning.set(key, item.text)
|
|
||||||
if (input.thinking)
|
|
||||||
setFrame(child, key, {
|
|
||||||
kind: "reasoning",
|
|
||||||
source: "reasoning",
|
|
||||||
text: `Thinking: ${item.text}`,
|
|
||||||
phase: "progress",
|
|
||||||
messageID: message.id,
|
|
||||||
partID: id,
|
|
||||||
})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
childTool(child, item, message.id)
|
|
||||||
}
|
|
||||||
if (message.error) {
|
|
||||||
setFrame(child, `error:${message.id}`, {
|
|
||||||
kind: "error",
|
|
||||||
source: "system",
|
|
||||||
text: message.error.message,
|
|
||||||
phase: "start",
|
|
||||||
messageID: message.id,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const hydrateChild = (child: ChildState): Promise<void> => {
|
|
||||||
const existing = hydrations.get(child.sessionID)
|
|
||||||
if (existing) return existing
|
|
||||||
const pendingPrompts = new Map(child.prompts)
|
|
||||||
const pendingTools = new Map(child.tools)
|
|
||||||
let retry = false
|
|
||||||
const task = input.sdk.message
|
|
||||||
.list({ sessionID: child.sessionID, limit: CHILD_MESSAGE_LIMIT, order: "desc" })
|
|
||||||
.then((response) => {
|
|
||||||
const buffered = hydrationEvents.get(child.sessionID) ?? []
|
|
||||||
hydrationEvents.delete(child.sessionID)
|
|
||||||
if (hydrationOverflow.delete(child.sessionID)) {
|
|
||||||
child.hydrated = false
|
|
||||||
retry = true
|
|
||||||
notifyDetail(child)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for (const [id, prompt] of pendingPrompts) {
|
|
||||||
if (!child.prompts.has(id)) child.prompts.set(id, prompt)
|
|
||||||
}
|
|
||||||
rebuild(child, structuredClone(response.data).toReversed() as SessionMessageInfo[])
|
|
||||||
for (const [id, tool] of pendingTools) {
|
|
||||||
if (!child.finishedTools.has(id) && !child.tools.has(id)) child.tools.set(id, tool)
|
|
||||||
}
|
|
||||||
for (const event of buffered) reduce(child, event)
|
|
||||||
child.hydrated = true
|
|
||||||
notifyDetail(child)
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
hydrationEvents.delete(child.sessionID)
|
|
||||||
hydrationOverflow.delete(child.sessionID)
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
hydrations.delete(child.sessionID)
|
|
||||||
if (retry) queueMicrotask(() => void hydrateChild(child))
|
|
||||||
})
|
|
||||||
hydrations.set(child.sessionID, task)
|
|
||||||
return task
|
|
||||||
}
|
|
||||||
|
|
||||||
const discover = (sessionID: string) => {
|
|
||||||
if (checked.has(sessionID) || children.has(sessionID) || sessionID === input.sessionID) return
|
|
||||||
checked.add(sessionID)
|
|
||||||
if (!pendingEvents.has(sessionID)) pendingEvents.set(sessionID, [])
|
|
||||||
void input.sdk.session
|
|
||||||
.get({ sessionID })
|
|
||||||
.then((session) => {
|
|
||||||
const buffered = pendingEvents.get(sessionID) ?? []
|
|
||||||
pendingEvents.delete(sessionID)
|
|
||||||
if (session.parentID !== input.sessionID) return
|
|
||||||
const child = ensureChild(sessionID)
|
|
||||||
if (session.agent) child.label = Locale.titlecase(session.agent)
|
|
||||||
child.title = session.title
|
|
||||||
for (const event of buffered) reduce(child, event)
|
|
||||||
touch(child)
|
|
||||||
input.emit()
|
|
||||||
void hydrateChild(child)
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
// Allow a later event to retry discovery after transient failures.
|
|
||||||
pendingEvents.delete(sessionID)
|
|
||||||
checked.delete(sessionID)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const reduce = (child: ChildState, event: V2Event) => {
|
|
||||||
if (event.type === "session.input.admitted") {
|
|
||||||
if (event.data.input.type === "user") child.prompts.set(event.data.inputID, event.data.input.data.text)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.input.promoted") {
|
|
||||||
const prompt = child.prompts.get(event.data.inputID)
|
|
||||||
if (prompt === undefined) return
|
|
||||||
child.prompts.delete(event.data.inputID)
|
|
||||||
if (userFrame(child, event.data.inputID, prompt)) {
|
|
||||||
touch(child, event.created)
|
|
||||||
notifyDetail(child)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.step.started") {
|
|
||||||
touch(child, event.created)
|
|
||||||
if (child.label === FALLBACK_LABEL && event.data.agent) child.label = Locale.titlecase(event.data.agent)
|
|
||||||
if (child.status !== "running") child.status = "running"
|
|
||||||
input.emit()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.text.started") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.text.delta") {
|
|
||||||
const id = `text:${event.data.ordinal}`
|
|
||||||
const key = fragmentKey(event.data.assistantMessageID, id)
|
|
||||||
const projected = child.projectedText.get(key)
|
|
||||||
const covered = projected?.indexOf(event.data.delta) ?? -1
|
|
||||||
if (projected && covered >= 0) {
|
|
||||||
child.projectedText.set(key, projected.slice(covered + event.data.delta.length))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const next = (child.text.get(key) ?? "") + event.data.delta
|
|
||||||
child.text.set(key, next)
|
|
||||||
setFrame(child, key, {
|
|
||||||
kind: "assistant",
|
|
||||||
source: "assistant",
|
|
||||||
text: next,
|
|
||||||
phase: "progress",
|
|
||||||
messageID: event.data.assistantMessageID,
|
|
||||||
partID: id,
|
|
||||||
})
|
|
||||||
touch(child, event.created)
|
|
||||||
notifyDetail(child)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.text.ended") {
|
|
||||||
const id = `text:${event.data.ordinal}`
|
|
||||||
const key = fragmentKey(event.data.assistantMessageID, id)
|
|
||||||
child.text.set(key, event.data.text)
|
|
||||||
child.projectedText.delete(key)
|
|
||||||
setFrame(child, key, {
|
|
||||||
kind: "assistant",
|
|
||||||
source: "assistant",
|
|
||||||
text: event.data.text,
|
|
||||||
phase: "progress",
|
|
||||||
messageID: event.data.assistantMessageID,
|
|
||||||
partID: id,
|
|
||||||
})
|
|
||||||
touch(child, event.created)
|
|
||||||
notifyDetail(child)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.reasoning.started") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.reasoning.delta") {
|
|
||||||
const id = `reasoning:${event.data.ordinal}`
|
|
||||||
const key = fragmentKey(event.data.assistantMessageID, id)
|
|
||||||
const projected = child.projectedReasoning.get(key)
|
|
||||||
const covered = projected?.indexOf(event.data.delta) ?? -1
|
|
||||||
if (projected && covered >= 0) {
|
|
||||||
child.projectedReasoning.set(key, projected.slice(covered + event.data.delta.length))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const next = (child.reasoning.get(key) ?? "") + event.data.delta
|
|
||||||
child.reasoning.set(key, next)
|
|
||||||
if (!input.thinking) return
|
|
||||||
setFrame(child, key, {
|
|
||||||
kind: "reasoning",
|
|
||||||
source: "reasoning",
|
|
||||||
text: `Thinking: ${next}`,
|
|
||||||
phase: "progress",
|
|
||||||
messageID: event.data.assistantMessageID,
|
|
||||||
partID: id,
|
|
||||||
})
|
|
||||||
notifyDetail(child)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.reasoning.ended") {
|
|
||||||
const id = `reasoning:${event.data.ordinal}`
|
|
||||||
const key = fragmentKey(event.data.assistantMessageID, id)
|
|
||||||
child.reasoning.set(key, event.data.text)
|
|
||||||
child.projectedReasoning.delete(key)
|
|
||||||
if (!input.thinking) return
|
|
||||||
setFrame(child, key, {
|
|
||||||
kind: "reasoning",
|
|
||||||
source: "reasoning",
|
|
||||||
text: `Thinking: ${event.data.text}`,
|
|
||||||
phase: "progress",
|
|
||||||
messageID: event.data.assistantMessageID,
|
|
||||||
partID: id,
|
|
||||||
})
|
|
||||||
notifyDetail(child)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.tool.input.started") {
|
|
||||||
if (child.finishedTools.has(event.data.callID)) return
|
|
||||||
child.tools.set(event.data.callID, { name: event.data.name, input: {}, started: event.created })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.tool.called") {
|
|
||||||
if (child.finishedTools.has(event.data.callID)) return
|
|
||||||
const current = child.tools.get(event.data.callID)
|
|
||||||
child.tools.set(event.data.callID, {
|
|
||||||
name: current?.name ?? "tool",
|
|
||||||
input: event.data.input,
|
|
||||||
started: current?.started ?? event.created,
|
|
||||||
providerState: event.data.state,
|
|
||||||
})
|
|
||||||
childTool(
|
|
||||||
child,
|
|
||||||
structuredClone({
|
|
||||||
type: "tool",
|
|
||||||
id: event.data.callID,
|
|
||||||
name: current?.name ?? "tool",
|
|
||||||
executed: event.data.executed,
|
|
||||||
providerState: event.data.state,
|
|
||||||
state: { status: "running", input: event.data.input, structured: {}, content: [] },
|
|
||||||
time: { created: current?.started ?? event.created, ran: event.created },
|
|
||||||
}) as SessionMessageAssistantTool,
|
|
||||||
event.data.assistantMessageID,
|
|
||||||
)
|
|
||||||
touch(child, event.created)
|
|
||||||
notifyDetail(child)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.tool.success" || event.type === "session.tool.failed") {
|
|
||||||
if (child.finishedTools.has(event.data.callID)) return
|
|
||||||
const current = child.tools.get(event.data.callID)
|
|
||||||
const failed = event.type === "session.tool.failed"
|
|
||||||
childTool(
|
|
||||||
child,
|
|
||||||
structuredClone({
|
|
||||||
type: "tool",
|
|
||||||
id: event.data.callID,
|
|
||||||
name: current?.name ?? "tool",
|
|
||||||
executed: event.data.executed,
|
|
||||||
providerState: current?.providerState,
|
|
||||||
providerResultState: event.data.resultState,
|
|
||||||
state: failed
|
|
||||||
? {
|
|
||||||
status: "error",
|
|
||||||
input: current?.input ?? {},
|
|
||||||
structured: {},
|
|
||||||
content: [],
|
|
||||||
error: event.data.error,
|
|
||||||
result: event.data.result,
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
status: "completed",
|
|
||||||
input: current?.input ?? {},
|
|
||||||
structured: event.data.structured,
|
|
||||||
content: event.data.content,
|
|
||||||
result: event.data.result,
|
|
||||||
},
|
|
||||||
time: {
|
|
||||||
created: current?.started ?? event.created,
|
|
||||||
ran: current?.started,
|
|
||||||
completed: event.created,
|
|
||||||
},
|
|
||||||
}) as SessionMessageAssistantTool,
|
|
||||||
event.data.assistantMessageID,
|
|
||||||
)
|
|
||||||
touch(child, event.created)
|
|
||||||
notifyDetail(child)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.step.ended") return
|
|
||||||
if (event.type === "session.step.failed") {
|
|
||||||
setFrame(child, `error:step:${event.data.assistantMessageID}`, {
|
|
||||||
kind: "error",
|
|
||||||
source: "system",
|
|
||||||
text: event.data.error.message,
|
|
||||||
phase: "start",
|
|
||||||
messageID: event.data.assistantMessageID,
|
|
||||||
})
|
|
||||||
touch(child, event.created)
|
|
||||||
notifyDetail(child)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.execution.started") {
|
|
||||||
child.status = "running"
|
|
||||||
touch(child, event.created)
|
|
||||||
input.emit()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
event.type === "session.execution.succeeded" ||
|
|
||||||
event.type === "session.execution.failed" ||
|
|
||||||
event.type === "session.execution.interrupted"
|
|
||||||
) {
|
|
||||||
child.status =
|
|
||||||
event.type === "session.execution.succeeded"
|
|
||||||
? "completed"
|
|
||||||
: event.type === "session.execution.interrupted"
|
|
||||||
? "cancelled"
|
|
||||||
: "error"
|
|
||||||
touch(child, event.created)
|
|
||||||
input.emit()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const mainTool = (item: SessionMessageAssistantTool, active?: Record<string, unknown>) => {
|
|
||||||
if (item.name !== "subagent" || item.state.status !== "completed") return
|
|
||||||
const found = childSessionID(record(item.state.structured))
|
|
||||||
if (!found) return
|
|
||||||
const child = ensureChild(found.sessionID)
|
|
||||||
applyMeta(child, record(item.state.input))
|
|
||||||
if (found.running) child.background = true
|
|
||||||
if (child.status === "running") {
|
|
||||||
const running = found.running && (!active || found.sessionID in active)
|
|
||||||
child.status = running ? "running" : "completed"
|
|
||||||
}
|
|
||||||
touch(child, item.time.completed ?? item.time.created)
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
main(event) {
|
|
||||||
if (event.type === "session.tool.input.started") {
|
|
||||||
if (event.data.name === "subagent") pendingCalls.set(event.data.callID, {})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.tool.called") {
|
|
||||||
if (pendingCalls.has(event.data.callID)) pendingCalls.set(event.data.callID, event.data.input)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type === "session.tool.failed") {
|
|
||||||
pendingCalls.delete(event.data.callID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (event.type !== "session.tool.success") return
|
|
||||||
const pending = pendingCalls.get(event.data.callID)
|
|
||||||
pendingCalls.delete(event.data.callID)
|
|
||||||
const found = childSessionID(record(event.data.structured))
|
|
||||||
if (!found) return
|
|
||||||
const child = ensureChild(found.sessionID)
|
|
||||||
applyMeta(child, pending)
|
|
||||||
if (found.running) {
|
|
||||||
child.background = true
|
|
||||||
child.status = "running"
|
|
||||||
}
|
|
||||||
if (!found.running && child.status === "running") child.status = "completed"
|
|
||||||
touch(child, event.created)
|
|
||||||
input.emit()
|
|
||||||
if (!child.hydrated) void hydrateChild(child)
|
|
||||||
},
|
|
||||||
foreign(sessionID, event) {
|
|
||||||
const child = children.get(sessionID)
|
|
||||||
if (child) {
|
|
||||||
if (hydrations.has(sessionID)) {
|
|
||||||
const buffered = hydrationEvents.get(sessionID) ?? []
|
|
||||||
if (buffered.length < CHILD_EVENT_BUFFER_LIMIT) buffered.push(event)
|
|
||||||
else hydrationOverflow.add(sessionID)
|
|
||||||
hydrationEvents.set(sessionID, buffered)
|
|
||||||
}
|
|
||||||
reduce(child, event)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
discover(sessionID)
|
|
||||||
const buffered = pendingEvents.get(sessionID)
|
|
||||||
if (buffered && buffered.length < CHILD_EVENT_BUFFER_LIMIT) buffered.push(event)
|
|
||||||
},
|
|
||||||
async hydrate(next) {
|
|
||||||
for (const message of next.messages) {
|
|
||||||
if (message.type !== "assistant") continue
|
|
||||||
for (const item of message.content) {
|
|
||||||
if (item.type === "tool") mainTool(item, next.active)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Family index: adopt children directly from the current session list so
|
|
||||||
// historical subagents beyond the projected message window still get tabs.
|
|
||||||
const family = await input.sdk.session
|
|
||||||
.list({ parentID: input.sessionID, limit: FAMILY_LIST_LIMIT, order: "desc" })
|
|
||||||
.then((response) => response.data)
|
|
||||||
.catch(() => [])
|
|
||||||
for (const session of family) {
|
|
||||||
const child = ensureChild(session.id)
|
|
||||||
if (session.agent && child.label === FALLBACK_LABEL) child.label = Locale.titlecase(session.agent)
|
|
||||||
if (!child.title) child.title = session.title
|
|
||||||
touch(child, session.time.updated)
|
|
||||||
}
|
|
||||||
for (const sessionID of Object.keys(next.active)) discover(sessionID)
|
|
||||||
for (const child of children.values()) {
|
|
||||||
// Reconnect can miss a child's settled event; the active map is the
|
|
||||||
// authoritative live signal for still-running children.
|
|
||||||
if (child.status === "running" && !(child.sessionID in next.active)) child.status = "completed"
|
|
||||||
}
|
|
||||||
const current = selected ? children.get(selected) : undefined
|
|
||||||
if (current) await hydrateChild(current)
|
|
||||||
if (children.size > 0) input.emit()
|
|
||||||
},
|
|
||||||
select(sessionID) {
|
|
||||||
selected = sessionID
|
|
||||||
const child = sessionID ? children.get(sessionID) : undefined
|
|
||||||
if (child && !child.hydrated) void hydrateChild(child)
|
|
||||||
input.emit()
|
|
||||||
},
|
|
||||||
snapshot() {
|
|
||||||
const tabs = [...children.values()].map(tab).toSorted((a, b) => {
|
|
||||||
const active = Number(b.status === "running") - Number(a.status === "running")
|
|
||||||
if (active !== 0) return active
|
|
||||||
return b.lastUpdatedAt - a.lastUpdatedAt
|
|
||||||
})
|
|
||||||
const child = selected ? children.get(selected) : undefined
|
|
||||||
const details: Record<string, FooterSubagentDetail> = child
|
|
||||||
? { [child.sessionID]: { sessionID: child.sessionID, commits: child.frames.map((item) => item.commit) } }
|
|
||||||
: {}
|
|
||||||
return { tabs, details, permissions: [], questions: [] }
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,94 +0,0 @@
|
|||||||
// Dev-only JSONL event trace for direct interactive mode.
|
|
||||||
//
|
|
||||||
// Enable with OPENCODE_DIRECT_TRACE=1. Writes one JSON line per event to
|
|
||||||
// ~/.local/share/opencode/log/direct/<timestamp>-<pid>.jsonl. Also writes
|
|
||||||
// a latest.json pointer so you can quickly find the most recent trace.
|
|
||||||
//
|
|
||||||
// The trace captures the full closed loop: outbound prompts, inbound SDK
|
|
||||||
// events, reducer output, footer commits, and turn lifecycle markers.
|
|
||||||
// Useful for debugging stream ordering, permission behavior, and
|
|
||||||
// footer/transcript mismatches.
|
|
||||||
//
|
|
||||||
// Lazy-initialized: the first call to trace() decides whether tracing is
|
|
||||||
// active based on the env var, and subsequent calls return the cached result.
|
|
||||||
import fs from "fs"
|
|
||||||
import path from "path"
|
|
||||||
import { Global } from "@opencode-ai/core/global"
|
|
||||||
|
|
||||||
export type Trace = {
|
|
||||||
write(type: string, data?: unknown): void
|
|
||||||
}
|
|
||||||
|
|
||||||
let state: Trace | false | undefined
|
|
||||||
|
|
||||||
function stamp() {
|
|
||||||
return new Date()
|
|
||||||
.toISOString()
|
|
||||||
.replace(/[-:]/g, "")
|
|
||||||
.replace(/\.\d+Z$/, "Z")
|
|
||||||
}
|
|
||||||
|
|
||||||
function file() {
|
|
||||||
return path.join(Global.Path.log, "direct", `${stamp()}-${process.pid}.jsonl`)
|
|
||||||
}
|
|
||||||
|
|
||||||
function latest() {
|
|
||||||
return path.join(Global.Path.log, "direct", "latest.json")
|
|
||||||
}
|
|
||||||
|
|
||||||
function text(data: unknown) {
|
|
||||||
return JSON.stringify(
|
|
||||||
data,
|
|
||||||
(_key, value) => {
|
|
||||||
if (typeof value === "bigint") {
|
|
||||||
return String(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
return value
|
|
||||||
},
|
|
||||||
0,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function trace(): Trace | undefined {
|
|
||||||
if (state !== undefined) {
|
|
||||||
return state || undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!process.env.OPENCODE_DIRECT_TRACE) {
|
|
||||||
state = false
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
const target = file()
|
|
||||||
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
||||||
fs.writeFileSync(
|
|
||||||
latest(),
|
|
||||||
text({
|
|
||||||
time: new Date().toISOString(),
|
|
||||||
pid: process.pid,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
argv: process.argv.slice(2),
|
|
||||||
path: target,
|
|
||||||
}) + "\n",
|
|
||||||
)
|
|
||||||
state = {
|
|
||||||
write(type: string, data?: unknown) {
|
|
||||||
fs.appendFileSync(
|
|
||||||
target,
|
|
||||||
text({
|
|
||||||
time: new Date().toISOString(),
|
|
||||||
pid: process.pid,
|
|
||||||
type,
|
|
||||||
data,
|
|
||||||
}) + "\n",
|
|
||||||
)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
state.write("trace.start", {
|
|
||||||
argv: process.argv.slice(2),
|
|
||||||
cwd: process.cwd(),
|
|
||||||
path: target,
|
|
||||||
})
|
|
||||||
return state
|
|
||||||
}
|
|
||||||
@@ -1,220 +0,0 @@
|
|||||||
// Model variant resolution and persistence.
|
|
||||||
//
|
|
||||||
// Variants are provider-specific reasoning effort levels (e.g., "high", "max").
|
|
||||||
// Resolution priority: CLI --variant flag > saved preference > session history.
|
|
||||||
//
|
|
||||||
// The saved variant persists across sessions in ~/.local/state/opencode/model.json
|
|
||||||
// so your last-used variant sticks. Cycling (ctrl+t) updates both the active
|
|
||||||
// variant and the persisted file.
|
|
||||||
import path from "path"
|
|
||||||
import { FSUtil } from "@opencode-ai/core/fs-util"
|
|
||||||
import { Context, Effect, Layer } from "effect"
|
|
||||||
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
|
|
||||||
import { makeGlobalNode } from "@opencode-ai/core/effect/app-node"
|
|
||||||
import { makeRuntime } from "@opencode-ai/core/effect/runtime"
|
|
||||||
import { Global } from "@opencode-ai/core/global"
|
|
||||||
import { createSession, sessionVariant, type RunSession, type SessionMessages } from "./session.shared"
|
|
||||||
import type { RunInput, RunProvider } from "./types"
|
|
||||||
|
|
||||||
const MODEL_FILE = path.join(Global.Path.state, "model.json")
|
|
||||||
|
|
||||||
type ModelState = Record<string, unknown> & {
|
|
||||||
variant?: Record<string, string | undefined>
|
|
||||||
}
|
|
||||||
type VariantService = {
|
|
||||||
readonly resolveSavedVariant: (model: RunInput["model"]) => Effect.Effect<string | undefined>
|
|
||||||
readonly saveVariant: (model: RunInput["model"], variant: string | undefined) => Effect.Effect<void>
|
|
||||||
}
|
|
||||||
type VariantRuntime = {
|
|
||||||
resolveSavedVariant(model: RunInput["model"]): Promise<string | undefined>
|
|
||||||
saveVariant(model: RunInput["model"], variant: string | undefined): Promise<void>
|
|
||||||
}
|
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
||||||
return !!value && typeof value === "object" && !Array.isArray(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
class Service extends Context.Service<Service, VariantService>()("@opencode/RunVariant") {}
|
|
||||||
|
|
||||||
function modelKey(provider: string, model: string): string {
|
|
||||||
return `${provider}/${model}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function variantKey(model: NonNullable<RunInput["model"]>): string {
|
|
||||||
return modelKey(model.providerID, model.modelID)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function modelInfo(providers: RunProvider[] | undefined, model: NonNullable<RunInput["model"]>) {
|
|
||||||
const provider = providers?.find((item) => item.id === model.providerID)
|
|
||||||
return {
|
|
||||||
provider: provider?.name ?? model.providerID,
|
|
||||||
model: provider?.models[model.modelID]?.name ?? model.modelID,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatModelLabel(
|
|
||||||
model: NonNullable<RunInput["model"]>,
|
|
||||||
variant: string | undefined,
|
|
||||||
providers?: RunProvider[],
|
|
||||||
): string {
|
|
||||||
const names = modelInfo(providers, model)
|
|
||||||
const label = variant ? ` · ${variant}` : ""
|
|
||||||
return `${names.model} · ${names.provider}${label}`
|
|
||||||
}
|
|
||||||
|
|
||||||
export function cycleVariant(current: string | undefined, variants: string[]): string | undefined {
|
|
||||||
if (variants.length === 0) {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!current) {
|
|
||||||
return variants[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
const idx = variants.indexOf(current)
|
|
||||||
if (idx === -1 || idx === variants.length - 1) {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
return variants[idx + 1]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function pickVariant(model: RunInput["model"], input: RunSession | SessionMessages): string | undefined {
|
|
||||||
return sessionVariant(Array.isArray(input) ? createSession(input) : input, model)
|
|
||||||
}
|
|
||||||
|
|
||||||
function fitVariant(value: string | undefined, variants: string[]): string | undefined {
|
|
||||||
if (!value) {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
if (variants.length === 0 || variants.includes(value)) {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
// Picks the active variant. CLI flag wins, then saved preference, then session
|
|
||||||
// history. fitVariant() checks saved and session values against the available
|
|
||||||
// variants list -- if the provider doesn't offer a variant, it drops.
|
|
||||||
export function resolveVariant(
|
|
||||||
input: string | undefined,
|
|
||||||
session: string | undefined,
|
|
||||||
saved: string | undefined,
|
|
||||||
variants: string[],
|
|
||||||
): string | undefined {
|
|
||||||
if (input !== undefined) {
|
|
||||||
return input
|
|
||||||
}
|
|
||||||
|
|
||||||
const fallback = fitVariant(saved, variants)
|
|
||||||
const current = fitVariant(session, variants)
|
|
||||||
if (current !== undefined) {
|
|
||||||
return current
|
|
||||||
}
|
|
||||||
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
function state(value: unknown): ModelState {
|
|
||||||
if (!isRecord(value)) {
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
|
|
||||||
const variant = isRecord(value.variant)
|
|
||||||
? Object.fromEntries(
|
|
||||||
Object.entries(value.variant).flatMap(([key, item]) => {
|
|
||||||
if (typeof item !== "string") {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
return [[key, item] as const]
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: undefined
|
|
||||||
|
|
||||||
return {
|
|
||||||
...value,
|
|
||||||
variant,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const layer = Layer.fresh(
|
|
||||||
Layer.effect(
|
|
||||||
Service,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const file = yield* FSUtil.Service
|
|
||||||
|
|
||||||
const read = Effect.fn("RunVariant.read")(function* () {
|
|
||||||
return yield* file.readJson(MODEL_FILE).pipe(
|
|
||||||
Effect.map(state),
|
|
||||||
Effect.catchCause(() => Effect.succeed(state(undefined))),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
const resolveSavedVariant = Effect.fn("RunVariant.resolveSavedVariant")(function* (model: RunInput["model"]) {
|
|
||||||
if (!model) {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
return (yield* read()).variant?.[variantKey(model)]
|
|
||||||
})
|
|
||||||
|
|
||||||
const saveVariant = Effect.fn("RunVariant.saveVariant")(function* (
|
|
||||||
model: RunInput["model"],
|
|
||||||
variant: string | undefined,
|
|
||||||
) {
|
|
||||||
if (!model) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const current = yield* read()
|
|
||||||
const next = {
|
|
||||||
...current.variant,
|
|
||||||
}
|
|
||||||
const key = variantKey(model)
|
|
||||||
if (variant) {
|
|
||||||
next[key] = variant
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!variant) {
|
|
||||||
delete next[key]
|
|
||||||
}
|
|
||||||
|
|
||||||
yield* file
|
|
||||||
.writeJson(MODEL_FILE, {
|
|
||||||
...current,
|
|
||||||
variant: next,
|
|
||||||
})
|
|
||||||
.pipe(Effect.orElseSucceed(() => undefined))
|
|
||||||
})
|
|
||||||
|
|
||||||
return Service.of({
|
|
||||||
resolveSavedVariant,
|
|
||||||
saveVariant,
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
const node = makeGlobalNode({ service: Service, layer, deps: [FSUtil.node] })
|
|
||||||
|
|
||||||
/** @internal Exported for testing. */
|
|
||||||
export function createVariantRuntime(replacements?: readonly LayerNode.Replacement[]): VariantRuntime {
|
|
||||||
const runtime = makeRuntime(Service, LayerNode.compile(node, replacements))
|
|
||||||
return {
|
|
||||||
resolveSavedVariant: (model) => runtime.runPromise((svc) => svc.resolveSavedVariant(model)).catch(() => undefined),
|
|
||||||
saveVariant: (model, variant) => runtime.runPromise((svc) => svc.saveVariant(model, variant)).catch(() => {}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const runtime = createVariantRuntime()
|
|
||||||
|
|
||||||
export async function resolveSavedVariant(model: RunInput["model"]): Promise<string | undefined> {
|
|
||||||
return runtime.resolveSavedVariant(model)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function saveVariant(model: RunInput["model"], variant: string | undefined): void {
|
|
||||||
void runtime.saveVariant(model, variant)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export { runNonInteractive, type RunCommandInput } from "./run"
|
||||||
|
export { runV1Bridge, type V1RunCommandInput } from "./v1"
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
import type { EventSubscribeOutput, OpenCodeClient } from "@opencode-ai/client/promise"
|
import type {
|
||||||
|
EventSubscribeOutput,
|
||||||
|
JsonValue,
|
||||||
|
LLMToolContent,
|
||||||
|
LocationRef,
|
||||||
|
OpenCodeClient,
|
||||||
|
SessionMessageAssistantTool,
|
||||||
|
} from "@opencode-ai/client/promise"
|
||||||
import { SessionMessage } from "@opencode-ai/schema/session-message"
|
import { SessionMessage } from "@opencode-ai/schema/session-message"
|
||||||
import { EOL } from "node:os"
|
import { EOL } from "node:os"
|
||||||
import { readFile } from "node:fs/promises"
|
import { readFile } from "node:fs/promises"
|
||||||
|
import { toolOutputText, type MiniToolPart } from "@opencode-ai/tui/mini/tool"
|
||||||
import { UI } from "./ui"
|
import { UI } from "./ui"
|
||||||
import type { MiniToolPart } from "./types"
|
|
||||||
|
|
||||||
type Model = {
|
type Model = {
|
||||||
providerID: string
|
providerID: string
|
||||||
@@ -19,6 +26,7 @@ type File = {
|
|||||||
type Input = {
|
type Input = {
|
||||||
client: OpenCodeClient
|
client: OpenCodeClient
|
||||||
sessionID: string
|
sessionID: string
|
||||||
|
location: LocationRef
|
||||||
message: string
|
message: string
|
||||||
files: File[]
|
files: File[]
|
||||||
agent?: string
|
agent?: string
|
||||||
@@ -29,8 +37,9 @@ type Input = {
|
|||||||
auto: boolean
|
auto: boolean
|
||||||
/** True when the client is attached to a shared server rather than an exclusive in-process one. */
|
/** True when the client is attached to a shared server rather than an exclusive in-process one. */
|
||||||
attached: boolean
|
attached: boolean
|
||||||
renderTool: (part: MiniToolPart) => Promise<void>
|
compatibility?: "v1"
|
||||||
renderToolError: (part: MiniToolPart) => Promise<void>
|
renderTool: (part: SessionMessageAssistantTool) => Promise<void>
|
||||||
|
renderToolError: (part: SessionMessageAssistantTool) => Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
type StartedPart = {
|
type StartedPart = {
|
||||||
@@ -41,9 +50,12 @@ type StartedPart = {
|
|||||||
type ToolState = StartedPart & {
|
type ToolState = StartedPart & {
|
||||||
assistantMessageID: string
|
assistantMessageID: string
|
||||||
tool: string
|
tool: string
|
||||||
input: Record<string, unknown>
|
input: Record<string, JsonValue>
|
||||||
raw?: string
|
raw?: string
|
||||||
provider?: unknown
|
provider?: unknown
|
||||||
|
providerState?: SessionMessageAssistantTool["providerState"]
|
||||||
|
structured: Record<string, JsonValue>
|
||||||
|
content: LLMToolContent[]
|
||||||
}
|
}
|
||||||
|
|
||||||
type V2Event = EventSubscribeOutput
|
type V2Event = EventSubscribeOutput
|
||||||
@@ -66,11 +78,12 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
let submitted = false
|
let submitted = false
|
||||||
let promoted = false
|
let promoted = false
|
||||||
let emittedError = false
|
let emittedError = false
|
||||||
let questionRejected = false
|
|
||||||
let permissionRejected = false
|
let permissionRejected = false
|
||||||
let formCancelled = false
|
let formCancelled = false
|
||||||
let interrupted = false
|
let interrupted = false
|
||||||
|
let v1InvalidOutput = false
|
||||||
let admission: AbortController | undefined
|
let admission: AbortController | undefined
|
||||||
|
let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined
|
||||||
|
|
||||||
const emit = (type: string, timestamp: number, data: Record<string, unknown>) => {
|
const emit = (type: string, timestamp: number, data: Record<string, unknown>) => {
|
||||||
if (input.format !== "json") return false
|
if (input.format !== "json") return false
|
||||||
@@ -91,6 +104,17 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
UI.empty()
|
UI.empty()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const flushStep = () => {
|
||||||
|
if (!pendingStep) return
|
||||||
|
const value = pendingStep
|
||||||
|
pendingStep = undefined
|
||||||
|
if (!emit("step_start", value.timestamp, { part: value.part }) && input.format !== "json") {
|
||||||
|
UI.empty()
|
||||||
|
UI.println(value.label)
|
||||||
|
UI.empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const replyPermission = async (request: { id: string; action: string; resources: ReadonlyArray<string> }) => {
|
const replyPermission = async (request: { id: string; action: string; resources: ReadonlyArray<string> }) => {
|
||||||
if (!input.auto) {
|
if (!input.auto) {
|
||||||
permissionRejected = true
|
permissionRejected = true
|
||||||
@@ -112,14 +136,16 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const rejectQuestion = async (request: { id: string }) => {
|
|
||||||
questionRejected = true
|
|
||||||
await input.client.question.reject({ sessionID: input.sessionID, requestID: request.id }).catch(() => {})
|
|
||||||
}
|
|
||||||
|
|
||||||
const cancelForm = async (request: Pick<FormRequest, "id" | "sessionID">) => {
|
const cancelForm = async (request: Pick<FormRequest, "id" | "sessionID">) => {
|
||||||
|
try {
|
||||||
|
await input.client.form.cancel(
|
||||||
|
{ sessionID: request.sessionID, formID: request.id },
|
||||||
|
...formRequestOptions(request.sessionID === GLOBAL_FORM_SESSION_ID ? input.location : undefined),
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
if (!formAlreadySettled(error)) throw error
|
||||||
|
}
|
||||||
formCancelled = true
|
formCancelled = true
|
||||||
await input.client.form.cancel({ sessionID: request.sessionID, formID: request.id }).catch(() => {})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const consume = async () => {
|
const consume = async () => {
|
||||||
@@ -138,15 +164,13 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
await replyPermission(event.data)
|
await replyPermission(event.data)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if (event.type === "question.v2.asked" && submitted && event.data.sessionID === input.sessionID) {
|
|
||||||
await rejectQuestion(event.data)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (
|
if (
|
||||||
event.type === "form.created" &&
|
event.type === "form.created" &&
|
||||||
submitted &&
|
submitted &&
|
||||||
(event.data.form.sessionID === input.sessionID ||
|
(event.data.form.sessionID === input.sessionID ||
|
||||||
(!input.attached && event.data.form.sessionID === GLOBAL_FORM_SESSION_ID))
|
(!input.attached &&
|
||||||
|
event.data.form.sessionID === GLOBAL_FORM_SESSION_ID &&
|
||||||
|
sameLocation(event.location, input.location)))
|
||||||
) {
|
) {
|
||||||
await cancelForm(event.data.form)
|
await cancelForm(event.data.form)
|
||||||
continue
|
continue
|
||||||
@@ -163,7 +187,7 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
if (
|
if (
|
||||||
event.type === "session.execution.interrupted" &&
|
event.type === "session.execution.interrupted" &&
|
||||||
event.data.reason === "user" &&
|
event.data.reason === "user" &&
|
||||||
(interrupted || permissionRejected || questionRejected || formCancelled)
|
(interrupted || permissionRejected || formCancelled)
|
||||||
) {
|
) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -177,6 +201,14 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
type: "step-start",
|
type: "step-start",
|
||||||
snapshot: event.data.snapshot,
|
snapshot: event.data.snapshot,
|
||||||
}
|
}
|
||||||
|
if (input.compatibility === "v1") {
|
||||||
|
pendingStep = {
|
||||||
|
timestamp: time,
|
||||||
|
part,
|
||||||
|
label: `> ${event.data.agent} · ${event.data.model.id}`,
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
if (!emit("step_start", time, { part }) && input.format !== "json") {
|
if (!emit("step_start", time, { part }) && input.format !== "json") {
|
||||||
UI.empty()
|
UI.empty()
|
||||||
UI.println(`> ${event.data.agent} · ${event.data.model.id}`)
|
UI.println(`> ${event.data.agent} · ${event.data.model.id}`)
|
||||||
@@ -186,6 +218,7 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "session.text.started") {
|
if (event.type === "session.text.started") {
|
||||||
|
flushStep()
|
||||||
starts.set("text", { id: partID(event.id), timestamp: time })
|
starts.set("text", { id: partID(event.id), timestamp: time })
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -205,6 +238,7 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "session.reasoning.started") {
|
if (event.type === "session.reasoning.started") {
|
||||||
|
flushStep()
|
||||||
starts.set("reasoning", { id: partID(event.id), timestamp: time })
|
starts.set("reasoning", { id: partID(event.id), timestamp: time })
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -235,23 +269,33 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "session.tool.input.started") {
|
if (event.type === "session.tool.input.started") {
|
||||||
tools.set(event.data.callID, {
|
flushStep()
|
||||||
|
tools.set(toolKey(event.data.assistantMessageID, event.data.callID), {
|
||||||
id: partID(event.id),
|
id: partID(event.id),
|
||||||
timestamp: time,
|
timestamp: time,
|
||||||
assistantMessageID: event.data.assistantMessageID,
|
assistantMessageID: event.data.assistantMessageID,
|
||||||
tool: event.data.name,
|
tool: event.data.name,
|
||||||
input: {},
|
input: {},
|
||||||
|
structured: {},
|
||||||
|
content: [],
|
||||||
})
|
})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if (event.type === "session.tool.input.ended") {
|
if (event.type === "session.tool.input.ended") {
|
||||||
const current = tools.get(event.data.callID)
|
const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))
|
||||||
if (current) current.raw = event.data.text
|
if (current) current.raw = event.data.text
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if (event.type === "session.tool.input.delta") {
|
||||||
|
const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))
|
||||||
|
if (current) current.raw = (current.raw ?? "") + event.data.delta
|
||||||
|
continue
|
||||||
|
}
|
||||||
if (event.type === "session.tool.called") {
|
if (event.type === "session.tool.called") {
|
||||||
const current = tools.get(event.data.callID)
|
flushStep()
|
||||||
tools.set(event.data.callID, {
|
const key = toolKey(event.data.assistantMessageID, event.data.callID)
|
||||||
|
const current = tools.get(key)
|
||||||
|
tools.set(key, {
|
||||||
id: current?.id ?? partID(event.id),
|
id: current?.id ?? partID(event.id),
|
||||||
timestamp: current?.timestamp ?? time,
|
timestamp: current?.timestamp ?? time,
|
||||||
assistantMessageID: event.data.assistantMessageID,
|
assistantMessageID: event.data.assistantMessageID,
|
||||||
@@ -259,11 +303,39 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
input: event.data.input,
|
input: event.data.input,
|
||||||
raw: current?.raw,
|
raw: current?.raw,
|
||||||
provider: { executed: event.data.executed, state: event.data.state },
|
provider: { executed: event.data.executed, state: event.data.state },
|
||||||
|
providerState: event.data.state,
|
||||||
|
structured: {},
|
||||||
|
content: [],
|
||||||
})
|
})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if (event.type === "session.tool.progress") {
|
||||||
|
const current = tools.get(toolKey(event.data.assistantMessageID, event.data.callID))
|
||||||
|
if (current) {
|
||||||
|
current.structured = event.data.structured
|
||||||
|
current.content = event.data.content
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
if (event.type === "session.tool.success") {
|
if (event.type === "session.tool.success") {
|
||||||
const current = tools.get(event.data.callID) ?? fallbackTool(event)
|
const key = toolKey(event.data.assistantMessageID, event.data.callID)
|
||||||
|
const current = tools.get(key) ?? fallbackTool(event)
|
||||||
|
const tool: SessionMessageAssistantTool = {
|
||||||
|
type: "tool",
|
||||||
|
id: event.data.callID,
|
||||||
|
name: current.tool,
|
||||||
|
executed: event.data.executed,
|
||||||
|
providerState: current.providerState,
|
||||||
|
providerResultState: event.data.resultState,
|
||||||
|
state: {
|
||||||
|
status: "completed",
|
||||||
|
input: current.input,
|
||||||
|
structured: event.data.structured,
|
||||||
|
content: event.data.content,
|
||||||
|
result: event.data.result,
|
||||||
|
},
|
||||||
|
time: { created: current.timestamp, ran: current.timestamp, completed: time },
|
||||||
|
}
|
||||||
const part: MiniToolPart = {
|
const part: MiniToolPart = {
|
||||||
id: current.id,
|
id: current.id,
|
||||||
sessionID: input.sessionID,
|
sessionID: input.sessionID,
|
||||||
@@ -274,10 +346,7 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
state: {
|
state: {
|
||||||
status: "completed",
|
status: "completed",
|
||||||
input: current.input,
|
input: current.input,
|
||||||
output: event.data.content
|
output: toolOutputText(current.tool, event.data.content),
|
||||||
.filter((item) => item.type === "text")
|
|
||||||
.map((item) => item.text)
|
|
||||||
.join("\n"),
|
|
||||||
title: current.tool,
|
title: current.tool,
|
||||||
metadata: {
|
metadata: {
|
||||||
structured: event.data.structured,
|
structured: event.data.structured,
|
||||||
@@ -290,13 +359,31 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
time: { start: current.timestamp, end: time },
|
time: { start: current.timestamp, end: time },
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
tools.delete(event.data.callID)
|
tools.delete(key)
|
||||||
if (!emit("tool_use", time, { part })) await input.renderTool(part)
|
if (!emit("tool_use", time, { part })) await input.renderTool(tool)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if (event.type === "session.tool.failed") {
|
if (event.type === "session.tool.failed") {
|
||||||
const current = tools.get(event.data.callID) ?? fallbackTool(event)
|
const key = toolKey(event.data.assistantMessageID, event.data.callID)
|
||||||
|
const current = tools.get(key) ?? fallbackTool(event)
|
||||||
const error = event.data.error.message
|
const error = event.data.error.message
|
||||||
|
const tool: SessionMessageAssistantTool = {
|
||||||
|
type: "tool",
|
||||||
|
id: event.data.callID,
|
||||||
|
name: current.tool,
|
||||||
|
executed: event.data.executed,
|
||||||
|
providerState: current.providerState,
|
||||||
|
providerResultState: event.data.resultState,
|
||||||
|
state: {
|
||||||
|
status: "error",
|
||||||
|
input: current.input,
|
||||||
|
structured: current.structured,
|
||||||
|
content: current.content,
|
||||||
|
error: event.data.error,
|
||||||
|
result: event.data.result,
|
||||||
|
},
|
||||||
|
time: { created: current.timestamp, ran: current.timestamp, completed: time },
|
||||||
|
}
|
||||||
const part: MiniToolPart = {
|
const part: MiniToolPart = {
|
||||||
id: current.id,
|
id: current.id,
|
||||||
sessionID: input.sessionID,
|
sessionID: input.sessionID,
|
||||||
@@ -317,15 +404,28 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
time: { start: current.timestamp, end: time },
|
time: { start: current.timestamp, end: time },
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
tools.delete(event.data.callID)
|
tools.delete(key)
|
||||||
|
if (input.compatibility === "v1" && (permissionRejected || formCancelled)) continue
|
||||||
if (!emit("tool_use", time, { part })) {
|
if (!emit("tool_use", time, { part })) {
|
||||||
await input.renderToolError(part)
|
if (toolOutputText(current.tool, current.content).trim())
|
||||||
|
await input.renderTool({
|
||||||
|
...tool,
|
||||||
|
state: {
|
||||||
|
status: "completed",
|
||||||
|
input: current.input,
|
||||||
|
structured: current.structured,
|
||||||
|
content: current.content,
|
||||||
|
result: event.data.result,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await input.renderToolError(tool)
|
||||||
UI.error(error)
|
UI.error(error)
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "session.step.ended") {
|
if (event.type === "session.step.ended") {
|
||||||
|
flushStep()
|
||||||
const part = {
|
const part = {
|
||||||
id: partID(event.id),
|
id: partID(event.id),
|
||||||
sessionID: input.sessionID,
|
sessionID: input.sessionID,
|
||||||
@@ -340,14 +440,25 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if (event.type === "session.step.failed") {
|
if (event.type === "session.step.failed") {
|
||||||
if (interrupted || permissionRejected || questionRejected || formCancelled) continue
|
if (
|
||||||
|
input.compatibility === "v1" &&
|
||||||
|
event.data.error.message === "Provider stream ended without a terminal finish event"
|
||||||
|
) {
|
||||||
|
pendingStep = undefined
|
||||||
|
v1InvalidOutput = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (interrupted || permissionRejected || formCancelled) continue
|
||||||
|
flushStep()
|
||||||
emittedError = true
|
emittedError = true
|
||||||
process.exitCode = 1
|
process.exitCode = 1
|
||||||
if (!emit("error", time, { error: event.data.error })) UI.error(event.data.error.message)
|
if (!emit("error", time, { error: event.data.error })) UI.error(event.data.error.message)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if (event.type === "session.execution.failed") {
|
if (event.type === "session.execution.failed") {
|
||||||
if (!emittedError && !questionRejected && !formCancelled) {
|
if (input.compatibility === "v1" && (v1InvalidOutput || permissionRejected || formCancelled)) return
|
||||||
|
flushStep()
|
||||||
|
if (!emittedError && !formCancelled) {
|
||||||
emittedError = true
|
emittedError = true
|
||||||
process.exitCode = 1
|
process.exitCode = 1
|
||||||
if (!emit("error", time, { error: event.data.error })) UI.error(event.data.error.message)
|
if (!emit("error", time, { error: event.data.error })) UI.error(event.data.error.message)
|
||||||
@@ -355,6 +466,7 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (event.type === "session.execution.interrupted") {
|
if (event.type === "session.execution.interrupted") {
|
||||||
|
if (input.compatibility === "v1" && (permissionRejected || formCancelled)) return
|
||||||
if (event.data.reason === "user" && interrupted) process.exitCode = 130
|
if (event.data.reason === "user" && interrupted) process.exitCode = 130
|
||||||
if (event.data.reason !== "user" && !emittedError) {
|
if (event.data.reason !== "user" && !emittedError) {
|
||||||
emittedError = true
|
emittedError = true
|
||||||
@@ -429,19 +541,23 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
if (!response) return
|
if (!response) return
|
||||||
if (interrupted) await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})
|
if (interrupted) await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})
|
||||||
|
|
||||||
const [permissions, questions, forms] = await Promise.all([
|
const [permissions, forms, globals] = await Promise.all([
|
||||||
input.client.permission.list({ sessionID: input.sessionID }).catch(() => undefined),
|
input.client.permission.list({ sessionID: input.sessionID }).catch(() => undefined),
|
||||||
input.client.question.list({ sessionID: input.sessionID }).catch(() => undefined),
|
input.client.form.list({ sessionID: input.sessionID }).catch(() => undefined),
|
||||||
Promise.all(
|
input.attached
|
||||||
(input.attached ? [input.sessionID] : [input.sessionID, GLOBAL_FORM_SESSION_ID]).map((sessionID) =>
|
? Promise.resolve(undefined)
|
||||||
input.client.form.list({ sessionID }).catch(() => undefined),
|
: input.client.form.request
|
||||||
),
|
.list({
|
||||||
),
|
location: { directory: input.location.directory, workspace: input.location.workspaceID },
|
||||||
|
})
|
||||||
|
.catch(() => undefined),
|
||||||
])
|
])
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
...(permissions ?? []).map(replyPermission),
|
...(permissions ?? []).map(replyPermission),
|
||||||
...(questions ?? []).map(rejectQuestion),
|
...(forms ?? []).map(cancelForm),
|
||||||
...forms.flatMap((response) => response ?? []).map(cancelForm),
|
...(globals && sameLocation(globals.location, input.location)
|
||||||
|
? globals.data.filter((form) => form.sessionID === GLOBAL_FORM_SESSION_ID).map(cancelForm)
|
||||||
|
: []),
|
||||||
])
|
])
|
||||||
await completed
|
await completed
|
||||||
} finally {
|
} finally {
|
||||||
@@ -451,10 +567,34 @@ export async function runNonInteractivePrompt(input: Input) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sameLocation(left: LocationRef | undefined, right: LocationRef) {
|
||||||
|
return !!left && left.directory === right.directory && left.workspaceID === right.workspaceID
|
||||||
|
}
|
||||||
|
|
||||||
|
function formRequestOptions(location: LocationRef | undefined): [] | [{ headers: Record<string, string> }] {
|
||||||
|
if (!location) return []
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
"x-opencode-directory": encodeURIComponent(location.directory),
|
||||||
|
...(location.workspaceID ? { "x-opencode-workspace": location.workspaceID } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
function formAlreadySettled(error: unknown) {
|
||||||
|
return !!error && typeof error === "object" && Reflect.get(error, "_tag") === "FormAlreadySettledError"
|
||||||
|
}
|
||||||
|
|
||||||
function partID(eventID: string) {
|
function partID(eventID: string) {
|
||||||
return `prt_${eventID.replace(/^evt_/, "")}`
|
return `prt_${eventID.replace(/^evt_/, "")}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toolKey(messageID: string, callID: string) {
|
||||||
|
return `${messageID}\u0000${callID}`
|
||||||
|
}
|
||||||
|
|
||||||
function fallbackTool(event: {
|
function fallbackTool(event: {
|
||||||
id: string
|
id: string
|
||||||
created: number
|
created: number
|
||||||
@@ -466,6 +606,8 @@ function fallbackTool(event: {
|
|||||||
assistantMessageID: event.data.assistantMessageID,
|
assistantMessageID: event.data.assistantMessageID,
|
||||||
tool: "tool",
|
tool: "tool",
|
||||||
input: {},
|
input: {},
|
||||||
|
structured: {},
|
||||||
|
content: [],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -480,7 +622,7 @@ async function prepareFile(file: File) {
|
|||||||
const uri = file.url.startsWith("data:")
|
const uri = file.url.startsWith("data:")
|
||||||
? file.url
|
? file.url
|
||||||
: `data:${file.mime};base64,${(await readFile(new URL(file.url))).toString("base64")}`
|
: `data:${file.mime};base64,${(await readFile(new URL(file.url))).toString("base64")}`
|
||||||
return { attachment: { uri, mime: file.mime, name: file.filename } }
|
return { attachment: { uri, name: file.filename } }
|
||||||
}
|
}
|
||||||
const content = file.url.startsWith("data:")
|
const content = file.url.startsWith("data:")
|
||||||
? Buffer.from(file.url.slice(file.url.indexOf(",") + 1), "base64").toString("utf8")
|
? Buffer.from(file.url.slice(file.url.indexOf(",") + 1), "base64").toString("utf8")
|
||||||
@@ -1,15 +1,14 @@
|
|||||||
import { Service, type Endpoint } from "@opencode-ai/client/effect/service"
|
import { Service, type Endpoint } from "@opencode-ai/client/effect/service"
|
||||||
import { OpenCode, type OpenCodeClient } from "@opencode-ai/client/promise"
|
import { OpenCode, type OpenCodeClient, type SessionMessageAssistantTool } from "@opencode-ai/client/promise"
|
||||||
import { FSUtil } from "@opencode-ai/core/fs-util"
|
import { FSUtil } from "@opencode-ai/core/fs-util"
|
||||||
import { Model } from "@opencode-ai/schema/model"
|
|
||||||
import { open } from "node:fs/promises"
|
import { open } from "node:fs/promises"
|
||||||
import path from "node:path"
|
import path from "node:path"
|
||||||
import { readStdin } from "../util/io"
|
import { readStdin } from "../util/io"
|
||||||
import { ServerConnection } from "../services/server-connection"
|
import { ServerConnection } from "../services/server-connection"
|
||||||
import { loadRunAgents, waitForCatalogReady } from "./catalog.shared"
|
import { waitForCatalogReady } from "../services/catalog"
|
||||||
|
import { parseSessionTargetModel, resolveSessionTarget } from "../session-target"
|
||||||
|
import { toolInlineInfo } from "@opencode-ai/tui/mini/tool"
|
||||||
import { runNonInteractivePrompt } from "./noninteractive"
|
import { runNonInteractivePrompt } from "./noninteractive"
|
||||||
import { toolInlineInfo } from "./tool"
|
|
||||||
import type { MiniToolPart } from "./types"
|
|
||||||
import { UI } from "./ui"
|
import { UI } from "./ui"
|
||||||
|
|
||||||
export type RunCommandInput = {
|
export type RunCommandInput = {
|
||||||
@@ -39,78 +38,127 @@ type Prepared = {
|
|||||||
files: FilePart[]
|
files: FilePart[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ExecutionOptions = {
|
||||||
|
root?: string
|
||||||
|
directory?: string
|
||||||
|
useServerDirectory?: boolean
|
||||||
|
variant?: string
|
||||||
|
attached?: boolean
|
||||||
|
compatibility?: "v1"
|
||||||
|
}
|
||||||
|
|
||||||
|
class RunTargetError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
readonly sessionID?: string,
|
||||||
|
) {
|
||||||
|
super(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const ATTACH_FILE_MAX_BYTES = 10 * 1024 * 1024
|
const ATTACH_FILE_MAX_BYTES = 10 * 1024 * 1024
|
||||||
|
|
||||||
export function runNonInteractive(input: RunCommandInput) {
|
export function runNonInteractive(input: RunCommandInput) {
|
||||||
return run(input).catch((error) => reportError(input, error instanceof Error ? error.message : String(error)))
|
return runNonInteractiveWithOptions(input, {})
|
||||||
}
|
}
|
||||||
|
|
||||||
async function run(input: RunCommandInput) {
|
/** @internal Used only by the V1 command boundary. */
|
||||||
|
export function runNonInteractiveWithOptions(input: RunCommandInput, options: ExecutionOptions) {
|
||||||
|
return run(input, options).catch((error) => reportRunError(input, errorMessage(error)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run(input: RunCommandInput, options: ExecutionOptions) {
|
||||||
if (input.fork && !input.continue && !input.session) fail("--fork requires --continue or --session")
|
if (input.fork && !input.continue && !input.session) fail("--fork requires --continue or --session")
|
||||||
const root = process.env.PWD ?? process.cwd()
|
const root = options.root ?? process.env.PWD ?? process.cwd()
|
||||||
const directory = localDirectory(root)
|
const local = localDirectory(root)
|
||||||
|
const directory = options.useServerDirectory ? undefined : (options.directory ?? local)
|
||||||
const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin())
|
const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin())
|
||||||
if (!message?.trim()) fail("You must provide a message")
|
if (!message?.trim()) fail("You must provide a message")
|
||||||
const files = await Promise.all(input.file.map((file) => prepareFile(file, root)))
|
const files = await Promise.all(input.file.map((file) => prepareFile(file, root, options)))
|
||||||
const prepared = { directory, message, files }
|
const prepared = { directory, message, files }
|
||||||
return execute(input, prepared, input.server.endpoint)
|
return execute(input, prepared, input.server.endpoint, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function execute(input: RunCommandInput, prepared: Prepared, endpoint: Endpoint) {
|
async function execute(input: RunCommandInput, prepared: Prepared, endpoint: Endpoint, options: ExecutionOptions) {
|
||||||
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
|
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
|
||||||
const requestedDirectory = prepared.directory ?? (await client.location.get()).directory
|
|
||||||
if (!requestedDirectory) fail("Failed to resolve server directory")
|
|
||||||
const session = await selectSession(client, requestedDirectory, input)
|
|
||||||
const cwd = session?.location.directory ?? requestedDirectory
|
|
||||||
const workspace = session?.location.workspaceID
|
|
||||||
const explicit = parseRunModel(input.model)
|
const explicit = parseRunModel(input.model)
|
||||||
const explicitModel = explicit?.model
|
const target = await resolveSessionTarget({
|
||||||
const variant = explicit?.variant
|
client,
|
||||||
const sessionModel = session?.model ? { providerID: session.model.providerID, modelID: session.model.id } : undefined
|
location: prepared.directory ? { directory: prepared.directory } : undefined,
|
||||||
const defaultModel =
|
continue: input.continue,
|
||||||
!explicitModel && !sessionModel
|
session: input.session,
|
||||||
? await client.model
|
fork: input.fork,
|
||||||
.default({ location: { directory: cwd, workspace } })
|
model: explicit
|
||||||
.then((result) => (result.data ? { providerID: result.data.providerID, modelID: result.data.id } : undefined))
|
? { providerID: explicit.model.providerID, id: explicit.model.modelID, variant: explicit.variant }
|
||||||
: undefined
|
: undefined,
|
||||||
const model = pickRunModel(explicitModel, variant, sessionModel, defaultModel)
|
agent: input.agent,
|
||||||
if (variant && !model) return reportError(input, "Cannot select a variant before selecting a model", session?.id)
|
prepare: async (next) => {
|
||||||
if (model) {
|
const selected =
|
||||||
await waitForCatalogReady({ sdk: client, directory: cwd, workspace, model })
|
next.model ??
|
||||||
const available = await client.model.list({ location: { directory: cwd, workspace } })
|
(await client.model
|
||||||
if (!available.data.some((item) => item.providerID === model.providerID && item.id === model.modelID))
|
.default({ location: { directory: next.location.directory, workspace: next.location.workspaceID } })
|
||||||
return reportError(input, `Model unavailable: ${model.providerID}/${model.modelID}`, session?.id)
|
.then((result) => result.data))
|
||||||
}
|
const model = selected
|
||||||
const agent = await validateAgent(client, cwd, input.agent)
|
? {
|
||||||
const selected =
|
providerID: selected.providerID,
|
||||||
session ??
|
id: selected.id,
|
||||||
(await client.session.create({
|
variant: options.variant ?? ("variant" in selected ? selected.variant : undefined),
|
||||||
agent,
|
}
|
||||||
model: model ? { providerID: model.providerID, id: model.modelID, variant } : undefined,
|
: undefined
|
||||||
location: { directory: cwd },
|
if ((options.variant ?? explicit?.variant) && !model)
|
||||||
}))
|
throw new RunTargetError("Cannot select a variant before selecting a model", next.session?.id)
|
||||||
if (!session && input.title !== undefined) {
|
if (model) {
|
||||||
|
await waitForCatalogReady({
|
||||||
|
sdk: client,
|
||||||
|
directory: next.location.directory,
|
||||||
|
workspace: next.location.workspaceID,
|
||||||
|
model: { providerID: model.providerID, modelID: model.id },
|
||||||
|
})
|
||||||
|
const available = await client.model.list({
|
||||||
|
location: { directory: next.location.directory, workspace: next.location.workspaceID },
|
||||||
|
})
|
||||||
|
if (!available.data.some((item) => item.providerID === model.providerID && item.id === model.id))
|
||||||
|
throw new RunTargetError(`Model unavailable: ${model.providerID}/${model.id}`, next.session?.id)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
model,
|
||||||
|
agent: input.agent
|
||||||
|
? await validateAgent(client, next.location.directory, next.location.workspaceID, input.agent)
|
||||||
|
: next.agent,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}).catch((error) => {
|
||||||
|
if (!(error instanceof RunTargetError)) throw error
|
||||||
|
reportRunError(input, error.message, error.sessionID)
|
||||||
|
return undefined
|
||||||
|
})
|
||||||
|
if (!target) return
|
||||||
|
const model = target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined
|
||||||
|
const variant = target.model?.variant
|
||||||
|
if (!target.resume && input.title !== undefined) {
|
||||||
await client.session.rename({
|
await client.session.rename({
|
||||||
sessionID: selected.id,
|
sessionID: target.session.id,
|
||||||
title: input.title || prepared.message.slice(0, 50) + (prepared.message.length > 50 ? "..." : ""),
|
title: input.title || prepared.message.slice(0, 50) + (prepared.message.length > 50 ? "..." : ""),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
await runNonInteractivePrompt({
|
await runNonInteractivePrompt({
|
||||||
client,
|
client,
|
||||||
sessionID: selected.id,
|
sessionID: target.session.id,
|
||||||
|
location: target.location,
|
||||||
message: prepared.message,
|
message: prepared.message,
|
||||||
files: prepared.files,
|
files: prepared.files,
|
||||||
agent,
|
agent: target.agent,
|
||||||
model,
|
model,
|
||||||
variant,
|
variant,
|
||||||
thinking: input.thinking ?? false,
|
thinking: input.thinking ?? false,
|
||||||
format: input.format,
|
format: input.format,
|
||||||
auto: input.auto ?? false,
|
auto: input.auto ?? false,
|
||||||
attached: true,
|
attached: options.attached ?? true,
|
||||||
renderTool,
|
compatibility: options.compatibility,
|
||||||
renderToolError,
|
renderTool: (part) => renderTool(part, target.location.directory),
|
||||||
}).catch((error) => reportError(input, error instanceof Error ? error.message : String(error), selected.id))
|
renderToolError: (part) => renderToolError(part, target.location.directory),
|
||||||
|
}).catch((error) => reportRunError(input, errorMessage(error), target.session.id))
|
||||||
}
|
}
|
||||||
|
|
||||||
export function mergeInput(message: string | undefined, piped: string | undefined) {
|
export function mergeInput(message: string | undefined, piped: string | undefined) {
|
||||||
@@ -119,17 +167,6 @@ export function mergeInput(message: string | undefined, piped: string | undefine
|
|||||||
return message + "\n" + piped
|
return message + "\n" + piped
|
||||||
}
|
}
|
||||||
|
|
||||||
export function pickRunModel(
|
|
||||||
explicit: { providerID: string; modelID: string } | undefined,
|
|
||||||
variant: string | undefined,
|
|
||||||
session: { providerID: string; modelID: string } | undefined,
|
|
||||||
fallback: { providerID: string; modelID: string } | undefined,
|
|
||||||
) {
|
|
||||||
if (explicit) return explicit
|
|
||||||
if (!variant) return
|
|
||||||
return session ?? fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatMessage(message: string[]) {
|
function formatMessage(message: string[]) {
|
||||||
const value = message.map((part) => (part.includes(" ") ? `"${part.replace(/"/g, '\\"')}"` : part)).join(" ")
|
const value = message.map((part) => (part.includes(" ") ? `"${part.replace(/"/g, '\\"')}"` : part)).join(" ")
|
||||||
return value || undefined
|
return value || undefined
|
||||||
@@ -145,17 +182,20 @@ function localDirectory(root: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function parseRunModel(value?: string) {
|
export function parseRunModel(value?: string) {
|
||||||
if (!value) return
|
const ref = parseSessionTargetModel(value)
|
||||||
const ref = Model.Ref.parse(value)
|
if (!ref) return
|
||||||
return {
|
return {
|
||||||
model: { providerID: ref.providerID, modelID: ref.id },
|
model: { providerID: ref.providerID, modelID: ref.id },
|
||||||
variant: ref.variant,
|
variant: ref.variant,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function validateAgent(client: OpenCodeClient, directory: string, name?: string) {
|
async function validateAgent(client: OpenCodeClient, directory: string, workspace: string | undefined, name?: string) {
|
||||||
if (!name) return
|
if (!name) return
|
||||||
const agents = await loadRunAgents(client, directory).catch(() => undefined)
|
const agents = await client.agent
|
||||||
|
.list({ location: { directory, workspace } })
|
||||||
|
.then((result) => result.data)
|
||||||
|
.catch(() => undefined)
|
||||||
if (!agents) {
|
if (!agents) {
|
||||||
warning("failed to list agents. Falling back to default agent")
|
warning("failed to list agents. Falling back to default agent")
|
||||||
return
|
return
|
||||||
@@ -172,24 +212,13 @@ async function validateAgent(client: OpenCodeClient, directory: string, name?: s
|
|||||||
return name
|
return name
|
||||||
}
|
}
|
||||||
|
|
||||||
async function selectSession(client: OpenCodeClient, directory: string, input: RunCommandInput) {
|
async function prepareFile(input: string, directory: string, options: ExecutionOptions): Promise<FilePart> {
|
||||||
const selected = input.session
|
|
||||||
? await client.session.get({ sessionID: input.session }).catch(() => undefined)
|
|
||||||
: input.continue
|
|
||||||
? await client.session
|
|
||||||
.list({ directory, parentID: null, limit: 1, order: "desc" })
|
|
||||||
.then((result) => result.data[0])
|
|
||||||
: undefined
|
|
||||||
if (input.session && !selected) fail("Session not found")
|
|
||||||
if (!selected || !input.fork) return selected
|
|
||||||
return client.session.fork({ sessionID: selected.id })
|
|
||||||
}
|
|
||||||
|
|
||||||
async function prepareFile(input: string, directory: string): Promise<FilePart> {
|
|
||||||
const file = path.resolve(directory, input)
|
const file = path.resolve(directory, input)
|
||||||
const handle = await open(file, "r").catch(() => fail(`File not found: ${input}`))
|
const handle = await open(file, "r").catch(() => fail(`File not found: ${input}`))
|
||||||
try {
|
try {
|
||||||
const stat = await handle.stat()
|
const stat = await handle.stat()
|
||||||
|
if (options.compatibility === "v1" && options.attached && stat.isDirectory())
|
||||||
|
fail(`Cannot attach local directory without a shared filesystem: ${input}`)
|
||||||
if (!stat.isFile() || stat.size > ATTACH_FILE_MAX_BYTES)
|
if (!stat.isFile() || stat.size > ATTACH_FILE_MAX_BYTES)
|
||||||
fail(`Cannot attach a directory, special file, or file larger than 10 MiB: ${input}`)
|
fail(`Cannot attach a directory, special file, or file larger than 10 MiB: ${input}`)
|
||||||
const content = Buffer.alloc(Number(stat.size))
|
const content = Buffer.alloc(Number(stat.size))
|
||||||
@@ -224,8 +253,8 @@ function isBinaryContent(bytes: Uint8Array) {
|
|||||||
return bytes.reduce((count, byte) => count + Number(byte < 9 || (byte > 13 && byte < 32)), 0) / bytes.length > 0.3
|
return bytes.reduce((count, byte) => count + Number(byte < 9 || (byte > 13 && byte < 32)), 0) / bytes.length > 0.3
|
||||||
}
|
}
|
||||||
|
|
||||||
async function renderTool(part: MiniToolPart) {
|
async function renderTool(part: SessionMessageAssistantTool, directory: string) {
|
||||||
const info = toolInlineInfo(part)
|
const info = toolInlineInfo(part, directory)
|
||||||
if (info.mode === "block") {
|
if (info.mode === "block") {
|
||||||
UI.empty()
|
UI.empty()
|
||||||
UI.println(UI.Style.TEXT_NORMAL + info.icon, UI.Style.TEXT_NORMAL + info.title)
|
UI.println(UI.Style.TEXT_NORMAL + info.icon, UI.Style.TEXT_NORMAL + info.title)
|
||||||
@@ -240,8 +269,8 @@ async function renderTool(part: MiniToolPart) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function renderToolError(part: MiniToolPart) {
|
async function renderToolError(part: SessionMessageAssistantTool, directory: string) {
|
||||||
const info = toolInlineInfo(part)
|
const info = toolInlineInfo(part, directory)
|
||||||
UI.println(UI.Style.TEXT_NORMAL + "✗", UI.Style.TEXT_NORMAL + `${info.title} failed`)
|
UI.println(UI.Style.TEXT_NORMAL + "✗", UI.Style.TEXT_NORMAL + `${info.title} failed`)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,7 +278,15 @@ function warning(message: string) {
|
|||||||
UI.println(UI.Style.TEXT_WARNING_BOLD + "!", UI.Style.TEXT_NORMAL, message)
|
UI.println(UI.Style.TEXT_WARNING_BOLD + "!", UI.Style.TEXT_NORMAL, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportError(input: RunCommandInput, message: string, sessionID?: string) {
|
function errorMessage(error: unknown) {
|
||||||
|
if (error instanceof Error) return error.message
|
||||||
|
if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string")
|
||||||
|
return error.message
|
||||||
|
return String(error)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal Used by the V1 command boundary before a Session exists. */
|
||||||
|
export function reportRunError(input: Pick<RunCommandInput, "format">, message: string, sessionID?: string) {
|
||||||
process.exitCode = 1
|
process.exitCode = 1
|
||||||
if (input.format === "json") {
|
if (input.format === "json") {
|
||||||
process.stdout.write(
|
process.stdout.write(
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import type { Endpoint } from "@opencode-ai/client/effect/service"
|
||||||
|
import { Effect } from "effect"
|
||||||
|
import path from "node:path"
|
||||||
|
import { Standalone } from "../services/standalone"
|
||||||
|
import { reportRunError, runNonInteractiveWithOptions, type RunCommandInput } from "./run"
|
||||||
|
|
||||||
|
export type V1RunCommandInput = {
|
||||||
|
message: string[]
|
||||||
|
continue?: boolean
|
||||||
|
session?: string
|
||||||
|
fork?: boolean
|
||||||
|
model?: string
|
||||||
|
agent?: string
|
||||||
|
format: "default" | "json"
|
||||||
|
file: string[]
|
||||||
|
title?: string
|
||||||
|
server?: string
|
||||||
|
password?: string
|
||||||
|
username?: string
|
||||||
|
directory?: string
|
||||||
|
variant?: string
|
||||||
|
thinking?: boolean
|
||||||
|
dangerouslySkipPermissions?: boolean
|
||||||
|
standaloneCommand?: ReadonlyArray<string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runV1Bridge(input: V1RunCommandInput) {
|
||||||
|
const root = process.env.PWD ?? process.cwd()
|
||||||
|
const attached = input.server !== undefined
|
||||||
|
const local = !attached && input.directory ? path.resolve(root, input.directory) : root
|
||||||
|
try {
|
||||||
|
process.chdir(local)
|
||||||
|
} catch {
|
||||||
|
reportRunError(input, `Failed to change directory to ${local}`)
|
||||||
|
return Promise.resolve()
|
||||||
|
}
|
||||||
|
|
||||||
|
return Effect.runPromise(
|
||||||
|
Effect.scoped(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const endpoint = attached
|
||||||
|
? explicitEndpoint(input)
|
||||||
|
: yield* Standalone.start({ command: input.standaloneCommand })
|
||||||
|
yield* Effect.promise(() =>
|
||||||
|
runNonInteractiveWithOptions(nativeInput(input, endpoint), {
|
||||||
|
root: local,
|
||||||
|
directory: attached ? input.directory : local,
|
||||||
|
useServerDirectory: attached && input.directory === undefined,
|
||||||
|
variant: input.variant,
|
||||||
|
attached,
|
||||||
|
compatibility: "v1",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).catch((error) => reportRunError(input, error instanceof Error ? error.message : String(error)))
|
||||||
|
}
|
||||||
|
|
||||||
|
function nativeInput(input: V1RunCommandInput, endpoint: Endpoint): RunCommandInput {
|
||||||
|
return {
|
||||||
|
server: { endpoint },
|
||||||
|
message: input.message,
|
||||||
|
continue: input.continue,
|
||||||
|
session: input.session,
|
||||||
|
fork: input.fork,
|
||||||
|
model: input.model,
|
||||||
|
agent: input.agent,
|
||||||
|
format: input.format,
|
||||||
|
file: input.file,
|
||||||
|
title: input.title,
|
||||||
|
thinking: input.thinking,
|
||||||
|
auto: input.dangerouslySkipPermissions,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function explicitEndpoint(input: V1RunCommandInput): Endpoint {
|
||||||
|
const url = input.server
|
||||||
|
if (!url) throw new Error("Missing V1 server URL")
|
||||||
|
return {
|
||||||
|
url,
|
||||||
|
auth: input.password
|
||||||
|
? { type: "basic", username: input.username ?? "opencode", password: input.password }
|
||||||
|
: undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -54,7 +54,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
|
|||||||
}
|
}
|
||||||
const password =
|
const password =
|
||||||
options.mode === "service"
|
options.mode === "service"
|
||||||
? yield* ServiceConfig.password()
|
? config.password || randomBytes(32).toString("base64url")
|
||||||
: environmentPassword
|
: environmentPassword
|
||||||
? Redacted.value(environmentPassword)
|
? Redacted.value(environmentPassword)
|
||||||
: randomBytes(32).toString("base64url")
|
: randomBytes(32).toString("base64url")
|
||||||
@@ -69,7 +69,11 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
|
|||||||
serviceOptions === undefined
|
serviceOptions === undefined
|
||||||
? undefined
|
? undefined
|
||||||
: {
|
: {
|
||||||
onListen: (address, shutdown) => register(address, password, instanceID, serviceOptions.file, shutdown),
|
onListen: (address, shutdown) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
if (!config.password) yield* ServiceConfig.password(password)
|
||||||
|
return yield* register(address, password, instanceID, serviceOptions.file, shutdown)
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.provide(Logger.layer([], { mergeWithExisting: false })),
|
Effect.provide(Logger.layer([], { mergeWithExisting: false })),
|
||||||
@@ -154,8 +158,8 @@ const register = Effect.fnUntraced(function* (
|
|||||||
const recognizeIncumbent = Effect.fnUntraced(function* (options: DiscoverOptions, hostname: string, port: number) {
|
const recognizeIncumbent = Effect.fnUntraced(function* (options: DiscoverOptions, hostname: string, port: number) {
|
||||||
const found = yield* Service.incumbent({ ...options, url: serviceURL(hostname, port) }).pipe(
|
const found = yield* Service.incumbent({ ...options, url: serviceURL(hostname, port) }).pipe(
|
||||||
Effect.filterOrFail((value) => value !== undefined),
|
Effect.filterOrFail((value) => value !== undefined),
|
||||||
Effect.retry(Schedule.max([Schedule.spaced("100 millis"), Schedule.recurs(60)])),
|
Effect.retry(Schedule.spaced("100 millis")),
|
||||||
Effect.option,
|
Effect.timeoutOption("15 seconds"),
|
||||||
)
|
)
|
||||||
return Option.isSome(found)
|
return Option.isSome(found)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { ClientError, type OpenCodeClient } from "@opencode-ai/client/promise"
|
||||||
|
|
||||||
|
// Location plugins initialize asynchronously, so explicit model selection must
|
||||||
|
// wait for that exact model before prompt admission. The execution path owns
|
||||||
|
// the authoritative error if readiness times out.
|
||||||
|
export async function waitForCatalogReady(input: {
|
||||||
|
sdk: OpenCodeClient
|
||||||
|
directory: string
|
||||||
|
workspace?: string
|
||||||
|
model: { providerID: string; modelID: string }
|
||||||
|
timeoutMs?: number
|
||||||
|
signal?: AbortSignal
|
||||||
|
}) {
|
||||||
|
const deadline = Date.now() + (input.timeoutMs ?? 5_000)
|
||||||
|
while (Date.now() < deadline && !input.signal?.aborted) {
|
||||||
|
const models = await input.sdk.model
|
||||||
|
.list(
|
||||||
|
{ location: { directory: input.directory, workspace: input.workspace } },
|
||||||
|
{ signal: input.signal },
|
||||||
|
)
|
||||||
|
.then((result) => result.data)
|
||||||
|
.catch((error) => {
|
||||||
|
if (input.signal && error instanceof ClientError && error.reason === "Transport") throw error
|
||||||
|
return undefined
|
||||||
|
})
|
||||||
|
if (models?.some((model) => model.providerID === input.model.providerID && model.id === input.model.modelID)) return
|
||||||
|
await wait(25, input.signal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function wait(delay: number, signal?: AbortSignal) {
|
||||||
|
if (!signal) return new Promise<void>((resolve) => setTimeout(resolve, delay))
|
||||||
|
if (signal.aborted) return Promise.resolve()
|
||||||
|
return new Promise<void>((resolve) => {
|
||||||
|
const timer = setTimeout(done, delay)
|
||||||
|
signal.addEventListener("abort", done, { once: true })
|
||||||
|
function done() {
|
||||||
|
clearTimeout(timer)
|
||||||
|
signal?.removeEventListener("abort", done)
|
||||||
|
resolve()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user