From 88dc960af82573c6ba269a664eb719dcf051bb04 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 09:03:53 -0400 Subject: [PATCH 01/82] refactor(core): migrate built-in tools to internal plugins (#34956) --- packages/core/src/location-services.ts | 2 - packages/core/src/plugin/internal.ts | 47 ++++++++++ packages/core/src/tool/apply-patch.ts | 22 ++--- packages/core/src/tool/builtins.ts | 51 ----------- packages/core/src/tool/edit.ts | 22 ++--- packages/core/src/tool/grep.ts | 22 ++--- packages/core/src/tool/question.ts | 22 ++--- packages/core/src/tool/read.ts | 36 +++----- packages/core/src/tool/skill.ts | 22 ++--- packages/core/src/tool/todowrite.ts | 22 ++--- packages/core/src/tool/webfetch.ts | 23 ++--- packages/core/src/tool/websearch.ts | 20 ++--- packages/core/src/tool/write.ts | 22 ++--- packages/core/test/lib/tool.ts | 27 +++++- packages/core/test/location-layer.test.ts | 22 ++++- .../core/test/session-instructions.test.ts | 86 ++++++++++++------- packages/core/test/tool-apply-patch.test.ts | 11 ++- packages/core/test/tool-edit.test.ts | 11 ++- packages/core/test/tool-question.test.ts | 11 ++- packages/core/test/tool-read.test.ts | 21 ++++- packages/core/test/tool-skill.test.ts | 12 ++- packages/core/test/tool-todowrite.test.ts | 11 ++- packages/core/test/tool-webfetch.test.ts | 11 ++- packages/core/test/tool-websearch.test.ts | 11 ++- packages/core/test/tool-write.test.ts | 11 ++- 25 files changed, 310 insertions(+), 268 deletions(-) delete mode 100644 packages/core/src/tool/builtins.ts diff --git a/packages/core/src/location-services.ts b/packages/core/src/location-services.ts index 830b9b48be..b1749b34f7 100644 --- a/packages/core/src/location-services.ts +++ b/packages/core/src/location-services.ts @@ -41,7 +41,6 @@ import { InstructionContext } from "./instruction-context" import { SystemContextBuiltIns } from "./system-context/builtins" import { SessionContextEntry } from "./session/context-entry" import { SessionInstructions } from "./session/instructions" -import { BuiltInTools } from "./tool/builtins" import { McpTool } from "./tool/mcp" import { ReadToolFileSystem } from "./tool/read-filesystem" import { ToolRegistry } from "./tool/registry" @@ -89,7 +88,6 @@ export const locationServices = LayerNode.group([ QuestionV2.node, Generate.node, ReadToolFileSystem.node, - BuiltInTools.node, McpTool.node, SessionInstructions.node, SessionRunnerModel.node, diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index f522e85a66..939bb4e731 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -15,9 +15,11 @@ import { ConfigProviderPlugin } from "../config/plugin/provider" import { ConfigReferencePlugin } from "../config/plugin/reference" import { ConfigSkillPlugin } from "../config/plugin/skill" import { EventV2 } from "../event" +import { FileMutation } from "../file-mutation" import { FileSystem } from "../filesystem" import { FSUtil } from "../fs-util" import { Global } from "../global" +import { Image } from "../image" import { Integration } from "../integration" import { Location } from "../location" import { LocationMutation } from "../location-mutation" @@ -26,8 +28,11 @@ import { Npm } from "../npm" import { PluginV2 } from "../plugin" import { PluginRuntime } from "../plugin/runtime" import { PermissionV2 } from "../permission" +import { QuestionV2 } from "../question" import { Reference } from "../reference" import { Ripgrep } from "../ripgrep" +import { SessionInstructions } from "../session/instructions" +import { SessionTodo } from "../session/todo" import { Shell } from "../shell" import { SkillV2 } from "../skill" import { State } from "../state" @@ -41,9 +46,20 @@ import { ProviderPlugins } from "./provider" import { SdkPlugins } from "./sdk" import { SkillPlugin } from "./skill" import { VariantPlugin } from "./variant" +import { ApplyPatchTool } from "../tool/apply-patch" +import { EditTool } from "../tool/edit" import { GlobTool } from "../tool/glob" +import { GrepTool } from "../tool/grep" +import { QuestionTool } from "../tool/question" +import { ReadTool } from "../tool/read" +import { ReadToolFileSystem } from "../tool/read-filesystem" import { ShellTool } from "../tool/shell" +import { SkillTool } from "../tool/skill" import { SubagentTool } from "../tool/subagent" +import { TodoWriteTool } from "../tool/todowrite" +import { WebFetchTool } from "../tool/webfetch" +import { WebSearchTool } from "../tool/websearch" +import { WriteTool } from "../tool/write" export type Requirements = | AgentV2.Service @@ -51,10 +67,12 @@ export type Requirements = | CommandV2.Service | Config.Service | EventV2.Service + | FileMutation.Service | FileSystem.Service | FSUtil.Service | Global.Service | HttpClient.HttpClient + | Image.Service | Integration.Service | Location.Service | LocationMutation.Service @@ -62,11 +80,16 @@ export type Requirements = | Npm.Service | PermissionV2.Service | PluginRuntime.Service + | QuestionV2.Service + | ReadToolFileSystem.Service | Reference.Service | Ripgrep.Service + | SessionInstructions.Service + | SessionTodo.Service | Shell.Service | SkillV2.Service | Tools.Service + | WebSearchTool.ConfigService export interface Plugin { readonly id: string @@ -96,13 +119,20 @@ const layer = Layer.effectDiscard( Context.make(Global.Service, yield* Global.Service), Context.make(HttpClient.HttpClient, yield* HttpClient.HttpClient), Context.make(LocationMutation.Service, yield* LocationMutation.Service), + Context.make(FileMutation.Service, yield* FileMutation.Service), + Context.make(Image.Service, yield* Image.Service), Context.make(PermissionV2.Service, yield* PermissionV2.Service), + Context.make(QuestionV2.Service, yield* QuestionV2.Service), + Context.make(ReadToolFileSystem.Service, yield* ReadToolFileSystem.Service), + Context.make(SessionInstructions.Service, yield* SessionInstructions.Service), + Context.make(SessionTodo.Service, yield* SessionTodo.Service), Context.make(SkillV2.Service, yield* SkillV2.Service), Context.make(Reference.Service, yield* Reference.Service), Context.make(Ripgrep.Service, yield* Ripgrep.Service), Context.make(Shell.Service, yield* Shell.Service), Context.make(Tools.Service, yield* Tools.Service), Context.make(PluginRuntime.Service, yield* PluginRuntime.Service), + Context.make(WebSearchTool.ConfigService, yield* WebSearchTool.ConfigService), ) const add = (input: Plugin) => plugin.add(PluginV2.ID.make(input.id), (context: PluginContext) => @@ -117,9 +147,19 @@ const layer = Layer.effectDiscard( yield* add(SkillPlugin.Plugin) yield* add(ModelsDevPlugin) yield* add(ConfigExternalPlugin.Plugin) + yield* add(ApplyPatchTool.Plugin) + yield* add(EditTool.Plugin) yield* add(GlobTool.Plugin) + yield* add(GrepTool.Plugin) + yield* add(QuestionTool.Plugin) + yield* add(ReadTool.Plugin) yield* add(ShellTool.Plugin) + yield* add(SkillTool.Plugin) yield* add(SubagentTool.Plugin) + yield* add(TodoWriteTool.Plugin) + yield* add(WebFetchTool.Plugin) + yield* add(WebSearchTool.Plugin) + yield* add(WriteTool.Plugin) yield* add(ConfigAgentPlugin.Plugin) yield* add(ConfigCommandPlugin.Plugin) yield* add(ConfigSkillPlugin.Plugin) @@ -145,6 +185,8 @@ export const node = makeLocationNode({ Config.node, Location.node, LocationMutation.node, + FileMutation.node, + Image.node, ModelsDev.node, Npm.node, EventV2.node, @@ -153,6 +195,10 @@ export const node = makeLocationNode({ Global.node, httpClient, PermissionV2.node, + QuestionV2.node, + ReadToolFileSystem.node, + SessionInstructions.node, + SessionTodo.node, SkillV2.node, Reference.node, Ripgrep.node, @@ -160,5 +206,6 @@ export const node = makeLocationNode({ ToolRegistry.toolsNode, PluginRuntime.node, SdkPlugins.node, + WebSearchTool.configNode, ], }) diff --git a/packages/core/src/tool/apply-patch.ts b/packages/core/src/tool/apply-patch.ts index 3d7105a31a..2f481d8a0d 100644 --- a/packages/core/src/tool/apply-patch.ts +++ b/packages/core/src/tool/apply-patch.ts @@ -1,18 +1,16 @@ export * as ApplyPatchTool from "./apply-patch" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { ToolFailure } from "@opencode-ai/llm" import { FileDiff } from "@opencode-ai/schema/file-diff" import { createTwoFilesPatch, diffLines } from "diff" -import { Effect, Layer, Schema } from "effect" -import { makeLocationNode } from "../effect/app-node" +import { Effect, Schema } from "effect" import { FileMutation } from "../file-mutation" import { FSUtil } from "../fs-util" import { LocationMutation } from "../location-mutation" import { Patch } from "../patch" import { PermissionV2 } from "../permission" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "apply_patch" @@ -56,15 +54,15 @@ type Prepared = readonly after: string }) -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-apply-patch-tool", + effect: Effect.fn("ApplyPatchTool.Plugin")(function* (ctx: PluginContext) { const mutation = yield* LocationMutation.Service const files = yield* FileMutation.Service const fs = yield* FSUtil.Service const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.withPermission( Tool.make({ @@ -194,13 +192,7 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/apply-patch", - layer, - deps: [ToolRegistry.node, LocationMutation.node, FileMutation.node, FSUtil.node, PermissionV2.node], -}) +} function patchFile(change: Prepared): typeof FileDiff.Info.Type { const counts = diffLines(change.before, change.after).reduce( diff --git a/packages/core/src/tool/builtins.ts b/packages/core/src/tool/builtins.ts deleted file mode 100644 index c72d07d0e7..0000000000 --- a/packages/core/src/tool/builtins.ts +++ /dev/null @@ -1,51 +0,0 @@ -export * as BuiltInTools from "./builtins" - -import { makeLocationNode } from "../effect/app-node" -import { Context, Layer } from "effect" -import { ApplyPatchTool } from "./apply-patch" -import { EditTool } from "./edit" -import { GrepTool } from "./grep" -import { QuestionTool } from "./question" -import { ReadTool } from "./read" -import { ReadToolFileSystem } from "./read-filesystem" -import { SkillTool } from "./skill" -import { TodoWriteTool } from "./todowrite" -import { WebFetchTool } from "./webfetch" -import { WebSearchTool } from "./websearch" -import { WriteTool } from "./write" - -export class Service extends Context.Service>()("@opencode/v2/BuiltInTools") {} - -/** - * Composes only the shipped Location-scoped built-in tool transforms. - * Each tool retains its implementation and focused tests independently. Dynamic - * MCP and plugin tools later use separate scoped canonical registrations, while - * provider/model filtering belongs to a future materialization phase rather - * than this static list. The caller intentionally supplies shared Location - * services once to this merged set. - * - * TODO: Port the remaining launch-follow-up leaves deliberately: edit fuzzy - * parity, task, LSP, - * repo_clone, repo_overview, plan_exit, and Rune/code mode. Keep MCP and plugin - * transforms separate from this static built-in list. - */ -const layer = Layer.succeed(Service, Service.of({})) - -export const node = makeLocationNode({ - service: Service, - layer, - deps: [ - ApplyPatchTool.node, - EditTool.node, - GrepTool.node, - QuestionTool.node, - ReadTool.node, - ReadToolFileSystem.node, - SkillTool.node, - TodoWriteTool.node, - WebFetchTool.node, - WebSearchTool.node, - WebSearchTool.configNode, - WriteTool.node, - ], -}) diff --git a/packages/core/src/tool/edit.ts b/packages/core/src/tool/edit.ts index f0bdb488a0..17ff28cfc1 100644 --- a/packages/core/src/tool/edit.ts +++ b/packages/core/src/tool/edit.ts @@ -6,18 +6,16 @@ */ export * as EditTool from "./edit" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { ToolFailure } from "@opencode-ai/llm" import { FileDiff } from "@opencode-ai/schema/file-diff" import { createTwoFilesPatch, diffLines } from "diff" -import { Effect, Layer, Schema } from "effect" -import { makeLocationNode } from "../effect/app-node" +import { Effect, Schema } from "effect" import { FileMutation } from "../file-mutation" import { FSUtil } from "../fs-util" import { LocationMutation } from "../location-mutation" import { PermissionV2 } from "../permission" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "edit" @@ -87,15 +85,15 @@ export const toModelOutput = (output: Output, oldString: string, newString: stri // TODO: Add snapshots / undo after design exists. // TODO: Add LSP notification and diagnostics after V2 LSP runtime exists. -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-edit-tool", + effect: Effect.fn("EditTool.Plugin")(function* (ctx: PluginContext) { const mutation = yield* LocationMutation.Service const files = yield* FileMutation.Service const fs = yield* FSUtil.Service const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.withPermission( Tool.make({ @@ -214,10 +212,4 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/edit", - layer, - deps: [ToolRegistry.node, LocationMutation.node, FileMutation.node, FSUtil.node, PermissionV2.node], -}) +} diff --git a/packages/core/src/tool/grep.ts b/packages/core/src/tool/grep.ts index f455bd4c8a..e525606609 100644 --- a/packages/core/src/tool/grep.ts +++ b/packages/core/src/tool/grep.ts @@ -1,18 +1,16 @@ export * as GrepTool from "./grep" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { ToolFailure } from "@opencode-ai/llm" -import { Effect, Layer, Schema } from "effect" +import { Effect, Schema } from "effect" import path from "path" -import { makeLocationNode } from "../effect/app-node" import { FileSystem } from "../filesystem" import { FSUtil } from "../fs-util" import { Location } from "../location" import { PermissionV2 } from "../permission" import { Ripgrep } from "../ripgrep" import { RelativePath } from "../schema" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "grep" @@ -50,15 +48,15 @@ export const toModelOutput = (output: ModelOutput) => { } /** Grep leaf that defaults its filesystem root to the active Location. */ -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-grep-tool", + effect: Effect.fn("GrepTool.Plugin")(function* (ctx: PluginContext) { const fs = yield* FSUtil.Service const ripgrep = yield* Ripgrep.Service const location = yield* Location.Service const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.make({ description: @@ -128,10 +126,4 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/grep", - layer, - deps: [ToolRegistry.node, FSUtil.node, Ripgrep.node, Location.node, PermissionV2.node], -}) +} diff --git a/packages/core/src/tool/question.ts b/packages/core/src/tool/question.ts index e5ae0d7426..218edb57e9 100644 --- a/packages/core/src/tool/question.ts +++ b/packages/core/src/tool/question.ts @@ -1,13 +1,11 @@ export * as QuestionTool from "./question" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { ToolFailure } from "@opencode-ai/llm" -import { Effect, Layer, Schema } from "effect" -import { makeLocationNode } from "../effect/app-node" +import { Effect, Schema } from "effect" import { PermissionV2 } from "../permission" import { QuestionV2 } from "../question" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "question" @@ -44,13 +42,13 @@ export const toModelOutput = ( return `User has answered your questions: ${formatted}. You can now continue with the user's answers in mind.` } -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-question-tool", + effect: Effect.fn("QuestionTool.Plugin")(function* (ctx: PluginContext) { const question = yield* QuestionV2.Service const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.make({ description, @@ -85,10 +83,4 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/question", - layer, - deps: [ToolRegistry.node, PermissionV2.node, QuestionV2.node], -}) +} diff --git a/packages/core/src/tool/read.ts b/packages/core/src/tool/read.ts index c94418f94c..028456a4e1 100644 --- a/packages/core/src/tool/read.ts +++ b/packages/core/src/tool/read.ts @@ -1,9 +1,9 @@ export * as ReadTool from "./read" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { dirname } from "path" import { ToolFailure } from "@opencode-ai/llm" -import { Effect, Layer, Schema } from "effect" -import { makeLocationNode } from "../effect/app-node" +import { Effect, Schema } from "effect" import { FileSystem } from "../filesystem" import { FSUtil } from "../fs-util" import { Image } from "../image" @@ -13,9 +13,7 @@ import { PermissionV2 } from "../permission" import { SessionInstructions } from "../session/instructions" import { AbsolutePath } from "../schema" import { ReadToolFileSystem } from "./read-filesystem" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "read" const FILENAME = "AGENTS.md" @@ -32,9 +30,9 @@ const LocationInput = Schema.Struct({ const Input = LocationInput const Output = Schema.Union([FileSystem.Content, ReadToolFileSystem.TextPage, ReadToolFileSystem.ListPage]) -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-read-tool", + effect: Effect.fn("ReadTool.Plugin")(function* (ctx: PluginContext) { const reader = yield* ReadToolFileSystem.Service const mutation = yield* LocationMutation.Service const image = yield* Image.Service @@ -43,7 +41,7 @@ const layer = Layer.effectDiscard( const fs = yield* FSUtil.Service const location = yield* Location.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.make({ description: @@ -111,7 +109,10 @@ const layer = Layer.effectDiscard( const candidates = discovered.map(FSUtil.resolve).filter((file) => dirname(file) !== root) if (candidates.length === 0) return yield* sessionInstructions.load({ sessionID: context.sessionID, paths: candidates }) - }).pipe(Effect.catch(() => Effect.void), Effect.catchDefect(() => Effect.void)) + }).pipe( + Effect.catch(() => Effect.void), + Effect.catchDefect(() => Effect.void), + ) if ("encoding" in content && content.encoding === "base64" && SUPPORTED_IMAGE_MIMES.has(content.mime)) { return yield* image .normalize(resource, { ...content, encoding: "base64" }) @@ -137,19 +138,4 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/read", - layer, - deps: [ - ToolRegistry.node, - ReadToolFileSystem.node, - LocationMutation.node, - Image.node, - PermissionV2.node, - SessionInstructions.node, - FSUtil.node, - Location.node, - ], -}) +} diff --git a/packages/core/src/tool/skill.ts b/packages/core/src/tool/skill.ts index 1f8b122903..1c5d23a047 100644 --- a/packages/core/src/tool/skill.ts +++ b/packages/core/src/tool/skill.ts @@ -1,15 +1,13 @@ export * as SkillTool from "./skill" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import path from "path" import { ToolFailure } from "@opencode-ai/llm" -import { Effect, Layer, Schema } from "effect" -import { makeLocationNode } from "../effect/app-node" +import { Effect, Schema } from "effect" import { FSUtil } from "../fs-util" import { SkillV2 } from "../skill" import { PermissionV2 } from "../permission" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "skill" const FILE_LIMIT = 10 @@ -54,13 +52,13 @@ export const toModelOutput = (skill: SkillV2.Info, files: ReadonlyArray) const unableToLoad = (name: string, error?: unknown) => new ToolFailure({ message: `Unable to load skill ${name}`, error }) -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-skill-tool", + effect: Effect.fn("SkillTool.Plugin")(function* (ctx: PluginContext) { const fs = yield* FSUtil.Service const skills = yield* SkillV2.Service const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.make({ description, @@ -100,10 +98,4 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/skill", - layer, - deps: [ToolRegistry.node, FSUtil.node, SkillV2.node, PermissionV2.node], -}) +} diff --git a/packages/core/src/tool/todowrite.ts b/packages/core/src/tool/todowrite.ts index bc1ba1fbb3..5f34ebd5aa 100644 --- a/packages/core/src/tool/todowrite.ts +++ b/packages/core/src/tool/todowrite.ts @@ -1,13 +1,11 @@ export * as TodoWriteTool from "./todowrite" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { ToolFailure } from "@opencode-ai/llm" -import { Effect, Layer, Schema } from "effect" -import { makeLocationNode } from "../effect/app-node" +import { Effect, Schema } from "effect" import { PermissionV2 } from "../permission" import { SessionTodo } from "../session/todo" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "todowrite" @@ -22,13 +20,13 @@ export type Output = typeof Output.Type export const toModelOutput = (output: Output) => JSON.stringify(output.todos, null, 2) -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-todowrite-tool", + effect: Effect.fn("TodoWriteTool.Plugin")(function* (ctx: PluginContext) { const todos = yield* SessionTodo.Service const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.make({ description: @@ -53,10 +51,4 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/todowrite", - layer, - deps: [ToolRegistry.node, PermissionV2.node, SessionTodo.node], -}) +} diff --git a/packages/core/src/tool/webfetch.ts b/packages/core/src/tool/webfetch.ts index d3889d6a7a..efac4a2a75 100644 --- a/packages/core/src/tool/webfetch.ts +++ b/packages/core/src/tool/webfetch.ts @@ -1,17 +1,14 @@ export * as WebFetchTool from "./webfetch" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { ToolFailure } from "@opencode-ai/llm" -import { Duration, Effect, Layer, Schema } from "effect" +import { Duration, Effect, Schema } from "effect" import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" import { Parser } from "htmlparser2" import TurndownService from "turndown" -import { makeLocationNode } from "../effect/app-node" -import { LayerNodePlatform } from "../effect/app-node-platform" import { PermissionV2 } from "../permission" import { collectBoundedResponseBody } from "./http-body" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "webfetch" export const MAX_RESPONSE_BYTES = 5 * 1024 * 1024 @@ -115,13 +112,13 @@ const convert = (content: string, contentType: string, format: Format) => { return content } -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-webfetch-tool", + effect: Effect.fn("WebFetchTool.Plugin")(function* (ctx: PluginContext) { const http = yield* HttpClient.HttpClient const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.make({ description, @@ -178,13 +175,7 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/webfetch", - layer, - deps: [ToolRegistry.node, PermissionV2.node, LayerNodePlatform.httpClient], -}) +} export function extractTextFromHTML(html: string) { let text = "" diff --git a/packages/core/src/tool/websearch.ts b/packages/core/src/tool/websearch.ts index 6d62236316..80a2422cee 100644 --- a/packages/core/src/tool/websearch.ts +++ b/packages/core/src/tool/websearch.ts @@ -1,19 +1,17 @@ export * as WebSearchTool from "./websearch" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { ToolFailure } from "@opencode-ai/llm" import { Context, Duration, Effect, Layer, Schema } from "effect" import { HttpClient, HttpClientRequest } from "effect/unstable/http" import { makeLocationNode } from "../effect/app-node" -import { LayerNodePlatform } from "../effect/app-node-platform" import { truthy } from "../flag/flag" import { InstallationVersion } from "../installation/version" import { PositiveInt } from "../schema" import { PermissionV2 } from "../permission" import { Tool } from "./tool" -import { Tools } from "./tools" import { collectBoundedResponseBody } from "./http-body" import { checksum } from "../util/encode" -import { ToolRegistry } from "./registry" export const name = "websearch" export const NO_RESULTS = "No search results found. Please try a different query." @@ -189,14 +187,14 @@ const Output = Schema.Struct({ text: Schema.String, }) -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-websearch-tool", + effect: Effect.fn("WebSearchTool.Plugin")(function* (ctx: PluginContext) { const http = yield* HttpClient.HttpClient const config = yield* ConfigService const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.make({ description, @@ -251,10 +249,4 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/websearch", - layer, - deps: [ToolRegistry.node, PermissionV2.node, LayerNodePlatform.httpClient, configNode], -}) +} diff --git a/packages/core/src/tool/write.ts b/packages/core/src/tool/write.ts index 39ad0b20fb..73885b2187 100644 --- a/packages/core/src/tool/write.ts +++ b/packages/core/src/tool/write.ts @@ -6,15 +6,13 @@ */ export * as WriteTool from "./write" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { ToolFailure } from "@opencode-ai/llm" -import { Effect, Layer, Schema } from "effect" -import { makeLocationNode } from "../effect/app-node" +import { Effect, Schema } from "effect" import { FileMutation } from "../file-mutation" import { LocationMutation } from "../location-mutation" import { PermissionV2 } from "../permission" -import { ToolRegistry } from "./registry" import { Tool } from "./tool" -import { Tools } from "./tools" export const name = "write" @@ -44,14 +42,14 @@ export const toModelOutput = (output: Output) => // TODO: Add snapshots / undo after design exists. // TODO: Add LSP notification and diagnostics after V2 LSP runtime exists. -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const tools = yield* Tools.Service +export const Plugin = { + id: "core-write-tool", + effect: Effect.fn("WriteTool.Plugin")(function* (ctx: PluginContext) { const mutation = yield* LocationMutation.Service const files = yield* FileMutation.Service const permission = yield* PermissionV2.Service - yield* tools + yield* ctx.tool .register({ [name]: Tool.withPermission( Tool.make({ @@ -92,10 +90,4 @@ const layer = Layer.effectDiscard( }) .pipe(Effect.orDie) }), -) - -export const node = makeLocationNode({ - name: "tool/write", - layer, - deps: [ToolRegistry.node, LocationMutation.node, FileMutation.node, PermissionV2.node], -}) +} diff --git a/packages/core/test/lib/tool.ts b/packages/core/test/lib/tool.ts index fa625a591b..74c1b710ab 100644 --- a/packages/core/test/lib/tool.ts +++ b/packages/core/test/lib/tool.ts @@ -2,7 +2,9 @@ import { AgentV2 } from "@opencode-ai/core/agent" import type { PermissionV2 } from "@opencode-ai/core/permission" import { SessionMessage } from "@opencode-ai/core/session/message" import { ToolRegistry } from "@opencode-ai/core/tool/registry" -import { Effect } from "effect" +import { Tools } from "@opencode-ai/core/tool/tools" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" +import { Effect, type Scope } from "effect" export const toolIdentity = { agent: AgentV2.ID.make("build"), @@ -34,6 +36,29 @@ export function waitForTool( }) } +/** + * Registers a core tool plugin's tools against the real registry without booting the + * full plugin host. Only the tool domain is live; focused tool tests exercise + * registration, materialization, and settlement through the same path production uses. + */ +export const registerToolPlugin = (plugin: { + readonly id: string + readonly effect: (context: PluginContext) => Effect.Effect +}): Effect.Effect => + Effect.gen(function* () { + const tools = yield* Tools.Service + const context: Pick = { + tool: { + register: tools.register, + execute: { + before: () => Effect.die("registerToolPlugin does not support tool hooks"), + after: () => Effect.die("registerToolPlugin does not support tool hooks"), + }, + }, + } + yield* plugin.effect(context as PluginContext) + }) + export const settleTool = (registry: ToolRegistry.Interface, input: ToolRegistry.ExecuteInput, model = testModel) => registry.materialize({ model }).pipe(Effect.flatMap((materialized) => materialized.settle(input))) diff --git a/packages/core/test/location-layer.test.ts b/packages/core/test/location-layer.test.ts index a6a2c18fa8..77b7207c42 100644 --- a/packages/core/test/location-layer.test.ts +++ b/packages/core/test/location-layer.test.ts @@ -73,9 +73,25 @@ describe("LocationServiceMap", () => { const catalog = yield* Catalog.Service yield* catalog.transform((editor) => editor.provider.update(ProviderV2.ID.make("test"), () => {})) const registry = yield* ToolRegistry.Service - yield* waitForTool(registry, "glob") - yield* waitForTool(registry, "shell") - yield* waitForTool(registry, "subagent") + // Tool plugins register during the forked PluginInternal boot; wait for + // every expected tool rather than relying on batch ordering. + yield* Effect.forEach( + [ + "edit", + "glob", + "grep", + "question", + "read", + "shell", + "skill", + "subagent", + "todowrite", + "webfetch", + "websearch", + "write", + ], + (name) => waitForTool(registry, name), + ) return { providers: yield* catalog.provider.all(), tools: yield* toolDefinitions(registry), diff --git a/packages/core/test/session-instructions.test.ts b/packages/core/test/session-instructions.test.ts index b9e401be4b..e87fce7234 100644 --- a/packages/core/test/session-instructions.test.ts +++ b/packages/core/test/session-instructions.test.ts @@ -33,8 +33,24 @@ import { ToolHooks } from "@opencode-ai/core/tool/hooks" import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" import { ToolRegistry } from "@opencode-ai/core/tool/registry" import { tempLocationLayer } from "./fixture/location" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" import { testEffect } from "./lib/effect" -import { settleTool, testModel } from "./lib/tool" +import { registerToolPlugin, settleTool, testModel } from "./lib/tool" + +const readToolNode = makeLocationNode({ + name: "test/read-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(ReadTool.Plugin)), + deps: [ + ToolRegistry.toolsNode, + ReadToolFileSystem.node, + LocationMutation.node, + Image.node, + PermissionV2.node, + SessionInstructions.node, + FSUtil.node, + Location.node, + ], +}) const projects = Layer.succeed( ProjectV2.Service, @@ -69,7 +85,7 @@ const testLayer = AppNodeBuilder.build( FSUtil.node, LocationMutation.node, ReadToolFileSystem.node, - ReadTool.node, + readToolNode, ToolRegistry.node, ToolRegistry.toolsNode, ToolHooks.node, @@ -156,7 +172,9 @@ describe("SessionInstructions", () => { expect(firstInjected[0]!.text).toBe( `Instructions from: ${deepPath}\ndeep-instructions\n\nInstructions from: ${subPath}\nsub-instructions`, ) - expect(firstInjected[0]!.description).toBe(`Loaded ${path.relative(dir, deepPath)}, ${path.relative(dir, subPath)}`) + expect(firstInjected[0]!.description).toBe( + `Loaded ${path.relative(dir, deepPath)}, ${path.relative(dir, subPath)}`, + ) // The synthetic's metadata carries the durable dedup ledger. expect(firstInjected[0]!.metadata).toEqual({ instruction: { paths: [deepPath, subPath] } }) expect(firstInjected[0]!.text).not.toContain("root-instructions") @@ -192,47 +210,49 @@ describe("SessionInstructions", () => { // Seed the durable history with a prior synthetic that already claims sub's AGENTS.md // via the instruction metadata ledger. yield* seedSynthetic(sessionID, [subPath]) - expect((yield* synthetics(sessionID))).toHaveLength(1) + expect(yield* synthetics(sessionID)).toHaveLength(1) yield* settleTool(registry, readCall(sessionID, "call-sub", "sub/file.txt")) // The durable claim on the prior synthetic prevents re-injection; no new synthetic. - expect((yield* synthetics(sessionID))).toHaveLength(1) + expect(yield* synthetics(sessionID)).toHaveLength(1) }), ) - it.effect("discovers AGENTS.md on a directory listing, including the listed directory's own, and dedups with a later file read", () => - Effect.gen(function* () { - const location = yield* Location.Service - const dir = location.directory - const rootPath = path.resolve(dir, "AGENTS.md") - const pkgPath = path.resolve(dir, "packages", "foo", "AGENTS.md") - yield* mkdir(path.resolve(dir, "packages", "foo")) - yield* writeAgents(rootPath, "root-instructions") - yield* writeAgents(pkgPath, "pkg-instructions") - yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "packages", "foo", "file.txt"), "content")) + it.effect( + "discovers AGENTS.md on a directory listing, including the listed directory's own, and dedups with a later file read", + () => + Effect.gen(function* () { + const location = yield* Location.Service + const dir = location.directory + const rootPath = path.resolve(dir, "AGENTS.md") + const pkgPath = path.resolve(dir, "packages", "foo", "AGENTS.md") + yield* mkdir(path.resolve(dir, "packages", "foo")) + yield* writeAgents(rootPath, "root-instructions") + yield* writeAgents(pkgPath, "pkg-instructions") + yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "packages", "foo", "file.txt"), "content")) - const session = yield* SessionV2.Service - const registry = yield* ToolRegistry.Service - const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id + const session = yield* SessionV2.Service + const registry = yield* ToolRegistry.Service + const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id - // Listing packages/foo/ discovers its own AGENTS.md, walking up to but excluding - // the Location root (already supplied by the core/instructions baseline). - yield* settleTool(registry, readCall(sessionID, "call-list", "packages/foo")) + // Listing packages/foo/ discovers its own AGENTS.md, walking up to but excluding + // the Location root (already supplied by the core/instructions baseline). + yield* settleTool(registry, readCall(sessionID, "call-list", "packages/foo")) - const firstInjected = yield* synthetics(sessionID) - expect(firstInjected).toHaveLength(1) - expect(firstInjected[0]!.text).toBe(`Instructions from: ${pkgPath}\npkg-instructions`) - expect(firstInjected[0]!.description).toBe(`Loaded ${path.relative(dir, pkgPath)}`) - expect(firstInjected[0]!.metadata).toEqual({ instruction: { paths: [pkgPath] } }) - expect(firstInjected[0]!.text).not.toContain("root-instructions") + const firstInjected = yield* synthetics(sessionID) + expect(firstInjected).toHaveLength(1) + expect(firstInjected[0]!.text).toBe(`Instructions from: ${pkgPath}\npkg-instructions`) + expect(firstInjected[0]!.description).toBe(`Loaded ${path.relative(dir, pkgPath)}`) + expect(firstInjected[0]!.metadata).toEqual({ instruction: { paths: [pkgPath] } }) + expect(firstInjected[0]!.text).not.toContain("root-instructions") - // A subsequent file read under the listed directory is a dedup: pkg's AGENTS.md is - // already injected for this session, so nothing new is emitted. - yield* settleTool(registry, readCall(sessionID, "call-file", "packages/foo/file.txt")) + // A subsequent file read under the listed directory is a dedup: pkg's AGENTS.md is + // already injected for this session, so nothing new is emitted. + yield* settleTool(registry, readCall(sessionID, "call-file", "packages/foo/file.txt")) - expect((yield* synthetics(sessionID))).toHaveLength(1) - }), + expect(yield* synthetics(sessionID)).toHaveLength(1) + }), ) it.effect("listing the Location root directory injects no instructions", () => @@ -253,7 +273,7 @@ describe("SessionInstructions", () => { // dropped by the dirname filter, and up() only walks upward so nested dirs are unseen. yield* settleTool(registry, readCall(sessionID, "call-root-list", ".")) - expect((yield* synthetics(sessionID))).toHaveLength(0) + expect(yield* synthetics(sessionID)).toHaveLength(0) }), ) diff --git a/packages/core/test/tool-apply-patch.test.ts b/packages/core/test/tool-apply-patch.test.ts index 8084cbc24e..a717b799e3 100644 --- a/packages/core/test/tool-apply-patch.test.ts +++ b/packages/core/test/tool-apply-patch.test.ts @@ -16,8 +16,15 @@ import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" import { ApplyPatchTool } from "@opencode-ai/core/tool/apply-patch" import { location } from "./fixture/location" import { tmpdir } from "./fixture/tmpdir" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" import { testEffect } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" + +const applyPatchToolNode = makeLocationNode({ + name: "test/apply-patch-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(ApplyPatchTool.Plugin)), + deps: [ToolRegistry.toolsNode, LocationMutation.node, FileMutation.node, FSUtil.node, PermissionV2.node], +}) const sessionID = SessionV2.ID.make("ses_apply_patch_tool_test") const assertions: PermissionV2.AssertInput[] = [] @@ -101,7 +108,7 @@ const withTool = (directory: string, body: (registry: ToolRegistry.Inte ToolRegistry.toolsNode, LocationMutation.node, FileMutation.node, - ApplyPatchTool.node, + applyPatchToolNode, ]), [ [FSUtil.node, filesystem], diff --git a/packages/core/test/tool-edit.test.ts b/packages/core/test/tool-edit.test.ts index 2c684523b7..9df73c9b7d 100644 --- a/packages/core/test/tool-edit.test.ts +++ b/packages/core/test/tool-edit.test.ts @@ -17,8 +17,15 @@ import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" import { EditTool } from "@opencode-ai/core/tool/edit" import { location } from "./fixture/location" import { tmpdir } from "./fixture/tmpdir" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" import { testEffect } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" + +const editToolNode = makeLocationNode({ + name: "test/edit-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(EditTool.Plugin)), + deps: [ToolRegistry.toolsNode, LocationMutation.node, FileMutation.node, FSUtil.node, PermissionV2.node], +}) const sessionID = SessionV2.ID.make("ses_edit_tool_test") const assertions: PermissionV2.AssertInput[] = [] @@ -91,7 +98,7 @@ const withTool = (directory: string, body: (registry: ToolRegistry.Inte ToolRegistry.toolsNode, LocationMutation.node, FileMutation.node, - EditTool.node, + editToolNode, ]), [ [FSUtil.node, filesystem], diff --git a/packages/core/test/tool-question.test.ts b/packages/core/test/tool-question.test.ts index 5c5c95da61..dc01563022 100644 --- a/packages/core/test/tool-question.test.ts +++ b/packages/core/test/tool-question.test.ts @@ -9,7 +9,8 @@ import { ToolRegistry } from "@opencode-ai/core/tool/registry" import { QuestionTool } from "@opencode-ai/core/tool/question" import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" import { testEffect } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" const sessionID = SessionV2.ID.make("ses_question_tool_test") const assertions: PermissionV2.AssertInput[] = [] @@ -43,8 +44,14 @@ const question = Layer.succeed( list: () => Effect.die("unused"), }), ) +const questionToolNode = makeLocationNode({ + name: "test/question-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(QuestionTool.Plugin)), + deps: [ToolRegistry.toolsNode, PermissionV2.node, QuestionV2.node], +}) + const it = testEffect( - AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, QuestionTool.node]), [ + AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, questionToolNode]), [ [PermissionV2.node, permission], [QuestionV2.node, question], [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig], diff --git a/packages/core/test/tool-read.test.ts b/packages/core/test/tool-read.test.ts index 3c94888d57..f6f60df485 100644 --- a/packages/core/test/tool-read.test.ts +++ b/packages/core/test/tool-read.test.ts @@ -19,8 +19,25 @@ import { ToolRegistry } from "@opencode-ai/core/tool/registry" import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" import { ReadTool } from "@opencode-ai/core/tool/read" import { ReadToolFileSystem } from "@opencode-ai/core/tool/read-filesystem" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" +import { SessionInstructions } from "@opencode-ai/core/session/instructions" import { testEffect } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" + +const readToolNode = makeLocationNode({ + name: "test/read-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(ReadTool.Plugin)), + deps: [ + ToolRegistry.toolsNode, + ReadToolFileSystem.node, + LocationMutation.node, + Image.node, + PermissionV2.node, + SessionInstructions.node, + FSUtil.node, + Location.node, + ], +}) const assertions: PermissionV2.AssertInput[] = [] const missingPath = "__missing_read_target__.txt" @@ -130,7 +147,7 @@ const unavailableImage = Layer.succeed( Image.Service.of({ normalize: () => Effect.fail(new Image.ResizerUnavailableError()) }), ) const readLayer = (imageLayer: Layer.Layer) => - AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, ReadTool.node]), [ + AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, readToolNode]), [ [ReadToolFileSystem.node, reader], [PermissionV2.node, permission], [Config.node, config], diff --git a/packages/core/test/tool-skill.test.ts b/packages/core/test/tool-skill.test.ts index 4831acb799..23e51f6d08 100644 --- a/packages/core/test/tool-skill.test.ts +++ b/packages/core/test/tool-skill.test.ts @@ -13,7 +13,15 @@ import { ToolRegistry } from "@opencode-ai/core/tool/registry" import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" import { tmpdir } from "./fixture/tmpdir" import { it } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" + +const skillToolNode = makeLocationNode({ + name: "test/skill-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(SkillTool.Plugin)), + deps: [ToolRegistry.toolsNode, FSUtil.node, SkillV2.node, PermissionV2.node], +}) const sessionID = SessionV2.ID.make("ses_skill_tool_test") @@ -66,7 +74,7 @@ describe("SkillTool", () => { }), ) const skillToolLayer = AppNodeBuilder.build( - LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, SkillTool.node]), + LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, skillToolNode]), [ [PermissionV2.node, permission], [SkillV2.node, skills], diff --git a/packages/core/test/tool-todowrite.test.ts b/packages/core/test/tool-todowrite.test.ts index 170d1230a3..977ece9fc8 100644 --- a/packages/core/test/tool-todowrite.test.ts +++ b/packages/core/test/tool-todowrite.test.ts @@ -15,7 +15,14 @@ import { TodoWriteTool } from "@opencode-ai/core/tool/todowrite" import { ToolRegistry } from "@opencode-ai/core/tool/registry" import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" import { testEffect } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" + +const todoWriteToolNode = makeLocationNode({ + name: "test/todowrite-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(TodoWriteTool.Plugin)), + deps: [ToolRegistry.toolsNode, PermissionV2.node, SessionTodo.node], +}) const sessionID = SessionV2.ID.make("ses_todowrite_tool_test") const assertions: PermissionV2.AssertInput[] = [] @@ -43,7 +50,7 @@ const it = testEffect( SessionTodo.node, ToolRegistry.node, ToolRegistry.toolsNode, - TodoWriteTool.node, + todoWriteToolNode, ]), [ [PermissionV2.node, permission], diff --git a/packages/core/test/tool-webfetch.test.ts b/packages/core/test/tool-webfetch.test.ts index 2fe46f0ae5..421c09f876 100644 --- a/packages/core/test/tool-webfetch.test.ts +++ b/packages/core/test/tool-webfetch.test.ts @@ -10,8 +10,15 @@ import { SessionV2 } from "@opencode-ai/core/session" import { ToolRegistry } from "@opencode-ai/core/tool/registry" import { WebFetchTool } from "@opencode-ai/core/tool/webfetch" import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" import { testEffect } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" + +const webFetchToolNode = makeLocationNode({ + name: "test/webfetch-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(WebFetchTool.Plugin)), + deps: [ToolRegistry.toolsNode, PermissionV2.node, LayerNodePlatform.httpClient], +}) const sessionID = SessionV2.ID.make("ses_webfetch_test") const requests: Array<{ readonly url: string; readonly headers: Record }> = [] @@ -40,7 +47,7 @@ const permission = Layer.succeed( }), ) const toolLayer = (replacements: LayerNode.Replacements = []) => - AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, WebFetchTool.node]), [ + AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, webFetchToolNode]), [ [PermissionV2.node, permission], [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig], ...replacements, diff --git a/packages/core/test/tool-websearch.test.ts b/packages/core/test/tool-websearch.test.ts index 0b99a80ecb..53984ef69b 100644 --- a/packages/core/test/tool-websearch.test.ts +++ b/packages/core/test/tool-websearch.test.ts @@ -9,8 +9,15 @@ import { SessionV2 } from "@opencode-ai/core/session" import { ToolRegistry } from "@opencode-ai/core/tool/registry" import { WebSearchTool } from "@opencode-ai/core/tool/websearch" import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" import { testEffect } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" + +const webSearchToolNode = makeLocationNode({ + name: "test/websearch-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(WebSearchTool.Plugin)), + deps: [ToolRegistry.toolsNode, PermissionV2.node, LayerNodePlatform.httpClient, WebSearchTool.configNode], +}) const sessionID = SessionV2.ID.make("ses_websearch_test") const payload = (text: string) => @@ -125,7 +132,7 @@ const websearchConfig = Layer.succeed( ) const it = testEffect( AppNodeBuilder.build( - LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, WebSearchTool.configNode, WebSearchTool.node]), + LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, WebSearchTool.configNode, webSearchToolNode]), [ [PermissionV2.node, permission], [LayerNodePlatform.httpClient, http], diff --git a/packages/core/test/tool-write.test.ts b/packages/core/test/tool-write.test.ts index 2bd950f8a0..80fb011cc2 100644 --- a/packages/core/test/tool-write.test.ts +++ b/packages/core/test/tool-write.test.ts @@ -17,8 +17,15 @@ import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" import { WriteTool } from "@opencode-ai/core/tool/write" import { location } from "./fixture/location" import { tmpdir } from "./fixture/tmpdir" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" import { testEffect } from "./lib/effect" -import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool" +import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool" + +const writeToolNode = makeLocationNode({ + name: "test/write-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(WriteTool.Plugin)), + deps: [ToolRegistry.toolsNode, LocationMutation.node, FileMutation.node, PermissionV2.node], +}) const sessionID = SessionV2.ID.make("ses_write_tool_test") const assertions: PermissionV2.AssertInput[] = [] @@ -75,7 +82,7 @@ const withTool = (directory: string, body: (registry: ToolRegistry.Inte ToolRegistry.toolsNode, LocationMutation.node, FileMutation.node, - WriteTool.node, + writeToolNode, ]), [ [FSUtil.node, filesystem], From 698ef25f3320dece7fed7e31c4948dfe371dbd10 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Fri, 3 Jul 2026 15:38:54 +0200 Subject: [PATCH 02/82] fix(run): use parentID filter for subagent hydration (#35168) --- .../src/cli/cmd/run/stream-v2.subagent.ts | 4 ++-- .../test/cli/run/stream-v2.transport.test.ts | 21 +++++++++++++++---- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts b/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts index 1988d18d89..eac116b0b8 100644 --- a/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts +++ b/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts @@ -657,8 +657,8 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac // 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.v2.session - .list({ limit: FAMILY_LIST_LIMIT, order: "desc" }, { throwOnError: true }) - .then((response) => response.data.data.filter((session) => session.parentID === input.sessionID)) + .list({ parentID: input.sessionID, limit: FAMILY_LIST_LIMIT, order: "desc" }, { throwOnError: true }) + .then((response) => response.data.data) .catch(() => []) for (const session of family) { const child = ensureChild(session.id) diff --git a/packages/opencode/test/cli/run/stream-v2.transport.test.ts b/packages/opencode/test/cli/run/stream-v2.transport.test.ts index c09617701f..7c2fc9f70e 100644 --- a/packages/opencode/test/cli/run/stream-v2.transport.test.ts +++ b/packages/opencode/test/cli/run/stream-v2.transport.test.ts @@ -119,11 +119,20 @@ function sdk(input: { // The generated methods have conditional return types for throwOnError; the // minimal shapes below are enough for family discovery and model fallback. spyOn(client.v2.session, "list").mockImplementation( - () => - ok({ + (request) => { + const parentID = request?.parentID + return ok({ location: { directory: "/tmp", project: { id: "proj_1", directory: "/tmp" } }, - data: input.sessions ?? [], - }) as never, + data: + input.sessions?.filter((session) => + parentID === undefined + ? true + : parentID === null + ? session.parentID === undefined + : session.parentID === parentID, + ) ?? [], + }) as never + }, ) spyOn(client.v2.model, "default").mockImplementation( () => @@ -1237,6 +1246,10 @@ describe("V2 mini transport", () => { footer: ui.api, }) const states = ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) + expect(client.v2.session.list).toHaveBeenCalledWith( + { parentID: "ses_1", limit: 100, order: "desc" }, + { throwOnError: true }, + ) expect(states.at(-1)?.tabs).toMatchObject([ { sessionID: "ses_child_old", From 1fa605ad5ec1712de1490302f3b867b94b93171f Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Fri, 3 Jul 2026 16:35:19 +0200 Subject: [PATCH 03/82] fix(run): handle unattended form blockers (#35170) --- packages/opencode/src/cli/cmd/run.ts | 1 + .../src/cli/cmd/run/noninteractive.ts | 38 +++++- .../test/cli/run/noninteractive.test.ts | 121 ++++++++++++++++++ 3 files changed, 156 insertions(+), 4 deletions(-) create mode 100644 packages/opencode/test/cli/run/noninteractive.test.ts diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index fc495213c4..f56775e26c 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -958,6 +958,7 @@ export const RunCommand = effectCmd({ thinking, format: args.format === "json" ? "json" : "default", dangerouslySkipPermissions: args["dangerously-skip-permissions"], + attached: Boolean(args.attach), renderTool: tool, renderToolError: toolError, }) diff --git a/packages/opencode/src/cli/cmd/run/noninteractive.ts b/packages/opencode/src/cli/cmd/run/noninteractive.ts index 440436c704..fe6b95267c 100644 --- a/packages/opencode/src/cli/cmd/run/noninteractive.ts +++ b/packages/opencode/src/cli/cmd/run/noninteractive.ts @@ -33,6 +33,8 @@ type Input = { thinking: boolean format: "default" | "json" dangerouslySkipPermissions: boolean + /** True when the client is attached to a shared server rather than an exclusive in-process one. */ + attached: boolean renderTool: (part: ToolPart) => Promise renderToolError: (part: ToolPart) => Promise } @@ -50,6 +52,13 @@ type ToolState = StartedPart & { provider?: unknown } +type FormRequest = Extract["data"]["form"] + +// MCP elicitations are temporarily owned by the "global" sentinel instead of a real +// session. An exclusive local process may treat them as this run's blockers; an +// attached client must not cancel input that may belong to another session. +const GLOBAL_FORM_SESSION_ID = "global" + export async function runNonInteractivePrompt(input: Input) { const controller = new AbortController() const events = await input.client.v2.event.subscribe({ @@ -69,6 +78,7 @@ export async function runNonInteractivePrompt(input: Input) { let emittedError = false let questionRejected = false let permissionRejected = false + let formCancelled = false let interrupted = false let admission: AbortController | undefined @@ -117,6 +127,11 @@ export async function runNonInteractivePrompt(input: Input) { await input.client.v2.session.question.reject({ sessionID: input.sessionID, requestID: request.id }).catch(() => {}) } + const cancelForm = async (request: Pick) => { + formCancelled = true + await input.client.v2.session.form.cancel({ sessionID: request.sessionID, formID: request.id }).catch(() => {}) + } + const consume = async () => { while (!controller.signal.aborted) { const next = await stream.next() @@ -131,6 +146,15 @@ export async function runNonInteractivePrompt(input: Input) { await rejectQuestion(event.data) continue } + if ( + event.type === "form.created" && + submitted && + (event.data.form.sessionID === input.sessionID || + (!input.attached && event.data.form.sessionID === GLOBAL_FORM_SESSION_ID)) + ) { + await cancelForm(event.data.form) + continue + } if (!("sessionID" in event.data) || event.data.sessionID !== input.sessionID) continue const time = "timestamp" in event.data ? toMillis(event.data.timestamp) : Date.now() @@ -144,7 +168,7 @@ export async function runNonInteractivePrompt(input: Input) { if ( event.type === "session.next.execution.settled" && event.data.outcome === "interrupted" && - (interrupted || permissionRejected || questionRejected) + (interrupted || permissionRejected || questionRejected || formCancelled) ) { return } @@ -320,14 +344,14 @@ export async function runNonInteractivePrompt(input: Input) { continue } if (event.type === "session.next.step.failed") { - if (interrupted || permissionRejected || questionRejected) continue + if (interrupted || permissionRejected || questionRejected || formCancelled) continue emittedError = true process.exitCode = 1 if (!emit("error", time, { error: event.data.error })) UI.error(event.data.error.message) continue } if (event.type === "session.next.execution.settled") { - if (event.data.outcome === "failure" && !emittedError && !questionRejected) { + if (event.data.outcome === "failure" && !emittedError && !questionRejected && !formCancelled) { emittedError = true process.exitCode = 1 const error = event.data.error ?? { type: "unknown", message: "Session execution failed" } @@ -406,13 +430,19 @@ export async function runNonInteractivePrompt(input: Input) { if (!response.data.data) throw new Error("Prompt was not admitted") if (interrupted) await input.client.v2.session.interrupt({ sessionID: input.sessionID }).catch(() => {}) - const [permissions, questions] = await Promise.all([ + const [permissions, questions, forms] = await Promise.all([ input.client.v2.session.permission.list({ sessionID: input.sessionID }).catch(() => undefined), input.client.v2.session.question.list({ sessionID: input.sessionID }).catch(() => undefined), + Promise.all( + (input.attached ? [input.sessionID] : [input.sessionID, GLOBAL_FORM_SESSION_ID]).map((sessionID) => + input.client.v2.session.form.list({ sessionID }).catch(() => undefined), + ), + ), ]) await Promise.all([ ...(permissions?.data?.data ?? []).map(replyPermission), ...(questions?.data?.data ?? []).map(rejectQuestion), + ...forms.flatMap((response) => response?.data?.data ?? []).map(cancelForm), ]) await completed } finally { diff --git a/packages/opencode/test/cli/run/noninteractive.test.ts b/packages/opencode/test/cli/run/noninteractive.test.ts new file mode 100644 index 0000000000..15cf799c75 --- /dev/null +++ b/packages/opencode/test/cli/run/noninteractive.test.ts @@ -0,0 +1,121 @@ +import { afterEach, describe, expect, mock, spyOn, test } from "bun:test" +import { OpencodeClient, type V2Event } from "@opencode-ai/sdk/v2" +import { runNonInteractivePrompt } from "@/cli/cmd/run/noninteractive" + +type FormInfo = Extract["data"]["form"] + +function ok(data: T) { + return Promise.resolve({ + data, + error: undefined, + request: new Request("https://opencode.test"), + response: new Response(), + }) +} + +function form(id: string, sessionID: string): FormInfo { + return { id, sessionID, mode: "form", fields: [] } +} + +function formCreated(info: FormInfo): V2Event { + return { id: `evt_${info.id}`, type: "form.created", data: { form: info } } +} + +function prompted(messageID: string): V2Event { + return { + id: "evt_prompted", + type: "session.next.prompted", + data: { timestamp: 1, sessionID: "ses_1", messageID, prompt: { text: "hello" }, delivery: "steer" }, + } +} + +function settled(outcome: "success" | "interrupted" = "success"): V2Event { + return { + id: "evt_settled", + type: "session.next.execution.settled", + data: { timestamp: 2, sessionID: "ses_1", outcome }, + } +} + +// Runs one non-interactive prompt against a mocked SDK. `turn` produces the +// live events the prompt admission triggers, keyed by the generated message ID. +async function run(input: { + turn: (messageID: string) => V2Event[] + pendingForms?: FormInfo[] + attached?: boolean +}) { + const sdk = new OpencodeClient() + const values: V2Event[] = [{ id: "evt_connected", type: "server.connected", data: {} }] + let wake: (() => void) | undefined + const stream = (async function* (): AsyncGenerator { + while (true) { + const value = values.shift() + if (!value) { + await new Promise((resolve) => { + wake = resolve + }) + continue + } + yield value + } + })() + spyOn(sdk.v2.event, "subscribe").mockImplementation( + () => Promise.resolve({ stream }) as ReturnType, + ) + spyOn(sdk.v2.session.permission, "list").mockImplementation(() => ok({ data: [] }) as never) + spyOn(sdk.v2.session.question, "list").mockImplementation(() => ok({ data: [] }) as never) + spyOn(sdk.v2.session.form, "list").mockImplementation((request) => + ok({ data: input.pendingForms?.filter((item) => item.sessionID === request.sessionID) ?? [] }) as never, + ) + spyOn(sdk.v2.session.form, "cancel").mockImplementation(() => ok(undefined) as never) + spyOn(sdk.v2.session, "prompt").mockImplementation((request) => { + const messageID = request.id ?? "msg_prompt" + values.push(...input.turn(messageID)) + wake?.() + wake = undefined + return ok({ data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", timeCreated: 1 } }) as never + }) + await runNonInteractivePrompt({ + client: sdk, + sessionID: "ses_1", + message: "hello", + files: [], + thinking: false, + format: "default", + dangerouslySkipPermissions: false, + attached: input.attached ?? false, + renderTool: () => Promise.resolve(), + renderToolError: () => Promise.resolve(), + }) + return sdk +} + +afterEach(() => { + mock.restore() +}) + +describe("runNonInteractivePrompt", () => { + test("cancels session and global form blockers and exits on pre-promotion interrupt", async () => { + const sdk = await run({ + pendingForms: [form("frm_pending", "ses_1"), form("frm_pending_global", "global")], + // No prompted event: the execution settles interrupted before promotion, + // which must not leave the consume loop waiting forever. + turn: () => [formCreated(form("frm_live", "global")), settled("interrupted")], + }) + expect(sdk.v2.session.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }) + expect(sdk.v2.session.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" }) + expect(sdk.v2.session.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_pending_global" }) + }) + + test("attach mode cancels only session-owned forms", async () => { + const sdk = await run({ + attached: true, + pendingForms: [form("frm_pending", "ses_1"), form("frm_pending_global", "global")], + turn: (messageID) => [formCreated(form("frm_live", "global")), prompted(messageID), settled()], + }) + expect(sdk.v2.session.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" }) + expect(sdk.v2.session.form.list).not.toHaveBeenCalledWith({ sessionID: "global" }) + expect(sdk.v2.session.form.cancel).not.toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }) + expect(sdk.v2.session.form.cancel).not.toHaveBeenCalledWith({ sessionID: "global", formID: "frm_pending_global" }) + }) +}) From a2769b5ade6cbb544de05ba402eb1b6bbddcd368 Mon Sep 17 00:00:00 2001 From: James Long Date: Fri, 3 Jul 2026 11:26:58 -0400 Subject: [PATCH 04/82] fix(core): rewrite replacements while hoisting layers (#35176) --- packages/core/src/effect/layer-node.ts | 2 +- packages/core/src/location-services.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/core/src/effect/layer-node.ts b/packages/core/src/effect/layer-node.ts index b58692a155..9dbc3d5160 100644 --- a/packages/core/src/effect/layer-node.ts +++ b/packages/core/src/effect/layer-node.ts @@ -230,7 +230,7 @@ export function hoist { const allReplacements = replacements.concat([[Location.node, Location.boundNode(ref)]]) + // Apply replacements during hoist, not afterward: replacements can + // introduce new tagged dependencies (Location.boundNode depends on + // Project), and the hoist walk is the only pass that can still slice + // those back out. const location = LayerNode.hoist(locationServices, Node.tags.values.global, allReplacements) return LayerNode.compile(location.node).pipe( From 12d9f4b29b595869670ccc9b867e8eb9279b1a9f Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 3 Jul 2026 10:57:16 -0500 Subject: [PATCH 05/82] feat(codemode): add confined execution package (#35118) Co-authored-by: opencode-agent[bot] --- bun.lock | 39 +- packages/codemode/AGENTS.md | 15 + packages/codemode/README.md | 338 ++ packages/codemode/codemode.md | 1218 ++++++ packages/codemode/package.json | 26 + packages/codemode/src/codemode.ts | 4126 ++++++++++++++++++++ packages/codemode/src/index.ts | 21 + packages/codemode/src/token.ts | 10 + packages/codemode/src/tool-error.ts | 11 + packages/codemode/src/tool-runtime.ts | 829 ++++ packages/codemode/src/tool.ts | 348 ++ packages/codemode/src/values.ts | 34 + packages/codemode/test/codemode.test.ts | 1110 ++++++ packages/codemode/test/enumeration.test.ts | 159 + packages/codemode/test/parity.test.ts | 425 ++ packages/codemode/test/promise.test.ts | 453 +++ packages/codemode/test/signature.test.ts | 341 ++ packages/codemode/test/stdlib.test.ts | 495 +++ packages/codemode/tsconfig.json | 7 + 19 files changed, 10004 insertions(+), 1 deletion(-) create mode 100644 packages/codemode/AGENTS.md create mode 100644 packages/codemode/README.md create mode 100644 packages/codemode/codemode.md create mode 100644 packages/codemode/package.json create mode 100644 packages/codemode/src/codemode.ts create mode 100644 packages/codemode/src/index.ts create mode 100644 packages/codemode/src/token.ts create mode 100644 packages/codemode/src/tool-error.ts create mode 100644 packages/codemode/src/tool-runtime.ts create mode 100644 packages/codemode/src/tool.ts create mode 100644 packages/codemode/src/values.ts create mode 100644 packages/codemode/test/codemode.test.ts create mode 100644 packages/codemode/test/enumeration.test.ts create mode 100644 packages/codemode/test/parity.test.ts create mode 100644 packages/codemode/test/promise.test.ts create mode 100644 packages/codemode/test/signature.test.ts create mode 100644 packages/codemode/test/stdlib.test.ts create mode 100644 packages/codemode/tsconfig.json diff --git a/bun.lock b/bun.lock index 6a203012b5..be72ef8802 100644 --- a/bun.lock +++ b/bun.lock @@ -141,6 +141,20 @@ "effect", ], }, + "packages/codemode": { + "name": "@opencode-ai/codemode", + "version": "0.0.1", + "dependencies": { + "acorn": "8.15.0", + "effect": "catalog:", + "typescript": "catalog:", + }, + "devDependencies": { + "@tsconfig/bun": "catalog:", + "@types/bun": "catalog:", + "@typescript/native-preview": "catalog:", + }, + }, "packages/console/app": { "name": "@opencode-ai/console-app", "version": "1.17.13", @@ -583,6 +597,7 @@ "@octokit/rest": "catalog:", "@openauthjs/openauth": "catalog:", "@opencode-ai/client": "workspace:*", + "@opencode-ai/codemode": "workspace:*", "@opencode-ai/llm": "workspace:*", "@opencode-ai/plugin": "workspace:*", "@opencode-ai/protocol": "workspace:*", @@ -1939,6 +1954,8 @@ "@opencode-ai/client": ["@opencode-ai/client@workspace:packages/client"], + "@opencode-ai/codemode": ["@opencode-ai/codemode@workspace:packages/codemode"], + "@opencode-ai/console-app": ["@opencode-ai/console-app@workspace:packages/console/app"], "@opencode-ai/console-core": ["@opencode-ai/console-core@workspace:packages/console/core"], @@ -3025,7 +3042,7 @@ "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], - "acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "acorn": ["acorn@8.15.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="], "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], @@ -5707,6 +5724,8 @@ "@astrojs/mdx/@astrojs/markdown-remark": ["@astrojs/markdown-remark@6.3.11", "", { "dependencies": { "@astrojs/internal-helpers": "0.7.6", "@astrojs/prism": "3.3.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "import-meta-resolve": "^4.2.0", "js-yaml": "^4.1.1", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.2", "remark-smartypants": "^3.0.2", "shiki": "^3.21.0", "smol-toml": "^1.6.0", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.0.0", "unist-util-visit-parents": "^6.0.2", "vfile": "^6.0.3" } }, "sha512-hcaxX/5aC6lQgHeGh1i+aauvSwIT6cfyFjKWvExYSxUhZZBBdvCliOtu06gbQyhbe0pGJNoNmqNlQZ5zYUuIyQ=="], + "@astrojs/mdx/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "@astrojs/mdx/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], "@astrojs/sitemap/zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], @@ -5917,6 +5936,8 @@ "@malept/flatpak-bundler/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="], + "@mdx-js/mdx/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "@mdx-js/mdx/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], "@modelcontextprotocol/sdk/hono": ["hono@4.12.23", "", {}, "sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA=="], @@ -6165,6 +6186,8 @@ "astro/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="], + "astro/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "astro/common-ancestor-path": ["common-ancestor-path@1.0.1", "", {}, "sha512-L3sHRo1pXXEqX8VU28kfgUY+YGsk09hPqZiZmLacNib6XNTCM8ubYeT7ryXQw8asB1sKgcU5lkB7ONug08aB8w=="], "astro/diff": ["diff@5.2.2", "", {}, "sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A=="], @@ -6251,6 +6274,8 @@ "engine.io-client/ws": ["ws@8.20.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w=="], + "esast-util-from-js/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "esbuild-plugin-copy/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], "esbuild-plugin-copy/chokidar": ["chokidar@3.6.0", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="], @@ -6309,6 +6334,8 @@ "md-to-react-email/marked": ["marked@7.0.4", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-t8eP0dXRJMtMvBojtkcsA7n48BkauktUKzfkPSCq85ZMTJ0v76Rke4DYz01omYpPTUh4p/f7HePgRo3ebG8+QQ=="], + "micromark-extension-mdxjs/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], "miniflare/acorn": ["acorn@8.14.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA=="], @@ -6429,6 +6456,8 @@ "tar/yallist": ["yallist@5.0.0", "", {}, "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw=="], + "terser/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "terser/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="], "thread-stream/real-require": ["real-require@1.0.0", "", {}, "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g=="], @@ -6447,6 +6476,8 @@ "unifont/ofetch": ["ofetch@1.5.1", "", { "dependencies": { "destr": "^2.0.5", "node-fetch-native": "^1.6.7", "ufo": "^1.6.1" } }, "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA=="], + "unplugin/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "unplugin/chokidar": ["chokidar@3.6.0", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="], "unused-filename/path-exists": ["path-exists@5.0.0", "", {}, "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ=="], @@ -6461,6 +6492,8 @@ "verror/core-util-is": ["core-util-is@1.0.2", "", {}, "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ=="], + "vite-plugin-dynamic-import/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "vite-plugin-icons-spritesheet/glob": ["glob@11.1.0", "", { "dependencies": { "foreground-child": "^3.3.1", "jackspeak": "^4.1.1", "minimatch": "^10.1.1", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^2.0.0" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw=="], "vitest/@vitest/expect": ["@vitest/expect@4.1.7", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.7", "@vitest/utils": "4.1.7", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-1R+tw0ortHEbZDGMymm+pN7/AFQ/RkFFdtd7EN+VBpynKmLbP8A3rpEXdshBJ7+8hQ9zBJh/i1s0yKNtxAnU7w=="], @@ -6885,6 +6918,8 @@ "@standard-community/standard-openapi/effect/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + "@storybook/csf-plugin/unplugin/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], + "@storybook/csf-plugin/unplugin/webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/wasm-util@0.10.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="], @@ -7043,6 +7078,8 @@ "opencode-gitlab-auth/open/wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], + "openid-client/lru-cache/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], + "p-locate/p-limit/yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], "pkg-dir/find-up/locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="], diff --git a/packages/codemode/AGENTS.md b/packages/codemode/AGENTS.md new file mode 100644 index 0000000000..88dd9c81d9 --- /dev/null +++ b/packages/codemode/AGENTS.md @@ -0,0 +1,15 @@ +# @opencode-ai/codemode + +- This local package owns confined execution over explicit schema-described tools. Applications own authorization, persistence, external authority, and tool-specific delivery semantics. +- Do not add a speculative generic permission or approval policy. A host omits tools it does not expose and enforces domain authorization inside each provided tool. +- Keep Code Mode unaware of host session, channel, and conversation models. The hosting application supplies trusted execution scope around it. +- Tool schemas are the model-facing Interface. Keep arguments minimal and natural to the operation; never add unrelated IDs as ambient capability tokens. + +## Future Design Notes + +- If a captured user-visible output channel returns (an earlier `output.text`/`output.file`/`output.image` API was removed from v1), keep `output` as its name, distinct from the program return value: `return` stays the structured result for the model, while `output.*` describes artifacts the host may render into a conversation or UI after execution. Keep this host-neutral and let applications decide how captured output is delivered. In v1, hosts collect media host-side (outside the sandbox) instead. +- Improve the sandbox failure taxonomy. Distinguish parse/compile mistakes, unsupported syntax, user-thrown errors, invalid returned data, tool refusal, tool internal failure, timeout, and genuine runtime defects so agents can recover accurately instead of treating everything as a generic execution failure. +- Preserve the public/private error split. Tool authors should be able to return a safe model-visible message while retaining a private cause for host diagnostics. Unknown host failures must remain sanitized by default. +- Think deliberately about richer binary boundaries before allowing `Blob`, `File`, `ArrayBuffer`, streams, or typed arrays beyond today's JSON-like values. If CodeMode supports binary tool args/results, use explicit tagged data shapes and clear size limits rather than relying on ambient runtime serialization. +- Keep host capabilities explicit. Globals such as `fetch`, `crypto`, filesystem handles, extra modules, or network clients should be opt-in runtime capabilities with obvious policy defaults, not ambient authority. Default to unavailable unless a host deliberately provides the capability. +- If `fetch` is added, model it as a host-provided outbound capability with policy controls: allowed origins, methods, headers, response size, timeout, and whether response bodies may be returned, emitted, or only summarized through a tool. diff --git a/packages/codemode/README.md b/packages/codemode/README.md new file mode 100644 index 0000000000..3f1f641b3f --- /dev/null +++ b/packages/codemode/README.md @@ -0,0 +1,338 @@ +# @opencode-ai/codemode + +Effect-native confined code execution over explicit, schema-described tools. + +CodeMode lets a model write a small JavaScript program that can call only the tools supplied by the host. The program can sequence calls, transform plain data, branch, loop, and run independent calls in parallel without receiving ambient filesystem, process, network, module, or application authority. + +The package is currently private to this workspace. Its API is designed around three uses: + +```ts +// One execution +yield * CodeMode.execute({ tools, code }) + +// A reusable runtime +const runtime = CodeMode.make({ tools, limits }) +yield * runtime.execute(code) + +// One agent-facing code tool +const codeTool = runtime.agentTool() +``` + +## Install + +Within this workspace: + +```json +{ + "dependencies": { + "@opencode-ai/codemode": "workspace:*" + } +} +``` + +Hosts interact with CodeMode through `effect` (tool `run` implementations, `Effect`-typed results), so they should depend on `effect` themselves. + +## Quick Start + +Define tools with Effect Schema, then place them in the object tree exposed to programs as `tools`: + +```ts +import { CodeMode, Tool } from "@opencode-ai/codemode" +import { Effect, Schema } from "effect" + +const lookupOrder = Tool.make({ + description: "Look up an order by ID", + input: Schema.Struct({ id: Schema.String }), + output: Schema.Struct({ id: Schema.String, status: Schema.String }), + run: ({ id }) => Effect.succeed({ id, status: "open" }), +}) + +const runtime = CodeMode.make({ + tools: { + orders: { + lookup: lookupOrder, + }, + }, +}) + +const result = + yield * + runtime.execute(` + const order = await tools.orders.lookup({ id: "order_42" }) + return { id: order.id, needsAttention: order.status !== "complete" } +`) +``` + +`result` is always an `ExecuteResult`. Program, validation, limit, and tool failures are returned as diagnostics rather than failing the Effect. Host interruption remains interruption. + +Successful result values are JSON-safe data. A program that returns `undefined`, including by reaching the end without `return`, produces `null`; nested `undefined` values are normalized to `null` as well. + +## API + +### `Tool.make` + +```ts +const tool = Tool.make({ + description, + input, // Effect Schema (validating) or JSON Schema (render-only) + output, // optional; same choice + run, +}) +``` + +`input` and `output` each accept a validating Effect Schema or a render-only JSON Schema document (the natural shape for adapter-provided tools whose schemas arrive as JSON Schema, e.g. MCP definitions). Effect Schema input is decoded before `run` is invoked, and `run` returns the encoded representation of an Effect Schema `output`, which CodeMode decodes and copies before exposing it to the program. JSON Schemas only shape the model-visible signature; values pass through unvalidated (they still cross the plain-data boundary). + +`output` is optional. Without it the tool's signature advertises `Promise` and the host result is exposed as-is. + +The description and schemas are part of the model-visible tool contract. Keep descriptions concrete and put authorization in `run` or in the service it calls. + +### `CodeMode.execute` + +Use `CodeMode.execute` for a single execution: + +```ts +const result = + yield * + CodeMode.execute({ + tools: { orders: { lookup: lookupOrder } }, + code: `return await tools.orders.lookup({ id: "order_42" })`, + limits: { maxToolCalls: 10 }, + onToolCallStart: (call) => Effect.logDebug("CodeMode tool started", call), + onToolCallEnd: (call) => Effect.logDebug("CodeMode tool settled", call), + }) +``` + +The Effect environment is inferred from the supplied tools. CodeMode does not erase service requirements introduced by tool implementations. + +### `CodeMode.make` + +Use `CodeMode.make` when the tool set and execution policy are reused: + +```ts +const runtime = CodeMode.make({ + tools: { orders: { lookup: lookupOrder } }, + limits: { timeoutMs: 30_000 }, +}) + +runtime.catalog() // structured tool descriptions +runtime.instructions() // model-facing syntax and tool guide +runtime.execute(source) // ExecuteResult +runtime.agentTool() // { name, description, input, output, execute } +``` + +`catalog`, `instructions`, and `agentTool` are projections of the same configured tool tree. `agentTool().description` is exactly `instructions()`. + +### Results + +```ts +type ExecuteResult = ExecuteSuccess | ExecuteFailure + +interface ExecuteSuccess { + readonly ok: true + readonly value: Schema.Json + readonly logs?: ReadonlyArray + readonly truncated?: boolean + readonly toolCalls: ReadonlyArray +} + +interface ExecuteFailure { + readonly ok: false + readonly error: Diagnostic + readonly logs?: ReadonlyArray + readonly truncated?: boolean + readonly toolCalls: ReadonlyArray +} +``` + +`toolCalls` contains the names of calls admitted by the runtime in call order. It is retained on failure so hosts can audit partial execution without exposing inputs or host failures. `truncated` is present when the value or logs were cut to fit `maxOutputBytes` (see Execution Limits). + +### Tool-call hooks + +`onToolCallStart` receives `{ index, name, input }` after input decoding and before tool execution. The input is decoded host-side data and may include values produced by schema transformations; applications should avoid logging sensitive tool arguments indiscriminately. + +`onToolCallEnd` receives `{ index, name, input, durationMs, outcome, message? }` when an admitted call settles. `outcome` is `"success"` or `"failure"`; `message` is the model-safe failure message and is present only on failure. Interrupted calls (for example when the execution timeout fires) do not produce an end event. Both hooks are Effect-returning and must not fail. + +## Discovery + +The agent-tool instructions use a budgeted catalog. Every tool namespace is always listed with its tool count regardless of budget, and as many complete tool signatures (each with a one-line description) as fit an estimated-token budget are inlined. Selection is round-robin across namespaces for fairness: in each round (namespaces alphabetical), every namespace still holding un-inlined tools attempts to place its next-cheapest signature line against the shared budget, and a namespace whose next line does not fit drops out while the others keep going - so every namespace gets some representation before any namespace gets everything. The instructions state exactly how comprehensive the list is, both overall (`COMPLETE list` vs `PARTIAL - N of M shown`) and per namespace (`(3 tools)`, `(3 tools, 1 shown)`, `(3 tools, none shown)`). + +The default budget is 2,000 estimated tokens (characters / 4, the same heuristic OpenCode uses). Override it when constructing a runtime: + +```ts +const runtime = CodeMode.make({ + tools, + discovery: { maxInlineCatalogTokens: 6_000 }, +}) +``` + +The budget must be a non-negative safe integer. + +The runtime search tool is always registered - including when the catalog is fully inlined - so a speculative `tools.$codemode.search` call never fails as an unknown tool. It is only advertised in the instructions when the inlined list is partial: + +```ts +const matches = await tools.$codemode.search({ + query: "order status", + namespace: "orders", // optional: scope to one top-level namespace + limit: 10, +}) +``` + +`search` performs deterministic, additive field-weighted matching. The query is tokenized (camelCase boundaries split; every non-alphanumeric character is a separator; empties and `*` are dropped), and each term scores every tool: exact path or path-segment match (20), path substring (8), description substring (4), and searchable-text substring (2). Each term also carries naive singular variants (trailing `s`/`es` stripped), and a field check passes when the term or any variant matches - so a plural query term (`issues`) still finds a tool whose text only says `issue`, without changing the weights. The searchable text also includes the input schema's property names and their description strings, so a query naming a parameter finds its tool, and substring matching means partial words match. Scores sum across terms; matches are sorted by score (ties broken alphabetically by path) and capped at `limit` results (default 10). + +Each result contains the path, description, and generated TypeScript signature, so no second lookup is needed. The result signature is the pretty, JSDoc-annotated multiline form: each described input/output field carries its schema `description` as a `/** ... */` comment, and constraints TypeScript cannot express ride along as tags (`@deprecated`, `@default`, `@format`, `@minItems`, `@maxItems`). The inline catalog in the instructions keeps the compact single-line form. + +```ts +tools.github.list_issues(input: { + /** Repository owner */ + owner: string + /** Cursor from the previous response's pageInfo */ + after?: string + /** + * Results per page + * @default 30 + */ + perPage?: number +}): Promise +``` + +Result paths are rendered as JavaScript expressions rooted at `tools` (`tools.orders.lookup`, or `tools.context7["resolve-library-id"]` for non-identifier segments), so each `path` is directly usable as the call site. An empty query browses the catalog alphabetically by path; combined with `namespace` (`{ query: "", namespace: "orders" }`) it lists everything in that namespace. A query that names one tool path exactly (canonical path, `tools.`-prefixed path, or rendered JavaScript expression) is treated as a lookup and returns that tool alone. + +The instructions are structured markdown, ordered so the workflow sits at the top and the catalog at the bottom: a `## Workflow` section with numbered steps (find a tool via search when the catalog is partial, or pick from the inlined list when it is complete; call the exact path as-is; `JSON.parse` string results; return only the needed fields), a `## Rules` section holding only guidance the workflow does not already cover (only listed/search-result tools exist inside `tools`; filter and aggregate collections in code; treat `Promise` results as shapeless until verified; run independent calls through `Promise.all`; enumerate `tools` with `Object.keys`/`for...in`; browse a namespace via search when it is advertised), a short `## Syntax` section that assumes standard JavaScript and names only what is unusual (TypeScript annotations stripped; the data-boundary serialization of Date/Map/Set/RegExp) or missing (classes, generators, `for await...of`, `.then`/`.catch`/`.finally`), and the budgeted `## Available tools` catalog. Example call forms use explicit `.`/`` placeholders - never a real or fabricated tool name. + +A host cannot define its own `$codemode` top-level namespace. + +## Supported Programs + +CodeMode executes a deliberately bounded JavaScript subset. It supports: + +- Plain data literals, property access, assignment, and destructuring. +- `if`, conditional expressions, `switch`, `for`, `for...of` (arrays, strings, Maps, Sets), `for...in` (own keys of plain objects, index strings of arrays, and namespace/tool names of `tools` references - anything else is an error suggesting `for...of` or `Object.keys`, rather than real JS's surprising behavior of indices for strings and zero iterations for Maps/Sets), `while`, and `do...while`. +- Arrow functions and function declarations with closures, defaults, rest parameters, and destructuring. +- Optional chaining, nullish coalescing, templates, spread (arrays, strings, Maps, Sets), and `try`/`catch`. +- Common array, string, number, `Object`, `Math`, and `JSON` operations. Mutating array methods include `push`/`pop`/`shift`/`unshift`/`splice` (removes in place and returns the removed elements)/`fill`/`copyWithin`; array `keys`/`values`/`entries` return **arrays** (matching the Map/Set convention) and work with `for...of` and spread. String methods include `localeCompare` (locale/options arguments ignored), `normalize`, and the `trimLeft`/`trimRight` aliases. `Object.keys` also accepts arrays (index strings, as in JS) and tool references: `Object.keys(tools)` lists the top-level namespaces and `Object.keys(tools.ns)` the names at that node (a callable tool enumerates as `[]`; an unknown path is an `UnknownTool` diagnostic). `Object.values`/`Object.entries` on a tool reference fail with a pointer at `Object.keys(tools)` and `tools.$codemode.search`. +- `Date` - `Date.now()`/`Date.parse()`/`Date.UTC()`, `new Date(...)`, the getter methods, and date arithmetic/comparison via the time value. Dates stringify as ISO (`toString` included, for determinism across host timezones). +- Regular expressions - `/literals/` and `new RegExp(...)` with `test`/`exec` (stateful `lastIndex` for `g`), plus string `match`/`matchAll`/`replace`/`replaceAll`/`split`/`search` with patterns. Match results are arrays carrying `index` and named `groups` as own properties (`input` is omitted). Invalid patterns, invalid flags, and missing-`g` calls fail with catchable errors that say what was wrong and how to fix it (escaping hints, the exact `/pattern/g` to write). Patterns run on the host engine, so pathological backtracking is bounded only by the execution timeout. Function replacers are not supported. +- `Map` and `Set` - construction from entries/arrays/strings, `get`/`set`/`add`/`has`/`delete`/`clear`/`size`/`forEach`, and `keys`/`values`/`entries` returning **arrays** (not iterators). +- First-class promises - an un-awaited `tools.ns.tool(...)` is a promise value whose call starts immediately on a supervised fiber; `await` resolves it (awaiting a non-promise value is a no-op, and `return tools.ns.tool(...)` resolves like an async-function return). `Promise.all`, `Promise.allSettled`, and `Promise.race` accept any array mixing promises and plain values (built inline, beforehand, or via spread); `Promise.resolve`/`Promise.reject` construct settled promises. `Promise.allSettled` rejection reasons are the same plain `{ name?, message }` data a `catch` binding sees, and `Promise.race` interrupts its losing in-flight calls. At most 8 tool calls run concurrently. When a program completes, still-running un-awaited calls are awaited before the execution ends; a failure from a call that was never awaited surfaces as an unhandled-rejection diagnostic. +- `throw value` and `throw new Error(message)` for explicit program failure. `Error` (and `TypeError`/`RangeError`/`SyntaxError`/`ReferenceError`/`EvalError`/`URIError`) are real constructors, callable with or without `new`; error values are plain `{ name, message }` data that additionally satisfy `instanceof Error` (a specific type matches itself and `Error`, as in JS). Every caught failure - thrown errors, interpreter runtime errors, and tool failures - is `instanceof Error` in a `catch` block; a thrown non-error value (`throw "text"`) is not, matching JS. Caught failures carry the `name` the equivalent real-JS failure would have - `JSON.parse` and invalid regex patterns produce a `SyntaxError` (satisfying `instanceof SyntaxError`), an unknown identifier a `ReferenceError`, assigning to a constant a `TypeError`, a bad `normalize` form a `RangeError`; failures with no specific analogue (including tool failures) are named `"Error"`. `instanceof` also recognizes `Date`, `RegExp`, `Map`, `Set`, `Array`, `Object`, and `Promise`; any other right-hand side is a catchable error. + +Inside a program, Date/RegExp/Map/Set values stay live everywhere: the internal data checkpoints (`Object.*` helpers, spread, coercion inputs) preserve the instances, so `Object.values({ d: date })[0].getTime()` and a spread copy of an object holding a Map keep working. Only at the host boundary (final result, tool arguments, `JSON.stringify`) do the four value types serialize exactly as `JSON.stringify` would: a Date becomes its ISO string (`null` when invalid) and RegExp/Map/Set become `{}`. Promise values never cross a data boundary: an un-awaited promise in a result or tool argument produces a diagnostic that says to await it, instead of serializing to `{}`. + +It does not expose `eval`, dynamic imports, modules, classes, generators, timers, host globals, prototype mutation, custom promise constructors (`new Promise`), promise chaining (`.then`/`.catch`/`.finally` - `await` with `try`/`catch` is the supported style), or arbitrary method calls. Unsupported syntax returns an `UnsupportedSyntax` diagnostic with a source location when available. + +CodeMode is an orchestration language, not a general JavaScript runtime. + +## Execution Limits + +The limits are exactly three knobs: + +| Limit | Default | Bounds | +| ---------------- | -------------------: | -------------------------------------------------------------------- | +| `timeoutMs` | none - no timeout | Wall-clock execution time. | +| `maxToolCalls` | none - unlimited | Tool calls admitted during the execution. | +| `maxOutputBytes` | none - no truncation | Model-facing output: the serialized result value plus captured logs. | + +No limit has a default, on purpose: execution budgets are host policy, not library policy - a host that wants a bound sets one; a host that can interrupt the execution fiber (as OpenCode does on user cancel) may set no timeout, and a host with its own tool-output truncation (as OpenCode has) may leave `maxOutputBytes` unset. A host with neither should set `maxOutputBytes`, or oversized results silently flood model context. + +Pass only the overrides you need: + +```ts +const runtime = CodeMode.make({ + tools, + limits: { + maxToolCalls: 20, + timeoutMs: 60_000, + }, +}) +``` + +Limits are safe integers. `timeoutMs` must be at least `1`; the others may be `0`. Invalid configuration throws a `RangeError` when `CodeMode.make` or `CodeMode.execute` is called. An explicitly `undefined` value is the same as leaving the limit unset. + +Exceeding a configured `maxOutputBytes` never fails the execution. An oversized result value is replaced by its truncated serialized text plus an explanatory marker, logs are kept from the start until the remaining budget is exhausted (with a final marker line noting the cut), and the result carries `truncated: true`. + +When configured, the timeout interrupts in-flight tool Effects, including eagerly started calls the program has not awaited (their fibers are supervised by the execution). The interpreter yields cooperatively between steps, so the timeout also interrupts pure busy loops (`while (true) {}`) - no separate work budget exists. Tool implementations remain responsible for making their external operations interruptible or independently bounded. + +Two interpreter internals are fixed constants rather than knobs: at most 8 tool calls run concurrently, and values crossing a data boundary may nest at most 32 levels deep (deeper values fail as `InvalidDataValue`, which reads better than a native stack-overflow error). Neither is part of the public contract. + +## Diagnostics + +Failures are data: + +| Kind | Meaning | +| ----------------------- | -------------------------------------------------------------------------------------------------------- | +| `ParseError` | Source is empty or cannot be parsed. | +| `UnsupportedSyntax` | Parsed JavaScript is outside the supported subset. | +| `UnknownTool` | A program referenced a tool the host did not provide. | +| `InvalidToolInput` | Tool input failed schema decoding or safe-data copying. | +| `InvalidToolOutput` | Tool output failed schema decoding or safe-data copying. | +| `InvalidDataValue` | Program data violated the plain-data contract (depth, circularity, blocked properties, non-data values). | +| `ToolCallLimitExceeded` | Calls exceeded `maxToolCalls`. | +| `TimeoutExceeded` | Execution exceeded `timeoutMs`. | +| `ToolFailure` | A tool refused or failed. | +| `ExecutionFailure` | The program threw or another execution error occurred. | + +Unknown host failures, defects, invalid outputs, and copying failures are sanitized. To return a safe operational refusal, fail with `toolError`: + +```ts +import { toolError } from "@opencode-ai/codemode" + +run: ({ id }) => (authorized(id) ? loadOrder(id) : Effect.fail(toolError("Order is unavailable"))) +``` + +Only the supplied message is model-visible. The optional cause is never returned in `ExecuteResult`; hosts should perform any required internal logging before crossing this boundary. + +## Authority Boundary + +CodeMode confines programs to the supplied tool tree, but it does not decide what those tools may do. + +The host owns: + +- Authentication and authorization. +- Tool selection and immutable scope. +- Credentials and network clients. +- Persistence, idempotency, approval, and durable side effects. +- Logging and redaction policy. + +CodeMode owns: + +- Parsing and interpreting the supported subset without `eval`. +- Schema boundaries around tool calls. +- Plain-data copying and blocked prototype members. +- Resource limits, call accounting, and normalized diagnostics. +- Model-facing tool discovery and instructions. + +A program cannot gain authority through prose or generated code. It can only exercise authority already present in the supplied tools. Do not expose a broad tool and expect the prompt to restrict it. + +## Laws + +The public contract is guided by these equivalences: + +- `CodeMode.execute({ ...options, code })` is equivalent to `CodeMode.make(options).execute(code)`. +- `CodeMode.make(options).agentTool().execute({ code })` is equivalent to `CodeMode.make(options).execute(code)`. +- `CodeMode.make(options).agentTool().description` equals `CodeMode.make(options).instructions()`. +- A tool implementation is not invoked unless its input has decoded successfully. +- A tool result is not visible to the program unless its output has decoded and crossed the plain-data boundary successfully. +- Unknown host failures do not become model-visible diagnostics; `ToolError` is the explicit safe-message channel. +- Host interruption remains interruption rather than an `ExecuteFailure`. + +## Non-Goals + +- Generic permission prompts or approval workflows. +- Durable pause/resume, replay, or storage adapters. +- Exactly-once external side effects. +- Application authorization or product policy. +- A filesystem or process sandbox for arbitrary JavaScript. +- Compatibility with the full JavaScript language or npm ecosystem. + +Applications that need approval or durable consequences should model those above CodeMode and expose only the currently authorized tools. + +## Testing + +From the package directory: + +```sh +bun test +bun run typecheck +``` + +The direct suite covers public projections, discovery, schema boundaries, diagnostic sanitization, resource limits, tool-call observation, and interruption. diff --git a/packages/codemode/codemode.md b/packages/codemode/codemode.md new file mode 100644 index 0000000000..41b801044d --- /dev/null +++ b/packages/codemode/codemode.md @@ -0,0 +1,1218 @@ +# CodeMode - Status, Decisions, and Remaining Work + +This document is the working plan for `@opencode-ai/codemode` and its OpenCode integration. +It captures every locked decision, everything already implemented, and a detailed TODO of what +remains - enough context that someone (human or agent) can pick up any item cold. + +Tracking issue: https://github.com/anomalyco/opencode/issues/34787 +Working branch: `codemode-v2` (base: `dev`) + +--- + +## 1. What this is + +CodeMode gives a model one `execute` tool that runs JavaScript/TypeScript programs against a +tree of schema-described tools (`tools..(input)`), instead of exposing dozens +of MCP tools individually. The point is **control flow**: sequencing, filtering, and composing +tool calls in one program instead of round-tripping through the agent loop, plus not flooding +the context window when users connect many MCP servers. + +Architecture split (locked): + +- **`packages/codemode` (`@opencode-ai/codemode`)** - the generic, host-agnostic runtime: + a hand-rolled, Effect-native, tree-walking interpreter over acorn ASTs (TypeScript stripped + via `typescript`'s `transpileModule`), the tool runtime/data boundary, discovery/search, and + `Tool.make`. It knows nothing about OpenCode, MCP, permissions, or rendering. +- **`packages/opencode`** - the OpenCode integration: an MCP adapter that converts MCP tool + definitions into `Tool.make(...)` definitions, permission gating, host-side attachment + collection, the agent-facing `execute` tool, and TUI progress rendering. + +This package was seeded from the experiments workspace implementation +(`experiments/agents/packages/codemode`, package `@agents/codemode`) and then modified here. +The older vendored interpreter in `packages/opencode/src/session/rune/` was superseded by this +package and was **deleted** in Wave 3 (done, see below). + +--- + +## 2. Locked decisions + +From issue #34787 and design discussion. Do not relitigate these casually. + +### Core direction + +- Generic CodeMode lives in its own package: `@opencode-ai/codemode` (repo scope convention; + the issue's `@opencode/codemode` name was normalized to the `@opencode-ai/*` convention). +- **Keep the hand-rolled interpreter.** No QuickJS/V8/sandbox-engine dependency. We own and + test the whole surface; the model only needs orchestration syntax, not a full runtime. +- Naming: `CodeMode`, `Tool`, `ToolError`, `UnknownTool` (diagnostic kind), `$codemode` + reserved discovery namespace. (Historical names - "rune", "capability" - are dead.) +- Existing OpenCode core tools (bash/edit/patch/...) stay registered normally for v1. + CodeMode covers MCP tools, user-registered tools, and deferred tools only. +- Test runner is `bun test`; typecheck is `tsgo --noEmit` (repo conventions). Not vitest. +- **Never reference external prior-art implementations** (other companies' code-execution + products/blog posts) in code, comments, commit messages, or docs in this repo. + +### MCP / tools + +- The MCP adapter lives in OpenCode, not here. It converts MCP definitions into ordinary + `Tool.make(...)` definitions and hands CodeMode a plain tool tree. +- Permissions stay in the OpenCode adapter (each tool's `run` wraps the permission ask). + CodeMode stays dumb - no permission model in this package. +- Namespace collisions: last write wins (plain JS object override). No `tools.mcp.*` prefix, + no `_2` suffixing, no cleverness. OpenCode groups flat `server_tool` MCP names into + `tools..` namespaces before handing them over. + +### Discovery / search + +- **Search only - no separate `describe`.** `tools.$codemode.search({ query?, namespace?, +limit? })` over the final tool tree, owned by this package. +- Search result item shape: `{ path, description, signature }` in an `{ items, total }` + wrapper. The `signature` string embeds the full input/output TypeScript types - in search + results it is the pretty, JSDoc-annotated multiline form (Fix 7), so per-field schema + `description`s and constraints (`@default`, `@format`, `@deprecated`, `@minItems`, + `@maxItems`) ride along as field comments. The original spec's separate `input`/`output` + raw-schema fields are deliberately NOT added: shapes are already fully expressed in the + TypeScript signature and schema annotations now arrive as JSDoc - intent satisfied, letter + deviated. Result `path`s render a JavaScript expression rooted at `tools` (for example + `tools.github.list_issues` or `tools.context7["resolve-library-id"]`) so each is directly + usable as the call site; the internal `ToolDescription.path` stays unprefixed. +- Default limit: **10** (done). Exact-path lookup goes through search too: a query equal to a + canonical tool path, `tools.`-prefixed path, or rendered JavaScript expression returns that + tool alone (done). +- Signatures render **native payloads**: `Promise`, NOT `Promise>`. + There is no result envelope; attachments never appear in return types (they are collected + host-side, see below). +- Tools without an output schema render `unknown` as their return type. + +### Schemas / Tool.make + +- `Tool.make` carries rich metadata so search can render real signatures. +- Support **Effect Schema** (first-class, validating) and **JSON Schema** (initially + render-only - used for TypeScript rendering; the adapter may validate on its own). Leave + room for Standard Schema later. +- Tool implementations are **Effect-based** for v1 (`run` returns `Effect`). Promise + normalization for plugin authors can come later. + +### Attachments / output + +- **No `output.text/file/image` API in v1.** (Deleted in Wave 2.) +- Tool calls return native structured payloads into the sandbox. Files/images emitted by + child tools **never enter the sandbox** - the OpenCode adapter strips and accumulates them + host-side as calls happen, then returns them on the outer `execute` tool result as ordinary + tool-result attachments (OpenCode already has `Tool.ExecuteResult.attachments` -> vision + plumbing in `message-v2.ts`). +- No base64 in CodeMode values, ever. The model routes nothing; it can't accidentally dump + image bytes into context or drop attachments. + +### Runtime behavior + +- Limits are EXACTLY the three public knobs: `{ timeoutMs, maxToolCalls, maxOutputBytes }` - + matching the original locked spec exactly. NO limit has a default (user direction, Fix 6 + for the first two; extended to `maxOutputBytes` in the truncation-layering fix below): + absent = no timeout / unlimited calls / no output truncation - budgets are host policy. + A host without its own output bounding should set `maxOutputBytes` explicitly, or + oversized results silently flood model context. OpenCode's adapter policy (user + direction): NO limits at all - no timeout, unlimited tool calls (each child call is + permission-gated; user cancel interrupts the execution fiber and its children), and no + CodeMode truncation (output bounding is OpenCode's native tool-output truncation). + The internal limit system that Wave 2 kept behind + an `@internal` `InternalExecutionLimits` type (maxOperations, maxDataBytes, maxValueDepth, + maxCollectionLength, maxSourceBytes, maxAuditBytes, maxConcurrency) was deleted outright in + Fix 5 (see Post-wave fixes). Two internals survive as fixed constants, not knobs: + `TOOL_CALL_CONCURRENCY = 8` (the fork semaphore) and `MAX_VALUE_DEPTH = 32` (the `copyIn` + boundary depth check, kept only because it beats a native stack-overflow RangeError as an + error message; still reports `InvalidDataValue`). +- Truncation layering RESOLVED (user direction): CodeMode truncation is off in OpenCode. + `execute` is a normal `Tool.define` tool, so OpenCode's native tool-output truncation + (50KB / 2000 lines in `tool.ts` + `truncate.ts`, full output dumped to a file) applies to + it with no special-casing - verified by tracing `wrap()` in `tool.ts:130-144` (the + `metadata.truncated` exemption never fires for `execute`). One truncation layer, the + host's. `maxOutputBytes` remains available for hosts without their own bounding. +- Pure-JS built-ins only. **No ambient authority**: no fs, child processes, network/fetch, + process/env, or timers in v1. The agent has the bash tool for that. +- Forgiving JS semantics are locked (see section 3, Wave 1a/1b-i) - missing props read `undefined`, + `typeof` never throws, NaN/Infinity flow in-sandbox, etc. +- `console.*` is captured into `logs` on the result; the host appends them to model-facing + output. Not a tool call; costs no tool budget. +- Simple tool-call **start/end hooks** for nested progress: `onToolCallStart({ index, name, +input })` and `onToolCallEnd({ index, name, input, durationMs, outcome, message? })`. + Interrupted calls fire no end event. No `CurrentToolCall` context service (removed in + Wave 2). + +--- + +## 3. Current status (what is already done on `codemode-v2`) + +Everything below is committed and pushed on `codemode-v2` (six commits, in pairs of +generic-package + OpenCode-integration: waves 0-5, Fixes 4-9, then the DSL-expansion pass / +real-JS error names / truncation layering). Verification: from `packages/codemode`, +`bun test` (211 pass / 0 fail across `codemode/parity/stdlib/promise/enumeration/signature`) +and `bun run typecheck`; from `packages/opencode`, `bun run typecheck` and +`bun test test/tool/` (all green - the adapter suites are `test/tool/code-mode.test.ts`, +43 tests, and `test/tool/code-mode-integration.test.ts`, 16 tests, moved from +`test/session/` by the registry promotion; registry coverage in +`test/tool/registry.test.ts`). + +### Wave 0 - scaffold (done) + +- `packages/codemode` created from the experiments implementation: `src/{index,codemode,tool, +tool-error,tool-runtime}.ts`, README, AGENTS.md, tests. +- `package.json`: name `@opencode-ai/codemode`, deps `acorn@8.15.0`, `typescript: catalog:`, + `effect: catalog:` (both repos pin effect `4.0.0-beta.83`; opencode's effect patch only + touches `unstable/httpapi`, which this package doesn't use). +- Tests converted vitest -> `bun:test`. Only src change from verbatim: the `CurrentToolCall` + Context.Service key string renamed to `@opencode-ai/codemode/CurrentToolCall`. + +### Wave 1a - forgiving JS semantics (done) + +Ported from the old opencode rune work; `test/parity.test.ts` (24 tests) is the acceptance +spec. The seeded interpreter was deliberately strict; these behaviors replaced that: + +- **H1**: NaN/Infinity flow as in-sandbox values (`copyIn` admits them; `NaN`/`Infinity` are + bindable globals; `charCodeAt` returns real NaN). Normalized to `null` only at the data + boundary (`copyOut` - single chokepoint for final results AND tool-call arguments), matching + `JSON.stringify`. Guards like `Number.isNaN(x)` / `parseInt(x) || 0` work. +- **H2/H3**: unknown property reads on strings/numbers/arrays -> `undefined` (incl. under + `?.`), instead of throwing. This was the real-transcript failure: models write + `result?.login ?? result` against JSON-string tool results. +- **H4**: `typeof undeclaredIdentifier` -> `"undefined"` (short-circuits before resolution). +- **H5**: `Boolean`/`String`/`Number` accepted as array callbacks (`filter(Boolean)`). +- **H6**: `{...null}` / `{...undefined}` object spread is a no-op. Array spread of + null/undefined still throws (real JS throws too). + +### Wave 1b-i - stdlib value types: Date, RegExp, Map, Set (done) + +`src/values.ts` holds `SandboxDate/SandboxRegExp/SandboxMap/SandboxSet` (own module so both +`codemode.ts` and `tool-runtime.ts` import without a cycle). Design: + +- Opaque-by-default: all four join `isRuntimeReference`, with explicit carve-outs (member + access allowlists, Date in binary/unary ops, Map/Set in spread/for...of, console formatting, + `containsOpaqueReference` for operator guards; the `runtimeValueBytes` byte-accounting + carve-out died with that machinery in Fix 5). +- **JSON semantics at every boundary and checkpoint**: Date -> ISO string (invalid -> null), + RegExp/Map/Set -> `{}`. `copyIn` also converts host `Date`/`RegExp`/`Map`/`Set` instances the + same way (a host tool may legitimately return them). (Narrowed by the DSL-expansion pass: + intra-sandbox checkpoints now preserve the instances; JSON forms apply at the host + boundary only.) +- Date: `Date.now/parse/UTC`, `new Date(epoch|string|components)`, getters + UTC variants, + `end - start`, `a < b`, `+date`; `toString` is ISO for cross-host determinism. +- RegExp: literals + `new RegExp`, `test`/`exec` (stateful `lastIndex` for `g`), string + `match/matchAll/replace/replaceAll/split/search`. Match results are plain arrays carrying + `index`/named `groups` as own properties (enabled by a general array own-property read fix); + `input` omitted deliberately. Function replacers unsupported (clear error). Patterns run on + the host engine - catastrophic backtracking is bounded only by `timeoutMs` (accepted, in + README). +- Map/Set: full method sets; `keys/values/entries` return **arrays** (not iterators); + `for...of` + spread work; `Object.fromEntries(map)`, `Array.from(map|set)`; SameValueZero + keys (NaN findable). (The incremental byte totals and `maxCollectionLength`/`maxDataBytes` + enforcement this wave added were deleted in Fix 5.) +- Rode along, same spirit: `typeof` never throws for any value (`typeof fn` -> `"function"`), + `!` works on any value, `for...of` over strings, `{...sandboxValue}` no-op, template + interpolation renders `/regex/` and ISO dates directly. + +### Wave 2 - API layer (done) + +The package's public contract, reshaped for the Wave 3 adapter. 101 tests / 0 fail after this +wave; both packages typecheck clean. + +- **`Tool.make` schema flexibility** (`src/tool.ts`): `input`/`output` each accept an Effect + Schema (validating, decoded both directions as before) OR a raw JSON Schema document + (render-only - no validation, values pass through; rendering handles `$defs`/`definitions` + - `$ref`). `output` is **optional** -> signature renders `Promise` and the host + result is exposed as-is. Discrimination via `Schema.isSchema`. New helpers exported from + `tool.ts`: `inputTypeScript`/`outputTypeScript`/`decodeInput`/`decodeOutput`/ + `jsonSchemaToTypeScript`; `tool-runtime.ts` consumes them (no direct `Schema.*` use there + anymore). Types `JsonSchema`/`ToolSchema` exported from the index. Note: an empty + `Schema.Struct({})` renders as `{ } | Array` (effect's JSON Schema emission) - + cosmetic, fixed in Wave 4. +- **`output.*` API deleted**: `OutputItem`(+Schema), result `output` fields, the `output` + global/namespace dispatch, `invokeOutput`/`outputItem`/helpers, interpreter output fields, + instructions line, README section, seeded tests. AGENTS.md keeps a rephrased + future-design note (channel name stays `output` if it ever returns). +- **Hooks**: `CurrentToolCall` removed entirely (class, provideService, `Services` Exclude + special-casing, index export). `onToolCall` -> `onToolCallStart({ index, name, input })` + + `onToolCallEnd({ index, name, input, durationMs, outcome: "success"|"failure", message? })`. + End fires symmetrically via `Effect.tap`/`tapError` around the settling portion (host run + + output decode + boundary copy; search too - its post-record body is wrapped in `Effect.try` + so failures are typed and observable). `message` is the model-safe failure message + (`ToolError`/`ToolRuntimeError` message, else "Tool execution failed"). Interrupted calls + fire no end event (timeout kills the whole execution anyway). +- **Limits collapse**: public `ExecutionLimits` = `{ timeoutMs?, maxToolCalls?, +maxOutputBytes? }` (defaults 10_000 / 100 / 32_000). This wave kept the other knobs as + internal defaults reachable through an `@internal` `InternalExecutionLimits` type; Fix 5 + later deleted that type and the internal limit system entirely. +- **`maxOutputBytes` truncation** (CodeMode-owned, never fails): applied via `boundOutput` in + a final `Effect.map` over every result path (success/timeout/normalized failure). Oversized + serialized values become truncated text + ` [result truncated: N bytes exceeds the M-byte +output limit; return a smaller value]`; logs keep leading lines within the remaining budget + - `[logs truncated: showing K of N lines]`; result gains `truncated: true` (also added to + `ExecuteResultSchema`). UTF-8-safe truncation (no split code points). (The in-sandbox + `maxDataBytes` check that used to throw first on oversized raw values died in Fix 5 - + truncation is now the only result-size mechanism.) +- **Search polish**: default limit 12 -> **10** (`defaultSearchLimit`); exact-path lookup - a + trimmed query equal to one tool path (optionally `tools.`-prefixed) returns that tool alone + (`total: 1`), bypassing ranking. Tokenization/ranking/shape unchanged. + +### Wave 3 - OpenCode MCP adapter (done) + +`packages/opencode/src/session/code-mode.ts` rewritten as a thin adapter over this package; +the vendored rune interpreter is gone. Same `define(mcpTools, mcpDefs, servers)` signature, so +`tools.ts` gating (flag on + MCP tools exist -> single `execute` tool, early-return suppresses +per-MCP registration; MCP resource tools unaffected) is unchanged. + +- **Tool tree**: `groupByServer` (longest-sanitized-prefix, ported) groups flat `server_tool` + keys into `CatalogEntry`s carrying the raw MCP `inputSchema`/`outputSchema` as render-only + JSON Schema; `toolTree` turns each into `Tool.make({ description, input, output?, run })` + under `tools..`. The agent-facing description is + `CodeMode.make({ tools }).instructions()` over a preview tree (placeholder runs, never + invoked) - so signature rendering, the inline-vs-search switch, and `$codemode.search` + availability all come from this package and stay consistent with execution. +- **`run` path**: per-child permission ask first (`ctx.ask({ permission: entry.key, patterns: +["*"], always: ["*"] })`, exactly the old gating; approving `execute` approves no child). + Denials and host failures are mapped to `toolError(message)` so they surface as safe, + catchable in-program failures (MCP `isError` text propagates as `e.message`; without this + they'd be sanitized to "Tool execution failed"). Dispatch reuses the ai-sdk wrapper from + `catalog.convertTool` (`entry.tool.execute!`), which owns callTool timeouts/progress-reset. +- **Result shaping** (`toSandboxResult`): prefer `structuredContent`; else joined text + content; media (image/audio/resource blob/resource_link) NEVER enters the sandbox - blocks + are stripped into a per-execution `Attachment[]` accumulator, and a media-only result + becomes a marker payload (`"[1 image attached to the result]"`, noun/count adjusted). An + MCP-shaped result with nothing extractable becomes `null`; non-MCP values pass through. + No handles, no `Result` envelope, no base64 in the sandbox, no data-size tuning (the + `maxDataBytes` budget that existed at the time was deleted in Fix 5). +- **Execute result**: `{ output: formatValue(value) + trailing "Logs:" section (success AND +error - logs are plain pre-formatted lines now), attachments: accumulated }` through the + existing `Tool.ExecuteResult.attachments` -> `message-v2.ts` vision plumbing; attachments + ride on both success and error results. Diagnostic `suggestions` not already contained in + the message are appended to error output. Native outer truncation stays on (adapter never + sets `metadata.truncated`); CodeMode's own `maxOutputBytes` (32 KB default at the time) + cut first - since the truncation-layering fix, native truncation is the only layer. + Limits: `{ timeoutMs: 30_000 }` at the time (matched the default MCP request timeout); + killed in Fix 6 - the adapter now passes no limits at all. +- **Progress**: `onToolCallStart`/`onToolCallEnd` -> `ctx.metadata({ toolCalls })` with + `{ tool, status: running|completed|error, input? }` per call index - the exact shape the + TUI `Execute` component (`packages/tui/src/routes/session/index.tsx`) already renders. + `$codemode.search` calls stream through the same channel. +- **Deletions/deps**: `src/session/rune/` (all five files) and + `test/session/rune-parity.test.ts` (superseded by this package's `test/parity.test.ts`) + deleted; `acorn` removed from opencode deps, `typescript` moved back to devDependencies, + `"@opencode-ai/codemode": "workspace:*"` added; `bun install` run (lockfile updated). +- **Tests**: both opencode suites rewritten against the adapter design - + `code-mode.test.ts` (34: grouping, description/signature rendering incl. the large-catalog + search fallback, execution, permission flow + denial, metadata streaming, attachment + accumulation + media-only marker, logs on success/error, truncation marker, + `toSandboxResult`/`formatValue`/`withLogs` units) and `code-mode-integration.test.ts` + (16: real in-memory MCP server; native structured results, attachment accumulation, isError + propagation, logs, permissions, live metadata). Old envelope/attachment-handle/`$rune` + describe/`renderType`/`rankTools` tests died with the old design (58+17+24 -> 34+16). + +### Wave 4 - instructions/prompting + polish (done) + +Instructions are now the budgeted-catalog + prompting-guidance form; verified e2e against a +real MCP config. Package still 101 tests / 0 fail; opencode adapter suites still 34 + 16; both +packages typecheck clean. + +- **Budgeted catalog** (`discoveryPlan` in `tool-runtime.ts`): the all-or-nothing + inline/search modes are gone - `DiscoveryMode` deleted, `DiscoveryOptions` is just + `{ maxInlineCatalogBytes? }` (default 16,000 UTF-8 bytes; later converted to + `maxInlineCatalogTokens`, default 4,000 estimated tokens - see Post-wave fixes). Port of + the old opencode + `describe()` `PREVIEW_BUDGET` algorithm, adapted to `ToolDescription`: every namespace is + ALWAYS listed with its tool count; full signature lines + (` - // `) are inlined + cheapest-first (line byte length, path tiebreak) within each namespace, namespaces processed + alphabetically; once one line does not fit, inlining stops for every remaining namespace + (counts only), exactly like the ported algorithm (this stop-everything behavior was later + replaced by round-robin fairness in Fix 8). The header states comprehensiveness + precisely: "Available tools (COMPLETE list - ...)" vs "Available tools (PARTIAL - N of M + shown; find the rest with tools.$codemode.search)"; namespace labels are `(N tools)` / + `(N tools, K shown)` / `(N tools, none shown)`. An empty tree renders "No tools are + currently available." +- **Search always registered** (documented decision): `DiscoveryPlan.searchIndex` is required + and built unconditionally (new exported `ToolRuntime.searchIndex(tools)`; `SearchEntry` type + exported); `CodeMode.execute` (one-shot) passes it too, preserving the + `execute`==`make().execute` law. A speculative `tools.$codemode.search` call on a small + catalog now succeeds instead of `UnknownTool`, and unknown-tool suggestions always point at + search. Search is _advertised_ in the instructions only when the inlined list is PARTIAL, + keeping small-catalog instructions tight. +- **Prompting content** in `instructions()`, mapping 1:1 to the section 5 transcript failures: + parse-string-results-as-JSON, return-small, console-for-intermediates, and + read-the-description-before-calling guidance. (The flat prose layout this wave produced + was later replaced wholesale by the markdown-section restructure - see Post-wave fixes - + which also deleted this wave's worked example.) +- **Cosmetic renderer fixes** (`renderSchema` in `tool.ts`): an object schema with no + properties renders `{}` (was `{ }`), and the empty `Schema.Struct({})` emission + (`anyOf: [{ type: "object" }, { type: "array" }]`, no properties/items) collapses to `{}` + (was `{ } | Array`). +- **Tests**: 4 package discovery tests rewritten for the budgeted behavior (COMPLETE small + catalog + search-still-registered; PARTIAL at budget 0; cheapest-first selection + + per-namespace labels + budget-exhaustion stopping later namespaces; mode-validation + assertion dropped); 3 opencode description assertions updated (COMPLETE/PARTIAL headers, + namespace labels, `(input: {})` rendering, cheapest-first op_0 shown / op_149 not). +- **E2E (verified, headless)**: from the repo root with `OPENCODE_EXPERIMENTAL_CODE_MODE=1`, + the scratch `.opencode/opencode.jsonc` (context7, github, playwright, sentry, memory, + sequential-thinking; left uncommitted/as-is), and `bun packages/opencode/src/index.ts run +--dangerously-skip-permissions -m opencode/claude-sonnet-4-5 "..."`. Confirmed: a single + `execute` tool registered alongside core tools (per-MCP registration suppressed; MCP + resource tools unaffected); the live description read back as "Available tools (PARTIAL - + 56 of 88 shown; find the rest with tools.$codemode.search):" with correct per-namespace + labels (context7/github/memory fully shown; playwright/sentry/sequential-thinking "none + shown" - the alphabetical-exhaustion starvation Fix 8 later replaced with round-robin + fairness); programs executed with in-program `$codemode.search` + calls and returned the correct answer. NOT verified e2e (headless only; covered by + unit/integration tests instead): TUI child-call rendering, attachments becoming visible + images, output truncation. + +### Wave 5 - Promise generalization (done) + +First-class promise values in the interpreter; the direct-tool-call-only `Promise.all` +restriction (and its bespoke AST checks) is gone. Package suite is 136 tests / 0 fail (35 new +in `test/promise.test.ts`); adapter suites and both typechecks unchanged/green; the opencode +adapter needed **no changes**. + +- **Decision: eager fork** (`const p = tools.a.b(x)` starts the call immediately on a + supervised child fiber; `await p` observes its settlement). Chosen over lazy because: + (1) it's spec-faithful - JS promise work starts at call time, so + `const a = t1(); const b = t2(); return [await a, await b]` gets real parallelism instead of + silently sequential awaits; (2) run-once is free - a fiber settles exactly once and + `Fiber.await` is idempotent, so `await p` twice or `Promise.all([p, p])` can never re-invoke + the tool (lazy needs a deferred/latch to match); (3) effect's structured concurrency does the + hard part - `Effect.forkChild` children are auto-supervised (interrupted when the parent + fiber exits) and `Effect.timeoutOrElse` is `raceFirst`, which runs the program on its own + raced fiber, so forked calls cannot escape the timeout (tested: in-flight forks are + interrupted, awaited or abandoned, direct or inside `Promise.all`). +- **Mechanics**: `SandboxPromise` in `values.ts` (fiber-backed for tool calls; fiberless + `immediate` effect for `Promise.resolve`/`reject`). Forks run + `semaphore.withPermit(invoke)` with `startImmediately: true` - a per-execution + `Semaphore.makeUnsafe(TOOL_CALL_CONCURRENCY)` (fixed 8, see Fix 5) caps live calls (the + "Effect.all or equivalent" cap lives where the work is, so combinator joins can be + sequential without losing parallelism), and the tool-call-count charge (`recordCall`) plus + `onToolCallStart` fire at the call site before any await. `await` of a non-promise is a passthrough no-op; a returned + top-level promise resolves like an async-function return (`return tools.a.b(x)` works + without await). +- **Promise combinators are normal functions over values**: `Promise.all`/`allSettled`/`race` + accept any array (or spreadable collection) mixing promises and plain data - inline, built + beforehand, spread, nested in variables. `allSettled` yields + `{ status: "fulfilled", value } | { status: "rejected", reason }` with reasons produced by + the same `caughtErrorValue` helper the `catch` binding uses (factored out of + `evaluateTryStatement`). `race` resolves/rejects with the first settlement and interrupts + losing in-flight calls; awaiting an interrupted loser afterwards is a catchable program + failure ("interrupted because another value settled a Promise.race first"), while any other + interrupt-only settlement keeps propagating as interruption (preserving the + host-interruption law). `Promise.resolve` flattens promises; `Promise.reject` rejects with + the reason via `ProgramThrow`. +- **Opaqueness/boundaries**: promises are runtime references - `typeof` -> `"object"` (real JS), + operators reject them, `copyIn` raises an await-hinting `InvalidDataValue` ("contains an + un-awaited Promise; await tool calls (...) before using their results") for results, tool + arguments, and `JSON.stringify` instead of `{}`. Property access on a promise is a + deliberate error (not the forgiving `undefined`): `.then/.catch/.finally` -> + `UnsupportedSyntax` pointing at `await` + try/catch; anything else -> "await it first". + `new Promise(...)` -> UnsupportedSyntax ("tool calls already return promises"); + `Promise.` lists the five available statics. `console.log(p)` prints + `[Promise (await it to get its value)]`. +- **Program-end drain**: on successful completion the interpreter awaits still-running + un-awaited fibers (like a runtime waiting on in-flight I/O at exit), so fire-and-forget + calls complete deterministically; a failure nobody could have handled surfaces as an + "Unhandled rejection from an un-awaited tool call: ..." diagnostic (kind preserved, + suggestion says to await) - keeping pre-wave failure visibility for un-awaited + statement-position calls. Settlement observation (await/all/allSettled/race) marks a + promise handled; failed executions skip the drain and children are interrupted by + supervision. +- **Deletions/updates**: `evaluatePromiseAll`, `evaluateParallelMap`, `isToolCallExpression`, + `isToolPath`, `forkForParallelCallback`, and `PromiseAllReference` deleted + (`PromiseMethodReference` over `all/allSettled/race/resolve/reject` replaces it); + `supportedSyntaxMessage`, the two instructions lines in `tool-runtime.ts`, and README + "Supported Programs" rewritten for the new surface. +- **Known divergences (deliberate)**: `p === q` on promises throws the operators-need-data + diagnostic instead of comparing identity; `{...promise}` errors instead of JS's silent `{}`; + a per-iteration `await` inside `items.map(async (i) => await tools.x(i))` runs sequentially + (interpreter callbacks compose synchronously) - the parallel idiom is mapping to un-awaited + calls and awaiting `Promise.all`, which the instructions show. + +### Post-wave fixes + +- **Key enumeration: `Object.keys(tools)` + `for...in` (done).** Motivating transcript: a + model tried to enumerate tool namespaces with `Object.keys(tools)` (failed with the generic + "Object.keys input must contain plain objects only." - `tools` is a `ToolReference`, not + plain data) and then `for (const key in tools)` ("Syntax 'ForInStatement' is not + supported"), and had to fall back to guessing namespace names from the instructions - + defeating discovery. Fixes, all in this package: + - `ToolRuntime.make` now returns a `keys(path)` capability (`namespaceKeys` in + `tool-runtime.ts`) threaded into the `Interpreter` alongside `invoke` - the interpreter + still never holds the host tool tree. `Object.keys(tools)` yields the top-level namespace + names (never `$codemode`, which is virtual - but `Object.keys(tools.$codemode)` yields + `["search"]`), `Object.keys(tools.ns)` the names at that node; a callable tool leaf + enumerates as `[]` (like `Object.keys` of a JS function); an unknown path throws an + `UnknownTool` diagnostic suggesting `Object.keys(tools)` and `$codemode.search` (matching + call-time unknown-tool behavior rather than silently returning `[]`). + - `Object.values`/`Object.entries` (and every other `Object.*` helper) on a tool reference + now fail with "...not plain data. Use Object.keys(tools) for names, or + tools.$codemode.search({ query }) for signatures." instead of the generic message. + - `Object.keys(array)` returns index strings (`["0", "1", ...]`) like real JS (was a + Backlog item). + - `for...in` (ForInStatement) iterates own enumerable string keys of plain objects, index + strings of arrays, and namespace/tool names of tool references - sharing the interpreter's + `enumerableKeys` helper with the `Object.keys` tool path. const/let declarations and bare + identifiers bind the key; break/continue work. Anything else (strings, Map/Set, numbers, + null, ...) is a clear error suggesting `for...of` or `Object.keys` - deliberately smaller + than real JS (which yields indices for strings and zero iterations for Maps/Sets/null). + - `supportedSyntaxMessage`, the instructions loops line, and README "Supported Programs" + mention the new surface; tests in `test/enumeration.test.ts` (14, incl. the exact + transcript program) plus one adapter-level assertion that `Object.keys(tools)` returns + MCP server names. + +- **Search ranking, namespace scoping, prefixed result paths (done).** + Motivation: the Wave 4 e2e run showed a model retrying calls because search-result paths + lacked the `tools.` prefix (a Backlog item), and the word-set ranker missed + parameter-name and partial-word queries. Fixes: + - **Ranking ported from the pre-rebuild implementation** (the `searchTextFor`/`tokenize`/ + `rankTools` algorithm in `packages/opencode/src/session/code-mode.ts` at git HEAD), + replacing the word-set ranker in `tool-runtime.ts`. Searchable text per tool = path + + description + input-schema property names + their `description` strings - extracted by + the new `inputProperties` helper in `tool.ts` (Effect Schemas via + `Schema.toJsonSchemaDocument`, the same emission signature rendering uses; JSON Schemas + read `properties` directly, resolving a trivial top-level `$ref`; try/catch falls back to + path + description). Queries tokenize on camelCase boundaries + non-alphanumeric + separators (empties and `*` dropped). Additive per-term scoring: exact path or + path-segment match 20, path substring 8, description substring 4, searchable-text + substring 2; summed across terms, filtered to score > 0, sorted score desc then path asc + (Fix 8 later made each field check accept the term OR a naive singular variant). + An empty query now browses ALPHABETICALLY by path (was declaration order). Kept: + `{ path, description, signature }` result items, default limit 10, exact-path instant + lookup, input validation errors. + - **Namespace scoping**: `tools.$codemode.search({ query?, namespace?, limit? })` - + `namespace` (validated as a string when provided) filters `SearchEntry`s to one top-level + namespace before ranking; `{ query: "", namespace: "github" }` lists that namespace + alphabetically. `searchSignature` updated. + - **Callable result paths**: search-result `path`s are rendered as JavaScript expressions + rooted at `tools` (`tools.github.list_issues`, or bracket notation for non-identifier + segments), directly usable as the call site. Internal `ToolDescription.path` stays + unprefixed; only the search RESULT items are rendered this way. Exact-path queries accept + canonical paths and rendered expressions. + - **Instructions** (`discoveryPlan`): an explicit calling-convention line and a browse + hint on the search advertisement (both since absorbed into the `## Rules` section by + the instructions restructure below). + - **Tests**: package search/discovery tests updated (prefixed paths, alphabetical browse) + plus new coverage for namespace scoping, parameter-name matching, partial-word substring + matching, alphabetical empty-query order, and prefixed exact-path lookup; one adapter + assertion updated to the prefixed path (suites stay 35 + 16, green). + +- **Instructions restructure: markdown sections, placeholder-only call forms (done).** + The flat prose instructions (which mixed a real catalog tool with fabricated result + fields in the worked example) are replaced by structured markdown in `discoveryPlan`, + ordered so the workflow sits at the top (the least likely part of a long description to + be truncated or skimmed away) and the catalog at the bottom (the per-section content + described here was later condensed by Fix 8 - Workflow/Rules deduped, Syntax inverted): + - **Intro** (2 lines): "Write a CodeMode program... Return code only." + "Execute + JavaScript in a confined runtime with access to the tools listed below under + `tools.*`." (the second line drops the tools clause when the tree is empty). + - **`## Workflow`**: numbered steps - find a tool via `tools.$codemode.search` -> read + the `{ path, description, signature }` matches -> call by path -> `typeof res === +"string" ? JSON.parse(res) : res` -> return only the needed fields. When the catalog is + COMPLETE the search/read steps collapse into "Pick a tool from the list under + `## Available tools`" and the steps renumber (4 instead of 5). + - **`## Rules`**: call-by-exact-path; TEXT-is-JSON -> JSON.parse; return small (never raw + payloads); filter/aggregate large collections in code instead of per-item round-trips; + console.log/warn/error/dir/table for intermediates; `Promise.all` parallelism (no + .then/.catch - await + try/catch); `Object.keys(tools)`/`for...in` enumeration; + browse-one-namespace via search (PARTIAL only); and host-side media handling (files/ + images never enter the program; a media-only call yields a small text marker - wording + verified against the adapter's `toSandboxResult`/`mediaMarker`). + - **`## Syntax`**: the dense syntax lines unchanged, minus the Promise.all and console + lines (moved into Rules) and the `for (const ns in tools)` fragment (redundant with + the enumeration rule). + - **`## Available tools`**: the budgeted catalog unchanged, with the COMPLETE/PARTIAL + header merged into the section heading (no trailing colon); the search-signature + advertisement follows when PARTIAL (its description-reading and browse clauses moved + to Workflow/Rules). + - Every call form in Workflow/Rules uses explicit `.`/`` + placeholders - the example builder that derived a worked example from the first inlined + catalog tool (`exampleArguments` + the example-selection machinery) is DELETED, so no + real catalog tool is cherry-picked into examples and no fabricated names or fields + appear anywhere in the instructions. Zero tools keep "No tools are currently + available." under minimal sections (intro + Syntax + Available tools). + - **Tests**: the package worked-example test replaced by section-structure/placeholder + assertions (section order; JSON.parse + return-small rules present; no + `total_count`/`list_issues`/real-tool example lines; browse hint only when PARTIAL; + zero-tool minimal sections) - 156 pass / 0 fail; adapter suites gain the same + assertions on the built description (still 35 + 16, green). + +**Fix 4 - token-budgeted catalog (was bytes)** (user direction: signatures need a token +budget; namespaces must always be present): + +- `src/token.ts` added: copy of `@opencode-ai/core/util/token` (`round(chars / 4)`), so + the package stays dependency-free; keep in sync if the core heuristic changes. +- `DiscoveryOptions.maxInlineCatalogBytes` -> `maxInlineCatalogTokens` (default 4,000 + estimated tokens ~ the old 16,000 bytes at 4 chars/token - behavior parity, not a size + reduction). `discoveryPlan` charges `estimate(catalogLine(tool))` per line; cheapest-first + - stop-on-first-miss unchanged at the time (stop-on-first-miss replaced by round-robin in + Fix 8). Namespace stub lines were and remain unbudgeted - every + namespace always appears with its tool count, even at budget 0 (asserted in package and + adapter tests). +- Ripple: chars/4 rounding erases small line-length differences, so equal-cost lines fall + to the lexicographic path tiebreak; the adapter's PARTIAL test now asserts the + lexicographic tail (`op_99`) is excluded instead of `op_149`. Fixed-prose measurements + (2026-07): preamble ~44 + Workflow ~146 + Rules ~362 + Syntax ~453 ~ 1,100 tokens fixed; + worst-case net description ~ fixed + 4,000 ~ 5,100 estimated tokens. + +**Fix 5 - internal limits removed** (user direction: only the three PUBLIC limits survive as +configurable knobs; the internal limit system dies): + +- `ExecutionLimits` (`timeoutMs` 10_000 / `maxToolCalls` 100 / `maxOutputBytes` 32_000 at + the time; Fix 6 later removed the first two defaults. Same validation: safe integers, + timeoutMs >= 1, others >= 0, RangeError otherwise) is now + the ENTIRE limit surface - exactly the shape section 2's original locked spec named. + `ResolvedExecutionLimits` shrank to those three fields; the `@internal` + `InternalExecutionLimits` type is deleted. +- **Deleted outright**: `maxOperations` and the whole operation-budget machinery + (`recordWork`/`recordOperation`/`budget.operations`, plus the `workUnits`/ + `cheapArrayMethods` cost helpers); `maxSourceBytes` (the pre-parse source-size check); + `maxDataBytes` (every byte-accounting path: `runtimeValueBytes`, `boundedProgramValue`, + the container-size caches (`containerSizes`/`objectCounts`), Map/Set incremental `bytes` + fields in `values.ts`, string-growth `limitString` checks, tool-argument/result byte + checks in `tool-runtime.ts`, and the final-result size check); `maxAuditBytes` (log and + audit-trail byte accounting - `toolCalls` records and the start/end hooks are unchanged); + `maxCollectionLength` (every array-length/object-field-count check - this knob was + actively harmful: an MCP tool returning 20k rows failed). The `OperationLimitExceeded` + and `AuditLimitExceeded` diagnostic kinds are gone from the `DiagnosticKind` union and + `ExecuteResultSchema` (fine - the package is unreleased). +- **Fixed constants, not knobs**: `TOOL_CALL_CONCURRENCY = 8` (codemode.ts; the fork + semaphore) and `MAX_VALUE_DEPTH = 32` (tool-runtime.ts; the `copyIn` depth check - kept + only because it produces a clearer error than a native stack-overflow RangeError; still + `InvalidDataValue`). The `DataLimits` plumbing through `tool-runtime.ts` is gone - + `copyIn(value, label)` needs no limits argument, and `ToolRuntime.make` takes just + `(tools, maxToolCalls, hooks?, searchIndex?)`. +- **Verified fact**: timeout interruption does NOT depend on the operation budget - the + Effect fiber runtime auto-yields between interpreter steps, so `timeoutMs` interrupts + even a pure `while (true) {}` loop (empirically verified: a 200ms timeout fired at + ~225ms with maxOperations set to MAX_SAFE_INTEGER before the deletion). A regression + test in `codemode.test.ts` asserts exactly this (`while(true){}` + `timeoutMs: 200` -> + `TimeoutExceeded`, elapsed well under a few seconds). +- **Kept (correctness, not budgets)**: circular detection (`copyIn` walks + + `rejectCircularInsertion` on mutations), plain-objects-only, blocked properties + (`__proto__`/`constructor`/`prototype`), data-only checks, and all three public-limit + behaviors unchanged. +- Behavior deltas beyond the intended kills: in-sandbox structures deeper than 32 levels + now fail at the data boundary (`copyIn`) instead of at construction; array index + assignment allows any non-negative integer index (holes permitted, message now "must be + a non-negative integer"); interpreter-produced deep/hostile structures that overflow the + native stack during a walk still normalize to the existing "Execution exceeded the + maximum nesting depth." data diagnostic - failures remain data everywhere. +- Tests: deleted the knob-only tests (stdlib Map/Set collection-length growth x2, + enumeration operation-budget, codemode maxDataBytes/maxSourceBytes/maxOperations/ + maxConcurrency-RangeError assertions, and the adapter's runaway-loop-via-operation-limit + test - superseded by the package timeout regression test); rewrote the helpers that used + `InternalExecutionLimits` as a convenience to plain `ExecutionLimits` + (promise/enumeration/stdlib run helpers). Package suite: 154 pass / 0 fail; adapter + suites: 34 + 16. + +**Fix 6 - no default timeout / tool-call cap** (user direction): `timeoutMs` and +`maxToolCalls` lost their defaults (were 10_000 / 100) - absent now means no timeout / +unlimited calls. Budgets are host policy, not library policy; `maxOutputBytes` kept its +32,000 default at the time (removed later - see the truncation-layering entry: absent now +means no truncation). `ResolvedExecutionLimits` carries `number | undefined` for both, the +timeout wrapper is only applied when configured, and `ToolRuntime.make` treats undefined +`maxToolCalls` as uncapped. Validation is unchanged when values ARE provided (safe integers, +timeoutMs >= 1, others >= 0). The OpenCode adapter is unaffected in behavior it sets +(explicit 30s timeout) but now runs with unlimited tool calls. Immediately after, per user +direction, the adapter's 30s timeout was killed too: `CODE_LIMITS` is deleted and OpenCode +passes NO limits - no timeout, no tool-call cap. Rationale: user cancel interrupts the +execution fiber and structured concurrency takes the program and in-flight child calls down +with it; every child call is permission-gated; output truncation (32KB default) is the only +active bound. New regression test: 150 tool calls succeed with no limits configured (would +have tripped the old default 100). Package suite: 155 pass / 0 fail. + +**Fix 7 - JSDoc-annotated search signatures**: `tools.$codemode.search` result signatures are +now the pretty, indented multiline form with per-field JSDoc - ported from the pre-rebuild +rune renderer in this repo's git history (`renderType(def, { pretty })`/`docTags`/`jsdoc`/ +`renderObject`), adapted to the current renderer's conventions (`Array`, `unknown` +fallback, existing `$defs`/`$ref` handling and empty-object `{}` collapse; the old +`Result`/`returnType` machinery was deliberately not ported - payloads stay native). +Semantics: each described input/output field carries its schema `description` as a +`/** ... */` comment at the right indent (nested objects recurse deeper); constraints TS can't +express surface as JSDoc tags - `@deprecated`, `@default ` (unserializable defaults +skipped), `@format`, `@minItems`/`@maxItems`; `*/` inside text is neutralized to `* /`; +multiline descriptions become `*`-prefixed blocks with blank edges trimmed; undescribed, +untagged fields get no comment. Implementation: `renderSchema` in `tool.ts` grew a +`RenderContext` (`{ definitions, pretty }`), a `MAX_RENDER_DEPTH = 8` recursion ceiling plus +a `$ref` `seen` guard (the renderer previously had neither - a cyclic `$defs` would have +looped; it now degrades to the ref name/`unknown`), and try/catch totality on the public +helpers (`toTypeScript`/`jsonSchemaToTypeScript`/`inputTypeScript`/`outputTypeScript` never +throw - pathological schemas render `unknown`); each helper takes an optional trailing +`pretty = false` parameter, so existing callers are unchanged and compact output stays +byte-identical (inline `catalogLine`s and the token budget depend on it). `SearchEntry` +gained an eagerly-computed `signature` field (built once per tool at index-build time in +`toSearchEntry` - rendering is cheap and the search hot path stays allocation-free); both +ranked results and exact-path lookups serve it. Works for both tool kinds: Effect Schema +annotations (`Schema.String.annotate({ description })`) flow through the emitted JSON +Schema, and raw JSON Schema (MCP) property metadata is read directly - both covered in +`test/signature.test.ts` (12 tests) plus one strengthened adapter assertion (MCP property +description appears as JSDoc in a live search result; the tool description/catalog contains +no `/**`). README search section updated with an example. Package suite: 167 pass / 0 fail; +adapter suites: 34 + 16. + +**Fix 8 - condensed instructions + round-robin catalog fairness + plural-aware search** +(user direction: the fixed instruction prose was too verbose; two discovery fixes ride +along). All in `tool-runtime.ts`; no interpreter changes. + +- **Syntax section inverted**: the three dense allowlist lines (~453 estimated tokens) + are replaced by four short lines (~188) built on "models already know JavaScript; name + only what is unusual or missing": (1) standard modern JS works - functions/closures, + destructuring, template literals, loops, try/catch, spread, optional chaining, the + usual Array/String/Object/Math/JSON methods, plus Date/RegExp/Map/Set and + Promise.all/allSettled/race/resolve/reject; (2) TypeScript type annotations are + stripped before execution, decorators are not supported; (3) NOT supported (each fails + with a message naming the alternative): classes, generators, for await...of, + .then/.catch/.finally (use await with try/catch), `x instanceof Error` (caught errors + are plain `{ name, message }` objects), splice; (4) the data-boundary note (Dates -> + ISO strings; Map/Set/RegExp -> `{}`). Every claim was verified against the interpreter + before writing: probed empirically - classes/generators/for-await/.then/.catch/ + .finally/`instanceof Error`/splice/decorators/BigInt/labeled statements/tagged + templates/object getters all fail with clear diagnostics; TS annotations/`as`/ + interfaces/type aliases are stripped and TS **enums actually work** (transpileModule + compiles them to an IIFE the interpreter runs), hence enums deliberately unmentioned. + `supportedSyntaxMessage` (the in-diagnostic text in `codemode.ts`) is untouched. +- **Workflow/Rules deduped**: the call-by-exact-path, JSON.parse-string-results, and + return-small content now lives ONLY in the numbered Workflow steps (with their + compliance-driving justifications inline: "most tools return JSON as a string", "raw + payloads get truncated and waste context"); Rules keeps only bullets adding new + content - filter/aggregate collections in code, console.\* intermediates (logs ride + back), Promise.all parallelism, Object.keys/for...in enumeration, browse-namespace + (PARTIAL only), and the media rule compressed to one line. The no-.then/.catch + guidance moved to the Syntax not-supported line. Content upgrades: the PARTIAL search + step gained query-style guidance (`- short phrases like "list issues" work best`; a + clearly-a-query-string example, not a tool name), and the exact-path guidance is now + "call it with the result's `path` as-is (never guess segments)" / COMPLETE: "use it + as-is rather than guessing segments". +- **Fixed-prose measurements** (instructions split on `"\n## "`, catalog budget 0, + bytes/3.7 - same method as Fix 4; chars/4 in parentheses): + preamble 44 -> 44 (41 -> 41), Workflow 146 -> 187 (135 -> 171), Rules 362 -> 191 + (332 -> 176), Syntax 453 -> 188 (419 -> 174); fixed prose total 1,005 -> 610 (927 -> 562), + ~ 40% reduction with no behavioral content dropped. Workflow grew slightly because it + absorbed the deduped parse/return-small justifications. +- **Round-robin namespace inlining** (`discoveryPlan`): the ported stop-on-first-miss + behavior (alphabetically-late namespaces starved to "none shown" while an early + namespace inlines everything) is replaced by round-robin fairness - in each round + (namespaces alphabetical), every namespace still holding un-inlined tools attempts to + place its next-cheapest line against the shared token budget; a namespace whose next + line does not fit is done while the others keep going; stop when all are done. Every + namespace gets some representation before any namespace gets everything. Kept: + `estimate` (chars/4) budget accounting, unbudgeted namespace stub lines, per-namespace + `(N tools)`/`(N tools, K shown)`/`(N tools, none shown)` labels, COMPLETE vs PARTIAL + header, alphabetical namespace order in the output, cheapest-first within each + namespace's shown set. +- **Plural/singular search fix**: `tokenize`d terms matched one-directionally (term must + be substring of indexed text), so query "issues" missed a tool whose text only says + "issue". Now each term expands to `termForms` - the term plus naive singular variants + (trailing "es" stripped when length > 3, trailing "s" when length > 2) - and each of + the four field checks passes when ANY form matches. Weights, exact-path lookup, and + namespace scoping untouched. A true plural path match still outranks a singular-only + description match (path substring 8 + searchable 2 > description 4 + searchable 2). +- **Tests**: package instruction/structure assertions updated to the new text; new + syntax-section test (leads with "Standard modern JavaScript works", names the + verified not-supported list, keeps the data-boundary note); the budget-exhaustion + test rewritten to assert the new fairness (alpha.expensive not fitting must NOT + prevent beta.cheap from showing: PARTIAL 2 of 3, `- beta (1 tool)` fully shown); new + plural/singular test (query "issues" finds a singular-only tool; ranking still + prefers the true "issues" path match). Adapter: description assertions updated; the + large-catalog PARTIAL test now asserts `zeta_only_tool` IS shown (`- zeta (1 tool)` + + its inlined line) - it was "none shown" under starvation. README updated (budgeted + catalog paragraph -> round-robin; search paragraph -> singular variants; + instructions-structure paragraph -> new section contents). Package suite: 169 pass / + 0 fail; adapter suites: 34 + 16. + +**Fix 9 - prompting trims per user review of Fix 8** (user reviewed the condensed +instructions and directed further cuts): + +- Default `maxInlineCatalogTokens` 4,000 -> **2,000** (user wants ~2k tokens of signatures + auto-inlined; round-robin fairness from Fix 8 spreads it across all namespaces). +- Console rule and files/images rule DROPPED from `## Rules`. Replaced by a single + `unknown`-treatment warning: "A result typed `Promise` has no guaranteed + shape - verify what actually came back before relying on its fields." (Deliberately + does NOT suggest console.log - user review: naming it there nudges models to log AND + return the same data; the prompt stays console-neutral, neither for nor against.) + The media-stripping MECHANISM is unchanged and still tested; only the prose about it + is gone - the `[N images attached]` marker is self-explanatory in context. +- Kept as-is per user: the JSON.parse workflow step (maps to the original motivating + transcript failure; NOT copied from prior art - see section 5 note), the browse-namespace rule + (undecided), no no-fetch/ambient-authority rule added (proposed, not approved). +- Explicitly REJECTED for now: auto-parsing JSON-looking text results at the adapter + boundary ("could get weird" - type flips, program-sees vs tool-sent divergence). Logged + as a next-iteration follow-up below. + +**DSL-expansion pass - interpreter-surface batch from section 4** (the deferred medium-tier JS +parity items, done as one focused pass; no public API or limit changes): + +- **`instanceof` + real Error values**: the `errorConstructors` names (`Error`, + `TypeError`, `RangeError`, `SyntaxError`, `ReferenceError`, `EvalError`, `URIError`) are + bound globals (`ErrorConstructorReference`, callable with or without `new`; `typeof` -> + `"function"`). Error values stay the same plain `{ name, message }` null-prototype + objects as before - the constructor name additionally rides on a NON-ENUMERABLE symbol + key (`ErrorBrand`), which every `Object.entries`-based walk (copyIn/copyOut, spread, + JSON.stringify) is blind to, so serialization is byte-identical to the old shape and the + brand is lost on spread/boundary copies exactly like JS loses the prototype. + `caughtErrorValue` produces `{ name, message }` wrappers via `createErrorValue`, so + caught interpreter AND tool failures are `instanceof Error` and carry the `name` the + equivalent real-JS failure would have (follow-up fix, user-directed - "closest to real + JS"): `InterpreterRuntimeError` gained an `errorName` field ("Error" default) set + fluently at throw sites via `.as(name)` - `JSON.parse` failures are `"SyntaxError"` (and + now include the engine's position detail in the message; safe - derived from the + program-supplied string), invalid regex patterns/flags `"SyntaxError"`, unknown + identifiers and TDZ access `"ReferenceError"`, assignment to a constant `"TypeError"`, + a bad `normalize` form `"RangeError"`; a host Error reaching the catch path directly + keeps its own name when it is one of the standard seven. Tool failures and everything + without a specific analogue stay `"Error"` - internal class names never leak. Specific + names satisfy the specific `instanceof` (`e instanceof SyntaxError`), matching JS. + The operator is handled in `evaluateBinaryExpression` + BEFORE the data-only operand check (like `typeof`, it observes any lhs - promises and + functions included); recognized rhs: the error constructors (a specific type matches its + own brand or `Error`, never a sibling), `Date`/`RegExp`/`Map`/`Set` (sandbox classes), + `Array`, `Object` (any object/function-ish value), `Promise` (`SandboxPromise`), and + `Number`/`String`/`Boolean` (always false - no boxed values exist); anything else is a + catchable error naming the recognized constructors. +- **Array methods**: `splice` (mutating, returns the removed elements; insertions run + `rejectCircularInsertion` like push/unshift; one-arg form removes to the end, undefined + delete count removes nothing), `fill` (circular-checked value) and `copyWithin` + (host-delegated), and `keys`/`values`/`entries` returning **arrays** (the Map/Set + convention - for...of and spread work either way). The `retryableArrayMethods` + "rewrite using map/filter" hint set emptied out and was deleted with its branch; unknown + array properties still read `undefined`. +- **String methods**: `localeCompare(that)` (locale/options arguments ignored - host + default locale; the dominant use is a sort comparator), `normalize(form?)` (invalid form + -> catchable error naming the four valid forms), `trimLeft`/`trimRight` as + trimStart/trimEnd aliases. +- **Actionable regex failures**: `toHostRegex` and `constructRegExp` now show the + offending pattern (or flags) plus the engine reason (deduped "Invalid regular + expression:" prefix via `regexFailureReason`) and a shared escaping hint + (`escapeRegexHint`); flags failures list the valid flag letters; the + replaceAll/matchAll missing-`g` errors spell out the exact `/pattern/g` to write and + the single-match alternative. +- **copyIn split (the important one)**: `copyIn(value, label, preserveSandboxValues = +false)` - recursion moved to a private `copyBounded`; `boundedData` (every intra-sandbox + checkpoint: `Object.*` helpers, coercion/Array.from/join inputs, template + interpolation, expression-result checkpoints) is now `copyIn(value, label, true)`, + which passes `SandboxDate`/`SandboxRegExp`/`SandboxMap`/`SandboxSet` through **by + reference as leaves** (contents not walked - Map/Set members are validated at their + mutation sites) while keeping the depth (`MAX_VALUE_DEPTH`), circularity, + plain-objects-only, blocked-property, and data-only checks; un-awaited promises keep + the await-hinting rejection in BOTH modes (deliberate - JS-parity pass-through was + considered and skipped to preserve the nudge). The HOST boundary (final result, + tool-call arguments, `JSON.stringify`, tool-result intake) uses the default mode and + still serializes JSON forms (Date -> ISO, RegExp/Map/Set -> `{}`); host instances met on + the preserving path are defensively wrapped into sandbox equivalents. Ripple: the + `Object.*` helpers treat sandbox values as empty objects (`Object.keys(map)` -> `[]`, + assign sources contribute nothing, hasOwn -> false - JS has no own enumerable props + there), so interpreter internals (`.map`/`.time`/`.regex`) can never leak; the + template-literal sandbox carve-out collapsed into `boundedData`. Object/array spread + already preserved instances (reference copies, no checkpoint) - now tested. +- **Console formatting**: `formatConsoleArgument` is total and deep + (`formatConsoleValue`): numbers render via `String` (`NaN`/`Infinity`/`-Infinity` + literally - never the JSON `null`; finite numbers match their JSON form), nested + strings are JSON-quoted, sandbox values keep their friendly forms at ANY depth (ISO + date, `/regex/flags`, `Map(n) [...]`, `Set(n) [...]`), opaque references become + in-place `[CodeMode reference]` markers instead of collapsing the whole argument, + cycles render `[Circular]` (reachable via Map/Set members, which mutation never + checkpoints), and depth beyond `MAX_CONSOLE_DEPTH = 32` (fixed constant, not a knob) + degrades to `...` - console can no longer fail a program. `console.table` guards with + `containsOpaqueReference` (sandbox cells render, e.g. ISO dates) and its row/cell + walkers treat sandbox values as scalar cells. +- **Prose**: the instructions Syntax not-supported line dropped its `instanceof +Error`/splice mentions (nothing else reworded); README updated (checkpoint + preservation vs boundary serialization, error values/`instanceof`, new array/string + methods, regex-failure behavior); `supportedSyntaxMessage` left untouched (it lists + supported syntax, was already non-exhaustive, and stays accurate). +- **Tests**: package suite 169 -> 209 (parity: Error/instanceof + real-JS error-name + coverage, splice/fill/copyWithin/keys/values/entries, localeCompare/normalize/trim-alias + describes; stdlib: checkpoint survival incl. tool-arg boundary pinning, stdlib + `instanceof`, regex-message assertions; codemode: NaN/Infinity + nested/cyclic console + rendering, table cells, caught-tool-failure `instanceof`); adapter suites unchanged + (34 + 16, green); both packages `tsgo --noEmit` clean. + +**Truncation layering - CodeMode truncation off in OpenCode** (user direction; resolves the +section 4 outer-truncation item the OPPOSITE way from "kill the outer one"): + +- `maxOutputBytes` lost its 32,000 default and now behaves exactly like the other two + limits: absent = no truncation. All three limits are uniformly no-default - budgets are + host policy. `ResolvedExecutionLimits.maxOutputBytes` is `number | undefined`; + `boundOutput` only runs when the host set the limit. Explicit values validate as before + (safe integer >= 0). +- OpenCode continues to pass NO limits, which now also means no CodeMode truncation. + `execute` is a normal `Tool.define` tool, so OpenCode's native tool-output truncation + applies with no special-casing - verified by tracing `wrap()` (`tool.ts:130-144`, + 50KB/2000-line thresholds in `truncate.ts`, full output dumped to a file under + `tool-output/`): the `metadata.truncated` self-truncation exemption never fires for + `execute` (its metadata never sets that key). One truncation layer, the host's - and it + is the richer one (file dump + explore/grep hint vs an inline marker). +- Hosts without their own output bounding set `maxOutputBytes` explicitly; README table + and prose updated, adapter comment rewritten. Tests: codemode +1 (absent limit -> 100KB + value + 50KB log line pass through unbounded, `truncated` undefined); the adapter test + that relied on the old default now asserts the oversized result reaches the shared + wrapper un-truncated. Suites: 210 + 50, tsgo clean both. + +**Docs polish** (post-API-review): stale `DiscoveryOptions` JSDoc fixed (claimed default +4,000 and alphabetical cheapest-first - now 2,000 and round-robin, matching Fix 8/9 reality) +and the README's incorrect "`effect` as a peer dependency" line corrected (`effect` is a +regular dependency; hosts depend on it themselves because the API surface is Effect-typed). + +**Registry promotion + permission-aware catalog** (the "promote to a proper tool service" +restructure; fixes the section 4 permission-advertising bug): + +- **The adapter moved** `src/session/code-mode.ts` -> `src/tool/code-mode.ts` and is now a + registry-resident tool service on the TaskTool precedent: `CodeModeTool = +Tool.define(CODE_MODE_TOOL, ...)` whose init depends on `MCP.Service`, `Agent.Service`, + and `Session.Service`. It is yielded in `ToolRegistry.layer`, gated into `builtin` by + `flags.experimentalCodeMode` (like the lsp/plan experiments), and `MCP.node` joined the + registry's `node.deps` (`MCP.node` has no ToolRegistry dependency, so no cycle). The + session-level special-casing in `session/tools.ts` (ad-hoc `SessionCodeMode.define` + + append) is deleted; the early return that suppresses raw per-MCP registration when the + flag is on stays session-side, keyed on the same flag+tool-count condition. +- **Enablement** lives in `ToolRegistry.tools()` next to the WebSearchTool check: the MCP + tool count is consulted once (an Effect) before the synchronous filter, and code mode + passes the predicate iff `flags.experimentalCodeMode` && count > 0. +- **Description split on the `describeTask` precedent**: the tool's static base + description is a two-line summary; `describeCodeMode(agent)` in `registry.tools()` + appends the full CodeMode instructions (workflow/rules/syntax + grouped catalog, + `catalogInstructions` in the adapter) at the same composition point as task - so + `plugin.trigger("tool.definition")` sees the base description first. +- **Permission-aware catalog + dispatch** (the bug fix): the visibility predicate from + `llm/request.ts` `resolveTools` is hoisted to `Permission.visibleTools(tools, ruleset)` + (a record filter over `Permission.disabled` - only a hard `deny` with pattern `"*"` + hides a tool; ask-level rules stay fully visible and prompt at call time) and + `resolveTools` now uses it, so the two paths cannot drift. `describeCodeMode` filters + with the merged agent+session ruleset that `SessionTools.resolve` passes into the + registry before building the catalog/search index; `execute` rebuilds the runtime per + execution from a fresh, filtered `mcp.tools()` snapshot using the same merged ruleset + (`Agent.get(ctx.agent)` + `Session.get(ctx.sessionID)`, matching the merge + `SessionTools.context` wires into `ctx.ask`) - a denied tool is not dispatchable + even if the model guesses its name and yields the normal unknown-tool diagnostic. + Documented gap (out of scope by design): per-message `user.tools[key] === false` arrives + at request-prep after descriptions are built and has no child-call equivalent. +- **Preserved behavior**: cancellation race + pre-aborted-signal guard, `toSandboxResult` + unwrap order, attachment accumulation, `CODE_MODE_TOOL` at all title sites, no execution + limits (native truncation only), `displayInput`, per-child `ctx.ask` gating (now wired + through `Tool.Context` exactly like every registry tool). +- **Explicit non-goal**: memoizing the catalog builder keyed on (ToolsChanged generation, + permission ruleset) was considered and deliberately skipped - the per-turn rebuild is + cheap (grouping + string rendering); revisit only if profiling shows it matters. +- **Tests**: the two adapter suites moved to `test/tool/{code-mode,code-mode-integration} +.test.ts` (mocked `MCP.Service`/`Agent.Service`/`Session.Service` replacing the direct + `define(...)` construction; description assertions target `catalogInstructions`, the + registry's composition input) and gained permission coverage: deny excluded from + catalog/search, ask-level stays visible and callable, denied tool undispatchable + (unknown-tool diagnostic), `Permission.visibleTools` semantics. `test/tool/ +registry.test.ts` gained four registry-level tests: registered with flag+MCP tools, + excluded without MCP tools, excluded with flag off, and deny/ask catalog filtering + through `registry.tools()`. Suites: 43 + 16 adapter tests, 16 registry tests, all green. + +**Shared MCP invocation middle (`McpInvoke.invoke`)** (closes the section 4 "plugin hooks skip +child calls" gap): + +- `packages/opencode/src/mcp/invoke.ts` extracts the duplicated "invoke an MCP tool" + middle into one shared `McpInvoke.invoke(input)`: plugin `tool.execute.before` hook -> + permission ask (`{ permission: key, patterns: ["*"], always: ["*"] }` via the caller's + `ctx.ask`) -> dispatch through the ai-sdk tool's execute inside the `Tool.execute` + tracing span (`tool.name`/`tool.call_id`/`session.id`/`message.id` attributes) -> + plugin `tool.execute.after` hook. It returns the RAW result the ai-sdk execute + resolved with; each caller keeps its own shaping edge - the legacy per-MCP loop in + `SessionTools.resolve` applies its existing model-facing shaping/truncation, code + mode applies `toSandboxResult`. It lives under `src/mcp/` because both callers + already depend on MCP and the function is about invoking an MCP-backed ai-sdk tool, + not about sessions or code mode. +- **After-hook payload**: fired inside `McpInvoke.invoke` with the raw MCP result - + which is exactly what the legacy loop always passed (the raw `CallToolResult`, not + the shaped `{title, output, metadata}`), so legacy behavior is preserved bit-for-bit + and the hook payload cannot drift between callers. No callback/edge-firing design + was needed. +- **Synthetic child callID**: code-mode child calls pass `${parentCallID}/${n}` as the + hook/span callID (`parentCallID` = the `execute` call's `ctx.callID`, falling back to + the entry key; `n` = per-execution counter starting at 1, shared across all child + calls in one program). callID is an opaque string - nothing parses it. The ai-sdk + `toolCallId` (`options.toolCallId`) stays each caller's existing value + (`ctx.callID ?? entry.key` for code mode). +- **Child-scoped hook failures**: `CodeModeTool` (which now also yields + `Plugin.Service`) wraps the whole child call - hooks, ask, dispatch - in + `toCatchable` (the generalization of the old `askPermission` catchCause), so a plugin + hook failure fails ONLY that child call as a catchable in-program `toolError`; other + calls in the same program keep running and interruption still propagates as + interruption. Legacy semantics unchanged: a hook failure fails the tool call. +- **Tests**: `test/tool/code-mode.test.ts` +2 (child calls fire before/after with the + MCP key and `parent/1`, `parent/2` ids, after hook carries the raw MCP result; a + failing before hook is caught in-program, gates dispatch, and leaves the outer + execute ok) - both code-mode harnesses gained a `Plugin.Service` mock (pass-through + trigger by default, overridable). New `test/session/tools.test.ts` (3 tests) pins + `SessionTools.resolve` at the real-registry seam (LayerNode.compile, fake MCP layer): + flag on + MCP tools -> `execute` present, raw MCP keys suppressed; flag off -> raw + keys present, `execute` absent; and the legacy raw-MCP execute fires before/after + hooks keyed by the ai-sdk toolCallId with the raw result payload. Suites: adapter + 45 + 16, session/tool/permission all green; this package untouched (211 pass). + +**Signature rendering + compound-assignment parity fixes** (externally reported, both +verified real with failing tests before fixing): + +- **Non-identifier property names in rendered signatures** (`src/tool.ts`): `renderSchema` + emitted raw property names, so schema properties like `foo-bar`/`@type`/`x.y`/`123` + rendered invalid TypeScript (`{ foo-bar?: string }`). Fixed with a `renderKey` helper - + bare identifiers stay bare, everything else is `JSON.stringify`-quoted - applied in the + single `field` closure both the compact and pretty renderings share. The + `identifierSegment` regex now lives in `tool.ts` (exported) and `tool-runtime.ts`'s + bracket-notation `toolExpression` imports it: one source of truth for "is this a bare + identifier" across object keys and tool paths. Tests: `signature.test.ts` +4 (compact, + pretty with JSDoc on a quoted key, JSON Schema input+output, Effect Schema struct). +- **Numeric schema unions keep their real alternatives** (`src/tool.ts`): the old + `anyOf`/`oneOf` renderer collapsed any union containing `{ type: "number" }` to just + `number`, dropping real JSON Schema alternatives (`string | number`, `number | null`, + etc.). The collapse is now restricted to Effect's number-schema artifact + (`number | "NaN" | "Infinity" | "-Infinity"`, emitted as single-value string enums), + while raw JSON Schema unions render every branch. Tests: `signature.test.ts` +3. +- **Compound assignment now matches binary-operator semantics** (`src/codemode.ts`): + `applyCompoundAssignment` did raw JS ops on interpreter wrapper objects, so `x += y` + diverged from `x = x + y` (sandbox Date `d += 1` produced `"[object Object]1"`; + `d -= 400` gave `NaN` instead of epoch arithmetic). The operator table + coercion moved + verbatim out of `evaluateBinaryExpression` into a shared `applyBinaryOperator`; + compound assignment validates against a `compoundOperators` set (`+=` ... `>>>=`) and + dispatches through it (`operator.slice(0, -1)`). Logical assignments (`&&=`/`||=`/`??=`) + keep their separate short-circuit path (`evaluateLogicalAssignment`), and both + assignment call sites still wrap results in `boundedData`. Deliberate side effect: + compound assignment now rejects opaque references, consistent with binary operators. + Tests: `parity.test.ts` +5 (Date `+=` concat parity, Date `-=`/`/=` epoch parity, + string `+=` object/array, member-target compound, 13-case operator sweep vs real JS). + Package suite: 220 pass. + +--- + +## 4. Remaining work (detailed TODO) + +### Next DSL-expansion pass (done - see the DSL-expansion pass entry in section 3) + +Batch these together - per user direction: important, but deliberately deferred to one +focused interpreter-surface pass rather than picked off piecemeal. + +- [x] Medium-tier JS parity items deferred from the original audit: caught errors are plain + `{ name, message }` objects, not `instanceof Error` (and `Error` isn't a value - + `x instanceof Error` is unsupported syntax); `splice` (still a + "rewrite using map/filter" hint) and array `entries()/keys()/values()`; + `localeCompare`/`normalize`/`trimLeft`/`trimRight`; friendlier regex-y error messages. + (`fill`/`copyWithin` - which the hint set also covered - were implemented too since + they are trivial host delegations, so the hint set is gone entirely.) +- [x] `Date`/`Map`/`Set`/`RegExp` values passing through `Object.*` helpers and coercion + checkpoints take their JSON forms (e.g. `Object.values({ d: date })` yields the ISO + string, not the Date - calling `.getTime()` on it then fails). Currently deliberate + (documented in README) but flagged as important: fix in this pass by letting sandbox + values survive `Object.*`/spread checkpoints instead of JSON-serializing them. +- [x] `console.log(NaN)` prints `"null"` (goes through the boundary chokepoint) - could + special-case number formatting in `formatConsoleArgument`. +- [x] Sandbox values nested inside logged containers print `[CodeMode reference]` + (`console.log({ m: map })`) - could deep-format instead. + +### Next iteration: text-result handling (deliberate follow-up, user-directed) + +- [ ] Revisit how MCP text results reach the program. Today: `structuredContent` when the + server sends it, else joined text as a plain string (the program JSON.parses it, + guided by a workflow step). Considered and deferred: (a) conservative boundary + auto-parse (text starting with `{`/`[` that parses cleanly becomes an object) - + rejected for now as potentially confusing (type flips; program sees something other + than what the tool sent); (b) raw-envelope passthrough with the envelope shape + stamped into every output schema - rejected (more digging per call, verbose + signatures). Result quality is dominated by whether servers declare output schemas; + revisit once real usage shows which failure modes matter. + +### Next iteration: stdlib surface (prioritized) + +Current instructions say "usual Array/String/Object/Math/JSON methods," but the interpreter is +intentionally a subset. Keep CodeMode focused on orchestration and data shaping, not a full host +runtime, but close the high-friction gaps models are likely to reach for. + +- [ ] **P0: tighten wording first** - change instructions/docs to say "common stdlib subset" + until the surface is broader. This avoids misleading the model into assuming every JS + helper exists. +- [ ] **P1: URL parsing helpers** - add `URL` and `URLSearchParams`. These are high-value for + tool orchestration (query strings, ids in URLs, API links), deterministic, and do not add + ambient host authority. +- [ ] **P2: Math completion** - add the missing standard deterministic `Math` methods + (`sin`/`cos`/`tan`, inverse/hyperbolic variants, `atan2`, `log1p`, `expm1`, `imul`, + `fround`, `clz32`, etc.). Decide explicitly on `Math.random`: likely acceptable because + `Date.now()` is already exposed, but document the nondeterminism if enabled. +- [ ] **P3: base64 helpers** - add string-only `atob`/`btoa` equivalents. Useful for API/tool + payload cleanup and does not require opening the broader binary boundary. +- [ ] **P4: small crypto helper** - consider `crypto.randomUUID()` only, not full `crypto`. + UUID generation is a common orchestration need; broader crypto can wait until there is a + concrete use case and a clear capability boundary. +- [ ] **P5: text/binary primitives** - consider `TextEncoder`/`TextDecoder` first, then + `ArrayBuffer`/typed arrays/`DataView`/`Blob`/`File` only with an explicit boundary design + (serialization, size limits, and how values cross tool args/results). This is reasonable + but lower priority than URL/base64 because CodeMode is still plain-data oriented. +- [ ] **P6: date/formatting conveniences** - consider `Date` setters and common formatting + helpers (`toUTCString`, maybe `Intl` later). Lower priority; most orchestration can use + existing getters, `Date.parse`, `Date.UTC`, and ISO strings. +- [ ] **P7: environment/config access** - do not expose raw `process.env` as a global ambient + authority. If this becomes useful, add an explicit host-provided/whitelisted capability + (for example a small env/config tool or injected read-only object) so secrets are not + accidentally exposed to arbitrary CodeMode programs. + +Explicit non-goals for now: `structuredClone`, `WeakMap`/`WeakSet`, and timers +(`setTimeout`/`setInterval`/`queueMicrotask`). They do not materially improve the current tool +orchestration use case. + +### Wiring-review findings (subagent code review of the OpenCode integration, triaged) + +Pre-PR fixes (user-approved cut): + +- [x] **Cancellation does not interrupt the interpreter** - the no-limits rationale claimed + "user cancel interrupts the execution fiber," but `tools.ts` runs tools via + `run.promise` -> `Effect.runPromise` (`effect/bridge.ts:64-66`) with NO abort wiring; + on cancel the ai-sdk abandons the promise, child MCP calls abort (they hold + `ctx.abort`) but the interpreter fiber spun on - `while(true){}` or a try/catch + loop was uncancellable with no timeout backstop. Verified by hand, not just the + reviewer. FIXED in the adapter: `Effect.raceFirst(runtime.execute(code), cancelled)` + where `cancelled` is an `Effect.callback` abort-signal watcher (listener removed on + interruption) resuming with an `ok: false` "Execution cancelled." result - the abort + winning the race interrupts the execution fiber (interpreter auto-yield makes busy + loops preemptible, same mechanism as timeoutMs) and returning a value keeps the + runner's post-abort `completeToolCall` bookkeeping on its normal path. A pre-aborted + signal short-circuits at entry before the program starts (racing alone still lets + the loser run its first steps). Tests: +2 adapter (child call triggers abort + deterministically then the program enters `while(true){}` - would hang if + interruption broke; pre-aborted signal runs nothing). Adapter suite 34 -> 36. + (Wiring abort->interrupt into the shared `tools.ts` runner for ALL tools remains a + worthwhile separate change.) +- [x] **Permission-denied/disabled MCP tools are still advertised in the catalog** - the + non-code-mode path filters them from the model's view (`llm/request.ts:208-213`); + code mode builds the catalog from all of `mcp.tools()`, so the model is invited to + call tools that can only fail at permission time, and per-message `tools[key]=false` + disabling has no child-call equivalent. Fix: filter the catalog with the same + ruleset. + DONE (see the "Registry promotion + permission-aware catalog" entry in section 3): the + shared `Permission.visibleTools` predicate filters both the appended + catalog/description (`describeCodeMode`, agent ruleset) and the execute-time tool + tree (merged agent+session ruleset) - hard-denied tools are neither advertised nor + dispatchable. Ask-level tools stay visible/callable. Per-message + `tools[key] === false` remains a documented gap by design (it arrives at + request-prep, after descriptions are built). +- [x] Style: `code-mode.ts` is the only `src/session` sibling without the + `export * as ... from "./..."` self-reexport footer, forcing a star import at + `tools.ts:26` (AGENTS.md violation). Add footer + import the projection. + DONE: added `export * as SessionCodeMode from "./code-mode"` footer; `tools.ts` now + imports the named `SessionCodeMode` projection. +- [x] Trivial: latent `groupByServer` fallback bug - `key.slice(0, key.indexOf("_"))` is + `slice(0, -1)` when no underscore (unreachable today; guard or drop); dead + `CODE_MODE_TOOL` export (integration points hardcode `"execute"` - use it or inline + it). + DONE: no-underscore key now falls back to the whole key (test pins it); the four + `title: "execute"` sites in `code-mode.ts` now reference `CODE_MODE_TOOL`. + +Post-MVP (logged, not blocking an experimental flag): + +- [x] **Plugin `tool.execute.before/after` hooks skip child calls** - legacy MCP + registration fires them per tool (`tools.ts:419-441`); under code mode only the + outer `execute` fires them, so auditing/intercepting plugins silently lose MCP + coverage when the flag flips. + DONE (see the "Shared MCP invocation middle" entry in section 3): both paths now run + `McpInvoke.invoke` (`src/mcp/invoke.ts`) - hooks AND the `Tool.execute` span fire + for child calls with synthetic `${parentCallID}/${n}` callIDs; hook failures are + child-scoped, catchable in-program errors. +- [x] Description/preview rebuilt every assistant turn - `registry.tools()` re-runs + `groupByServer` + a throwaway `CodeMode.make(...).instructions()` per turn + (`describeCodeMode`). DECIDED as an explicit non-goal: memoizing the catalog + builder keyed on (ToolsChanged generation, permission ruleset) was considered and + deliberately skipped - the per-turn rebuild is cheap (grouping + string + rendering); revisit only if profiling shows it matters. A second `CodeMode.make` + per execution is inherent (description precedes execution). +- [ ] Child permission rejection round-trips through the defect channel - `ctx.ask` + defect (`tools.ts:90` orDie) recovered via `catchCause` + `Cause.squash` + (`code-mode.ts:238-245`). Works, interrupts preserved, but fragile coupling; + exposing the typed rejection on `Tool.Context.ask` would be cleaner. +- [ ] No collision guard on the `execute` tool id (a plugin/custom tool named `execute` + is silently shadowed; a log line would do). +- [ ] Style nits: triple-nested `yield*` in `tools.ts:101-107` argument position (bind + first, like neighbors); single-use micro-helpers (`toJsonSchema` is a bare cast); + comment density far above session-neighbor norm; adapter tests use raw + `Effect.runPromise` + hand-built layers with `as any` instead of the + `testEffect`/`LayerNode.compile` fixture pattern (`test/tool/grep.test.ts:25-31`) + and star-import `Truncate`. +- [ ] Reviewer observation worth keeping: MCP server instructions (`sys.mcp`, + `session/system.ts:110-126`) still inject prose referencing server-native tool + names that are no longer directly callable under code mode. + +### Backlog / loose ends (non-blocking, any order) + +- [ ] `evaluateUpdateExpression` (`++`/`--`) still uses raw `Number(current)`, so `d++` on a + sandbox Date yields `NaN` where `d += 1` now uses epoch semantics (and real JS `d++` + would give epoch+0 numeric). Pre-existing, out of scope of the compound-assignment + parity fix; route it through `applyBinaryOperator` if it ever matters. +- [ ] Media-only marker could name what it attached when MCP provides names: `image`/`audio` + blocks carry no filename (mime + data only) so the generic + `[N images attached to the result]` stays, but `resource`/`resource_link` blocks have + URIs/names we could surface, e.g. `[2 files attached: chart.png, data.csv]`. Minor. +- [x] Truncation layering decided (user direction): the OPPOSITE of killing the outer layer - + CodeMode truncation off in OpenCode (`maxOutputBytes` lost its default; absent = no + truncation, uniform with the other two limits), native tool-output truncation is the + single active layer (verified: `execute` flows through `tool.ts` `wrap()` like any + normal tool, no exemption). See the section 3 entry. +- [x] Flaky wall-clock assertion removed from `test/promise.test.ts`: the parallelism test + now relies solely on the deterministic `trace.maxActive > 1` counter (which proves + true temporal overlap). The timeout tests were never flaky - 100ms timeout vs 60s + tool sleeps (600x margin) with counter-based assertions. +- [ ] Attachment propagation believed correct but unverified end-to-end at the OpenCode + wiring layer (codemode strips -> `Tool.ExecuteResult.attachments` -> processor + normalizes -> `FilePart`s visible to the model). Code-reviewed as sound; confirm with + one interactive session (an image-returning MCP tool) when convenient. Same session + can eyeball TUI child-call rendering via `metadata.toolCalls`. +- [x] Commit hygiene: all work committed and pushed on `codemode-v2` as six commits, in + generic-package + OpenCode-integration pairs (waves 0-5; Fixes 4-9; DSL pass + + error names + truncation layering). Future work: commit only when explicitly asked; + push with `--no-verify` per repo convention. The scratch `.opencode/opencode.jsonc` + stays uncommitted. +- [ ] MVP scope decided (user direction): the interactive e2e eyeball is NOT required - + remaining pre-PR work is essentially just opening the PR. Attachment-propagation + verification (below) stays parked as post-MVP. + +--- + +## 5. Context and gotchas for whoever picks this up + +- **Motivating failure (why forgiving semantics + prompting matter):** in a real transcript, + the model wrote `me.result?.login ?? me.result` where the tool result was a JSON _string_ - + the old strict interpreter threw (`String property 'login' is not available`); then the + model returned a raw 105KB payload, which native truncation dumped to a file, costing a + subagent round-trip to extract one number. Interpreter forgiveness stops the crashes; + Wave 4 prompting stops the payload dumping. Both are needed. +- Realistically **all MCP tools render `Promise`** (no outputSchema), so the + instructions prose is the only lever for result-shape behavior in the dominant case. +- **`copyIn` has two roles, split by a mode flag** (DSL-expansion pass): host<->sandbox + boundary (default mode - final result, tool arguments, `JSON.stringify`, tool-result + intake; sandbox value types serialize to JSON forms) AND intra-sandbox data checkpoint + (`boundedData` = `copyIn(value, label, true)` - sandbox value instances pass through by + reference as leaves, everything else keeps the same plain-data validation). If you add a + new value type, follow the Wave 1b-i pattern: class in `values.ts`, opaque-by-default via + `isRuntimeReference`, explicit carve-outs, JSON form in `copyIn`'s boundary mode plus + pass-through in its preserving mode, console formatting (`formatConsoleValue`), tests - + and make sure the `Object.*` helpers treat it as an empty object so class fields never + leak. +- The interpreter throws synchronously inside `Effect.gen`/`Effect.sync` freely; everything is + normalized by `catchCause` -> `normalizeError` into `Diagnostic` data. Program failures are + **data, never Effect failures**; only interruption propagates. +- `parseProgram` wraps source in `async function __codemode__() { ... }`, transpiles TS, then + slices between the first `{` and last `}` - line/col diagnostics are offset accordingly + (`sourceLocation`). Don't inject prologue code; it breaks the offsets. +- OpenCode wraps every tool's output with auto-truncation (`Tool.define` wrapper, + `truncate.output`, 2000 lines / 50KB, saves full output to disk and appends a hint) unless + `metadata.truncated` is set. The `execute` tool currently rides that for free. +- Effect version: both repos pin `effect@4.0.0-beta.83` via bun catalogs. This package uses + v4-only APIs (`Schema.Decoder`, `Schema.toJsonSchemaDocument`, `Context.Service`, + `Cause.hasInterruptsOnly`, `Effect.timeoutOrElse`). The effect-smol checkout referenced in + the workspace is the implementation source of truth for v4 behavior questions. +- File map (this package): `src/codemode.ts` - types/limits/parser/Interpreter/execute/make; + `src/tool-runtime.ts` - tool tree, `copyIn`/`copyOut`, search/discovery, invoke path; + `src/tool.ts` - `Tool.make` + JSON-Schema->TS rendering; `src/values.ts` - sandbox value + types; `src/tool-error.ts` - `ToolError`; tests in `test/{codemode,parity,stdlib}.test.ts`. +- OpenCode file map (integration points): `src/tool/code-mode.ts` (the adapter, now a + registry tool service - `CodeModeTool` + `catalogInstructions`; formerly + `src/session/code-mode.ts`); `src/tool/registry.ts` (`describeCodeMode`, enablement in + `tools()`, `MCP.node` dep); `src/session/tools.ts` (raw-MCP-registration suppression + when the flag is on); `src/permission/index.ts` (`Permission.visibleTools`, the shared + visibility predicate, also used by `src/session/llm/request.ts` `resolveTools`); + `src/mcp/index.ts` (`MCP.tools()`/`MCP.defs()`); `src/mcp/catalog.ts` (`convertTool`, + `server_tool` naming); `src/tool/tool.ts` (`ExecuteResult.attachments`, truncation + wrapper); `src/session/message-v2.ts` (attachments -> vision); + `packages/tui/src/routes/session/index.tsx` (`Execute` progress component); + `src/effect/runtime-flags.ts` (feature flag). diff --git a/packages/codemode/package.json b/packages/codemode/package.json new file mode 100644 index 0000000000..b2d9ec3ea2 --- /dev/null +++ b/packages/codemode/package.json @@ -0,0 +1,26 @@ +{ + "$schema": "https://json.schemastore.org/package.json", + "name": "@opencode-ai/codemode", + "version": "0.0.1", + "description": "Effect-native confined code execution over schema-described tools", + "private": true, + "type": "module", + "license": "MIT", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsgo --noEmit", + "test": "bun test" + }, + "dependencies": { + "acorn": "8.15.0", + "effect": "catalog:", + "typescript": "catalog:" + }, + "devDependencies": { + "@tsconfig/bun": "catalog:", + "@types/bun": "catalog:", + "@typescript/native-preview": "catalog:" + } +} diff --git a/packages/codemode/src/codemode.ts b/packages/codemode/src/codemode.ts new file mode 100644 index 0000000000..f8a01f23b0 --- /dev/null +++ b/packages/codemode/src/codemode.ts @@ -0,0 +1,4126 @@ +import { parse } from "acorn" +import { Cause, Effect, Exit, Fiber, Schema, Semaphore } from "effect" +import { DiagnosticCategory, ModuleKind, ScriptTarget, flattenDiagnosticMessageText, transpileModule } from "typescript" +import { + copyIn, + copyOut, + isBlockedMember, + ToolReference, + ToolRuntime, + ToolRuntimeError, + type HostTools, + type SafeObject, + type ToolCall, + type ToolDescription, + type Services, +} from "./tool-runtime.js" +import type { Definition } from "./tool.js" +import { ToolError } from "./tool-error.js" +import { isSandboxValue, SandboxDate, SandboxMap, SandboxPromise, SandboxRegExp, SandboxSet } from "./values.js" + +/** A tool call admitted during an execution. */ +export type { ToolCall, ToolCallStarted, ToolDescription } from "./tool-runtime.js" +export { ToolError, toolError } from "./tool-error.js" + +/** Resource budgets enforced independently during each CodeMode program execution. */ +export type ExecutionLimits = { + /** Maximum wall-clock execution time in milliseconds. No default: absent means no timeout. */ + readonly timeoutMs?: number + /** Maximum number of tool calls admitted by the runtime. No default: absent means unlimited. */ + readonly maxToolCalls?: number + /** + * Maximum UTF-8 bytes of model-facing output: the serialized result value plus captured + * logs. Excess output is truncated with an explanatory marker instead of failing. No + * default: absent means no truncation (for hosts with their own output bounding). + */ + readonly maxOutputBytes?: number +} + +/** Controls how much of the tool catalog is inlined in agent instructions. */ +export type DiscoveryOptions = { + /** + * Estimated-token budget (chars/4, default 2000) for inlined full tool signatures in agent + * instructions. Signatures that fit are inlined round-robin across namespaces; every + * namespace is always listed with its tool count regardless of budget, and + * `tools.$codemode.search` is always registered. + */ + readonly maxInlineCatalogTokens?: number +} + +type ToolTree = { + readonly [name: string]: Definition | ToolTree +} + +type ResolvedExecutionLimits = { + /** Undefined means no timeout. */ + readonly timeoutMs: number | undefined + /** Undefined means unlimited tool calls. */ + readonly maxToolCalls: number | undefined + /** Undefined means no output truncation. */ + readonly maxOutputBytes: number | undefined +} + +/** Options for one CodeMode execution. */ +export type ExecuteOptions = {}> = { + /** Source for one program in the supported JavaScript subset. */ + code: string + /** Explicit tool tree exposed to the program as `tools`. */ + tools?: Tools & ToolTree> + /** Per-execution overrides for the default resource limits. */ + limits?: ExecutionLimits + /** Observes decoded tool input immediately before tool execution. */ + onToolCallStart?: (call: ToolRuntime.ToolCallStarted) => Effect.Effect> + /** Observes each admitted tool call as it settles, with outcome and duration. */ + onToolCallEnd?: (call: ToolRuntime.ToolCallEnded) => Effect.Effect> +} + +/** A normalized program diagnostic safe to return across an agent tool boundary. */ +export type Diagnostic = { + readonly kind: DiagnosticKind + readonly message: string + readonly location?: { readonly line: number; readonly column: number } + readonly suggestions?: ReadonlyArray +} + +/** A JSON value that can cross the confined interpreter boundary. */ +export type DataValue = Schema.Json + +/** Successful execution after the result has crossed the plain-data boundary. */ +export type ExecuteSuccess = { + readonly ok: true + readonly value: DataValue + readonly logs?: ReadonlyArray + /** Present when the value or logs were truncated to fit `maxOutputBytes`. */ + readonly truncated?: boolean + readonly toolCalls: ReadonlyArray +} + +/** Failed execution with calls admitted before the diagnostic was produced. */ +export type ExecuteFailure = { + readonly ok: false + readonly error: Diagnostic + readonly logs?: ReadonlyArray + /** Present when the logs were truncated to fit `maxOutputBytes`. */ + readonly truncated?: boolean + readonly toolCalls: ReadonlyArray +} + +/** Result of executing a CodeMode program. Program failures are data, not Effect failures. */ +export type ExecuteResult = ExecuteSuccess | ExecuteFailure + +/** Reusable CodeMode configuration shared by `execute` and `agentTool`. */ +export type CodeModeOptions = {}> = Omit, "code"> & { + /** Progressive-disclosure configuration for the agent-facing tool catalog. */ + readonly discovery?: DiscoveryOptions +} + +/** Input schema for the single agent-facing tool produced by `runtime.agentTool()`. */ +export const ExecuteInputSchema = Schema.Struct({ code: Schema.String }) + +const DiagnosticKindSchema = Schema.Literals([ + "ParseError", + "UnsupportedSyntax", + "UnknownTool", + "InvalidToolInput", + "InvalidToolOutput", + "InvalidDataValue", + "ToolCallLimitExceeded", + "TimeoutExceeded", + "ToolFailure", + "ExecutionFailure", +]) + +/** Structured success or diagnostic result schema returned by CodeMode execution. */ +export const ExecuteResultSchema = Schema.Union([ + Schema.Struct({ + ok: Schema.Literal(true), + value: Schema.Json, + logs: Schema.optionalKey(Schema.Array(Schema.String)), + truncated: Schema.optionalKey(Schema.Boolean), + toolCalls: Schema.Array(Schema.Struct({ name: Schema.String })), + }), + Schema.Struct({ + ok: Schema.Literal(false), + error: Schema.Struct({ + kind: DiagnosticKindSchema, + message: Schema.String, + location: Schema.optionalKey(Schema.Struct({ line: Schema.Number, column: Schema.Number })), + suggestions: Schema.optionalKey(Schema.Array(Schema.String)), + }), + logs: Schema.optionalKey(Schema.Array(Schema.String)), + truncated: Schema.optionalKey(Schema.Boolean), + toolCalls: Schema.Array(Schema.Struct({ name: Schema.String })), + }), +]) + +/** Agent-facing projection of a configured CodeMode runtime. */ +export type AgentToolDefinition = { + readonly name: "code" + readonly description: string + readonly input: typeof ExecuteInputSchema + readonly output: typeof ExecuteResultSchema + readonly execute: (input: { readonly code: string }) => Effect.Effect +} + +/** Reusable confined runtime over one explicit tool tree. */ +export type CodeModeRuntime = { + /** Lists schema-described tool paths provided by the host. */ + readonly catalog: () => ReadonlyArray + /** Builds model-facing syntax guidance and visible tool signatures. */ + readonly instructions: () => string + /** Projects the configured runtime as one agent-facing `code` tool. */ + readonly agentTool: () => AgentToolDefinition + /** Executes a program using this runtime's configured host tools. */ + readonly execute: (code: string) => Effect.Effect +} + +type SourcePosition = { + line: number + column: number +} + +type SourceLocation = { + start: SourcePosition + end: SourcePosition +} + +type AstNode = { + type: string + loc?: SourceLocation + [key: string]: unknown +} + +type ProgramNode = AstNode & { + type: "Program" + body: Array +} + +type Binding = { + mutable: boolean + value: unknown + // Absent means initialized. `false` marks a parameter binding seeded into its scope but not + // yet bound, so a default that forward-references a later parameter sees a TDZ error (as in JS) + // rather than silently resolving to an outer binding of the same name. + initialized?: boolean +} + +type StatementResult = + | { kind: "none" } + | { kind: "value"; value: unknown } + | { kind: "return"; value: unknown } + | { kind: "break" } + | { kind: "continue" } + +type MemberReference = { + target: SafeObject | Array + key: string | number +} + +class CodeModeFunction { + constructor( + readonly parameters: ReadonlyArray, + readonly body: AstNode, + readonly capturedScopes: ReadonlyArray>, + ) {} +} + +class IntrinsicReference { + constructor( + readonly receiver: unknown, + readonly name: string, + ) {} +} + +class ComputedValue { + constructor(readonly value: unknown) {} +} + +class PromiseNamespace {} + +type PromiseMethodName = "all" | "allSettled" | "race" | "resolve" | "reject" + +class PromiseMethodReference { + constructor(readonly name: PromiseMethodName) {} +} + +// A built-in global namespace (`Object`, `Math`, `JSON`, `Array`, ...); members resolve to a +// GlobalMethodReference, except known constants (e.g. `Math.PI`) which resolve to a value. +type GlobalNamespaceName = "Object" | "Math" | "JSON" | "Array" | "console" | "Date" | "RegExp" | "Map" | "Set" + +class GlobalNamespace { + constructor(readonly name: GlobalNamespaceName) {} +} + +class GlobalMethodReference { + constructor( + readonly namespace: GlobalNamespaceName | "Number" | "String", + readonly name: string, + ) {} +} + +class CoercionFunction { + constructor(readonly name: "Number" | "String" | "Boolean" | "parseInt" | "parseFloat") {} +} + +class ProgramThrow { + constructor(readonly value: unknown) {} +} + +class ErrorConstructorReference { + constructor(readonly name: string) {} +} + +// Non-enumerable so spread/copyOut preserve the plain `{ name, message }` data shape. +const ErrorBrand: unique symbol = Symbol("codemode.error") + +const brandError = (errorValue: SafeObject, name: string): SafeObject => { + Object.defineProperty(errorValue, ErrorBrand, { value: name }) + return errorValue +} + +const createErrorValue = (name: string, message: string): SafeObject => + brandError(Object.assign(Object.create(null) as SafeObject, { name, message }), name) + +const errorBrandName = (value: unknown): string | undefined => + value !== null && typeof value === "object" + ? ((value as Record)[ErrorBrand] as string | undefined) + : undefined + +/** Stable categories produced by program, schema, tool, and limit failures. */ +export type DiagnosticKind = + | "ParseError" + | "UnsupportedSyntax" + | "UnknownTool" + | "InvalidToolInput" + | "InvalidToolOutput" + | "InvalidDataValue" + | "ToolCallLimitExceeded" + | "TimeoutExceeded" + | "ToolFailure" + | "ExecutionFailure" + +const arrayMethods = new Set([ + "map", + "filter", + "find", + "findIndex", + "findLast", + "findLastIndex", + "some", + "every", + "includes", + "join", + "reduce", + "reduceRight", + "flatMap", + "forEach", + "sort", + "toSorted", + "slice", + "concat", + "indexOf", + "lastIndexOf", + "at", + "flat", + "reverse", + "toReversed", + "with", + "push", + "pop", + "shift", + "unshift", + "splice", + "fill", + "copyWithin", + "keys", + "values", + "entries", +]) + +const mathConstants = new Set(["PI", "E", "LN2", "LN10", "LOG2E", "LOG10E", "SQRT2", "SQRT1_2"]) + +const numberMethods = new Set(["toFixed", "toPrecision", "toExponential", "toString"]) + +const stringMethods = new Set([ + "toLowerCase", + "toUpperCase", + "trim", + "trimStart", + "trimEnd", + "trimLeft", + "trimRight", + "split", + "slice", + "substring", + "substr", + "includes", + "startsWith", + "endsWith", + "indexOf", + "lastIndexOf", + "replace", + "replaceAll", + "repeat", + "padStart", + "padEnd", + "charAt", + "charCodeAt", + "codePointAt", + "at", + "concat", + "toString", + "match", + "matchAll", + "search", + "localeCompare", + "normalize", +]) + +const numberConstants = new Set(["MAX_SAFE_INTEGER", "MIN_SAFE_INTEGER", "MAX_VALUE", "MIN_VALUE", "EPSILON"]) + +const numberStatics = new Set(["isInteger", "isFinite", "isNaN", "isSafeInteger", "parseInt", "parseFloat"]) + +const stringStatics = new Set(["fromCharCode", "fromCodePoint"]) + +const consoleMethods = new Set(["log", "info", "debug", "warn", "error", "dir", "table"]) + +const promiseStatics = new Set(["all", "allSettled", "race", "resolve", "reject"]) + +const errorConstructors = new Set([ + "Error", + "TypeError", + "RangeError", + "SyntaxError", + "ReferenceError", + "EvalError", + "URIError", +]) + +const valueConstructors = new Set(["Date", "RegExp", "Map", "Set"]) + +const dateMethods = new Set([ + "getTime", + "valueOf", + "toISOString", + "toJSON", + "toString", + "getFullYear", + "getMonth", + "getDate", + "getDay", + "getHours", + "getMinutes", + "getSeconds", + "getMilliseconds", + "getUTCFullYear", + "getUTCMonth", + "getUTCDate", + "getUTCDay", + "getUTCHours", + "getUTCMinutes", + "getUTCSeconds", + "getUTCMilliseconds", + "getTimezoneOffset", +]) +const dateStatics = new Set(["now", "parse", "UTC"]) + +const regexpMethods = new Set(["test", "exec", "toString"]) +// Read-only host regex fields surfaced as plain values. +const regexpProperties = new Set([ + "source", + "flags", + "lastIndex", + "global", + "ignoreCase", + "multiline", + "sticky", + "unicode", + "dotAll", +]) + +const mapMethods = new Set(["get", "set", "has", "delete", "clear", "forEach", "keys", "values", "entries"]) +const setMethods = new Set(["add", "has", "delete", "clear", "forEach", "keys", "values", "entries"]) + +const OptionalShortCircuit: unique symbol = Symbol("codemode.optional-short-circuit") + +const supportedSyntaxMessage = + "Supported orchestration syntax: tools.* calls (they return promises - resolve them with await), data literals, destructuring, optional chaining, template literals, conditionals, switch, loops (incl. for...of and for...in over object/array/tools keys), arrow functions, spread, try/catch, array methods (map/filter/find/findIndex/some/every/reduce/flatMap/forEach/sort/slice/concat/indexOf/lastIndexOf/at/flat/reverse/includes/join), string methods (incl. match/matchAll/replace/split with regular expressions), Date/RegExp/Map/Set, Object/Math/JSON helpers, captured console.log/warn/error/dir/table, and Promise.all/allSettled/race/resolve/reject over arrays mixing promises and plain values for parallel tool calls (promise chaining with .then/.catch is not supported - use await with try/catch)." + +const unsupportedSyntax = (kind: string, node: AstNode): InterpreterRuntimeError => + new InterpreterRuntimeError( + `Syntax '${kind}' is not supported in CodeMode. ${supportedSyntaxMessage}`, + node, + "UnsupportedSyntax", + [supportedSyntaxMessage], + ) + +/** How many eagerly forked tool calls may run at once. Fixed; not a configurable knob. */ +const TOOL_CALL_CONCURRENCY = 8 + +/** Console formatting recursion ceiling; deeper values render as "...". Fixed; not a knob. */ +const MAX_CONSOLE_DEPTH = 32 + +const validateLimit = ( + name: keyof ExecutionLimits, + value: Value, + minimum: number, +): Value => { + if (value !== undefined && (!Number.isSafeInteger(value) || value < minimum)) { + throw new RangeError(`${name} must be a safe integer greater than or equal to ${minimum}.`) + } + return value +} + +// No limit has a default: absent means no timeout / unlimited calls / no output truncation - +// budgets are host policy, not library policy. A host without its own output bounding should +// pass maxOutputBytes explicitly, or oversized results flood model context. +const resolveExecutionLimits = (limits?: ExecutionLimits): ResolvedExecutionLimits => ({ + timeoutMs: validateLimit("timeoutMs", limits?.timeoutMs, 1), + maxToolCalls: validateLimit("maxToolCalls", limits?.maxToolCalls, 0), + maxOutputBytes: validateLimit("maxOutputBytes", limits?.maxOutputBytes, 0), +}) + +class InterpreterRuntimeError extends Error { + readonly node?: AstNode + /** + * The constructor name a program observes when it catches this failure (`caught.name`, and + * the brand behind `caught instanceof SyntaxError` etc.). "Error" unless the failing + * operation names a standard type in real JS - e.g. JSON.parse and invalid regex patterns + * throw SyntaxError, an unknown identifier is a ReferenceError, a bad normalize form is a + * RangeError. + */ + errorName: string = "Error" + + constructor( + message: string, + node?: AstNode, + readonly kind: DiagnosticKind = "ExecutionFailure", + readonly suggestions?: ReadonlyArray, + ) { + super(message) + this.name = "InterpreterRuntimeError" + + if (node) { + this.node = node + } + } + + as(errorName: string): this { + this.errorName = errorName + return this + } +} + +const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null + +const asNode = (value: unknown, context: string): AstNode => { + if (!isRecord(value) || typeof value.type !== "string") { + throw new InterpreterRuntimeError(`Invalid AST node while reading ${context}.`) + } + + return value as AstNode +} + +const getArray = (node: AstNode, key: string): Array => { + const value = node[key] + if (!Array.isArray(value)) { + throw new InterpreterRuntimeError(`Expected '${key}' to be an array.`, node) + } + + return value +} + +const getString = (node: AstNode, key: string): string => { + const value = node[key] + if (typeof value !== "string") { + throw new InterpreterRuntimeError(`Expected '${key}' to be a string.`, node) + } + + return value +} + +const getBoolean = (node: AstNode, key: string): boolean => { + const value = node[key] + if (typeof value !== "boolean") { + throw new InterpreterRuntimeError(`Expected '${key}' to be a boolean.`, node) + } + + return value +} + +const getOptionalNode = (node: AstNode, key: string): AstNode | undefined => { + const value = node[key] + if (value === undefined || value === null) { + return undefined + } + + return asNode(value, key) +} + +const getNode = (node: AstNode, key: string): AstNode => { + const value = node[key] + return asNode(value, key) +} + +const parseProgram = (code: string): ProgramNode => { + const transpiled = transpileModule(`async function __codemode__() {\n${code}\n}`, { + reportDiagnostics: true, + compilerOptions: { + target: ScriptTarget.ESNext, + module: ModuleKind.ESNext, + }, + }) + const diagnostic = transpiled.diagnostics?.find((item) => item.category === DiagnosticCategory.Error) + + if (diagnostic) { + throw new InterpreterRuntimeError( + `Failed to parse TypeScript: ${flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`, + undefined, + "ParseError", + ) + } + + const bodyStart = transpiled.outputText.indexOf("{") + 1 + const bodyEnd = transpiled.outputText.lastIndexOf("}") + const executableCode = transpiled.outputText.slice(bodyStart, bodyEnd) + const parsed = parse(executableCode, { + ecmaVersion: "latest", + sourceType: "script", + allowReturnOutsideFunction: true, + allowAwaitOutsideFunction: true, + locations: true, + }) as unknown + + if (!isRecord(parsed) || parsed.type !== "Program" || !Array.isArray(parsed.body)) { + throw new InterpreterRuntimeError("Failed to parse script as a Program node.") + } + + return parsed as ProgramNode +} + +const formatLocation = (node?: AstNode): string => { + if (!node || !node.loc) { + return "" + } + + const location = sourceLocation(node) + return ` (line ${location.line}, col ${location.column})` +} + +const sourceLocation = (node: AstNode): { readonly line: number; readonly column: number } => ({ + line: Math.max(1, (node.loc?.start.line ?? 2) - 1), + column: Math.max(1, (node.loc?.start.column ?? 4) - 3), +}) + +const publicErrorMessage = (message: string): string => + message.replace(/\/(?:Users|home|private|tmp|var\/folders)\/[^\s"'`]+/g, "") + +const normalizeError = (error: unknown): Diagnostic => { + if (error instanceof InterpreterRuntimeError) { + return { + kind: error.kind, + message: `${error.message}${formatLocation(error.node)}`, + ...(error.node?.loc ? { location: sourceLocation(error.node) } : {}), + ...(error.suggestions ? { suggestions: error.suggestions } : {}), + } + } + + if (error instanceof ToolRuntimeError) { + return { + kind: error.kind, + message: error.message, + ...(error.suggestions.length > 0 ? { suggestions: error.suggestions } : {}), + } + } + + if (error instanceof ToolError) { + return { kind: "ToolFailure", message: publicErrorMessage(error.message) } + } + + if (error instanceof ProgramThrow) { + const value = error.value + let message: string + if (containsRuntimeReference(value)) { + // A thrown tool/function reference must not leak its internal structure. + message = "a non-data value" + } else if (typeof value === "string") { + message = value + } else if ( + value !== null && + typeof value === "object" && + typeof (value as { message?: unknown }).message === "string" + ) { + message = (value as { message: string }).message + } else { + try { + message = JSON.stringify(copyOut(value)) ?? String(value) + } catch { + message = String(value) + } + } + return { kind: "ExecutionFailure", message: `Uncaught: ${message}` } + } + + if (error instanceof RangeError && /call stack|recursion/i.test(error.message)) { + return { + kind: "ExecutionFailure", + message: "Execution exceeded the maximum nesting depth.", + } + } + + if (error instanceof Error) { + return { + kind: error.name === "SyntaxError" ? "ParseError" : "ExecutionFailure", + message: publicErrorMessage(error.message), + } + } + + // A non-Error thrown by a host tool (raw string / number / Symbol) still routes through + // path redaction so filesystem paths can never leak through the catch-all branch. + return { + kind: "ExecutionFailure", + message: publicErrorMessage(String(error)), + } +} + +// Shared by catch bindings, Promise.allSettled rejection reasons, and Promise.race losers. +const caughtErrorValue = (thrown: unknown): unknown => { + if (thrown instanceof ProgramThrow) return thrown.value + if (thrown instanceof InterpreterRuntimeError) return createErrorValue(thrown.errorName, thrown.message) + const name = thrown instanceof Error && errorConstructors.has(thrown.name) ? thrown.name : "Error" + return createErrorValue(name, normalizeError(thrown).message) +} + +const boundedData = (value: unknown, label: string): unknown => copyIn(value, label, true) + +const isRuntimeReference = (value: unknown): boolean => + value instanceof CodeModeFunction || + value instanceof ToolReference || + value instanceof IntrinsicReference || + value instanceof GlobalNamespace || + value instanceof GlobalMethodReference || + value instanceof PromiseNamespace || + value instanceof PromiseMethodReference || + value instanceof SandboxPromise || + value instanceof CoercionFunction || + value instanceof ErrorConstructorReference || + isSandboxValue(value) + +const containsRuntimeReference = (value: unknown, seen = new Set()): boolean => { + if (isRuntimeReference(value)) return true + if (value === null || typeof value !== "object") return false + if (seen.has(value)) return false + seen.add(value) + const contains = Array.isArray(value) + ? value.some((item) => containsRuntimeReference(item, seen)) + : Object.values(value).some((item) => containsRuntimeReference(item, seen)) + seen.delete(value) + return contains +} + +// Like containsRuntimeReference, but sandbox value types (Date/RegExp/Map/Set) count as data: +// operators and switch treat them as ordinary object operands (identity equality, ToPrimitive +// coercion) rather than rejecting them as opaque interpreter machinery. +const containsOpaqueReference = (value: unknown, seen = new Set()): boolean => { + if (isSandboxValue(value)) return false + if (isRuntimeReference(value)) return true + if (value === null || typeof value !== "object") return false + if (seen.has(value)) return false + seen.add(value) + const contains = Array.isArray(value) + ? value.some((item) => containsOpaqueReference(item, seen)) + : Object.values(value).some((item) => containsOpaqueReference(item, seen)) + seen.delete(value) + return contains +} + +// `typeof` never throws in JS; map every interpreter value to its JS-visible category. +// A SandboxPromise falls through to the final `typeof value` and reports "object", exactly +// like a real JS promise. +const typeofValue = (value: unknown): string => { + if ( + value instanceof CodeModeFunction || + value instanceof CoercionFunction || + value instanceof IntrinsicReference || + value instanceof GlobalMethodReference || + value instanceof PromiseMethodReference || + value instanceof PromiseNamespace || + value instanceof ErrorConstructorReference + ) + return "function" + if (value instanceof ToolReference) return value.path.length > 0 ? "function" : "object" + if (value instanceof GlobalNamespace) { + return value.name === "Math" || value.name === "JSON" || value.name === "console" ? "object" : "function" + } + return typeof value +} + +// `x instanceof C` against the constructors CodeMode knows. Like `typeof`, it observes any +// left-hand value (opaque references included) without coercing it. Error checks use the +// error brand: `instanceof Error` accepts every branded error; a specific error type matches +// its own brand only (as in JS, where TypeError instances are also Error instances). +const instanceofValue = (lhs: unknown, rhs: unknown, node: AstNode): boolean => { + if (rhs instanceof ErrorConstructorReference) { + const brand = errorBrandName(lhs) + return brand !== undefined && (rhs.name === "Error" || brand === rhs.name) + } + if (rhs instanceof GlobalNamespace) { + switch (rhs.name) { + case "Date": + return lhs instanceof SandboxDate + case "RegExp": + return lhs instanceof SandboxRegExp + case "Map": + return lhs instanceof SandboxMap + case "Set": + return lhs instanceof SandboxSet + case "Array": + return Array.isArray(lhs) + case "Object": + return lhs !== null && (typeof lhs === "object" || typeofValue(lhs) === "function") + } + } + if (rhs instanceof PromiseNamespace) return lhs instanceof SandboxPromise + // Number/String/Boolean wrap primitives in JS; no boxed values exist in CodeMode, so + // `x instanceof Number` is always false - exactly what it is for primitives in JS. + if (rhs instanceof CoercionFunction && (rhs.name === "Number" || rhs.name === "String" || rhs.name === "Boolean")) { + return false + } + throw new InterpreterRuntimeError( + "The right-hand side of 'instanceof' must be a constructor CodeMode knows: Error (or a specific error type like TypeError), Date, RegExp, Map, Set, Array, Object, or Promise.", + node, + ) +} + +// A regex engine failure message without the engine's own "Invalid regular expression:" +// prefix, so composed diagnostics read as one sentence instead of stuttering the phrase. +const regexFailureReason = (error: unknown): string => + (error instanceof Error ? error.message : String(error)).replace(/^Invalid regular expression:\s*/i, "") + +const escapeRegexHint = + 'To match special characters like ( ) [ ] { } + * ? . literally, escape them with a backslash (e.g. "\\\\(") or test for them with String.includes instead.' + +// A string method's pattern argument as a host regex: a sandbox regex passes its own host +// instance through (so `g` lastIndex semantics follow the spec across calls); a string becomes +// a pattern, exactly as String.prototype.match/matchAll/search do (`extraFlags` adds matchAll's +// implicit `g`). Invalid patterns fail as catchable program errors that say what was wrong +// with the pattern and how to fix it. +const toHostRegex = (arg: unknown, method: string, node: AstNode, extraFlags = ""): RegExp => { + if (arg instanceof SandboxRegExp) return arg.regex + if (typeof arg === "string") { + try { + return new RegExp(arg, extraFlags) + } catch (error) { + throw new InterpreterRuntimeError( + `String.${method} received the string ${JSON.stringify(arg)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`, + node, + ).as("SyntaxError") + } + } + throw new InterpreterRuntimeError( + `String.${method} expects a regular expression (a /pattern/flags literal or new RegExp(...)) or a string pattern, not ${arg === null ? "null" : typeof arg}.`, + node, + ) +} + +// A host match result as a sandbox value: a plain array of the full match and captures, with +// `index` and named `groups` attached as own array properties (readable, and dropped at data +// boundaries exactly like JSON.stringify drops them in JS). `input` is omitted - it duplicates +// the whole subject string per match. +const matchToValue = (match: RegExpMatchArray): Array => { + const result: Array = Array.from(match, (group) => group) + if (match.index !== undefined) (result as Record & Array).index = match.index + if (match.groups) { + const groups: SafeObject = Object.create(null) as SafeObject + for (const [key, group] of Object.entries(match.groups)) { + if (!isBlockedMember(key)) groups[key] = group + } + ;(result as Record & Array).groups = groups + } + return result +} + +const invokeStringMethod = (value: string, name: string, args: Array, node: AstNode): unknown => { + const str = (index: number): string => { + const arg = args[index] + if (typeof arg !== "string") + throw new InterpreterRuntimeError(`String.${name} expects argument ${index + 1} to be a string.`, node) + return arg + } + const num = (index: number): number => { + const arg = args[index] + if (typeof arg !== "number") + throw new InterpreterRuntimeError(`String.${name} expects argument ${index + 1} to be a number.`, node) + return arg + } + const optNum = (index: number): number | undefined => (args[index] === undefined ? undefined : num(index)) + const optStr = (index: number): string | undefined => (args[index] === undefined ? undefined : str(index)) + + let result: unknown + switch (name) { + case "toLowerCase": + result = value.toLowerCase() + break + case "toUpperCase": + result = value.toUpperCase() + break + case "trim": + result = value.trim() + break + // trimLeft/trimRight are the legacy aliases of trimStart/trimEnd, kept because models write them. + case "trimStart": + case "trimLeft": + result = value.trimStart() + break + case "trimEnd": + case "trimRight": + result = value.trimEnd() + break + // Locale/options arguments are ignored: comparison runs with the host default locale, and + // the common use is a sort comparator where any consistent order works. + case "localeCompare": + result = value.localeCompare(str(0)) + break + case "normalize": { + const form = optStr(0) + try { + result = value.normalize(form) + } catch { + throw new InterpreterRuntimeError( + `String.normalize expects the form "NFC", "NFD", "NFKC", or "NFKD" (got ${JSON.stringify(form)}).`, + node, + ).as("RangeError") + } + break + } + case "split": { + if (args.length === 0) { + result = [value] + break + } + if (args[0] instanceof SandboxRegExp) { + result = value.split((args[0] as SandboxRegExp).regex, optNum(1)) + break + } + const requestedLimit = optNum(1) + result = value.split(str(0), requestedLimit === undefined ? undefined : requestedLimit >>> 0) + break + } + case "slice": + result = value.slice(optNum(0), optNum(1)) + break + case "includes": + result = value.includes(str(0), optNum(1)) + break + case "startsWith": + result = value.startsWith(str(0), optNum(1)) + break + case "endsWith": + result = value.endsWith(str(0), optNum(1)) + break + case "indexOf": + result = value.indexOf(str(0), optNum(1)) + break + case "lastIndexOf": + result = value.lastIndexOf(str(0), optNum(1)) + break + case "replace": + case "replaceAll": { + if (args[0] instanceof CodeModeFunction || args[1] instanceof CodeModeFunction) { + throw new InterpreterRuntimeError( + `String.${name} does not support function replacers in CodeMode; use match/matchAll and rebuild the string instead.`, + node, + "UnsupportedSyntax", + [supportedSyntaxMessage], + ) + } + if (args[0] instanceof SandboxRegExp) { + const pattern = (args[0] as SandboxRegExp).regex + const replacement = str(1) + if (name === "replaceAll" && !pattern.global) { + throw new InterpreterRuntimeError( + `String.replaceAll requires a regular expression with the global (g) flag: write /${pattern.source}/${pattern.flags}g, or use String.replace to replace only the first match.`, + node, + ) + } + result = name === "replace" ? value.replace(pattern, replacement) : value.replaceAll(pattern, replacement) + break + } + if (name === "replace") { + result = value.replace(str(0), str(1)) + break + } + result = value.replaceAll(str(0), str(1)) + break + } + case "match": { + const pattern = toHostRegex(args[0], name, node) + const matched = value.match(pattern) + if (matched === null) return null + // A global match is a plain array of matched strings; a non-global match carries + // index/groups own properties, so bypass the copying data checkpoint to keep them. + if (pattern.global) return boundedData(matched, "String.match result") + return matchToValue(matched) + } + case "matchAll": { + const pattern = toHostRegex(args[0], name, node, "g") + if (!pattern.global) { + throw new InterpreterRuntimeError( + `String.matchAll requires a regular expression with the global (g) flag: write /${pattern.source}/${pattern.flags}g, or use String.match for a single match.`, + node, + ) + } + // Materialized as an array (not an iterator); each entry is a match array with + // index/groups own properties. Match count is bounded by the subject length. + return Array.from(value.matchAll(pattern), matchToValue) + } + case "search": { + result = value.search(toHostRegex(args[0], name, node)) + break + } + case "repeat": { + const count = num(0) + if (!Number.isFinite(count) || count < 0) + throw new InterpreterRuntimeError("String.repeat expects a finite non-negative count.", node) + result = value.repeat(count) + break + } + case "padStart": + result = value.padStart(num(0), optStr(1)) + break + case "padEnd": + result = value.padEnd(num(0), optStr(1)) + break + case "charAt": + result = value.charAt(optNum(0) ?? 0) + break + case "at": + result = value.at(optNum(0) ?? 0) + break + case "substring": + result = value.substring(optNum(0) ?? 0, optNum(1)) + break + case "substr": + result = value.substr(optNum(0) ?? 0, optNum(1)) + break + // JS charCodeAt returns NaN out of range; NaN flows as an ordinary in-sandbox value + // (normalized to null only at the data boundary - see copyOut), so return it as-is. + case "charCodeAt": + result = value.charCodeAt(optNum(0) ?? 0) + break + case "codePointAt": + result = value.codePointAt(optNum(0) ?? 0) + break + case "toString": + result = value + break + case "concat": { + result = value.concat(...args.map((_, index) => str(index))) + break + } + default: + throw new InterpreterRuntimeError(`String method '${name}' is not available in CodeMode.`, node) + } + return boundedData(result, `String.${name} result`) +} + +const invokeNumberMethod = (value: number, name: string, args: Array, node: AstNode): unknown => { + const optNum = (index: number): number | undefined => { + const arg = args[index] + if (arg === undefined) return undefined + if (typeof arg !== "number") throw new InterpreterRuntimeError(`Number.${name} expects a number argument.`, node) + return arg + } + let result: unknown + switch (name) { + case "toFixed": + result = value.toFixed(optNum(0)) + break + case "toExponential": + result = value.toExponential(optNum(0)) + break + case "toPrecision": { + const digits = optNum(0) + result = digits === undefined ? value.toString() : value.toPrecision(digits) + break + } + case "toString": { + const radix = optNum(0) + if (radix !== undefined && (radix < 2 || radix > 36)) { + throw new InterpreterRuntimeError("Number.toString radix must be between 2 and 36.", node) + } + result = value.toString(radix) + break + } + default: + throw new InterpreterRuntimeError(`Number method '${name}' is not available in CodeMode.`, node) + } + return boundedData(result, `Number.${name} result`) +} + +// JavaScript's String(...) without tripping over CodeMode's null-prototype data objects. +const coerceToString = (value: unknown): string => { + if (value === null) return "null" + if (value === undefined) return "undefined" + // Sandbox values stringify deterministically: Date as ISO (not the host's locale/timezone + // toString), RegExp as its literal form, Map/Set with their JS Object.prototype tags. + if (value instanceof SandboxDate) + return Number.isFinite(value.time) ? new Date(value.time).toISOString() : "Invalid Date" + if (value instanceof SandboxRegExp) return `/${value.regex.source}/${value.regex.flags}` + if (value instanceof SandboxMap) return "[object Map]" + if (value instanceof SandboxSet) return "[object Set]" + if (typeof value === "object") { + return Array.isArray(value) + ? value.map((item) => (item === null || item === undefined ? "" : coerceToString(item))).join(",") + : "[object Object]" + } + return String(value) +} + +/** Compound assignment operators (`x op= y`), each applying the binary operator `op`. */ +const compoundOperators = new Set(["+=", "-=", "*=", "/=", "%=", "**=", "&=", "|=", "^=", "<<=", ">>=", ">>>="]) + +const coerceToNumber = (value: unknown): number => { + if (value instanceof SandboxDate) return value.time + if (isSandboxValue(value)) return Number.NaN + return value !== null && typeof value === "object" && !Array.isArray(value) ? Number.NaN : Number(value) +} + +const invokeCoercion = (ref: CoercionFunction, args: Array, node: AstNode): unknown => { + // Sandbox values coerce before the data checkpoint (which would JSON-serialize them): + // Number(date) is its time value, String(date) its ISO form, Boolean(x) is true. + const raw = args[0] + if (isSandboxValue(raw)) { + if (ref.name === "Boolean") return true + if (ref.name === "Number") return coerceToNumber(raw) + if (ref.name === "String") return coerceToString(raw) + if (ref.name === "parseInt") return parseInt(coerceToString(raw)) + return parseFloat(coerceToString(raw)) + } + const value = boundedData(args[0], `${ref.name} input`) + if (ref.name === "Number") return coerceToNumber(value) + if (ref.name === "Boolean") return Boolean(value) + if (ref.name === "parseInt") { + const radix = args[1] + if (radix !== undefined && typeof radix !== "number") + throw new InterpreterRuntimeError("parseInt expects a numeric radix.", node) + return parseInt(coerceToString(value), radix) + } + if (ref.name === "parseFloat") return parseFloat(coerceToString(value)) + return coerceToString(value) +} + +const invokeObjectMethod = (name: string, args: Array, node: AstNode): unknown => { + const requireObject = (): Record => { + const value = boundedData(args[0], `Object.${name} input`) + // Sandbox values (Date/RegExp/Map/Set) have no own enumerable properties in JS, so the + // Object.* helpers see them as empty objects - never their interpreter internals. + if (isSandboxValue(value)) return {} + if (value === null || typeof value !== "object" || Array.isArray(value)) { + throw new InterpreterRuntimeError(`Object.${name} expects a data object.`, node) + } + return value as Record + } + const guardedSet = (out: Record, key: string, item: unknown): void => { + if (isBlockedMember(key)) throw new InterpreterRuntimeError(`Property '${key}' is not available in CodeMode.`, node) + out[key] = item + } + switch (name) { + case "keys": { + // Object.keys(array) yields index strings (["0", "1", ...]) exactly as in JS; objects + // yield their own enumerable keys. (Tool references never reach here - the interpreter + // resolves them against the host tool tree first.) + const value = boundedData(args[0], "Object.keys input") + if (isSandboxValue(value)) return [] + if (Array.isArray(value)) return Object.keys(value) + if (value === null || typeof value !== "object") { + throw new InterpreterRuntimeError("Object.keys expects a data object or array.", node) + } + return Object.keys(value) + } + case "values": + return Object.values(requireObject()) + case "entries": + return Object.entries(requireObject()).map(([key, item]) => [key, item]) + case "hasOwn": + return Object.hasOwn(requireObject(), String(args[1])) + case "assign": { + const out: Record = Object.create(null) + for (const source of args) { + if (source === null || source === undefined) continue + const value = boundedData(source, "Object.assign input") + // A sandbox value source contributes nothing (no own enumerable properties in JS). + if (isSandboxValue(value)) continue + if (value === null || typeof value !== "object" || Array.isArray(value)) + throw new InterpreterRuntimeError("Object.assign expects data objects.", node) + for (const [key, item] of Object.entries(value)) guardedSet(out, key, item) + } + return out + } + case "fromEntries": { + // A Map is the idiomatic fromEntries source; use its entries directly (the data + // checkpoint would serialize a Map to {}). + if (args[0] instanceof SandboxMap) { + const out: Record = Object.create(null) + for (const [key, item] of (args[0] as SandboxMap).map.entries()) guardedSet(out, coerceToString(key), item) + return out + } + const pairs = boundedData(args[0], "Object.fromEntries input") + if (!Array.isArray(pairs)) + throw new InterpreterRuntimeError("Object.fromEntries expects an array of [key, value] pairs.", node) + const out: Record = Object.create(null) + for (const pair of pairs) { + if (!Array.isArray(pair)) + throw new InterpreterRuntimeError("Object.fromEntries expects [key, value] pairs.", node) + guardedSet(out, String(pair[0]), pair[1]) + } + return out + } + default: + throw new InterpreterRuntimeError(`Object.${name} is not available in CodeMode.`, node) + } +} + +const invokeMathMethod = (name: string, args: Array, node: AstNode): number => { + const nums = args.map((arg) => { + if (typeof arg !== "number") throw new InterpreterRuntimeError(`Math.${name} expects number arguments.`, node) + return arg + }) + const [a = Number.NaN, b = Number.NaN] = nums + switch (name) { + case "max": + return Math.max(...nums) + case "min": + return Math.min(...nums) + case "abs": + return Math.abs(a) + case "floor": + return Math.floor(a) + case "ceil": + return Math.ceil(a) + case "round": + return Math.round(a) + case "trunc": + return Math.trunc(a) + case "sign": + return Math.sign(a) + case "sqrt": + return Math.sqrt(a) + case "cbrt": + return Math.cbrt(a) + case "pow": + return Math.pow(a, b) + case "hypot": + return Math.hypot(...nums) + case "log": + return Math.log(a) + case "log2": + return Math.log2(a) + case "log10": + return Math.log10(a) + case "exp": + return Math.exp(a) + default: + throw new InterpreterRuntimeError(`Math.${name} is not available in CodeMode.`, node) + } +} + +const invokeJsonMethod = (name: string, args: Array, node: AstNode): unknown => { + switch (name) { + case "stringify": { + const replacer = args[1] + if (Array.isArray(replacer) || replacer instanceof CodeModeFunction) { + throw new InterpreterRuntimeError( + "JSON.stringify replacers are not supported in CodeMode.", + node, + "UnsupportedSyntax", + [supportedSyntaxMessage], + ) + } + const space = args[2] + const indent = typeof space === "number" || typeof space === "string" ? space : undefined + // copyIn first so only Data Values serialize, never a CodeModeFunction/ToolReference. + return JSON.stringify(copyOut(copyIn(args[0], "JSON.stringify value")), null, indent) + } + case "parse": { + const text = args[0] + if (typeof text !== "string") throw new InterpreterRuntimeError("JSON.parse expects a string.", node) + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch (error) { + // The engine reason is derived from the program-supplied string (token/position), so + // it is safe to surface - and the position is exactly what a model needs to fix it. + throw new InterpreterRuntimeError( + `JSON.parse received invalid JSON: ${error instanceof Error ? error.message : String(error)}`, + node, + ).as("SyntaxError") + } + return copyIn(parsed, "JSON.parse result") + } + default: + throw new InterpreterRuntimeError(`JSON.${name} is not available in CodeMode.`, node) + } +} + +const invokeArrayStatic = (name: string, args: Array, node: AstNode): unknown => { + switch (name) { + case "isArray": + return Array.isArray(args[0]) + case "of": + return [...args] + case "from": { + if (args.length > 1) { + throw new InterpreterRuntimeError( + "Array.from(...) does not support a map function in CodeMode; call .map() on the result instead.", + node, + "UnsupportedSyntax", + [supportedSyntaxMessage], + ) + } + // Map/Set materialize directly (the data checkpoint would serialize them to {}). + if (args[0] instanceof SandboxMap) + return Array.from((args[0] as SandboxMap).map.entries(), ([key, item]) => [key, item]) + if (args[0] instanceof SandboxSet) return Array.from((args[0] as SandboxSet).set.values()) + const source = boundedData(args[0], "Array.from input") + if (typeof source === "string") return Array.from(source) + if (Array.isArray(source)) return [...source] + if ( + source !== null && + typeof source === "object" && + typeof (source as { length?: unknown }).length === "number" + ) { + return Array.from(source as ArrayLike) + } + throw new InterpreterRuntimeError("Array.from expects an array, string, Map, Set, or array-like value.", node) + } + default: + throw new InterpreterRuntimeError(`Array.${name} is not available in CodeMode.`, node) + } +} + +const invokeNumberStatic = (name: string, args: Array, node: AstNode): unknown => { + const value = args[0] + switch (name) { + case "isInteger": + return Number.isInteger(value) + case "isFinite": + return Number.isFinite(value) + case "isNaN": + return Number.isNaN(value) + case "isSafeInteger": + return Number.isSafeInteger(value) + case "parseInt": { + const radix = args[1] + if (radix !== undefined && typeof radix !== "number") + throw new InterpreterRuntimeError("Number.parseInt expects a numeric radix.", node) + return parseInt(coerceToString(value), radix) + } + case "parseFloat": + return parseFloat(coerceToString(value)) + default: + throw new InterpreterRuntimeError(`Number.${name} is not available in CodeMode.`, node) + } +} + +const invokeStringStatic = (name: string, args: Array, node: AstNode): unknown => { + const codes = args.map((arg) => { + if (typeof arg !== "number") throw new InterpreterRuntimeError(`String.${name} expects number arguments.`, node) + return arg + }) + switch (name) { + case "fromCharCode": + return String.fromCharCode(...codes) + case "fromCodePoint": + return String.fromCodePoint(...codes) + default: + throw new InterpreterRuntimeError(`String.${name} is not available in CodeMode.`, node) + } +} + +const invokeDateStatic = (name: string, args: Array, node: AstNode): number => { + switch (name) { + case "now": + return Date.now() + case "parse": + return Date.parse(coerceToString(args[0])) + case "UTC": { + const parts = args.map((arg) => coerceToNumber(arg)) + return Date.UTC(...(parts as Parameters)) + } + default: + throw new InterpreterRuntimeError(`Date.${name} is not available in CodeMode.`, node) + } +} + +const invokeDateMethod = (value: SandboxDate, name: string, node: AstNode): unknown => { + const hosted = new Date(value.time) + switch (name) { + case "getTime": + case "valueOf": + return value.time + case "toISOString": { + if (!Number.isFinite(value.time)) throw new InterpreterRuntimeError("Invalid time value.", node) + return hosted.toISOString() + } + // toJSON of an invalid date is null in JS (never a throw); toString stays ISO for + // determinism across host timezones/locales. + case "toJSON": + return Number.isFinite(value.time) ? hosted.toISOString() : null + case "toString": + return coerceToString(value) + case "getFullYear": + return hosted.getFullYear() + case "getMonth": + return hosted.getMonth() + case "getDate": + return hosted.getDate() + case "getDay": + return hosted.getDay() + case "getHours": + return hosted.getHours() + case "getMinutes": + return hosted.getMinutes() + case "getSeconds": + return hosted.getSeconds() + case "getMilliseconds": + return hosted.getMilliseconds() + case "getUTCFullYear": + return hosted.getUTCFullYear() + case "getUTCMonth": + return hosted.getUTCMonth() + case "getUTCDate": + return hosted.getUTCDate() + case "getUTCDay": + return hosted.getUTCDay() + case "getUTCHours": + return hosted.getUTCHours() + case "getUTCMinutes": + return hosted.getUTCMinutes() + case "getUTCSeconds": + return hosted.getUTCSeconds() + case "getUTCMilliseconds": + return hosted.getUTCMilliseconds() + case "getTimezoneOffset": + return hosted.getTimezoneOffset() + default: + throw new InterpreterRuntimeError(`Date method '${name}' is not available in CodeMode.`, node) + } +} + +const invokeRegExpMethod = (value: SandboxRegExp, name: string, args: Array, node: AstNode): unknown => { + switch (name) { + // test/exec run on the sandbox regex's own host instance, so `g`-flag lastIndex advances + // across calls per the spec. + case "test": + return value.regex.test(coerceToString(args[0])) + case "exec": { + const matched = value.regex.exec(coerceToString(args[0])) + if (matched === null) return null + return matchToValue(matched) + } + case "toString": + return coerceToString(value) + default: + throw new InterpreterRuntimeError(`RegExp method '${name}' is not available in CodeMode.`, node) + } +} + +const invokeGlobalMethod = (ref: GlobalMethodReference, args: Array, node: AstNode): unknown => { + if (ref.namespace === "console") + throw new InterpreterRuntimeError(`console.${ref.name} is not available in CodeMode.`, node) + if (ref.namespace === "Object") return invokeObjectMethod(ref.name, args, node) + if (ref.namespace === "Math") return invokeMathMethod(ref.name, args, node) + if (ref.namespace === "Array") return invokeArrayStatic(ref.name, args, node) + if (ref.namespace === "Number") return invokeNumberStatic(ref.name, args, node) + if (ref.namespace === "String") return invokeStringStatic(ref.name, args, node) + if (ref.namespace === "Date") { + if (!dateStatics.has(ref.name)) + throw new InterpreterRuntimeError(`Date.${ref.name} is not available in CodeMode.`, node) + return invokeDateStatic(ref.name, args, node) + } + if (ref.namespace === "RegExp" || ref.namespace === "Map" || ref.namespace === "Set") { + throw new InterpreterRuntimeError(`${ref.namespace}.${ref.name} is not available in CodeMode.`, node) + } + return invokeJsonMethod(ref.name, args, node) +} + +// Iterable spread sources: arrays, strings (code points), Maps (entry pairs), and Sets (values). +const spreadItems = (spread: unknown): Array | undefined => { + if (Array.isArray(spread)) return spread + if (typeof spread === "string") return Array.from(spread) + if (spread instanceof SandboxMap) + return Array.from(spread.map.entries(), ([key, item]): Array => [key, item]) + if (spread instanceof SandboxSet) return Array.from(spread.set.values()) + return undefined +} + +// Every identifier a parameter pattern binds, used to seed TDZ slots before defaults run. +const collectPatternNames = (pattern: AstNode, out: Array = []): Array => { + switch (pattern.type) { + case "Identifier": + out.push(getString(pattern, "name")) + break + case "AssignmentPattern": + collectPatternNames(getNode(pattern, "left"), out) + break + case "RestElement": + collectPatternNames(getNode(pattern, "argument"), out) + break + case "ArrayPattern": + for (const element of getArray(pattern, "elements")) { + if (element !== null) collectPatternNames(asNode(element, "elements"), out) + } + break + case "ObjectPattern": + for (const property of getArray(pattern, "properties")) { + const prop = asNode(property, "properties") + collectPatternNames(prop.type === "RestElement" ? getNode(prop, "argument") : getNode(prop, "value"), out) + } + break + } + return out +} + +class Interpreter { + private scopes: Array> + private readonly invokeTool: (path: ReadonlyArray, args: Array) => Effect.Effect + // Enumerable namespace/tool names at a node of the host tool tree, threaded from + // ToolRuntime.make like invokeTool: the interpreter never holds the tree itself. + private readonly toolKeys: (path: ReadonlyArray) => ReadonlyArray + private readonly logs: Array + private lastValue: unknown + // Caps how many eagerly forked tool calls run at once (the parallel-call concurrency cap). + private readonly callPermits: Semaphore.Semaphore + // Fiber-backed promises whose settlement no program construct has observed yet. Successful + // program completion drains these (like a runtime waiting on in-flight work at exit) and + // surfaces a never-awaited failure as an unhandled-rejection diagnostic. + private readonly pendingSettlements = new Set() + + constructor( + invokeTool: (path: ReadonlyArray, args: Array) => Effect.Effect, + toolKeys: (path: ReadonlyArray) => ReadonlyArray, + logs: Array = [], + ) { + const globalScope = new Map() + this.scopes = [globalScope] + this.invokeTool = invokeTool + this.toolKeys = toolKeys + this.logs = logs + this.lastValue = undefined + this.callPermits = Semaphore.makeUnsafe(TOOL_CALL_CONCURRENCY) + globalScope.set("tools", { mutable: false, value: new ToolReference([]) }) + globalScope.set("Promise", { mutable: false, value: new PromiseNamespace() }) + globalScope.set("undefined", { mutable: false, value: undefined }) + globalScope.set("Object", { mutable: false, value: new GlobalNamespace("Object") }) + globalScope.set("Math", { mutable: false, value: new GlobalNamespace("Math") }) + globalScope.set("JSON", { mutable: false, value: new GlobalNamespace("JSON") }) + globalScope.set("Number", { mutable: false, value: new CoercionFunction("Number") }) + globalScope.set("String", { mutable: false, value: new CoercionFunction("String") }) + globalScope.set("Boolean", { mutable: false, value: new CoercionFunction("Boolean") }) + globalScope.set("Array", { mutable: false, value: new GlobalNamespace("Array") }) + globalScope.set("console", { mutable: false, value: new GlobalNamespace("console") }) + globalScope.set("parseInt", { mutable: false, value: new CoercionFunction("parseInt") }) + globalScope.set("parseFloat", { mutable: false, value: new CoercionFunction("parseFloat") }) + globalScope.set("Date", { mutable: false, value: new GlobalNamespace("Date") }) + globalScope.set("RegExp", { mutable: false, value: new GlobalNamespace("RegExp") }) + globalScope.set("Map", { mutable: false, value: new GlobalNamespace("Map") }) + globalScope.set("Set", { mutable: false, value: new GlobalNamespace("Set") }) + // Error constructors are real values, so `x instanceof Error` works and `Error("msg")` + // (with or without `new`) constructs a branded { name, message } error object. + for (const name of errorConstructors) { + globalScope.set(name, { mutable: false, value: new ErrorConstructorReference(name) }) + } + // NaN/Infinity flow as ordinary in-sandbox values (normalized to null only at the data + // boundary - see copyOut), so their global bindings must exist too, e.g. `reduce(max, -Infinity)`. + globalScope.set("NaN", { mutable: false, value: NaN }) + globalScope.set("Infinity", { mutable: false, value: Infinity }) + } + + run(program: ProgramNode): Effect.Effect { + const self = this + // Run the program body in its own module scope on top of the builtin global scope, so + // top-level declarations (`let undefined = 5`, `const Object = ...`) shadow builtins like + // JS module scope, instead of colliding with the seeded globals. + this.pushScope() + return Effect.gen(function* () { + self.hoistFunctions(program.body) + let value: unknown = undefined + let returned = false + for (const statement of program.body) { + const result = yield* self.evaluateStatement(statement) + + if (result.kind === "return") { + value = result.value + returned = true + break + } + + if (result.kind === "break" || result.kind === "continue") { + throw new InterpreterRuntimeError(`Unexpected '${result.kind}' outside of a loop.`, statement) + } + + if (result.kind === "value") { + self.lastValue = result.value + } + } + if (!returned) value = self.lastValue + + // The program body runs inside an implicit async function, so a returned promise + // resolves before crossing the data boundary - `return tools.ns.tool(...)` works + // without an explicit await, exactly as in JS. + if (value instanceof SandboxPromise) value = yield* self.settlePromise(value) + yield* self.drainPendingSettlements() + return value + }).pipe(Effect.ensuring(Effect.sync(() => self.popScope()))) + } + + // Awaits every fiber-backed promise the program abandoned (fire-and-forget tool calls), so + // their work completes before the execution ends - mirroring a JS runtime waiting on + // in-flight I/O at exit. A failure nobody could have handled becomes an unhandled-rejection + // diagnostic (interrupted calls, e.g. Promise.race losers, are ignored). + private drainPendingSettlements(): Effect.Effect { + const self = this + return Effect.gen(function* () { + for (const promise of [...self.pendingSettlements]) { + const exit = yield* self.observePromise(promise) + if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) continue + const failure = normalizeError(Cause.squash(exit.cause)) + throw new InterpreterRuntimeError( + `Unhandled rejection from an un-awaited tool call: ${failure.message}`, + undefined, + failure.kind, + ["Await tool calls - `const result = await tools.ns.tool(...)` - so failures can be caught and handled."], + ) + } + }) + } + + // Eagerly starts a tool call on a supervised child fiber (so the execution timeout and + // scope teardown interrupt it) gated by the concurrency semaphore, and wraps the fiber in a + // first-class promise value. `startImmediately` makes the runtime admit the call - charging + // the tool-call budget and firing onToolCallStart - at the call site, before any await. + private createToolCallPromise( + path: ReadonlyArray, + args: Array, + ): Effect.Effect { + const self = this + return Effect.map( + Effect.forkChild(this.callPermits.withPermit(Effect.suspend(() => self.invokeTool(path, args))), { + startImmediately: true, + }), + (fiber) => { + const promise = new SandboxPromise(fiber) + self.pendingSettlements.add(promise) + return promise + }, + ) + } + + // The promise's settlement as an Exit, marking it observed for unhandled-rejection tracking. + // Fiber settlement is idempotent, so observing the same promise repeatedly (await twice, + // Promise.all([p, p])) never re-runs the underlying call. + private observePromise(promise: SandboxPromise): Effect.Effect> { + this.pendingSettlements.delete(promise) + return promise.fiber !== undefined ? Fiber.await(promise.fiber) : Effect.exit(promise.immediate ?? Effect.void) + } + + // `await promise`: succeed with the fulfilled value or re-raise the failure so try/catch + // observes it exactly like a synchronous throw at the await site. + private settlePromise(promise: SandboxPromise, node?: AstNode): Effect.Effect { + const self = this + return Effect.flatMap(this.observePromise(promise), (exit) => self.unwrapPromiseExit(promise, exit, node)) + } + + private unwrapPromiseExit( + promise: SandboxPromise | undefined, + exit: Exit.Exit, + node?: AstNode, + ): Effect.Effect { + if (Exit.isSuccess(exit)) return Effect.succeed(exit.value) + // A call Promise.race interrupted after losing settles as a catchable program failure; + // any other interruption is execution teardown (timeout/host) and must keep propagating + // as interruption rather than becoming program-visible data. + if (promise?.interrupted === true && Cause.hasInterruptsOnly(exit.cause)) { + return Effect.fail( + new InterpreterRuntimeError( + "This tool call was interrupted because another value settled a Promise.race first.", + node, + ), + ) + } + return Effect.failCause(exit.cause) + } + + private evaluateStatement(node: AstNode): Effect.Effect { + switch (node.type) { + case "ExpressionStatement": + return Effect.map(this.evaluateExpression(getNode(node, "expression")), (value) => ({ kind: "value", value })) + case "VariableDeclaration": + return Effect.map(this.evaluateVariableDeclaration(node), () => ({ kind: "none" })) + case "ReturnStatement": { + const argumentNode = getOptionalNode(node, "argument") + return argumentNode + ? Effect.map(this.evaluateExpression(argumentNode), (value) => ({ kind: "return", value })) + : Effect.succeed({ kind: "return", value: undefined }) + } + case "BlockStatement": + return this.evaluateBlock(node) + case "IfStatement": + return this.evaluateIfStatement(node) + case "SwitchStatement": + return this.evaluateSwitchStatement(node) + case "WhileStatement": + return this.evaluateWhileStatement(node) + case "DoWhileStatement": + return this.evaluateDoWhileStatement(node) + case "ForStatement": + return this.evaluateForStatement(node) + case "ForOfStatement": + return this.evaluateForOfStatement(node) + case "ForInStatement": + return this.evaluateForInStatement(node) + case "BreakStatement": + return Effect.succeed(this.evaluateBreakStatement(node)) + case "ContinueStatement": + return Effect.succeed(this.evaluateContinueStatement(node)) + case "ThrowStatement": + return this.evaluateThrowStatement(node) + case "TryStatement": + return this.evaluateTryStatement(node) + case "EmptyStatement": + return Effect.succeed({ kind: "none" }) + case "FunctionDeclaration": + return Effect.succeed({ kind: "none" }) // bound ahead of time by hoistFunctions + default: + throw unsupportedSyntax(node.type, node) + } + } + + private evaluateBlock(node: AstNode): Effect.Effect { + this.pushScope() + const self = this + return Effect.gen(function* () { + const body = getArray(node, "body") + self.hoistFunctions(body) + + for (const statementValue of body) { + const statement = asNode(statementValue, "body") + const result = yield* self.evaluateStatement(statement) + + if (result.kind === "value") { + self.lastValue = result.value + continue + } + + if (result.kind !== "none") { + return result + } + } + + return { kind: "none" } satisfies StatementResult + }).pipe(Effect.ensuring(Effect.sync(() => self.popScope()))) + } + + private createFunction(node: AstNode): CodeModeFunction { + if (node.generator === true) { + throw new InterpreterRuntimeError( + "Generator functions are not supported in CodeMode.", + node, + "UnsupportedSyntax", + [supportedSyntaxMessage], + ) + } + return new CodeModeFunction( + getArray(node, "params").map((parameter, index) => asNode(parameter, `params[${index}]`)), + getNode(node, "body"), + this.scopes.slice(), + ) + } + + // Function declarations are hoisted: bound in their scope before the body runs, so a + // program can call a helper defined further down (matching JavaScript). + private hoistFunctions(statements: Array): void { + for (const statementValue of statements) { + if (!isRecord(statementValue) || statementValue.type !== "FunctionDeclaration") continue + const node = statementValue as AstNode + this.declare(getString(getNode(node, "id"), "name"), this.createFunction(node), true, node) + } + } + + private evaluateIfStatement(node: AstNode): Effect.Effect { + const testNode = getNode(node, "test") + const consequentNode = getNode(node, "consequent") + const alternateNode = getOptionalNode(node, "alternate") + + return Effect.flatMap(this.evaluateExpression(testNode), (test) => + test + ? this.evaluateStatement(consequentNode) + : alternateNode + ? this.evaluateStatement(alternateNode) + : Effect.succeed({ kind: "none" }), + ) + } + + private evaluateSwitchStatement(node: AstNode): Effect.Effect { + const self = this + this.pushScope() + return Effect.gen(function* () { + const discriminant = yield* self.evaluateExpression(getNode(node, "discriminant")) + if (containsOpaqueReference(discriminant)) { + throw new InterpreterRuntimeError( + "Switch discriminants must be data values in CodeMode.", + node, + "InvalidDataValue", + ) + } + const cases = getArray(node, "cases").map((value, index) => asNode(value, `cases[${index}]`)) + let defaultIndex: number | undefined + let selected: number | undefined + for (const [index, branch] of cases.entries()) { + const test = getOptionalNode(branch, "test") + if (!test) { + defaultIndex = index + continue + } + const candidate = yield* self.evaluateExpression(test) + if (containsOpaqueReference(candidate)) { + throw new InterpreterRuntimeError( + "Switch case values must be data values in CodeMode.", + test, + "InvalidDataValue", + ) + } + if (candidate === discriminant) { + selected = index + break + } + } + const start = selected ?? defaultIndex + if (start === undefined) return { kind: "none" } satisfies StatementResult + for (let index = start; index < cases.length; index += 1) { + for (const statementValue of getArray(cases[index]!, "consequent")) { + const result = yield* self.evaluateStatement(asNode(statementValue, "consequent")) + if (result.kind === "break") return { kind: "none" } satisfies StatementResult + if (result.kind === "return" || result.kind === "continue") return result + if (result.kind === "value") self.lastValue = result.value + } + } + return { kind: "none" } satisfies StatementResult + }).pipe(Effect.ensuring(Effect.sync(() => self.popScope()))) + } + + private evaluateWhileStatement(node: AstNode): Effect.Effect { + const testNode = getNode(node, "test") + const bodyNode = getNode(node, "body") + + const self = this + return Effect.gen(function* () { + while (yield* self.evaluateExpression(testNode)) { + const result = yield* self.evaluateStatement(bodyNode) + + if (result.kind === "continue") { + continue + } + + if (result.kind === "break") { + return { kind: "none" } satisfies StatementResult + } + + if (result.kind === "return") { + return result + } + + if (result.kind === "value") { + self.lastValue = result.value + } + } + + return { kind: "none" } satisfies StatementResult + }) + } + + private evaluateDoWhileStatement(node: AstNode): Effect.Effect { + const bodyNode = getNode(node, "body") + const testNode = getNode(node, "test") + + const self = this + return Effect.gen(function* () { + do { + const result = yield* self.evaluateStatement(bodyNode) + + if (result.kind === "continue") { + continue + } + + if (result.kind === "break") { + return { kind: "none" } satisfies StatementResult + } + + if (result.kind === "return") { + return result + } + + if (result.kind === "value") { + self.lastValue = result.value + } + } while (yield* self.evaluateExpression(testNode)) + + return { kind: "none" } satisfies StatementResult + }) + } + + private evaluateForStatement(node: AstNode): Effect.Effect { + this.pushScope() + const self = this + return Effect.gen(function* () { + const initNode = getOptionalNode(node, "init") + const testNode = getOptionalNode(node, "test") + const updateNode = getOptionalNode(node, "update") + const bodyNode = getNode(node, "body") + + if (initNode) { + if (initNode.type === "VariableDeclaration") { + yield* self.evaluateVariableDeclaration(initNode) + } else { + yield* self.evaluateExpression(initNode) + } + } + + const perIterationBindings = + initNode?.type === "VariableDeclaration" && getString(initNode, "kind") !== "var" + ? Array.from(self.currentScope().keys()) + : [] + + while (testNode ? yield* self.evaluateExpression(testNode) : true) { + let iterationScope: Map | undefined + if (perIterationBindings.length > 0) { + iterationScope = new Map( + perIterationBindings.map((name) => { + const binding = self.currentScope().get(name)! + return [name, { ...binding }] + }), + ) + self.scopes.push(iterationScope) + } + const result = yield* self.evaluateStatement(bodyNode).pipe( + Effect.ensuring( + Effect.sync(() => { + if (iterationScope) self.popScope() + }), + ), + ) + + if (result.kind === "return") { + return result + } + + if (result.kind === "break") { + return { kind: "none" } satisfies StatementResult + } + + if (result.kind === "value") { + self.lastValue = result.value + } + + if (iterationScope) { + const loopScope = self.currentScope() + for (const name of perIterationBindings) { + loopScope.set(name, { ...iterationScope.get(name)! }) + } + } + + if (updateNode) { + yield* self.evaluateExpression(updateNode) + } + + if (result.kind === "continue") { + continue + } + } + + return { kind: "none" } satisfies StatementResult + }).pipe(Effect.ensuring(Effect.sync(() => self.popScope()))) + } + + private evaluateForOfStatement(node: AstNode): Effect.Effect { + if (getBoolean(node, "await")) { + throw new InterpreterRuntimeError("for await...of is not supported.", node) + } + + const self = this + return Effect.gen(function* () { + const left = getNode(node, "left") + const right = yield* self.evaluateExpression(getNode(node, "right")) + const body = getNode(node, "body") + + // Arrays iterate in place; strings iterate code points; Maps iterate [key, value] + // pairs and Sets iterate values over a snapshot (mutation during iteration is safe). + const iterable = Array.isArray(right) ? right : spreadItems(right) + if (iterable === undefined) { + throw new InterpreterRuntimeError("for...of requires an array, string, Map, or Set value in CodeMode.", node) + } + + let declaration: { readonly pattern: AstNode; readonly mutable: boolean } | undefined + let assignmentName: string | undefined + + if (left.type === "VariableDeclaration") { + const declarations = getArray(left, "declarations") + if (declarations.length !== 1) { + throw new InterpreterRuntimeError("for...of supports one declared binding.", left) + } + + const declarator = asNode(declarations[0], "declarations[0]") + declaration = { pattern: getNode(declarator, "id"), mutable: getString(left, "kind") !== "const" } + } else if (left.type === "Identifier") { + assignmentName = getString(left, "name") + } else { + throw new InterpreterRuntimeError("Unsupported for...of binding.", left) + } + + for (const value of iterable) { + if (declaration) { + self.pushScope() + yield* self.declarePattern(declaration.pattern, value, declaration.mutable, left) + } else if (assignmentName) { + self.setIdentifierValue(assignmentName, value, left) + } + + const result = yield* self.evaluateStatement(body).pipe( + Effect.ensuring( + Effect.sync(() => { + if (declaration) self.popScope() + }), + ), + ) + + if (result.kind === "return") { + return result + } + + if (result.kind === "break") { + return { kind: "none" } + } + + if (result.kind === "value") { + self.lastValue = result.value + } + + if (result.kind === "continue") { + continue + } + } + + return { kind: "none" } + }) + } + + // Own enumerable string keys of a value, shared by `for...in` and `Object.keys` over tool + // references: plain data objects enumerate their own keys, arrays their index strings (plus + // any own non-index properties, e.g. match results' index/groups - exactly Object.keys in + // JS), and a tool reference the namespace/tool names at its path in the host tool tree. + // Returns undefined for everything else so callers can raise a contextual error. + private enumerableKeys(value: unknown): Array | undefined { + if (value instanceof ToolReference) { + return [...this.toolKeys(value.path)] + } + if (Array.isArray(value)) { + return Object.keys(value) + } + if (value !== null && typeof value === "object" && !isRuntimeReference(value)) { + return Object.keys(value) + } + return undefined + } + + private evaluateForInStatement(node: AstNode): Effect.Effect { + const self = this + return Effect.gen(function* () { + const left = getNode(node, "left") + const right = yield* self.evaluateExpression(getNode(node, "right")) + const body = getNode(node, "body") + + // Keys are snapshotted up front (mutation during iteration is safe): plain objects + // enumerate their own keys, arrays their index strings, and tool references the + // namespace/tool names at that node - the same enumeration Object.keys performs. + // Anything else (strings, Maps, Sets, numbers, null, ...) is a deliberate error rather + // than real JS's surprising behavior (indices for strings, zero iterations for + // Maps/Sets/null): the hint points at the constructs that do what the program means. + const keys = self.enumerableKeys(right) + if (keys === undefined) { + throw new InterpreterRuntimeError( + "for...in requires a plain object, array, or tools reference in CodeMode. Use for...of for arrays/strings/Maps/Sets, or Object.keys(value) for a key list.", + node, + ) + } + + let declaration: { readonly pattern: AstNode; readonly mutable: boolean } | undefined + let assignmentName: string | undefined + + if (left.type === "VariableDeclaration") { + const declarations = getArray(left, "declarations") + if (declarations.length !== 1) { + throw new InterpreterRuntimeError("for...in supports one declared binding.", left) + } + + const declarator = asNode(declarations[0], "declarations[0]") + declaration = { pattern: getNode(declarator, "id"), mutable: getString(left, "kind") !== "const" } + } else if (left.type === "Identifier") { + assignmentName = getString(left, "name") + } else { + throw new InterpreterRuntimeError("Unsupported for...in binding.", left) + } + + for (const key of keys) { + if (declaration) { + self.pushScope() + yield* self.declarePattern(declaration.pattern, key, declaration.mutable, left) + } else if (assignmentName) { + self.setIdentifierValue(assignmentName, key, left) + } + + const result = yield* self.evaluateStatement(body).pipe( + Effect.ensuring( + Effect.sync(() => { + if (declaration) self.popScope() + }), + ), + ) + + if (result.kind === "return") { + return result + } + + if (result.kind === "break") { + return { kind: "none" } + } + + if (result.kind === "value") { + self.lastValue = result.value + } + + if (result.kind === "continue") { + continue + } + } + + return { kind: "none" } + }) + } + + private evaluateBreakStatement(node: AstNode): StatementResult { + const labelNode = getOptionalNode(node, "label") + + if (labelNode) { + throw new InterpreterRuntimeError("Labeled break is not supported in v1.", node) + } + + return { kind: "break" } + } + + private evaluateContinueStatement(node: AstNode): StatementResult { + const labelNode = getOptionalNode(node, "label") + + if (labelNode) { + throw new InterpreterRuntimeError("Labeled continue is not supported in v1.", node) + } + + return { kind: "continue" } + } + + private evaluateThrowStatement(node: AstNode): Effect.Effect { + const argument = getNode(node, "argument") + return Effect.flatMap(this.evaluateExpression(argument), (value) => Effect.fail(new ProgramThrow(value))) + } + + private evaluateTryStatement(node: AstNode): Effect.Effect { + const body = getNode(node, "block") + const handler = getOptionalNode(node, "handler") + const finalizer = getOptionalNode(node, "finalizer") + const self = this + + const attempted = Effect.matchCauseEffect(this.evaluateStatement(body), { + onFailure: (cause) => { + if (cause.reasons.some(Cause.isInterruptReason) || !handler) { + return Effect.failCause(cause) + } + + // The program sees a plain { message } error (or the thrown value itself) - see + // caughtErrorValue, shared with Promise.allSettled rejection reasons. + const caught = caughtErrorValue(Cause.squash(cause)) + const parameter = getOptionalNode(handler, "param") + self.pushScope() + return Effect.gen(function* () { + if (parameter) yield* self.declarePattern(parameter, caught, true, handler) + return yield* self.evaluateStatement(getNode(handler, "body")) + }).pipe(Effect.ensuring(Effect.sync(() => self.popScope()))) + }, + onSuccess: Effect.succeed, + }) + + if (!finalizer) return attempted + + const isAbrupt = (result: StatementResult): boolean => + result.kind === "return" || result.kind === "break" || result.kind === "continue" + + return Effect.matchCauseEffect(attempted, { + onFailure: (cause) => + cause.reasons.some(Cause.isInterruptReason) + ? Effect.failCause(cause) + : Effect.flatMap(this.evaluateStatement(finalizer), (final) => + isAbrupt(final) ? Effect.succeed(final) : Effect.failCause(cause), + ), + onSuccess: (result) => + Effect.flatMap(this.evaluateStatement(finalizer), (final) => + isAbrupt(final) ? Effect.succeed(final) : Effect.succeed(result), + ), + }) + } + + private evaluateVariableDeclaration(node: AstNode): Effect.Effect { + const kind = getString(node, "kind") + const declarations = getArray(node, "declarations") + const self = this + return Effect.gen(function* () { + for (const declarationValue of declarations) { + const declaration = asNode(declarationValue, "declarations") + + if (declaration.type !== "VariableDeclarator") { + throw new InterpreterRuntimeError("Unsupported variable declaration shape.", declaration) + } + + const init = getOptionalNode(declaration, "init") + const value = init ? yield* self.evaluateExpression(init) : undefined + yield* self.declarePattern(getNode(declaration, "id"), value, kind !== "const", declaration) + } + }) + } + + private declarePattern( + pattern: AstNode, + value: unknown, + mutable: boolean, + node: AstNode, + ): Effect.Effect { + const self = this + return Effect.gen(function* () { + if (pattern.type === "Identifier") { + self.declare(getString(pattern, "name"), value, mutable, node) + return + } + + // Default values: `x = expr` / `{ a = 1 }` - the default is evaluated only when the value is undefined. + if (pattern.type === "AssignmentPattern") { + const resolved = value === undefined ? yield* self.evaluateExpression(getNode(pattern, "right")) : value + yield* self.declarePattern(getNode(pattern, "left"), resolved, mutable, node) + return + } + + if (pattern.type === "ObjectPattern") { + if (value === null || typeof value !== "object" || Array.isArray(value) || isRuntimeReference(value)) { + throw new InterpreterRuntimeError( + "Object destructuring requires a data object value.", + pattern, + "InvalidDataValue", + ) + } + + const consumed = new Set() + for (const propertyValue of getArray(pattern, "properties")) { + const property = asNode(propertyValue, "properties") + + // Object rest: `{ a, ...others }` - gather the not-yet-consumed own keys. + if (property.type === "RestElement") { + const rest: SafeObject = Object.create(null) as SafeObject + for (const [key, item] of Object.entries(value as SafeObject)) { + if (!consumed.has(key) && !isBlockedMember(key)) rest[key] = item + } + yield* self.declarePattern(getNode(property, "argument"), rest, mutable, property) + continue + } + + if ( + property.type !== "Property" || + getBoolean(property, "computed") || + getString(property, "kind") !== "init" + ) { + throw new InterpreterRuntimeError("Only named object destructuring properties are supported.", property) + } + + const keyNode = getNode(property, "key") + const key = keyNode.type === "Identifier" ? getString(keyNode, "name") : String(keyNode.value) + if (isBlockedMember(key)) { + throw new InterpreterRuntimeError(`Property '${key}' is not available in CodeMode.`, keyNode) + } + consumed.add(key) + yield* self.declarePattern(getNode(property, "value"), (value as SafeObject)[key], mutable, property) + } + return + } + + if (pattern.type === "ArrayPattern") { + if (!Array.isArray(value)) { + throw new InterpreterRuntimeError("Array destructuring requires an array value.", pattern) + } + + for (const [index, item] of getArray(pattern, "elements").entries()) { + if (item === null) continue + const element = asNode(item, `elements[${index}]`) + // Array rest: `[head, ...tail]` - binds the remaining elements (must be last). + if (element.type === "RestElement") { + yield* self.declarePattern(getNode(element, "argument"), value.slice(index), mutable, element) + break + } + yield* self.declarePattern(element, value[index], mutable, pattern) + } + return + } + + throw new InterpreterRuntimeError(`Unsupported binding pattern '${pattern.type}'.`, pattern) + }) + } + + private evaluateExpression(node: AstNode): Effect.Effect { + switch (node.type) { + case "Literal": { + // A regex literal parses as a Literal node carrying { pattern, flags }; construct the + // sandbox regex from those (the host `value` instance is never exposed). + const regex = node.regex + if (isRecord(regex) && typeof regex.pattern === "string") { + return Effect.sync(() => + this.constructRegExp([regex.pattern, typeof regex.flags === "string" ? regex.flags : ""], node), + ) + } + return Effect.sync(() => boundedData(node.value, "Literal")) + } + case "Identifier": + return Effect.sync(() => this.getIdentifierValue(getString(node, "name"), node)) + case "BinaryExpression": + return this.evaluateBinaryExpression(node) + case "LogicalExpression": + return this.evaluateLogicalExpression(node) + case "UnaryExpression": + return this.evaluateUnaryExpression(node) + case "AssignmentExpression": + return this.evaluateAssignmentExpression(node) + case "CallExpression": + return this.evaluateCallExpression(node) + case "ArrowFunctionExpression": + case "FunctionExpression": + return Effect.sync(() => this.createFunction(node)) + case "MemberExpression": + return this.readMember(node) + case "ChainExpression": + return Effect.map(this.evaluateExpression(getNode(node, "expression")), (value) => + value === OptionalShortCircuit ? undefined : value, + ) + case "ObjectExpression": + return this.evaluateObjectExpression(node) + case "ArrayExpression": + return this.evaluateArrayExpression(node) + case "TemplateLiteral": + return this.evaluateTemplateLiteral(node) + case "ConditionalExpression": + return this.evaluateConditionalExpression(node) + case "UpdateExpression": + return this.evaluateUpdateExpression(node) + case "AwaitExpression": { + // `await` resolves a promise value; awaiting anything else is a passthrough no-op, + // matching real JS semantics for non-thenables. + const self = this + return Effect.flatMap(this.evaluateExpression(getNode(node, "argument")), (value) => + value instanceof SandboxPromise ? self.settlePromise(value, node) : Effect.succeed(value), + ) + } + case "NewExpression": + return this.evaluateNewExpression(node) + default: + throw unsupportedSyntax(node.type, node) + } + } + + private evaluateNewExpression(node: AstNode): Effect.Effect { + const callee = getNode(node, "callee") + if (callee.type !== "Identifier") { + throw unsupportedSyntax("NewExpression", node) + } + const name = getString(callee, "name") + const argNodes = getArray(node, "arguments") + const self = this + if (name === "Promise") { + throw new InterpreterRuntimeError( + "new Promise(...) is not supported in CodeMode; tool calls already return promises - call the tool and await the result.", + node, + "UnsupportedSyntax", + [supportedSyntaxMessage], + ) + } + if (errorConstructors.has(name)) { + return Effect.gen(function* () { + const arg = + argNodes.length > 0 ? yield* self.evaluateExpression(asNode(argNodes[0], "arguments[0]")) : undefined + return createErrorValue(name, arg === undefined ? "" : coerceToString(arg)) + }) + } + if (valueConstructors.has(name)) { + return Effect.gen(function* () { + const args = yield* self.evaluateCallArguments(argNodes) + switch (name) { + case "Date": + return self.constructDate(args) + case "RegExp": + return self.constructRegExp(args, node) + case "Map": + return self.constructMap(args[0], node) + default: + return self.constructSet(args[0], node) + } + }) + } + throw unsupportedSyntax("NewExpression", node) + } + + private constructDate(args: Array): SandboxDate { + if (args.length === 0) return new SandboxDate(Date.now()) + if (args.length === 1) { + const arg = args[0] + if (arg instanceof SandboxDate) return new SandboxDate(arg.time) + if (typeof arg === "number") return new SandboxDate(new Date(arg).getTime()) + if (typeof arg === "string") return new SandboxDate(Date.parse(arg)) + return new SandboxDate(Number.NaN) + } + // new Date(year, month, day?, hours?, ...) - local-time component form. + const parts = args.map((arg) => coerceToNumber(arg)) + return new SandboxDate(new Date(...(parts as [number, number])).getTime()) + } + + private constructRegExp(args: Array, node: AstNode): SandboxRegExp { + const first = args[0] + const pattern = + first instanceof SandboxRegExp ? first.regex.source : first === undefined ? "" : coerceToString(first) + const flagsArg = args[1] + if (flagsArg !== undefined && typeof flagsArg !== "string") { + throw new InterpreterRuntimeError( + `RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`, + node, + ) + } + const flags = flagsArg ?? (first instanceof SandboxRegExp ? first.regex.flags : "") + try { + return new SandboxRegExp(pattern, flags) + } catch (error) { + // Say which part was rejected and how to fix it, instead of passing the engine + // message through bare. A flags failure names the flags; a pattern failure gets the + // escaping hint (the usual cause is an unescaped metacharacter in a built-up string). + const reason = regexFailureReason(error) + throw new InterpreterRuntimeError( + /flag/i.test(reason) + ? `new RegExp(...) received invalid flags ${JSON.stringify(flags)} (${reason}). Valid flags are d, g, i, m, s, u, v, and y.` + : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`, + node, + ).as("SyntaxError") + } + } + + private constructMap(init: unknown, node: AstNode): SandboxMap { + const target = new SandboxMap() + if (init === undefined || init === null) return target + const entries = Array.isArray(init) + ? init + : init instanceof SandboxMap + ? Array.from(init.map.entries(), ([key, item]): Array => [key, item]) + : undefined + if (entries === undefined) { + throw new InterpreterRuntimeError( + "new Map(...) expects an array of [key, value] pairs, a Map, or no argument.", + node, + ) + } + for (const pair of entries) { + if (!Array.isArray(pair)) { + throw new InterpreterRuntimeError("new Map(...) expects [key, value] pairs.", node) + } + target.map.set(pair[0], pair[1]) + } + return target + } + + private constructSet(init: unknown, node: AstNode): SandboxSet { + const target = new SandboxSet() + if (init === undefined || init === null) return target + const items = Array.isArray(init) + ? init + : init instanceof SandboxSet + ? Array.from(init.set.values()) + : typeof init === "string" + ? Array.from(init) + : undefined + if (items === undefined) { + throw new InterpreterRuntimeError("new Set(...) expects an array, Set, string, or no argument.", node) + } + for (const item of items) target.set.add(item) + return target + } + + private evaluateBinaryExpression(node: AstNode): Effect.Effect { + const operator = getString(node, "operator") + const self = this + return Effect.gen(function* () { + const lhs = yield* self.evaluateExpression(getNode(node, "left")) + const rhs = yield* self.evaluateExpression(getNode(node, "right")) + // Like `typeof`, `instanceof` observes any value without coercing it (a promise or + // function operand is a legitimate question, not an error), so it is handled before + // the data-only operand check. + if (operator === "instanceof") return instanceofValue(lhs, rhs, node) + return boundedData(self.applyBinaryOperator(operator, lhs, rhs, node), "Binary expression result") + }) + } + + /** + * Applies a binary operator to two already-evaluated operands with CodeMode's coercion + * semantics. Shared by binary expressions and compound assignment (`x op= y` must behave + * exactly like `x = x op y`, coercion included). + */ + private applyBinaryOperator(operator: string, lhs: unknown, rhs: unknown, node: AstNode): unknown { + if (containsOpaqueReference(lhs) || containsOpaqueReference(rhs)) { + throw new InterpreterRuntimeError("Binary operators require data values in CodeMode.", node, "InvalidDataValue") + } + // Data objects/arrays are null-prototype, so JS's ToPrimitive throws an opaque host + // "No default value" TypeError when an operator coerces them. Coerce to their JS string + // form first (as String(x) / template literals do) so operators behave like JavaScript. + // A Date follows its ToPrimitive hints: string for `+` (concatenation), its time value + // for arithmetic and ordering - so `end - start` and `a < b` work as in JS. + // Identity (=== / !==) and the right operand of `in` keep their raw object value. + const coerceOperand = (operand: unknown): unknown => { + if (operand instanceof SandboxDate) return operator === "+" ? coerceToString(operand) : operand.time + return operand !== null && typeof operand === "object" ? coerceToString(operand) : operand + } + const bothObjects = lhs !== null && typeof lhs === "object" && rhs !== null && typeof rhs === "object" + const l = coerceOperand(lhs) + const r = coerceOperand(rhs) + switch (operator) { + case "+": + return (l as string) + (r as string) + case "-": + return (l as number) - (r as number) + case "*": + return (l as number) * (r as number) + case "/": + return (l as number) / (r as number) + case "%": + return (l as number) % (r as number) + case "**": + return (l as number) ** (r as number) + // Two objects compare by identity in JS (no ToPrimitive); only object-vs-primitive coerces. + case "==": + return bothObjects ? lhs === rhs : l == r + case "===": + return lhs === rhs + case "!=": + return bothObjects ? lhs !== rhs : l != r + case "!==": + return lhs !== rhs + case "<": + return (l as string) < (r as string) + case "<=": + return (l as string) <= (r as string) + case ">": + return (l as string) > (r as string) + case ">=": + return (l as string) >= (r as string) + case "&": + return (l as number) & (r as number) + case "|": + return (l as number) | (r as number) + case "^": + return (l as number) ^ (r as number) + case "<<": + return (l as number) << (r as number) + case ">>": + return (l as number) >> (r as number) + case ">>>": + return (l as number) >>> (r as number) + case "in": + if (rhs === null || typeof rhs !== "object") { + throw new InterpreterRuntimeError("The 'in' operator requires a data object on the right-hand side.", node) + } + // Own properties only, so arrays don't leak the host Array.prototype (map/constructor/...). + return Object.hasOwn(rhs as object, coerceOperand(lhs) as PropertyKey) + default: + throw new InterpreterRuntimeError(`Unsupported binary operator '${operator}'.`, node) + } + } + + private evaluateLogicalExpression(node: AstNode): Effect.Effect { + const operator = getString(node, "operator") + return Effect.flatMap(this.evaluateExpression(getNode(node, "left")), (left) => { + if (operator === "&&") return left ? this.evaluateExpression(getNode(node, "right")) : Effect.succeed(left) + if (operator === "||") return left ? Effect.succeed(left) : this.evaluateExpression(getNode(node, "right")) + if (operator === "??") + return left !== null && left !== undefined + ? Effect.succeed(left) + : this.evaluateExpression(getNode(node, "right")) + throw new InterpreterRuntimeError(`Unsupported logical operator '${operator}'.`, node) + }) + } + + private evaluateUnaryExpression(node: AstNode): Effect.Effect { + const operator = getString(node, "operator") + const argument = getNode(node, "argument") + // `typeof undeclaredIdentifier` is `"undefined"` in JS (never a ReferenceError), so + // feature-detection guards like `typeof x !== "undefined"` don't crash. Short-circuit before + // evaluating the argument; a declared-but-TDZ binding still falls through to the normal throw. + if (operator === "typeof" && argument.type === "Identifier" && !this.resolveBinding(getString(argument, "name"))) { + return Effect.succeed("undefined") + } + return Effect.map(this.evaluateExpression(argument), (value) => { + // `typeof` and `!` never throw in JS - they observe any value (functions and runtime + // references included) without coercing it, so feature detection and negation work. + if (operator === "typeof") return typeofValue(value) + if (operator === "!") return !value + if (containsOpaqueReference(value)) { + throw new InterpreterRuntimeError("Unary operators require data values in CodeMode.", node, "InvalidDataValue") + } + // Numeric/bitwise unary operators ToPrimitive their operand; a Date yields its time value + // (`+date` is the epoch-ms idiom), other null-prototype data objects/arrays coerce to + // their JS string form first (see evaluateBinaryExpression). + const operand = + value instanceof SandboxDate + ? value.time + : value !== null && typeof value === "object" + ? coerceToString(value) + : value + let result: unknown + switch (operator) { + case "+": + result = +(operand as number) + break + case "-": + result = -(operand as number) + break + case "~": + result = ~(operand as number) + break + default: + throw new InterpreterRuntimeError(`Unsupported unary operator '${operator}'.`, node) + } + return boundedData(result, "Unary expression result") + }) + } + + private evaluateAssignmentExpression(node: AstNode): Effect.Effect { + const left = getNode(node, "left") + const operator = getString(node, "operator") + const self = this + return Effect.gen(function* () { + if (operator === "??=" || operator === "||=" || operator === "&&=") { + return yield* self.evaluateLogicalAssignment(node, left, operator) + } + const rightValue = yield* self.evaluateExpression(getNode(node, "right")) + if (left.type === "Identifier") { + const name = getString(left, "name") + if (operator === "=") return self.setIdentifierValue(name, rightValue, left) + const next = boundedData( + self.applyCompoundAssignment(operator, self.getIdentifierValue(name, left), rightValue, node), + "Assignment result", + ) + return self.setIdentifierValue(name, next, left) + } + if (left.type === "MemberExpression") { + if (operator === "=") return yield* self.writeMember(left, rightValue) + return yield* self.modifyMember(left, (current) => { + const next = boundedData( + self.applyCompoundAssignment(operator, current, rightValue, node), + "Assignment result", + ) + return Effect.succeed({ write: true, next, result: next }) + }) + } + throw new InterpreterRuntimeError("Assignment target must be an Identifier or MemberExpression.", left) + }) + } + + private evaluateLogicalAssignment( + node: AstNode, + left: AstNode, + operator: string, + ): Effect.Effect { + const self = this + const shouldAssign = (current: unknown): boolean => + operator === "??=" ? current === null || current === undefined : operator === "||=" ? !current : Boolean(current) + if (left.type === "Identifier") { + const name = getString(left, "name") + return Effect.gen(function* () { + const current = self.getIdentifierValue(name, left) + if (!shouldAssign(current)) return current + const rightValue = yield* self.evaluateExpression(getNode(node, "right")) + return self.setIdentifierValue(name, rightValue, left) + }) + } + if (left.type === "MemberExpression") { + // Resolve the member exactly once; evaluate the RHS only if we actually assign. + return self.modifyMember(left, (current) => + shouldAssign(current) + ? Effect.map(self.evaluateExpression(getNode(node, "right")), (rightValue) => ({ + write: true, + next: rightValue, + result: rightValue, + })) + : Effect.succeed({ write: false, next: current, result: current }), + ) + } + throw new InterpreterRuntimeError("Assignment target must be an Identifier or MemberExpression.", left) + } + + private evaluateUpdateExpression(node: AstNode): Effect.Effect { + const operator = getString(node, "operator") + const argument = getNode(node, "argument") + const prefix = getBoolean(node, "prefix") + + const increment = operator === "++" ? 1 : operator === "--" ? -1 : undefined + + if (increment === undefined) { + throw new InterpreterRuntimeError(`Unsupported update operator '${operator}'.`, node) + } + + if (argument.type === "Identifier") { + return Effect.sync(() => { + const name = getString(argument, "name") + const current = Number(this.getIdentifierValue(name, argument)) + const next = current + increment + this.setIdentifierValue(name, next, argument) + return prefix ? next : current + }) + } + + if (argument.type === "MemberExpression") { + return this.modifyMember(argument, (current) => { + const value = Number(current) + const next = value + increment + return Effect.succeed({ write: true, next, result: prefix ? next : value }) + }) + } + + throw new InterpreterRuntimeError("Update target must be an Identifier or MemberExpression.", argument) + } + + private evaluateCallExpression(node: AstNode): Effect.Effect { + const callee = getNode(node, "callee") + const argNodes = getArray(node, "arguments") + + const self = this + return Effect.gen(function* () { + const callable = yield* self.evaluateExpression(callee) + if (callable === OptionalShortCircuit) return OptionalShortCircuit + if ((callable === null || callable === undefined) && node.optional === true) return OptionalShortCircuit + + const args = yield* self.evaluateCallArguments(argNodes) + + if (callable instanceof ToolReference) { + if (callable.path.length === 0) throw new InterpreterRuntimeError("The tools root is not callable.", callee) + // An un-awaited tool call is a first-class promise value; the call itself starts now. + return yield* self.createToolCallPromise(callable.path, args) + } + if (callable instanceof PromiseMethodReference) { + return yield* self.invokePromiseMethod(callable, args, node) + } + if (callable instanceof CodeModeFunction) { + return yield* self.invokeFunction(callable, args) + } + if (callable instanceof IntrinsicReference) { + return yield* self.invokeIntrinsic(callable, args, node) + } + if (callable instanceof GlobalMethodReference) { + if (callable.namespace === "console") return self.invokeConsole(callable.name, args, node) + if (callable.namespace === "Object" && args[0] instanceof ToolReference) { + return self.invokeObjectMethodOnTools(callable.name, args[0] as ToolReference, node) + } + return boundedData(invokeGlobalMethod(callable, args, node), `${callable.namespace}.${callable.name} result`) + } + if (callable instanceof CoercionFunction) { + return boundedData(invokeCoercion(callable, args, node), `${callable.name} result`) + } + // `Error("msg")` without `new` constructs an error exactly like `new Error("msg")`, as in JS. + if (callable instanceof ErrorConstructorReference) { + return createErrorValue(callable.name, args[0] === undefined ? "" : coerceToString(args[0])) + } + throw new InterpreterRuntimeError("Only tools are callable in CodeMode.", callee) + }) + } + + // Object.* over a tool reference: `Object.keys(tools)` / `Object.keys(tools.ns)` enumerate + // namespace/tool names from the host tool tree - the discovery idiom a model reaches for + // first. Every other Object helper cannot produce data from a tool reference, so it fails + // with a pointer at the working idioms instead of the generic plain-objects-only message. + private invokeObjectMethodOnTools(name: string, ref: ToolReference, node: AstNode): unknown { + if (name === "keys") { + return boundedData(this.enumerableKeys(ref)!, "Object.keys result") + } + throw new InterpreterRuntimeError( + `Object.${name}(...) cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or tools.$codemode.search({ query }) for signatures.`, + node, + "InvalidDataValue", + ) + } + + private invokeConsole(name: string, args: Array, node: AstNode): undefined { + if (!consoleMethods.has(name)) + throw new InterpreterRuntimeError(`console.${name} is not available in CodeMode.`, node) + this.logs.push(publicErrorMessage(this.formatConsoleMessage(name, args, node))) + return undefined + } + + private formatConsoleMessage(name: string, args: Array, node: AstNode): string { + if (name === "dir") return args.length === 0 ? "undefined" : this.formatConsoleArgument(args[0]) + if (name === "table") return this.formatConsoleTable(args[0], args[1], node) + const prefix = name === "warn" ? "[warn] " : name === "error" ? "[error] " : name === "debug" ? "[debug] " : "" + return `${prefix}${args.map((arg) => this.formatConsoleArgument(arg)).join(" ")}` + } + + // Console arguments format deeply and totally: values render as a debugger would show them + // rather than as boundary JSON - numbers keep NaN/Infinity (JSON would say null), sandbox + // values keep their friendly forms at ANY depth (ISO date, /regex/flags, Map(n) [...], + // Set(n) [...]), opaque runtime references become "[CodeMode reference]" markers in place, + // and plain objects/arrays render JSON-style. Formatting never fails the program: cycles + // render "[Circular]" and extreme depth degrades to "...". + private formatConsoleArgument(value: unknown): string { + if (value === undefined) return "undefined" + // A top-level string prints bare; nested strings are JSON-quoted (see formatConsoleValue). + if (typeof value === "string") return value + return this.formatConsoleValue(value, new Set(), 0) + } + + private formatConsoleValue(value: unknown, seen: Set, depth: number): string { + // Nested undefined renders as null, matching what JSON boundary output would show. + if (value === null || value === undefined) return "null" + if (typeof value === "string") return JSON.stringify(value) + // String(value) keeps NaN/Infinity/-Infinity readable; finite numbers match their JSON form. + if (typeof value === "number" || typeof value === "boolean") return String(value) + if (typeof value !== "object") return String(value) + if (value instanceof SandboxPromise) return "[Promise (await it to get its value)]" + if (value instanceof SandboxDate) return coerceToString(value) + if (value instanceof SandboxRegExp) return coerceToString(value) + if (depth > MAX_CONSOLE_DEPTH) return "..." + if (seen.has(value)) return "[Circular]" + if (value instanceof SandboxMap) { + seen.add(value) + try { + const entries = Array.from(value.map.entries(), ([key, item]): Array => [key, item]) + return `Map(${value.map.size}) ${this.formatConsoleValue(entries, seen, depth + 1)}` + } finally { + seen.delete(value) + } + } + if (value instanceof SandboxSet) { + seen.add(value) + try { + return `Set(${value.set.size}) ${this.formatConsoleValue(Array.from(value.set.values()), seen, depth + 1)}` + } finally { + seen.delete(value) + } + } + if (isRuntimeReference(value)) return "[CodeMode reference]" + seen.add(value) + try { + if (Array.isArray(value)) { + return `[${value.map((item) => this.formatConsoleValue(item, seen, depth + 1)).join(",")}]` + } + return `{${Object.entries(value) + .map(([key, item]) => `${JSON.stringify(key)}:${this.formatConsoleValue(item, seen, depth + 1)}`) + .join(",")}}` + } finally { + seen.delete(value) + } + } + + private formatConsoleTable(value: unknown, columnsArgument: unknown, node: AstNode): string { + if (value === undefined) return "undefined" + // Sandbox values are legitimate table data (cells render their friendly forms); only + // truly opaque references (functions, tools, promises) collapse to the marker. + if (containsOpaqueReference(value)) return "[CodeMode reference]" + const data = boundedData(value, "console.table argument") + const columns = this.consoleTableColumns(columnsArgument, node) + const rows = this.consoleTableRows(data, columns) + const keys = columns ?? Array.from(new Set(rows.flatMap((row) => Object.keys(row.values)))) + const header = ["(index)", ...keys].join("\t") + return [ + header, + ...rows.map((row) => [row.index, ...keys.map((key) => this.formatConsoleTableCell(row.values[key]))].join("\t")), + ].join("\n") + } + + private consoleTableColumns(value: unknown, node: AstNode): ReadonlyArray | undefined { + if (value === undefined) return undefined + if (containsRuntimeReference(value)) return undefined + const columns = copyOut(copyIn(value, "console.table columns"), true) + return Array.isArray(columns) ? columns.map((column) => String(column)) : undefined + } + + private consoleTableRows( + data: unknown, + columns: ReadonlyArray | undefined, + ): Array<{ readonly index: string; readonly values: Record }> { + if (Array.isArray(data)) { + return data.map((item, index) => ({ index: String(index), values: this.consoleTableValues(item, columns) })) + } + if (data !== null && typeof data === "object" && !isSandboxValue(data)) { + return Object.entries(data).map(([index, item]) => ({ index, values: this.consoleTableValues(item, columns) })) + } + return [{ index: "0", values: { Value: data } }] + } + + private consoleTableValues(value: unknown, columns: ReadonlyArray | undefined): Record { + if (value !== null && typeof value === "object" && !Array.isArray(value) && !isSandboxValue(value)) { + const source = value as Record + if (columns !== undefined) return Object.fromEntries(columns.map((column) => [column, source[column]])) + return Object.fromEntries(Object.entries(source)) + } + return { Value: value } + } + + private formatConsoleTableCell(value: unknown): string { + if (value === undefined) return "" + if (typeof value === "string") return value + return this.formatConsoleValue(value, new Set(), 0) + } + + private evaluateCallArguments(argNodes: Array): Effect.Effect, unknown, R> { + const self = this + return Effect.gen(function* () { + const args: Array = [] + for (const [index, arg] of argNodes.entries()) { + const argNode = asNode(arg, `arguments[${index}]`) + if (argNode.type === "SpreadElement") { + const spread = yield* self.evaluateExpression(getNode(argNode, "argument")) + const items = spreadItems(spread) + if (items === undefined) + throw new InterpreterRuntimeError( + "Spread arguments require an array, string, Map, or Set in CodeMode.", + argNode, + ) + args.push(...items) + } else { + args.push(yield* self.evaluateExpression(argNode)) + } + } + return args + }) + } + + // Promise.* over ordinary runtime values. Combinators accept ANY array (or spreadable + // collection) mixing promise values and plain data - built inline, beforehand, via spread, + // whatever - because tool calls already run eagerly on their own fibers; the combinators + // only observe settlements. Joining is therefore sequential (no extra fibers) without + // costing parallelism, and the concurrency cap stays where the work is: the fork semaphore. + private invokePromiseMethod( + ref: PromiseMethodReference, + args: Array, + node: AstNode, + ): Effect.Effect { + const self = this + if (ref.name === "resolve") { + // Promise.resolve of a promise is that promise (JS flattens); anything else is a + // promise already fulfilled with the value. + const value = args[0] + return Effect.succeed( + value instanceof SandboxPromise ? value : new SandboxPromise(undefined, Effect.succeed(value)), + ) + } + if (ref.name === "reject") { + return Effect.sync(() => new SandboxPromise(undefined, Effect.fail(new ProgramThrow(args[0])))) + } + + const items = Array.isArray(args[0]) ? args[0] : spreadItems(args[0]) + if (items === undefined) { + throw new InterpreterRuntimeError( + `Promise.${ref.name} expects an array of promises or plain values (e.g. Promise.${ref.name}(items.map((item) => tools.ns.tool(item)))).`, + node, + ) + } + + switch (ref.name) { + case "all": { + // Mark every promise element observed up-front (Promise.all handles all of its + // members' failures, as in JS), then join in index order; the first failure rejects + // the whole call while unrelated in-flight members keep running. + const settles = items.map((item) => + item instanceof SandboxPromise ? this.settlePromise(item, node) : Effect.succeed(item), + ) + return Effect.gen(function* () { + const values: Array = [] + for (const settle of settles) values.push(yield* settle) + return values + }) + } + case "allSettled": { + const observations = items.map((item) => + item instanceof SandboxPromise + ? Effect.map(this.observePromise(item), (exit) => ({ promise: item as SandboxPromise | undefined, exit })) + : Effect.succeed({ promise: undefined as SandboxPromise | undefined, exit: Exit.succeed(item as unknown) }), + ) + return Effect.gen(function* () { + const outcomes: Array = [] + for (const observation of observations) { + const { exit, promise } = yield* observation + if (Exit.isSuccess(exit)) { + outcomes.push( + Object.assign(Object.create(null) as SafeObject, { status: "fulfilled", value: exit.value }), + ) + continue + } + const raceInterrupted = promise?.interrupted === true && Cause.hasInterruptsOnly(exit.cause) + if (Cause.hasInterruptsOnly(exit.cause) && !raceInterrupted) { + // Execution teardown (timeout/host interruption), not a program-level rejection. + return yield* Effect.failCause(exit.cause) + } + const thrown = raceInterrupted + ? new InterpreterRuntimeError( + "This tool call was interrupted because another value settled a Promise.race first.", + node, + ) + : Cause.squash(exit.cause) + outcomes.push( + Object.assign(Object.create(null) as SafeObject, { + status: "rejected", + reason: caughtErrorValue(thrown), + }), + ) + } + return outcomes + }) + } + case "race": { + if (items.length === 0) { + throw new InterpreterRuntimeError( + "Promise.race([]) would never settle; provide at least one promise or value.", + node, + ) + } + const observations = items.map((item, index) => + item instanceof SandboxPromise + ? Effect.map(this.observePromise(item), (exit) => ({ index, exit })) + : Effect.succeed({ index, exit: Exit.succeed(item as unknown) }), + ) + return Effect.gen(function* () { + // First settlement (fulfilled OR rejected) wins; the observations never fail, so + // racing them yields exactly that. Losing in-flight calls are then interrupted. + const winner = yield* Effect.raceAll(observations) + for (const [index, item] of items.entries()) { + if (index === winner.index || !(item instanceof SandboxPromise) || item.fiber === undefined) continue + item.interrupted = true + yield* Fiber.interrupt(item.fiber) + } + const winningItem = items[winner.index] + return yield* self.unwrapPromiseExit( + winningItem instanceof SandboxPromise ? winningItem : undefined, + winner.exit, + node, + ) + }) + } + } + } + + private invokeFunction(fn: CodeModeFunction, args: Array): Effect.Effect { + const self = this + return Effect.suspend(() => { + const savedScopes = self.scopes + self.scopes = [...fn.capturedScopes, new Map()] + const run = Effect.gen(function* () { + // Seed every parameter name into the scope as a TDZ slot first, so a default that + // references another parameter resolves to that (uninitialized) param rather than + // silently falling through to an outer binding of the same name - matching JS. + const paramScope = self.currentScope() + for (const parameter of fn.parameters) { + for (const name of collectPatternNames(parameter)) { + paramScope.set(name, { mutable: true, value: undefined, initialized: false }) + } + } + for (const [index, parameter] of fn.parameters.entries()) { + if (parameter.type === "RestElement") { + yield* self.declarePattern(getNode(parameter, "argument"), args.slice(index), true, parameter) + break + } + yield* self.declarePattern(parameter, args[index], true, parameter) + } + + if (fn.body.type === "BlockStatement") { + const result = yield* self.evaluateStatement(fn.body) + return result.kind === "return" || result.kind === "value" ? result.value : undefined + } + + return yield* self.evaluateExpression(fn.body) + }) + return run.pipe( + Effect.ensuring( + Effect.sync(() => { + self.scopes = savedScopes + }), + ), + ) + }) + } + + private invokeIntrinsic( + ref: IntrinsicReference, + args: Array, + node: AstNode, + ): Effect.Effect { + if (typeof ref.receiver === "string") { + return Effect.succeed(invokeStringMethod(ref.receiver, ref.name, args, node)) + } + if (typeof ref.receiver === "number") { + return Effect.succeed(invokeNumberMethod(ref.receiver, ref.name, args, node)) + } + if (Array.isArray(ref.receiver)) { + return this.invokeArrayMethod(ref.receiver, ref.name, args, node) + } + if (ref.receiver instanceof SandboxDate) { + return Effect.succeed(invokeDateMethod(ref.receiver, ref.name, node)) + } + if (ref.receiver instanceof SandboxRegExp) { + return Effect.succeed(invokeRegExpMethod(ref.receiver, ref.name, args, node)) + } + if (ref.receiver instanceof SandboxMap) { + return this.invokeMapMethod(ref.receiver, ref.name, args, node) + } + if (ref.receiver instanceof SandboxSet) { + return this.invokeSetMethod(ref.receiver, ref.name, args, node) + } + throw new InterpreterRuntimeError(`Method '${ref.name}' is not available in CodeMode.`, node) + } + + // Runs a Map/Set callback (forEach) accepting a user function or a builtin coercion, + // mirroring the array-method callback contract. + private applyCollectionCallback( + callback: unknown, + name: string, + node: AstNode, + ): (args: Array) => Effect.Effect { + if (!(callback instanceof CodeModeFunction) && !(callback instanceof CoercionFunction)) { + throw new InterpreterRuntimeError(`${name} expects a function callback.`, node) + } + return (callbackArgs) => + callback instanceof CoercionFunction + ? Effect.succeed(invokeCoercion(callback, callbackArgs, node)) + : this.invokeFunction(callback, callbackArgs) + } + + private invokeMapMethod( + target: SandboxMap, + name: string, + args: Array, + node: AstNode, + ): Effect.Effect { + switch (name) { + case "get": + return Effect.succeed(target.map.get(args[0])) + case "has": + return Effect.succeed(target.map.has(args[0])) + case "set": + return Effect.sync(() => { + target.map.set(args[0], args[1]) + return target + }) + case "delete": + return Effect.sync(() => target.map.delete(args[0])) + case "clear": + return Effect.sync(() => { + target.map.clear() + return undefined + }) + case "keys": + return Effect.sync(() => Array.from(target.map.keys())) + case "values": + return Effect.sync(() => Array.from(target.map.values())) + case "entries": + return Effect.sync(() => Array.from(target.map.entries(), ([key, item]): Array => [key, item])) + case "forEach": { + const apply = this.applyCollectionCallback(args[0], "Map.forEach", node) + return Effect.gen(function* () { + // Snapshot iteration, matching the array-method callback contract. + for (const [key, item] of Array.from(target.map.entries())) yield* apply([item, key, target]) + return undefined + }) + } + default: + throw new InterpreterRuntimeError(`Map method '${name}' is not available in CodeMode.`, node) + } + } + + private invokeSetMethod( + target: SandboxSet, + name: string, + args: Array, + node: AstNode, + ): Effect.Effect { + switch (name) { + case "has": + return Effect.succeed(target.set.has(args[0])) + case "add": + return Effect.sync(() => { + target.set.add(args[0]) + return target + }) + case "delete": + return Effect.sync(() => target.set.delete(args[0])) + case "clear": + return Effect.sync(() => { + target.set.clear() + return undefined + }) + case "keys": + case "values": + return Effect.sync(() => Array.from(target.set.values())) + case "entries": + return Effect.sync(() => Array.from(target.set.values(), (item): Array => [item, item])) + case "forEach": { + const apply = this.applyCollectionCallback(args[0], "Set.forEach", node) + return Effect.gen(function* () { + for (const item of Array.from(target.set.values())) yield* apply([item, item, target]) + return undefined + }) + } + default: + throw new InterpreterRuntimeError(`Set method '${name}' is not available in CodeMode.`, node) + } + } + + private invokeArrayMethod( + target: Array, + name: string, + args: Array, + node: AstNode, + ): Effect.Effect { + const optNumber = (value: unknown, label: string): number | undefined => { + if (value === undefined) return undefined + if (typeof value !== "number") + throw new InterpreterRuntimeError(`Array.${name} expects ${label} to be a number.`, node) + return value + } + switch (name) { + case "join": { + if (args.length > 1 || (args.length === 1 && typeof args[0] !== "string")) { + throw new InterpreterRuntimeError("Array.join expects zero arguments or one string separator.", node) + } + const input = boundedData(target, "Array.join input") as Array + return Effect.succeed( + input.map((item) => coerceToString(item ?? "")).join(args.length === 0 ? "," : (args[0] as string)), + ) + } + case "includes": + if (args.length === 0 || args.length > 2) + throw new InterpreterRuntimeError("Array.includes expects a value and optional start index.", node) + return Effect.succeed(target.includes(args[0], optNumber(args[1], "start index"))) + case "indexOf": + return Effect.succeed(target.indexOf(args[0], optNumber(args[1], "start index"))) + case "lastIndexOf": + return Effect.succeed( + args[1] === undefined + ? target.lastIndexOf(args[0]) + : target.lastIndexOf(args[0], optNumber(args[1], "start index")), + ) + case "at": + return Effect.succeed(target.at(optNumber(args[0], "index") ?? 0)) + case "slice": + return Effect.succeed(target.slice(optNumber(args[0], "start"), optNumber(args[1], "end"))) + case "concat": + return Effect.succeed(target.concat(...args)) + case "flat": + return Effect.succeed(target.flat(optNumber(args[0], "depth") ?? 1)) + case "reverse": + return Effect.succeed([...target].reverse()) + case "sort": + case "toSorted": + return this.sortArray(target, args[0], node) + case "toReversed": + return Effect.succeed([...target].reverse()) + case "with": { + const index = optNumber(args[0], "index") ?? 0 + const resolved = index < 0 ? target.length + index : index + if (resolved < 0 || resolved >= target.length) { + throw new InterpreterRuntimeError("Array.with index is out of range.", node) + } + const copied = [...target] + copied[resolved] = args[1] + return Effect.succeed(copied) + } + case "push": { + // Validate before mutating (so no rollback is needed): inserting a container into + // itself would create a cycle no later walk could survive. + for (const item of args) this.rejectCircularInsertion(target, item, "Array.push result", node) + target.push(...args) + return Effect.succeed(target.length) + } + case "unshift": { + for (const item of args) this.rejectCircularInsertion(target, item, "Array.unshift result", node) + target.unshift(...args) + return Effect.succeed(target.length) + } + case "pop": + return Effect.succeed(target.pop()) + case "shift": + return Effect.succeed(target.shift()) + case "splice": { + // Mutates in place and returns the removed elements, exactly like JS: one argument + // removes to the end, an undefined delete count removes nothing. + if (args.length === 0) return Effect.succeed(target.splice(0, 0)) + const start = optNumber(args[0], "start") ?? 0 + if (args.length === 1) return Effect.succeed(target.splice(start)) + const deleteCount = optNumber(args[1], "delete count") ?? 0 + const inserted = args.slice(2) + for (const item of inserted) this.rejectCircularInsertion(target, item, "Array.splice result", node) + return Effect.succeed(target.splice(start, deleteCount, ...inserted)) + } + case "fill": { + this.rejectCircularInsertion(target, args[0], "Array.fill result", node) + return Effect.succeed(target.fill(args[0], optNumber(args[1], "start"), optNumber(args[2], "end"))) + } + case "copyWithin": + return Effect.succeed( + target.copyWithin( + optNumber(args[0], "target index") ?? 0, + optNumber(args[1], "start") ?? 0, + optNumber(args[2], "end"), + ), + ) + // keys/values/entries return arrays (not iterators), matching the Map/Set convention; + // they work with for...of and spread either way. + case "keys": + return Effect.succeed(Array.from(target.keys())) + case "values": + return Effect.succeed([...target]) + case "entries": + return Effect.succeed(Array.from(target.entries(), ([index, item]): Array => [index, item])) + } + + const callback = args[0] + if (!(callback instanceof CodeModeFunction) && !(callback instanceof CoercionFunction)) { + throw new InterpreterRuntimeError(`Array.${name} expects a function callback.`, node) + } + const self = this + // Accept a user arrow function or a builtin coercion callable (Boolean/String/Number), so the + // idioms `filter(Boolean)` / `map(String)` / `map(Number)` work as in JS. Coercions are + // synchronous; only CodeModeFunctions can await tool calls. + const apply = (callbackArgs: Array): Effect.Effect => + callback instanceof CoercionFunction + ? Effect.succeed(invokeCoercion(callback, callbackArgs, node)) + : self.invokeFunction(callback, callbackArgs) + return Effect.gen(function* () { + // Iterate a snapshot taken at call time so a callback that mutates the array can't + // self-extend the loop - matching JS, where elements appended during iteration are not visited. + const items = target.slice() + switch (name) { + case "map": { + const values: Array = [] + for (const [index, item] of items.entries()) values.push(yield* apply([item, index, items])) + return values + } + case "flatMap": { + const values: Array = [] + for (const [index, item] of items.entries()) { + const mapped = yield* apply([item, index, items]) + if (Array.isArray(mapped)) values.push(...mapped) + else values.push(mapped) + } + return values + } + case "filter": { + const values: Array = [] + for (const [index, item] of items.entries()) { + if (yield* apply([item, index, items])) values.push(item) + } + return values + } + case "find": + for (const [index, item] of items.entries()) { + if (yield* apply([item, index, items])) return item + } + return undefined + case "findIndex": + for (const [index, item] of items.entries()) { + if (yield* apply([item, index, items])) return index + } + return -1 + case "some": + for (const [index, item] of items.entries()) { + if (yield* apply([item, index, items])) return true + } + return false + case "every": + for (const [index, item] of items.entries()) { + if (!(yield* apply([item, index, items]))) return false + } + return true + case "forEach": + for (const [index, item] of items.entries()) yield* apply([item, index, items]) + return undefined + case "reduce": { + let accumulator: unknown + let start: number + if (args.length >= 2) { + accumulator = args[1] + start = 0 + } else { + if (items.length === 0) + throw new InterpreterRuntimeError("Array.reduce of an empty array with no initial value.", node) + accumulator = items[0] + start = 1 + } + for (let index = start; index < items.length; index += 1) { + accumulator = yield* apply([accumulator, items[index], index, items]) + } + return accumulator + } + case "reduceRight": { + let accumulator: unknown + let start: number + if (args.length >= 2) { + accumulator = args[1] + start = items.length - 1 + } else { + if (items.length === 0) + throw new InterpreterRuntimeError("Array.reduceRight of an empty array with no initial value.", node) + accumulator = items[items.length - 1] + start = items.length - 2 + } + for (let index = start; index >= 0; index -= 1) { + accumulator = yield* apply([accumulator, items[index], index, items]) + } + return accumulator + } + case "findLast": + for (let index = items.length - 1; index >= 0; index -= 1) { + if (yield* apply([items[index], index, items])) return items[index] + } + return undefined + case "findLastIndex": + for (let index = items.length - 1; index >= 0; index -= 1) { + if (yield* apply([items[index], index, items])) return index + } + return -1 + } + throw new InterpreterRuntimeError(`Array method '${name}' is not available in CodeMode.`, node) + }) + } + + private sortArray( + target: Array, + comparator: unknown, + node: AstNode, + ): Effect.Effect, unknown, R> { + if (comparator !== undefined && !(comparator instanceof CodeModeFunction)) { + throw new InterpreterRuntimeError("Array.sort expects an arrow function comparator.", node) + } + if (!(comparator instanceof CodeModeFunction)) { + return Effect.sync(() => + [...target].sort((a, b) => { + const left = coerceToString(a) + const right = coerceToString(b) + return left < right ? -1 : left > right ? 1 : 0 + }), + ) + } + const self = this + const mergeSort = (items: Array): Effect.Effect, unknown, R> => { + if (items.length <= 1) return Effect.succeed(items) + const midpoint = Math.floor(items.length / 2) + return Effect.gen(function* () { + const left = yield* mergeSort(items.slice(0, midpoint)) + const right = yield* mergeSort(items.slice(midpoint)) + const merged: Array = [] + let leftIndex = 0 + let rightIndex = 0 + while (leftIndex < left.length && rightIndex < right.length) { + // Coerce the comparator's result like JS ToNumber (data objects -> NaN, never a host + // crash) and treat NaN as 0 - the spec's "no consistent order" -> keep the left element. + const order = coerceToNumber(yield* self.invokeFunction(comparator, [left[leftIndex], right[rightIndex]])) + if (Number.isNaN(order) || order <= 0) merged.push(left[leftIndex++]) + else merged.push(right[rightIndex++]) + } + return [...merged, ...left.slice(leftIndex), ...right.slice(rightIndex)] + }) + } + // Per spec, undefined elements sort to the end and the comparator is never called on them. + const defined = target.filter((item) => item !== undefined) + const undefinedCount = target.length - defined.length + return Effect.map(mergeSort(defined), (items) => [...items, ...Array(undefinedCount).fill(undefined)]) + } + + private evaluateObjectExpression(node: AstNode): Effect.Effect, unknown, R> { + const objectValue: Record = Object.create(null) as Record + const properties = getArray(node, "properties") + const self = this + return Effect.gen(function* () { + for (const propertyValue of properties) { + const property = asNode(propertyValue, "properties") + + if (property.type === "SpreadElement") { + const spread = yield* self.evaluateExpression(getNode(property, "argument")) + // JS treats `{ ...null }` / `{ ...undefined }` as a no-op, so the common + // `{ ...maybeOpts, override }` merge works when the operand is absent. Sandbox values + // (Date/RegExp/Map/Set) have no own enumerable properties in JS, so they are no-ops too. + if (spread === null || spread === undefined || isSandboxValue(spread)) continue + if (typeof spread !== "object" || Array.isArray(spread) || isRuntimeReference(spread)) { + throw new InterpreterRuntimeError( + "Object spread requires a data object in CodeMode.", + property, + "InvalidDataValue", + ) + } + for (const [key, value] of Object.entries(spread)) { + if (isBlockedMember(key)) + throw new InterpreterRuntimeError(`Property '${key}' is not available in CodeMode.`, property) + objectValue[key] = value + } + continue + } + + if (property.type !== "Property") { + throw new InterpreterRuntimeError("Only standard object properties are supported.", property) + } + + if (getString(property, "kind") !== "init") { + throw new InterpreterRuntimeError("Only init object properties are supported.", property) + } + + const keyNode = getNode(property, "key") + const valueNode = getNode(property, "value") + const computed = getBoolean(property, "computed") + + let key: PropertyKey + + if (computed) { + key = self.toPropertyKey(yield* self.evaluateExpression(keyNode), keyNode) + } else if (keyNode.type === "Identifier") { + key = getString(keyNode, "name") + } else if (keyNode.type === "Literal") { + key = self.toPropertyKey(keyNode.value, keyNode) + } else { + throw new InterpreterRuntimeError("Unsupported object property key shape.", keyNode) + } + + if (isBlockedMember(String(key))) { + throw new InterpreterRuntimeError(`Property '${String(key)}' is not available in CodeMode.`, keyNode) + } + objectValue[String(key)] = yield* self.evaluateExpression(valueNode) + } + + return objectValue + }) + } + + private evaluateArrayExpression(node: AstNode): Effect.Effect, unknown, R> { + const elements = getArray(node, "elements") + const values: Array = [] + + const self = this + return Effect.gen(function* () { + for (const elementValue of elements) { + if (elementValue === null) { + values.push(undefined) + continue + } + const element = asNode(elementValue, "elements") + if (element.type === "SpreadElement") { + const spread = yield* self.evaluateExpression(getNode(element, "argument")) + const items = spreadItems(spread) + if (items === undefined) + throw new InterpreterRuntimeError( + "Array spread requires an array, string, Map, or Set in CodeMode.", + element, + ) + values.push(...items) + } else { + values.push(yield* self.evaluateExpression(element)) + } + } + return values + }) + } + + private evaluateTemplateLiteral(node: AstNode): Effect.Effect { + const quasis = getArray(node, "quasis") + const expressions = getArray(node, "expressions") + + let output = "" + + const self = this + return Effect.gen(function* () { + for (let index = 0; index < quasis.length; index += 1) { + const quasi = asNode(quasis[index], "quasis") + const rawValue = quasi.value + + if (!isRecord(rawValue) || typeof rawValue.cooked !== "string") { + throw new InterpreterRuntimeError("Invalid template literal quasi.", quasi) + } + + output += rawValue.cooked + + if (index < expressions.length) { + const raw = yield* self.evaluateExpression(asNode(expressions[index], "expressions")) + // The preserving checkpoint keeps sandbox values intact, so coerceToString renders + // them directly (ISO date, /regex/ literal form) instead of a JSON-serialized husk. + output += coerceToString(boundedData(raw, "Template interpolation")) + } + } + + return output + }) + } + + private evaluateConditionalExpression(node: AstNode): Effect.Effect { + return Effect.flatMap(this.evaluateExpression(getNode(node, "test")), (test) => + this.evaluateExpression(getNode(node, test ? "consequent" : "alternate")), + ) + } + + private applyCompoundAssignment(operator: string, current: unknown, incoming: unknown, node: AstNode): unknown { + // `x op= y` is `x = x op y`: dispatch through the shared binary operator implementation + // so compound assignment inherits the same coercion semantics (Dates, data objects, ...). + // Only the arithmetic/bitwise operators are compoundable; logical assignments (&&=/||=/??=) + // short-circuit and are handled by evaluateLogicalAssignment before reaching here. + if (!compoundOperators.has(operator)) { + throw new InterpreterRuntimeError(`Unsupported assignment operator '${operator}'.`, node) + } + return this.applyBinaryOperator(operator.slice(0, -1), current, incoming, node) + } + + private getMemberReference( + node: AstNode, + ): Effect.Effect< + | MemberReference + | ToolReference + | PromiseMethodReference + | IntrinsicReference + | GlobalMethodReference + | ComputedValue + | typeof OptionalShortCircuit + | undefined, + unknown, + R + > { + const objectNode = getNode(node, "object") + const propertyNode = getNode(node, "property") + const computed = getBoolean(node, "computed") + const optional = node.optional === true + const self = this + return Effect.gen(function* () { + const objectValue = yield* self.evaluateExpression(objectNode) + if (objectValue === OptionalShortCircuit) return OptionalShortCircuit + if ((objectValue === null || objectValue === undefined) && optional) return OptionalShortCircuit + + const key = computed + ? self.toPropertyKey(yield* self.evaluateExpression(propertyNode), propertyNode) + : propertyNode.type === "Identifier" + ? getString(propertyNode, "name") + : self.toPropertyKey(yield* self.evaluateExpression(propertyNode), propertyNode) + + if (objectValue instanceof ToolReference) { + if (typeof key !== "string" || isBlockedMember(key)) { + throw new InterpreterRuntimeError("Tool paths must use safe string property names.", propertyNode) + } + return new ToolReference([...objectValue.path, key]) + } + + if (objectValue instanceof PromiseNamespace) { + if (typeof key === "string" && promiseStatics.has(key as PromiseMethodName)) { + return new PromiseMethodReference(key as PromiseMethodName) + } + throw new InterpreterRuntimeError( + `Promise.${String(key)} is not available in CodeMode. Available: Promise.all, Promise.allSettled, Promise.race, Promise.resolve, and Promise.reject; consume promises with await.`, + propertyNode, + ) + } + + if (objectValue instanceof GlobalNamespace) { + if (typeof key !== "string" || isBlockedMember(key)) { + throw new InterpreterRuntimeError( + `${objectValue.name}.${String(key)} is not available in CodeMode.`, + propertyNode, + ) + } + if (objectValue.name === "Math" && mathConstants.has(key)) { + return new ComputedValue((Math as unknown as Record)[key]) + } + return new GlobalMethodReference(objectValue.name, key) + } + + if (typeof objectValue === "string") { + if (key === "length") return new ComputedValue(objectValue.length) + if (typeof key === "number") return new ComputedValue(objectValue[key]) + if (typeof key === "string" && /^\d+$/.test(key)) return new ComputedValue(objectValue[Number(key)]) + if (typeof key === "string" && stringMethods.has(key)) return new IntrinsicReference(objectValue, key) + // Unknown property on a string reads as `undefined`, matching JS (`"x".foo === undefined`), + // instead of throwing - so defensive access like `result?.login ?? result` on a JSON-string + // tool result doesn't crash. (Optional chaining only guards null/undefined receivers, so a + // real string still reaches here.) Only the method allowlist above yields callables. + return new ComputedValue(undefined) + } + + if (typeof objectValue === "number") { + if (typeof key === "string" && numberMethods.has(key)) return new IntrinsicReference(objectValue, key) + // Unknown property on a number reads as `undefined`, matching JS, rather than throwing. + return new ComputedValue(undefined) + } + + // Number / String expose a small allowlist of statics; everything else stays opaque. + if (objectValue instanceof CoercionFunction && typeof key === "string" && !isBlockedMember(key)) { + if (objectValue.name === "Number" && numberConstants.has(key)) { + return new ComputedValue((Number as unknown as Record)[key]) + } + if (objectValue.name === "Number" && numberStatics.has(key)) return new GlobalMethodReference("Number", key) + if (objectValue.name === "String" && stringStatics.has(key)) return new GlobalMethodReference("String", key) + } + + // Sandbox value types expose their method/property allowlists; any other key reads as + // `undefined`, consistent with unknown-property reads on strings/numbers/arrays. + if (objectValue instanceof SandboxDate) { + if (typeof key === "string" && dateMethods.has(key)) return new IntrinsicReference(objectValue, key) + return new ComputedValue(undefined) + } + if (objectValue instanceof SandboxRegExp) { + if (typeof key === "string" && regexpProperties.has(key)) { + return new ComputedValue((objectValue.regex as unknown as Record)[key]) + } + if (typeof key === "string" && regexpMethods.has(key)) return new IntrinsicReference(objectValue, key) + return new ComputedValue(undefined) + } + if (objectValue instanceof SandboxMap) { + if (key === "size") return new ComputedValue(objectValue.map.size) + if (typeof key === "string" && mapMethods.has(key)) return new IntrinsicReference(objectValue, key) + return new ComputedValue(undefined) + } + if (objectValue instanceof SandboxSet) { + if (key === "size") return new ComputedValue(objectValue.set.size) + if (typeof key === "string" && setMethods.has(key)) return new IntrinsicReference(objectValue, key) + return new ComputedValue(undefined) + } + + // Any property access on a promise is a confused program (`p.then(...)`, `p.value`); + // reading `undefined` here would hide the missing await, so both paths get an explicit, + // await-hinting error instead of the forgiving unknown-property fallthrough. + if (objectValue instanceof SandboxPromise) { + if (key === "then" || key === "catch" || key === "finally") { + throw new InterpreterRuntimeError( + `Promise.prototype.${String(key)} is not supported in CodeMode; use await instead (with try/catch to handle failures) - e.g. \`const result = await tools.ns.tool(...)\`.`, + propertyNode, + "UnsupportedSyntax", + [supportedSyntaxMessage], + ) + } + throw new InterpreterRuntimeError( + "This value is an un-awaited Promise and has no readable properties; await it first - e.g. `const result = await tools.ns.tool(...)`.", + objectNode, + "InvalidDataValue", + ) + } + + if (isRuntimeReference(objectValue)) { + throw new InterpreterRuntimeError( + "CodeMode runtime references are opaque and do not expose properties.", + objectNode, + "InvalidDataValue", + ) + } + + if (typeof objectValue !== "object" || objectValue === null) { + throw new InterpreterRuntimeError("Cannot access a property on a non-object value.", objectNode) + } + + if (typeof key === "string" && isBlockedMember(key)) { + throw new InterpreterRuntimeError(`Property '${key}' is not available in CodeMode.`, propertyNode) + } + + if (Array.isArray(objectValue)) { + if ( + key !== "length" && + !(typeof key === "string" && arrayMethods.has(key)) && + typeof key !== "number" && + !/^\d+$/.test(key) + ) { + // Own non-index properties read through (match results carry index/groups); like JS, + // they are readable in place and dropped by JSON at data boundaries. + if (typeof key === "string" && Object.hasOwn(objectValue, key)) { + return new ComputedValue((objectValue as Record & Array)[key]) + } + // Unknown property on an array reads as `undefined`, matching JS (`[1,2].foo === undefined`), + // instead of throwing - so defensive access under optional chaining behaves as expected. + return new ComputedValue(undefined) + } + return { target: objectValue, key } + } + + return { target: objectValue as SafeObject, key } + }) + } + + private readMember(node: AstNode): Effect.Effect { + return Effect.map(this.getMemberReference(node), (reference) => { + if (reference === OptionalShortCircuit) return OptionalShortCircuit + if (reference instanceof ComputedValue) return reference.value + if ( + reference === undefined || + reference instanceof ToolReference || + reference instanceof PromiseMethodReference || + reference instanceof IntrinsicReference || + reference instanceof GlobalMethodReference + ) + return reference + if (Array.isArray(reference.target)) { + if (typeof reference.key === "string" && arrayMethods.has(reference.key)) { + return new IntrinsicReference(reference.target, reference.key) + } + return reference.key === "length" ? reference.target.length : reference.target[Number(reference.key)] + } + return reference.target[String(reference.key)] + }) + } + + private writeMember(node: AstNode, value: unknown): Effect.Effect { + return this.modifyMember(node, () => Effect.succeed({ write: true, next: value, result: value })) + } + + // Resolves the member reference EXACTLY ONCE (so a side-effecting object/key expression + // runs once), then lets `compute` decide whether to write - enabling compound assignment, + // updates, plain writes, and short-circuiting logical assignment to share one safe path. + private modifyMember( + node: AstNode, + compute: (current: unknown) => Effect.Effect<{ write: boolean; next: unknown; result: unknown }, unknown, R>, + ): Effect.Effect { + const self = this + return Effect.gen(function* () { + const reference = yield* self.getMemberReference(node) + if ( + reference === OptionalShortCircuit || + reference instanceof ComputedValue || + reference === undefined || + reference instanceof ToolReference || + reference instanceof PromiseMethodReference || + reference instanceof IntrinsicReference || + reference instanceof GlobalMethodReference + ) { + throw new InterpreterRuntimeError("Only data fields may be assigned in CodeMode.", node) + } + if (Array.isArray(reference.target)) { + if (reference.key === "length") + throw new InterpreterRuntimeError("Array length cannot be assigned in CodeMode.", node) + if (typeof reference.key === "string" && arrayMethods.has(reference.key)) { + throw new InterpreterRuntimeError("Array methods cannot be assigned in CodeMode.", node) + } + } + const key = Array.isArray(reference.target) ? Number(reference.key) : String(reference.key) + const current = (reference.target as Record)[key] + const { write, next, result } = yield* compute(current) + if (write) self.assignToReference(reference, key, next, node) + return result + }) + } + + // Rejects inserting a value that (transitively) contains the container it is being inserted + // into - the mutation that would create a circular structure no later walk could survive. + private rejectCircularInsertion( + container: object, + value: unknown, + label: string, + node: AstNode, + seen = new Set(), + ): void { + if (value === container) + throw new InterpreterRuntimeError(`${label} contains a circular value.`, node, "InvalidDataValue") + if (value === null || typeof value !== "object" || isRuntimeReference(value) || seen.has(value)) return + seen.add(value) + const items = Array.isArray(value) ? value : Object.values(value) + for (const item of items) this.rejectCircularInsertion(container, item, label, node, seen) + seen.delete(value) + } + + private assignToReference(reference: MemberReference, key: number | string, next: unknown, node: AstNode): void { + if (Array.isArray(reference.target)) { + const target = reference.target + const index = key as number + if (!Number.isInteger(index) || index < 0) { + throw new InterpreterRuntimeError( + "Array assignment index must be a non-negative integer.", + node, + "InvalidDataValue", + ) + } + this.rejectCircularInsertion(target, next, "Array assignment result", node) + target[index] = next + return + } + const target = reference.target as SafeObject + const objectKey = key as string + this.rejectCircularInsertion(target, next, "Object assignment result", node) + target[objectKey] = next + } + + private toPropertyKey(value: unknown, node: AstNode): string | number { + if (typeof value === "string" || typeof value === "number") { + return value + } + + throw new InterpreterRuntimeError("Property key must be a string or number.", node) + } + + private declare(name: string, value: unknown, mutable: boolean, node: AstNode): void { + const scope = this.currentScope() + + // A pre-seeded parameter slot (initialized === false) is being bound for the first time; + // anything else already present is a genuine duplicate declaration. + const existing = scope.get(name) + if (existing && existing.initialized !== false) { + throw new InterpreterRuntimeError(`Identifier '${name}' has already been declared.`, node) + } + + scope.set(name, { mutable, value, initialized: true }) + } + + private getIdentifierValue(name: string, node: AstNode): unknown { + const binding = this.resolveBinding(name) + + if (!binding) { + throw new InterpreterRuntimeError(`Unknown identifier '${name}'.`, node).as("ReferenceError") + } + + // A parameter default that forward-references a later (not-yet-bound) parameter - JS TDZ. + if (binding.initialized === false) { + throw new InterpreterRuntimeError(`Cannot access '${name}' before initialization.`, node).as("ReferenceError") + } + + return binding.value + } + + private setIdentifierValue(name: string, value: unknown, node: AstNode): unknown { + const binding = this.resolveBinding(name) + + if (!binding) { + throw new InterpreterRuntimeError(`Unknown identifier '${name}'.`, node).as("ReferenceError") + } + + if (!binding.mutable) { + throw new InterpreterRuntimeError(`Cannot assign to constant '${name}'.`, node).as("TypeError") + } + + binding.value = value + return value + } + + private resolveBinding(name: string): Binding | undefined { + for (let index = this.scopes.length - 1; index >= 0; index -= 1) { + const scope = this.scopes[index] + const binding = scope?.get(name) + + if (binding) { + return binding + } + } + + return undefined + } + + private currentScope(): Map { + const scope = this.scopes[this.scopes.length - 1] + + if (!scope) { + throw new InterpreterRuntimeError("Interpreter scope stack is empty.") + } + + return scope + } + + private pushScope(): void { + this.scopes.push(new Map()) + } + + private popScope(): void { + this.scopes.pop() + } +} + +/** + * Executes one Effect-native CodeMode program without constructing a reusable runtime. + * + * @example + * ```ts + * const result = yield* CodeMode.execute({ + * tools: { lookup }, + * code: `return await tools.lookup({ id: "order_42" })`, + * }) + * ``` + */ +const executeWithLimits = >( + options: ExecuteOptions, + limits: ResolvedExecutionLimits, + searchIndex: ToolRuntime.DiscoveryPlan["searchIndex"], +): Effect.Effect> => { + const hooks = { + ...(options.onToolCallStart === undefined ? {} : { onToolCallStart: options.onToolCallStart }), + ...(options.onToolCallEnd === undefined ? {} : { onToolCallEnd: options.onToolCallEnd }), + } + const tools = ToolRuntime.make( + (options.tools ?? {}) as HostTools>, + limits.maxToolCalls, + hooks, + searchIndex, + ) + const logs: Array = [] + const logged = () => (logs.length > 0 ? { logs: [...logs] } : {}) + + if (options.code.trim().length === 0) { + return Effect.succeed({ + ok: false, + error: { kind: "ParseError", message: "Code cannot be empty." }, + toolCalls: tools.calls, + }) + } + + const operation = Effect.gen(function* () { + const program = parseProgram(options.code) + const interpreter = new Interpreter>(tools.invoke, tools.keys, logs) + const value = yield* interpreter.run(program) + const result = copyOut(copyIn(value, "Execution result"), true) as DataValue + return { + ok: true, + value: result, + ...logged(), + toolCalls: tools.calls, + } satisfies ExecuteResult + }).pipe((program) => { + const timeoutMs = limits.timeoutMs + if (timeoutMs === undefined) return program + return program.pipe( + Effect.timeoutOrElse({ + duration: timeoutMs, + orElse: () => + Effect.succeed({ + ok: false, + error: { kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` }, + ...logged(), + toolCalls: tools.calls, + } satisfies ExecuteResult), + }), + ) + }) + + return operation.pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.interrupt + : Effect.succeed({ + ok: false, + error: normalizeError(Cause.squash(cause)), + ...logged(), + toolCalls: tools.calls, + } satisfies ExecuteResult), + ), + Effect.map((result) => (limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes))), + ) +} + +const utf8ByteLength = (value: string): number => new TextEncoder().encode(value).byteLength + +// Truncates to a UTF-8 byte budget without splitting a code point (a split multi-byte +// sequence decodes to a replacement character, which is dropped). +const utf8Truncate = (value: string, maxBytes: number): string => { + const bytes = new TextEncoder().encode(value) + if (bytes.byteLength <= maxBytes) return value + const text = new TextDecoder("utf-8").decode(bytes.slice(0, Math.max(0, maxBytes))) + return text.endsWith("\uFFFD") ? text.slice(0, -1) : text +} + +/** + * Bounds the model-facing output (serialized result value plus logs) to `maxOutputBytes`. + * Oversized values are replaced by their truncated serialized text with an explanatory marker, + * and logs are kept from the start until the remaining budget is exhausted. Truncation never + * fails the execution; `truncated: true` marks affected results. Only runs when the host set + * `maxOutputBytes` - with the limit absent, output passes through unbounded. + */ +const boundOutput = (result: ExecuteResult, maxOutputBytes: number): ExecuteResult => { + let truncated = false + + let value: DataValue = null + let valueBytes = 0 + if (result.ok) { + const serialized = JSON.stringify(result.value) ?? "null" + const bytes = utf8ByteLength(serialized) + if (bytes > maxOutputBytes) { + truncated = true + value = `${utf8Truncate(serialized, maxOutputBytes)} [result truncated: ${bytes} bytes exceeds the ${maxOutputBytes}-byte output limit; return a smaller value]` + valueBytes = maxOutputBytes + } else { + value = result.value + valueBytes = bytes + } + } + + const logs = result.logs ?? [] + const kept: Array = [] + const logBudget = Math.max(0, maxOutputBytes - valueBytes) + let logBytes = 0 + for (const line of logs) { + const lineBytes = utf8ByteLength(line) + 1 + if (logBytes + lineBytes > logBudget) break + logBytes += lineBytes + kept.push(line) + } + if (kept.length < logs.length) { + truncated = true + kept.push(`[logs truncated: showing ${kept.length} of ${logs.length} lines]`) + } + + if (!truncated) return result + const logsPart = kept.length > 0 ? { logs: kept } : {} + return result.ok + ? { ok: true, value, ...logsPart, truncated: true, toolCalls: result.toolCalls } + : { ok: false, error: result.error, ...logsPart, truncated: true, toolCalls: result.toolCalls } +} + +export const execute = >( + options: ExecuteOptions, +): Effect.Effect> => { + const tools = (options.tools ?? {}) as HostTools> + ToolRuntime.assertValidTools(tools) + return executeWithLimits(options, resolveExecutionLimits(options.limits), ToolRuntime.searchIndex(tools)) +} + +/** + * Creates an Effect-native runtime over explicit, schema-described tools. + * + * Use `execute` for host-driven execution or `agentTool` to expose one confined code tool to an + * agent framework. Tool requirements remain in the returned Effect environment. + * + * @example + * ```ts + * const runtime = CodeMode.make({ tools: { orders: { lookup } } }) + * const code = runtime.agentTool() + * ``` + */ +export const make = = {}>( + options: CodeModeOptions = {} as CodeModeOptions, +): CodeModeRuntime> => { + const tools = (options.tools ?? {}) as HostTools> + ToolRuntime.assertValidTools(tools) + const limits = resolveExecutionLimits(options.limits) + const discovery = ToolRuntime.discoveryPlan(tools, options.discovery?.maxInlineCatalogTokens) + const executeProgram = (code: string) => executeWithLimits({ ...options, code }, limits, discovery.searchIndex) + const catalog = discovery.catalog + const instructions = discovery.instructions + + return { + catalog: () => catalog, + instructions: () => instructions, + agentTool: () => ({ + name: "code", + description: instructions, + input: ExecuteInputSchema, + output: ExecuteResultSchema, + execute: ({ code }) => executeProgram(code), + }), + execute: executeProgram, + } +} + +/** Constructors for one-shot and reusable CodeMode execution. */ +export const CodeMode = { make, execute } diff --git a/packages/codemode/src/index.ts b/packages/codemode/src/index.ts new file mode 100644 index 0000000000..96629f486e --- /dev/null +++ b/packages/codemode/src/index.ts @@ -0,0 +1,21 @@ +export { ToolError, CodeMode, ExecuteInputSchema, ExecuteResultSchema, toolError } from "./codemode.js" +export { Tool } from "./tool.js" +export type { Definition as ToolDefinition, JsonSchema, ToolSchema } from "./tool.js" +export type { ToolCallEnded, ToolCallHooks } from "./tool-runtime.js" +export type { + AgentToolDefinition, + CodeModeOptions, + CodeModeRuntime, + DataValue, + Diagnostic, + DiagnosticKind, + DiscoveryOptions, + ExecuteFailure, + ExecuteOptions, + ExecuteResult, + ExecuteSuccess, + ExecutionLimits, + ToolCall, + ToolCallStarted, + ToolDescription, +} from "./codemode.js" diff --git a/packages/codemode/src/token.ts b/packages/codemode/src/token.ts new file mode 100644 index 0000000000..1e06bec1e4 --- /dev/null +++ b/packages/codemode/src/token.ts @@ -0,0 +1,10 @@ +/** + * Token estimation for budgeting model-facing text. Copied from + * `@opencode-ai/core/util/token` (chars / 4) so this package stays + * dependency-free; keep the two in sync if the heuristic ever changes. + */ +export * as Token from "./token.js" + +const CHARS_PER_TOKEN = 4 + +export const estimate = (input: string) => Math.max(0, Math.round(input.length / CHARS_PER_TOKEN)) diff --git a/packages/codemode/src/tool-error.ts b/packages/codemode/src/tool-error.ts new file mode 100644 index 0000000000..16460a019a --- /dev/null +++ b/packages/codemode/src/tool-error.ts @@ -0,0 +1,11 @@ +import { Schema } from "effect" + +/** Safe operational refusal from a standard tool pack, reported as `ToolFailure`. */ +export class ToolError extends Schema.TaggedErrorClass()("ToolError", { + message: Schema.String, + cause: Schema.optionalKey(Schema.Defect()), +}) {} + +/** Creates a tool refusal whose message is safe to include in an execution diagnostic. */ +export const toolError = (message: string, cause?: unknown): ToolError => + new ToolError({ message, ...(cause === undefined ? {} : { cause }) }) diff --git a/packages/codemode/src/tool-runtime.ts b/packages/codemode/src/tool-runtime.ts new file mode 100644 index 0000000000..fa3ddc6c2f --- /dev/null +++ b/packages/codemode/src/tool-runtime.ts @@ -0,0 +1,829 @@ +import { Cause, Effect } from "effect" +import { ToolError, toolError } from "./tool-error.js" +import { + decodeInput as decodeToolInput, + decodeOutput as decodeToolOutput, + identifierSegment, + inputProperties, + inputTypeScript, + isDefinition as isToolDefinition, + outputTypeScript, + type Definition, +} from "./tool.js" +import { estimate } from "./token.js" +import { SandboxDate, SandboxMap, SandboxPromise, SandboxRegExp, SandboxSet } from "./values.js" + +export type HostTool = (...args: Array) => Effect.Effect + +export type HostTools = { + [name: string]: HostTool | Definition | HostTools +} + +export type Services = Tools extends (...args: Array) => Effect.Effect + ? R + : Tools extends { + readonly _tag: "CodeModeTool" + readonly run: (input: unknown) => Effect.Effect + } + ? R + : Tools extends object + ? string extends keyof Tools + ? never + : Services + : never + +/** Minimal audit record retained for each admitted tool call. */ +export type ToolCall = { + readonly name: string +} + +/** Decoded tool call observed immediately before tool execution. */ +export type ToolCallStarted = { + readonly index: number + readonly name: string + readonly input: unknown +} + +/** Completed tool call observed immediately after tool execution settles. */ +export type ToolCallEnded = { + readonly index: number + readonly name: string + readonly input: unknown + readonly durationMs: number + readonly outcome: "success" | "failure" + /** Model-safe failure message; present only when `outcome` is `"failure"`. */ + readonly message?: string +} + +/** Non-throwing observation hooks fired around each admitted tool call. */ +export type ToolCallHooks = { + readonly onToolCallStart?: ((call: ToolCallStarted) => Effect.Effect) | undefined + readonly onToolCallEnd?: ((call: ToolCallEnded) => Effect.Effect) | undefined +} + +/** Model-visible description of one schema-backed tool. */ +export type ToolDescription = { + readonly path: string + readonly description: string + readonly signature: string +} + +export type SafeObject = Record + +const reservedNamespace = "$codemode" +const defaultMaxInlineCatalogTokens = 2_000 +const defaultSearchLimit = 10 +const searchSignature = + "tools.$codemode.search({ query?: string, namespace?: string, limit?: number }): Promise<{ items: Array<{ path: string; description: string; signature: string }>; total: number }>" +const toolExpression = (path: string) => + "tools" + + path + .split(".") + .map((segment) => (identifierSegment.test(segment) ? `.${segment}` : `[${JSON.stringify(segment)}]`)) + .join("") + +export class ToolReference { + constructor(readonly path: ReadonlyArray) {} +} + +/** + * Maximum nesting depth for values crossing a data boundary. Fixed (not a configurable + * limit) purely because it produces a clearer diagnostic than a native stack-overflow + * RangeError would. + */ +const MAX_VALUE_DEPTH = 32 + +export class ToolRuntimeError extends Error { + constructor( + readonly kind: + | "UnknownTool" + | "InvalidToolInput" + | "InvalidToolOutput" + | "InvalidDataValue" + | "ToolCallLimitExceeded", + message: string, + readonly suggestions: ReadonlyArray = [], + ) { + super(message) + this.name = "ToolRuntimeError" + } +} + +const isDefinition = (value: HostTool | Definition | HostTools): value is Definition => + isToolDefinition(value) + +const runHost = (effect: Effect.Effect): Effect.Effect => + effect.pipe( + Effect.catchCause((cause) => { + if (Cause.hasInterruptsOnly(cause)) return Effect.interrupt + const error = Cause.squash(cause) + return Effect.fail(error instanceof ToolError ? error : toolError("Tool execution failed", error)) + }), + ) + +const blockedMemberNames = new Set(["__proto__", "constructor", "prototype"]) + +export const isBlockedMember = (name: string): boolean => blockedMemberNames.has(name) + +/** + * Validates and copies a value against the plain-data contract (depth, circularity, plain + * objects only, blocked properties, data-only leaves). + * + * Two modes share the walk: + * - **Boundary** (`preserveSandboxValues` false, the default): the host<->sandbox boundary - + * final results, tool-call arguments, `JSON.stringify`. Sandbox value types serialize + * exactly as JSON.stringify would: Date -> ISO string (invalid -> null), RegExp/Map/Set -> {}. + * - **Intra-sandbox checkpoint** (`preserveSandboxValues` true; see `boundedData` in + * codemode.ts): Date/RegExp/Map/Set instances pass through untouched (treated as leaves, + * contents not walked), so values flowing through `Object.*` helpers, coercion inputs, and + * other in-sandbox checkpoints stay fully usable (`.getTime()`, `.has()`, ...). + * + * Both modes reject un-awaited promises with an await-hinting diagnostic. + */ +export const copyIn = (value: unknown, label: string, preserveSandboxValues = false): unknown => + copyBounded(value, label, 0, new Set(), preserveSandboxValues) + +const copyBounded = ( + value: unknown, + label: string, + depth: number, + seen: Set, + preserveSandboxValues: boolean, +): unknown => { + if (depth > MAX_VALUE_DEPTH) { + throw new ToolRuntimeError("InvalidDataValue", `${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`) + } + if ( + value === null || + value === undefined || + typeof value === "string" || + typeof value === "boolean" || + // NaN/Infinity are allowed to exist as in-sandbox intermediates (matching real JS and a real + // engine) so defensive guards like `Number.isNaN(x)` / `parseInt(x) || 0` can run. They are + // normalized to `null` when the value leaves the sandbox - see copyOut - exactly as + // JSON.stringify already does at any tool boundary. + typeof value === "number" + ) { + return value + } + + if (typeof value !== "object") { + throw new ToolRuntimeError("InvalidDataValue", `${label} must contain data only.`) + } + + // An un-awaited promise never crosses a data checkpoint as `{}`; the diagnostic tells the + // model exactly how to fix the program instead. + if (value instanceof SandboxPromise) { + throw new ToolRuntimeError( + "InvalidDataValue", + `${label} contains an un-awaited Promise; await tool calls (e.g. \`const result = await tools.ns.tool(...)\`) before using their results.`, + ) + } + + if (preserveSandboxValues) { + // Intra-sandbox checkpoints keep sandbox value instances alive as leaves; their contents + // are never walked here (Map/Set members are validated where mutation happens, and the + // real boundary still serializes them below). + if ( + value instanceof SandboxDate || + value instanceof SandboxRegExp || + value instanceof SandboxMap || + value instanceof SandboxSet + ) { + return value + } + // Host instances cannot normally reach an intra-sandbox checkpoint (tool results cross + // the boundary first), but wrap them defensively rather than degrading to JSON forms. + if (value instanceof Date) return new SandboxDate(value.getTime()) + if (value instanceof RegExp) return new SandboxRegExp(value.source, value.flags) + if (value instanceof Map) { + const wrapped = new SandboxMap() + for (const [key, item] of value.entries()) { + wrapped.map.set(copyBounded(key, label, depth + 1, seen, true), copyBounded(item, label, depth + 1, seen, true)) + } + return wrapped + } + if (value instanceof Set) { + const wrapped = new SandboxSet() + for (const item of value.values()) wrapped.set.add(copyBounded(item, label, depth + 1, seen, true)) + return wrapped + } + } + + // Sandbox value types (and their host counterparts, which a host tool may legitimately + // return) serialize exactly as JSON.stringify would at the data boundary: a Date is its + // toJSON() ISO string (invalid -> null), and RegExp/Map/Set have no JSON form beyond {}. + if (value instanceof SandboxDate) { + return Number.isFinite(value.time) ? new Date(value.time).toISOString() : null + } + if (value instanceof Date) { + return Number.isFinite(value.getTime()) ? value.toISOString() : null + } + if ( + value instanceof SandboxRegExp || + value instanceof SandboxMap || + value instanceof SandboxSet || + value instanceof RegExp || + value instanceof Map || + value instanceof Set + ) { + return Object.create(null) as SafeObject + } + + if (seen.has(value)) { + throw new ToolRuntimeError("InvalidDataValue", `${label} contains a circular value.`) + } + + seen.add(value) + + if (Array.isArray(value)) { + const copied = value.map((item) => copyBounded(item, label, depth + 1, seen, preserveSandboxValues)) + seen.delete(value) + return copied + } + + const prototype = Object.getPrototypeOf(value) + if (prototype !== Object.prototype && prototype !== null) { + throw new ToolRuntimeError("InvalidDataValue", `${label} must contain plain objects only.`) + } + + const copied: SafeObject = Object.create(null) as SafeObject + for (const [key, item] of Object.entries(value)) { + if (isBlockedMember(key)) { + throw new ToolRuntimeError("InvalidDataValue", `${label} contains blocked property '${key}'.`) + } + copied[key] = copyBounded(item, label, depth + 1, seen, preserveSandboxValues) + } + seen.delete(value) + return copied +} + +export const copyOut = (value: unknown, undefinedAsNull = false): unknown => { + if (value === undefined && undefinedAsNull) return null + // Normalize non-finite numbers to null as the value crosses out of the sandbox (final return + // and tool-call arguments both funnel through here), matching JSON semantics - NaN/Infinity + // have no JSON representation, so JSON.stringify would produce null anyway. + if (typeof value === "number" && !Number.isFinite(value)) { + return null + } + if (Array.isArray(value)) { + return value.map((item) => copyOut(item, undefinedAsNull)) + } + + if (value !== null && typeof value === "object" && !(value instanceof ToolReference)) { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyOut(item, undefinedAsNull)])) + } + + return value +} + +const definitions = ( + tools: HostTools, + path: ReadonlyArray = [], +): Array<{ path: string; definition: Definition }> => { + const entries: Array<{ path: string; definition: Definition }> = [] + for (const [name, value] of Object.entries(tools)) { + const next = [...path, name] + if (isDefinition(value)) entries.push({ path: next.join("."), definition: value }) + else if (typeof value !== "function") entries.push(...definitions(value, next)) + } + return entries +} + +const describeDefinition = (path: string, definition: Definition): ToolDescription => ({ + path, + description: definition.description, + signature: `${toolExpression(path)}(input: ${inputTypeScript(definition)}): Promise<${outputTypeScript(definition)}>`, +}) + +const visibleDefinitions = (tools: HostTools) => + definitions(tools).flatMap(({ path, definition }) => { + const description = describeDefinition(path, definition) + return [{ path, definition, description }] + }) + +export const catalog = (tools: HostTools): ReadonlyArray => + visibleDefinitions(tools).map(({ description }) => description) + +export type DiscoveryPlan = { + readonly catalog: ReadonlyArray + readonly instructions: string + readonly searchIndex: ReadonlyArray +} + +export type SearchEntry = { + readonly description: ToolDescription + /** + * JSDoc-annotated multiline signature shown on search-result items; the compact + * single-line form (inline catalog lines) stays in `description.signature`. + */ + readonly signature: string + /** Top-level namespace (first path segment), matched by the search `namespace` option. */ + readonly namespace: string + /** Lowercased path + description + input property names/descriptions, for substring matching. */ + readonly searchText: string +} + +/** + * Split a query into lowercased search terms. camelCase boundaries are split + * (`resolveLibrary` -> `resolve library`) and every non-alphanumeric character is a + * separator, so `resolve-library-id`, `resolveLibraryId`, and `resolve library id` all + * tokenize alike. Empties and the `*` wildcard are dropped. + */ +const tokenize = (query: string): Array => + query + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter((term) => term.length > 0 && term !== "*") + +/** + * A term plus its naive singular variants (trailing "s"/"es" stripped), so a plural + * query term ("issues") still matches indexed text that only carries the singular + * ("issue"). Matching is one-directional substring containment, so the variants are + * needed only on the query side; scoring weights are unchanged - each field check + * passes when ANY form matches. + */ +const termForms = (term: string): Array => { + const forms = [term] + if (term.endsWith("es") && term.length > 3) forms.push(term.slice(0, -2)) + if (term.endsWith("s") && term.length > 2) forms.push(term.slice(0, -1)) + return forms +} + +const firstLine = (text: string) => text.split("\n", 1)[0]!.trim() + +/** One-line description used on inline catalog lines; the full text stays in search results. */ +const brief = (text: string, max = 120) => { + const line = firstLine(text) + return line.length > max ? line.slice(0, max - 1) + "..." : line +} + +const catalogLine = (tool: ToolDescription) => { + const description = brief(tool.description) + return description === "" ? ` - ${tool.signature}` : ` - ${tool.signature} // ${description}` +} + +const toSearchEntry = (path: string, definition: Definition, description: ToolDescription): SearchEntry => ({ + description, + signature: `${toolExpression(path)}(input: ${inputTypeScript(definition, true)}): Promise<${outputTypeScript(definition, true)}>`, + namespace: path.split(".", 1)[0]!, + searchText: [ + path, + definition.description, + ...inputProperties(definition).flatMap(({ name, description: property }) => + property === undefined ? [name] : [name, property], + ), + ] + .join("\n") + .toLowerCase(), +}) + +/** The runtime search index over every described tool. Search is always registered. */ +export const searchIndex = (tools: HostTools): ReadonlyArray => + visibleDefinitions(tools).map(({ path, definition, description }) => toSearchEntry(path, definition, description)) + +export const assertValidTools = (tools: HostTools): void => { + if (Object.hasOwn(tools, reservedNamespace)) { + throw new Error(`Tool namespace '${reservedNamespace}' is reserved for CodeMode discovery tools.`) + } +} + +/** + * Budgeted catalog: every namespace is always listed with its tool count; full call + * signatures are inlined against the `maxInlineCatalogTokens` budget (estimated tokens, + * chars/4) round-robin across namespaces - in each round (namespaces alphabetical), every + * namespace still holding un-inlined tools attempts to place its next-cheapest line, and + * a namespace whose next line does not fit is done while the others keep going - so every + * namespace gets some representation before any namespace gets everything. The section + * states exactly how comprehensive it is - overall (COMPLETE vs PARTIAL) and per + * namespace. Namespace stub lines are never budgeted: every namespace appears with its + * tool count even at budget 0. + */ +export const discoveryPlan = ( + tools: HostTools, + maxInlineCatalogTokens = defaultMaxInlineCatalogTokens, +): DiscoveryPlan => { + if (!Number.isSafeInteger(maxInlineCatalogTokens) || maxInlineCatalogTokens < 0) { + throw new RangeError("discovery.maxInlineCatalogTokens must be a non-negative safe integer") + } + const visible = visibleDefinitions(tools) + const described = visible.map(({ description }) => description) + + const namespaces = new Map>() + for (const tool of described) { + const [namespace = tool.path] = tool.path.split(".") + const group = namespaces.get(namespace) ?? [] + group.push(tool) + namespaces.set(namespace, group) + } + const ordered = [...namespaces].sort(([left], [right]) => left.localeCompare(right)) + + // Select which signatures fit the budget before emitting, so the list can state + // exactly how comprehensive it is. Round-robin fairness: in each round (namespaces + // alphabetical), every namespace still holding un-inlined tools tries to place its + // next-cheapest line against the shared budget; a namespace whose next line does not + // fit is done - the others keep going - so every namespace gets some representation + // before any namespace gets everything. + const selections = ordered.map(([namespace, group]) => ({ + namespace, + picked: new Set(), + queue: [...group].sort( + (left, right) => + estimate(catalogLine(left)) - estimate(catalogLine(right)) || left.path.localeCompare(right.path), + ), + })) + let used = 0 + let active = selections.filter((selection) => selection.queue.length > 0) + while (active.length > 0) { + const stillActive: typeof active = [] + for (const selection of active) { + const tool = selection.queue[0]! + const cost = estimate(catalogLine(tool)) + if (used + cost > maxInlineCatalogTokens) continue + selection.queue.shift() + selection.picked.add(tool) + used += cost + if (selection.queue.length > 0) stillActive.push(selection) + } + active = stillActive + } + const shown = new Map>( + selections.map(({ namespace, picked }) => [namespace, picked]), + ) + const totalShown = selections.reduce((total, { picked }) => total + picked.size, 0) + const complete = totalShown === described.length + + const empty = described.length === 0 + + // Section order is deliberate: workflow first (the top is the least likely part of a long + // description to be truncated or skimmed away), then rules, then syntax, with the budgeted + // catalog at the bottom. Example call forms use explicit `.` placeholders - + // never a real or fabricated tool name. + const intro = [ + "Write a CodeMode program to answer the request. Return code only.", + empty + ? "Execute JavaScript in a confined runtime." + : complete + ? "Execute JavaScript in a confined runtime. Inside this program, `tools` contains only the host-provided tools listed below; surrounding agent tools are not available unless listed here." + : "Execute JavaScript in a confined runtime. Inside this program, `tools` contains only the host-provided tools listed or searchable below; surrounding agent tools are not available unless listed here.", + ] + + // The search step exists only when search is advertised (PARTIAL catalog); a COMPLETE + // catalog already shows every signature, so step 1 picks from the list instead. + const workflow = empty + ? [] + : [ + "", + "## Workflow", + "", + ...(complete + ? [ + "1. Pick a tool from the list under `## Available tools` - each line is the exact call signature; use it as-is rather than guessing segments.", + "2. Call it using the exact signature shown: `const res = await tools..(input)` - bracket notation may appear for names that are not JavaScript identifiers.", + '3. Parse text results: `const data = typeof res === "string" ? JSON.parse(res) : res` - most tools return JSON as a string.', + "4. Return only the fields you need: `return { : data. }` - raw payloads get truncated and waste context.", + ] + : [ + '1. Find a tool (skip when it is already listed below): `const { items } = await tools.$codemode.search({ query: "" })` - short phrases like "list issues" work best.', + "2. Read the matches: each item is `{ path, description, signature }` - read the description before using an unfamiliar tool.", + "3. Call it with the result's `path` as-is (never guess segments): `const res = await tools..(input)` - bracket notation may appear for names that are not JavaScript identifiers.", + '4. Parse text results: `const data = typeof res === "string" ? JSON.parse(res) : res` - most tools return JSON as a string.', + "5. Return only the fields you need: `return { : data. }` - raw payloads get truncated and waste context.", + ]), + ] + + const rules = empty + ? [] + : [ + "", + "## Rules", + "", + complete + ? "- Only tools listed here are available inside `tools`; tools from the surrounding agent/runtime are not implicitly exposed." + : "- Only tools listed here or returned by `tools.$codemode.search` are available inside `tools`; tools from the surrounding agent/runtime are not implicitly exposed.", + "- Filter, aggregate, and transform collections in code - never return them raw or call a tool per item across messages.", + "- A result typed `Promise` has no guaranteed shape - verify what actually came back before relying on its fields.", + "- Run independent calls in parallel: `await Promise.all(items.map((item) => tools..(item)))`.", + "- `Object.keys(tools)` lists namespaces; `Object.keys(tools.)` lists its tools; `for...in` works on both.", + ...(complete + ? [] + : ['- Browse one namespace: `await tools.$codemode.search({ query: "", namespace: "" })`.']), + ] + + const syntax = [ + "", + "## Syntax", + "", + "Standard modern JavaScript works: functions/closures, destructuring, template literals, loops, try/catch, spread, optional chaining, the usual Array/String/Object/Math/JSON methods, plus Date, RegExp, Map, Set, and Promise.all/allSettled/race/resolve/reject.", + "TypeScript type annotations are allowed and stripped before execution (decorators are not supported).", + "Not supported (each fails with a message naming the alternative): classes, generators, for await...of, .then/.catch/.finally (use await with try/catch).", + "Dates serialize to ISO strings at data boundaries; Map/Set/RegExp serialize to `{}`.", + ] + + const toolSection: Array = [""] + if (empty) { + toolSection.push("## Available tools", "", "No tools are currently available.") + } else { + toolSection.push( + complete + ? "## Available tools (COMPLETE list - every tool is shown below with its full call signature)" + : `## Available tools (PARTIAL - ${totalShown} of ${described.length} shown; find the rest with tools.$codemode.search)`, + "", + ) + for (const [namespace, group] of ordered) { + const picked = shown.get(namespace)! + const count = `${group.length} tool${group.length === 1 ? "" : "s"}` + // Annotate only when a namespace is not fully shown, so a comprehensive + // namespace reads cleanly and a truncated one is unambiguous. + const label = + picked.size === group.length + ? count + : picked.size === 0 + ? `${count}, none shown` + : `${count}, ${picked.size} shown` + toolSection.push(`- ${namespace} (${label})`) + for (const tool of group) if (picked.has(tool)) toolSection.push(catalogLine(tool)) + } + if (!complete) { + toolSection.push("", "Search returns complete callable signatures:", `- ${searchSignature}`) + } + } + + const lines = [...intro, ...workflow, ...rules, ...syntax, ...toolSection] + return { + catalog: described, + instructions: lines.join("\n"), + searchIndex: visible.map(({ path, definition, description }) => toSearchEntry(path, definition, description)), + } +} + +/** + * The enumerable names at one node of the host tool tree - namespace names at the root, + * tool/namespace names below - powering `Object.keys(tools)` and `for...in` over tool + * references. A callable tool is a leaf and enumerates as `[]` (like `Object.keys` of a + * function in JS). An unknown path is an `UnknownTool` error pointing at the working + * discovery idioms, mirroring how calling an unknown tool fails. + */ +const namespaceKeys = ( + tools: HostTools, + path: ReadonlyArray, + searchEnabled: boolean, +): ReadonlyArray => { + // The reserved discovery namespace is virtual (never present in the host tree); enumerate + // it explicitly so `Object.keys(tools.$codemode)` matches the callable surface. + if (searchEnabled && path.length === 1 && path[0] === reservedNamespace) return ["search"] + let value: HostTool | Definition | HostTools = tools + for (const segment of path) { + if ( + isBlockedMember(segment) || + typeof value === "function" || + isDefinition(value) || + !Object.hasOwn(value, segment) + ) { + throw new ToolRuntimeError( + "UnknownTool", + `Unknown tool namespace '${path.join(".")}'.`, + searchEnabled + ? [ + "Object.keys(tools) lists the available namespaces; tools.$codemode.search({ query }) finds described tools.", + ] + : ["Object.keys(tools) lists the available namespaces."], + ) + } + value = value[segment] as HostTool | Definition | HostTools + } + if (typeof value === "function" || isDefinition(value)) return [] + return Object.keys(value) +} + +const resolve = ( + tools: HostTools, + path: ReadonlyArray, + searchEnabled: boolean, +): HostTool | Definition => { + let value: HostTool | Definition | HostTools = tools + + for (const segment of path) { + if ( + isBlockedMember(segment) || + typeof value === "function" || + isDefinition(value) || + !Object.hasOwn(value, segment) + ) { + throw new ToolRuntimeError( + "UnknownTool", + `Unknown tool '${path.join(".")}'.`, + searchEnabled ? ["Use tools.$codemode.search({ query }) to find available described tools."] : [], + ) + } + value = value[segment] as HostTool | Definition | HostTools + } + + if (typeof value !== "function" && !isDefinition(value)) { + throw new ToolRuntimeError("UnknownTool", `Tool '${path.join(".")}' is not callable.`) + } + + return value +} + +export type ToolRuntime = { + readonly root: ToolReference + readonly calls: Array + readonly invoke: (path: ReadonlyArray, args: Array) => Effect.Effect + /** Enumerable namespace/tool names at one node of the host tool tree; see `namespaceKeys`. */ + readonly keys: (path: ReadonlyArray) => ReadonlyArray +} + +const failureMessage = (error: unknown): string => + error instanceof ToolError || error instanceof ToolRuntimeError ? error.message : "Tool execution failed" + +export const make = ( + tools: HostTools, + /** Undefined means unlimited tool calls. */ + maxToolCalls: number | undefined, + hooks?: ToolCallHooks, + searchIndex?: ReadonlyArray, +): ToolRuntime => { + const calls: Array = [] + const searchEnabled = searchIndex !== undefined + + // Wraps the settling portion of a tool call so onToolCallEnd observes success and failure + // symmetrically. Interruption (e.g. the execution timeout) fires neither outcome. + const observeEnd = (effect: Effect.Effect, call: ToolCallStarted): Effect.Effect => { + const onEnd = hooks?.onToolCallEnd + if (onEnd === undefined) return effect + const startedAt = Date.now() + return effect.pipe( + Effect.tap(() => onEnd({ ...call, durationMs: Date.now() - startedAt, outcome: "success" })), + Effect.tapError((error) => + onEnd({ ...call, durationMs: Date.now() - startedAt, outcome: "failure", message: failureMessage(error) }), + ), + ) + } + + const decodeOutput = (value: unknown, name: string) => + Effect.try({ + try: () => copyIn(value, `Result from tool '${name}'`), + catch: () => new ToolRuntimeError("InvalidToolOutput", `Invalid output from tool '${name}'.`), + }) + + const recordCall = (call: ToolCall): void => { + if (maxToolCalls !== undefined && calls.length >= maxToolCalls) { + throw new ToolRuntimeError("ToolCallLimitExceeded", `Execution exceeded its tool-call limit of ${maxToolCalls}.`) + } + calls.push(call) + } + + return { + root: new ToolReference([]), + calls, + keys: (path) => namespaceKeys(tools, path, searchEnabled), + invoke: (path, args) => + Effect.gen(function* () { + const name = path.join(".") + const externalArgs = args.map((arg) => copyOut(copyIn(arg, `Arguments for tool '${name}'`))) + const call = { name } + const recordAndObserve = (input: unknown) => + Effect.sync(() => { + recordCall(call) + return calls.length - 1 + }).pipe(Effect.tap((index) => hooks?.onToolCallStart?.({ index, name, input }) ?? Effect.void)) + if (name === "$codemode.search") { + if (!searchEnabled) throw new ToolRuntimeError("UnknownTool", `Unknown tool '${name}'.`) + const input = externalArgs[0] + if (externalArgs.length !== 1 || input === null || typeof input !== "object" || Array.isArray(input)) { + throw new ToolRuntimeError( + "InvalidToolInput", + "tools.$codemode.search expects { query?: string; namespace?: string; limit?: number }.", + ) + } + const request = input as { query?: unknown; namespace?: unknown; limit?: unknown } + if (request.query !== undefined && typeof request.query !== "string") { + throw new ToolRuntimeError( + "InvalidToolInput", + "tools.$codemode.search query must be a string when provided.", + ) + } + if (request.namespace !== undefined && typeof request.namespace !== "string") { + throw new ToolRuntimeError( + "InvalidToolInput", + "tools.$codemode.search namespace must be a string when provided.", + ) + } + if ( + request.limit !== undefined && + (typeof request.limit !== "number" || !Number.isSafeInteger(request.limit) || request.limit <= 0) + ) { + throw new ToolRuntimeError( + "InvalidToolInput", + "tools.$codemode.search limit must be a positive safe integer when provided.", + ) + } + const query = typeof request.query === "string" ? request.query : "" + const namespace = typeof request.namespace === "string" ? request.namespace : undefined + const index = yield* recordAndObserve(request) + return yield* observeEnd( + Effect.try({ + try: () => { + const limit = typeof request.limit === "number" ? request.limit : defaultSearchLimit + const scoped = + namespace === undefined ? searchIndex : searchIndex.filter((entry) => entry.namespace === namespace) + // A query that names one tool path exactly (canonical path or rendered + // JavaScript expression) is a lookup, not a search: return that tool alone. + const trimmed = query.trim() + const pathQuery = trimmed.startsWith("tools.") ? trimmed.slice("tools.".length) : trimmed + const exact = + pathQuery === "" + ? undefined + : scoped.find( + (entry) => + entry.description.path === pathQuery || toolExpression(entry.description.path) === trimmed, + ) + const terms = tokenize(query).map(termForms) + // Additive field-weighted scoring, summed across terms: exact path or path + // segment (20) > path substring (8) > description substring (4) > any + // searchable text, incl. input parameter names/descriptions (2). Each term + // matches a field when any of its forms (the term or a singular variant) + // does. An empty query browses everything, alphabetical by path. + const ranked = + exact !== undefined + ? [exact] + : scoped + .map((entry) => { + const path = entry.description.path.toLowerCase() + const description = entry.description.description.toLowerCase() + const score = terms.reduce( + (total, forms) => + total + + (forms.some((form) => path === form || path.endsWith(`.${form}`)) ? 20 : 0) + + (forms.some((form) => path.includes(form)) ? 8 : 0) + + (forms.some((form) => description.includes(form)) ? 4 : 0) + + (forms.some((form) => entry.searchText.includes(form)) ? 2 : 0), + 0, + ) + return { entry, score } + }) + .filter(({ score }) => terms.length === 0 || score > 0) + .sort( + (left, right) => + right.score - left.score || + left.entry.description.path.localeCompare(right.entry.description.path), + ) + .map(({ entry }) => entry) + // Result paths are rendered as JavaScript expressions so each `path` is + // directly usable as the call site (`await tools.github.list({ ... })` or + // `await tools.ns["dashed-name"]({ ... })`). The signature is the pretty, + // JSDoc-annotated form (schema descriptions and constraints ride along as + // field comments). + const items = ranked.slice(0, limit).map(({ description, signature }) => ({ + ...description, + path: toolExpression(description.path), + signature, + })) + return copyIn({ items, total: ranked.length }, "Result from tool '$codemode.search'") + }, + catch: (cause) => cause, + }), + { index, name, input: request }, + ) + } + + const tool = resolve(tools, path, searchEnabled) + let describedInput: unknown + if (isDefinition(tool)) { + if (externalArgs.length !== 1) + throw new ToolRuntimeError("InvalidToolInput", `Tool '${name}' expects exactly one input object.`) + describedInput = yield* Effect.try({ + try: () => decodeToolInput(tool, externalArgs[0]), + catch: (cause) => + new ToolRuntimeError("InvalidToolInput", `Invalid input for tool '${name}': ${String(cause)}`), + }) + } + const input = isDefinition(tool) ? describedInput : externalArgs + const index = yield* recordAndObserve(input) + const currentCall = { index, name, input } + if (isDefinition(tool)) { + return yield* observeEnd( + Effect.gen(function* () { + const raw = yield* runHost(Effect.suspend(() => tool.run(describedInput))) + const result = yield* Effect.try({ + try: () => decodeToolOutput(tool, raw), + catch: () => new ToolRuntimeError("InvalidToolOutput", `Invalid output from tool '${name}'.`), + }) + return yield* decodeOutput(result, name) + }), + currentCall, + ) + } + return yield* observeEnd( + Effect.gen(function* () { + return yield* decodeOutput(yield* runHost(Effect.suspend(() => tool(...externalArgs))), name) + }), + currentCall, + ) + }), + } +} + +export * as ToolRuntime from "./tool-runtime.js" diff --git a/packages/codemode/src/tool.ts b/packages/codemode/src/tool.ts new file mode 100644 index 0000000000..5a0d84ad52 --- /dev/null +++ b/packages/codemode/src/tool.ts @@ -0,0 +1,348 @@ +import { Effect, Schema } from "effect" + +/** + * JSON Schema subset accepted for render-only tool schemas. + * + * A JSON-Schema-described side of a tool is used to generate the model-visible TypeScript + * signature only - CodeMode performs no validation against it. This is the natural shape for + * adapter-provided tools (e.g. MCP definitions) whose schemas arrive as JSON Schema documents. + */ +export type JsonSchema = { + readonly type?: string | ReadonlyArray + readonly enum?: ReadonlyArray + readonly const?: unknown + readonly anyOf?: ReadonlyArray + readonly oneOf?: ReadonlyArray + readonly properties?: Readonly> + readonly required?: ReadonlyArray + readonly items?: JsonSchema + readonly additionalProperties?: boolean | JsonSchema + readonly description?: string + readonly default?: unknown + readonly format?: string + readonly deprecated?: boolean + readonly minItems?: number + readonly maxItems?: number + readonly $ref?: string + readonly $defs?: Readonly> + readonly definitions?: Readonly> +} + +/** Either a validating Effect Schema or a render-only JSON Schema document. */ +export type ToolSchema = Schema.Decoder | JsonSchema + +/** Schema-backed tool definition consumed by a CodeMode tool tree. */ +export type Definition = { + readonly _tag: "CodeModeTool" + readonly description: string + readonly input: ToolSchema + readonly output: ToolSchema | undefined + readonly run: (input: unknown) => Effect.Effect +} + +/** The value `run` receives: the decoded type for Effect Schemas, `unknown` for JSON Schemas. */ +export type InputType = S extends Schema.Decoder ? S["Type"] : unknown + +/** The value `run` returns: the encoded type for Effect Schemas, `unknown` otherwise. */ +export type ResultType = S extends Schema.Decoder ? S["Encoded"] : unknown + +/** Options for defining one CodeMode tool. */ +export type Options = { + readonly description: string + readonly input: I + readonly output?: O + readonly run: (input: InputType) => Effect.Effect, unknown, R> +} + +export const isDefinition = (value: unknown): value is Definition => + typeof value === "object" && value !== null && "_tag" in value && value._tag === "CodeModeTool" + +const isEffectSchema = (schema: ToolSchema): schema is Schema.Decoder & Schema.Top => Schema.isSchema(schema) + +const renderLiteral = (value: unknown): string => JSON.stringify(value) ?? "unknown" + +/** + * Bare TypeScript identifier - usable unquoted as an object key (and, in the tool runtime, + * with dot access as a tool-path segment). Anything else must be quoted/bracketed. + */ +export const identifierSegment = /^[A-Za-z_$][A-Za-z0-9_$]*$/ + +/** Renders a property name as a valid TS object key: bare when an identifier, quoted otherwise. */ +const renderKey = (name: string): string => (identifierSegment.test(name) ? name : JSON.stringify(name)) + +const effectNumberSentinel = (schema: JsonSchema) => + schema.type === "string" && + Array.isArray(schema.enum) && + schema.enum.length === 1 && + (schema.enum[0] === "NaN" || schema.enum[0] === "Infinity" || schema.enum[0] === "-Infinity") + +/** + * Recursion ceiling for schema rendering. Object, array, and union recursion all increment + * depth, so this bounds every recursion path - pathological or structurally cyclic schemas + * degrade to `unknown` instead of overflowing the stack (rendering must never throw). + */ +const MAX_RENDER_DEPTH = 8 + +type RenderContext = { + readonly definitions: Readonly> + /** Indented, JSDoc-annotated multiline rendering (search results); compact single line otherwise. */ + readonly pretty: boolean +} + +/** + * Schema constraints a TypeScript type cannot express natively but a model benefits from, + * surfaced as JSDoc tags (`@deprecated`, `@default`, `@format`, `@minItems`, `@maxItems`). + */ +const docTags = (schema: JsonSchema): Array => { + const tags: Array = [] + if (schema.deprecated === true) tags.push("@deprecated") + if (schema.default !== undefined) { + try { + const rendered = JSON.stringify(schema.default) + if (rendered !== undefined) tags.push(`@default ${rendered}`) + } catch { + // unserializable default: skip rather than emit a broken tag + } + } + if (typeof schema.format === "string") tags.push(`@format ${schema.format}`) + if (typeof schema.minItems === "number") tags.push(`@minItems ${schema.minItems}`) + if (typeof schema.maxItems === "number") tags.push(`@maxItems ${schema.maxItems}`) + return tags +} + +/** + * Format a schema `description` plus `tags` as a JSDoc comment at the given indent, + * preserving multi-line text (a single line stays `/** ... *\/`; multiple lines become a + * `*`-prefixed block). `*\/` is neutralized so nothing can close the comment early, and + * blank leading/trailing lines are trimmed. Returns "" (else a trailing newline) so + * callers can prepend it directly to the field line. + */ +const jsdoc = (description: string | undefined, tags: ReadonlyArray, pad: string): string => { + const lines = [...(description === undefined ? [] : description.split("\n")), ...tags].map((line) => + line.replaceAll("*/", "* /").replace(/\s+$/, ""), + ) + while (lines.length > 0 && lines[0]!.trim() === "") lines.shift() + while (lines.length > 0 && lines[lines.length - 1]!.trim() === "") lines.pop() + if (lines.length === 0) return "" + if (lines.length === 1) return `${pad}/** ${lines[0]} */\n` + const body = lines.map((line) => `${pad} *${line === "" ? "" : ` ${line}`}`).join("\n") + return `${pad}/**\n${body}\n${pad} */\n` +} + +const renderSchema = ( + schema: JsonSchema, + ctx: RenderContext, + depth = 0, + seen: ReadonlySet = new Set(), +): string => { + if (depth > MAX_RENDER_DEPTH) return "unknown" + if (schema.$ref) { + const name = schema.$ref.split("/").pop() + if (!name || !ctx.definitions[name]) return name ?? "unknown" + if (seen.has(name)) return name // recursive type: reference by name rather than loop + return renderSchema(ctx.definitions[name], ctx, depth, new Set([...seen, name])) + } + if (schema.const !== undefined) return renderLiteral(schema.const) + if (schema.enum) return schema.enum.map(renderLiteral).join(" | ") + const alternatives = schema.anyOf ?? schema.oneOf + if (alternatives) { + // Effect's number schema emits `anyOf: [{ type: "number" }, { const: "NaN" }, + // { const: "Infinity" }, { const: "-Infinity" }]`. Collapse only that artifact; + // real JSON Schema unions such as `string | number` or `number | null` must keep + // every branch. + if ( + alternatives.some((item) => item.type === "number") && + alternatives.every((item) => item.type === "number" || effectNumberSentinel(item)) + ) + return "number" + // An empty Schema.Struct({}) emits `anyOf: [{ type: "object" }, { type: "array" }]` + // (no properties/items); render the bare shape as {} instead of `{} | Array`. + if ( + alternatives.length === 2 && + alternatives[0]?.type === "object" && + alternatives[0].properties === undefined && + alternatives[1]?.type === "array" && + alternatives[1].items === undefined + ) { + return "{}" + } + return alternatives.map((item) => renderSchema(item, ctx, depth + 1, seen)).join(" | ") + } + if (Array.isArray(schema.type)) { + return schema.type.map((item) => renderSchema({ type: item }, ctx, depth + 1, seen)).join(" | ") + } + if (schema.type === "string") return "string" + if (schema.type === "number" || schema.type === "integer") return "number" + if (schema.type === "boolean") return "boolean" + if (schema.type === "null") return "null" + if (schema.type === "array") return `Array<${renderSchema(schema.items ?? {}, ctx, depth + 1, seen)}>` + if (schema.type === "object" || schema.properties) { + const required = new Set(schema.required ?? []) + const properties = Object.entries(schema.properties ?? {}) + const additional = schema.additionalProperties + const indexType = + additional && typeof additional === "object" ? renderSchema(additional, ctx, depth + 1, seen) : undefined + const field = ([name, value]: readonly [string, JsonSchema]) => + `${renderKey(name)}${required.has(name) ? "" : "?"}: ${renderSchema(value, ctx, depth + 1, seen)}` + + if (!ctx.pretty) { + const fields = properties.map(field) + if (indexType !== undefined) fields.push(`[key: string]: ${indexType}`) + return fields.length === 0 ? "{}" : `{ ${fields.join("; ")} }` + } + + // Pretty: an indented block, each described field preceded by its JSDoc comment. + if (properties.length === 0 && indexType === undefined) return "{}" + const pad = " ".repeat(depth + 1) + const lines = properties.map( + (entry) => `${jsdoc(entry[1].description, docTags(entry[1]), pad)}${pad}${field(entry)}`, + ) + if (indexType !== undefined) lines.push(`${pad}[key: string]: ${indexType}`) + return `{\n${lines.join("\n")}\n${" ".repeat(depth)}}` + } + return "unknown" +} + +export const toTypeScript = (schema: Schema.Top, decoded = false, pretty = false): string => { + try { + const visible = decoded ? Schema.toType(schema) : schema + const document = Schema.toJsonSchemaDocument(visible) as { + readonly schema: JsonSchema + readonly definitions?: Readonly> + } + return renderSchema(document.schema, { definitions: document.definitions ?? {}, pretty }) + } catch { + return "unknown" + } +} + +/** Renders a raw JSON Schema document as a TypeScript type string. */ +export const jsonSchemaToTypeScript = (schema: JsonSchema, pretty = false): string => { + try { + return renderSchema(schema, { definitions: { ...(schema.definitions ?? {}), ...(schema.$defs ?? {}) }, pretty }) + } catch { + return "unknown" + } +} + +/** One input property of a tool, extracted best-effort from its input schema. */ +export type InputProperty = { + readonly name: string + readonly description: string | undefined + readonly required: boolean +} + +/** + * The property names, descriptions, and required flags of a tool's input schema - the raw + * material for search text. Best-effort: Effect Schemas go through their + * JSON Schema document (the same emission signature rendering uses); JSON Schemas are read + * directly, resolving a trivial top-level `$ref` into `$defs`/`definitions` when present. + * Anything unresolvable yields `[]` (search falls back to path + description). + */ +export const inputProperties = (definition: Definition): Array => { + try { + const document = isEffectSchema(definition.input) + ? (Schema.toJsonSchemaDocument(definition.input) as { + readonly schema: JsonSchema + readonly definitions?: Readonly> + }) + : { + schema: definition.input, + definitions: { ...(definition.input.definitions ?? {}), ...(definition.input.$defs ?? {}) }, + } + const definitions = document.definitions ?? {} + let schema = document.schema + if (schema.$ref !== undefined) { + const name = schema.$ref.split("/").pop() + const resolved = name === undefined ? undefined : definitions[name] + if (resolved === undefined) return [] + schema = resolved + } + const required = new Set(schema.required ?? []) + return Object.entries(schema.properties ?? {}).map(([name, value]) => ({ + name, + description: typeof value.description === "string" ? value.description : undefined, + required: required.has(name), + })) + } catch { + return [] + } +} + +/** + * The model-visible TypeScript type of a tool's input. `pretty` renders an indented + * multiline block with schema descriptions and constraints as JSDoc comments on the + * fields; the default stays the compact single-line form. + */ +export const inputTypeScript = (definition: Definition, pretty = false): string => + isEffectSchema(definition.input) + ? toTypeScript(definition.input, false, pretty) + : jsonSchemaToTypeScript(definition.input, pretty) + +/** + * The model-visible TypeScript type of a tool's result; tools without an output schema + * return `unknown`. `pretty` renders the JSDoc-annotated multiline form, as for inputs. + */ +export const outputTypeScript = (definition: Definition, pretty = false): string => + definition.output === undefined + ? "unknown" + : isEffectSchema(definition.output) + ? toTypeScript(definition.output, true, pretty) + : jsonSchemaToTypeScript(definition.output, pretty) + +/** + * Decodes tool input before `run` is invoked. Effect Schemas validate (throwing on failure); + * JSON-Schema-described inputs pass through unvalidated (render-only). + */ +export const decodeInput = (definition: Definition, value: unknown): unknown => + isEffectSchema(definition.input) ? Schema.decodeUnknownSync(definition.input)(value) : value + +/** + * Decodes a tool result before it is exposed to the program. Effect Schemas validate and + * transform (throwing on failure); JSON Schema outputs and tools without an output schema pass + * the host value through unchanged. + */ +export const decodeOutput = (definition: Definition, value: unknown): unknown => + definition.output !== undefined && isEffectSchema(definition.output) + ? Schema.decodeUnknownSync(definition.output)(value) + : value + +/** + * Defines one schema-described tool available to a CodeMode program through `tools.*`. + * + * `input` and `output` each accept a validating Effect Schema or a render-only JSON Schema + * document. Effect Schema input is decoded before `run` is invoked, and `run` returns the + * encoded representation of an Effect Schema `output`, which CodeMode decodes before returning + * it to the program. JSON Schemas only shape the model-visible signature; values pass through + * unvalidated. `output` is optional - without it the signature advertises `unknown` and the + * host result is exposed as-is. The host tool remains responsible for authorization and + * durable side-effect handling. + * + * @example + * ```ts + * const lookup = Tool.make({ + * description: "Look up an order", + * input: Schema.Struct({ id: Schema.String }), + * output: Schema.Struct({ status: Schema.String }), + * run: ({ id }) => Effect.succeed({ status: "open" }), + * }) + * + * const fromJsonSchema = Tool.make({ + * description: "Call an adapter-described tool", + * input: { type: "object", properties: { id: { type: "string" } }, required: ["id"] }, + * run: (input) => callHost(input), + * }) + * ``` + */ +export const make = ( + options: Options, +): Definition => ({ + _tag: "CodeModeTool", + description: options.description, + input: options.input, + output: options.output, + run: (input) => options.run(input as InputType), +}) + +/** Constructors for schema-backed tools exposed inside CodeMode programs. */ +export const Tool = { make, isDefinition } diff --git a/packages/codemode/src/values.ts b/packages/codemode/src/values.ts new file mode 100644 index 0000000000..07f22adb8a --- /dev/null +++ b/packages/codemode/src/values.ts @@ -0,0 +1,34 @@ +import type { Effect, Fiber } from "effect" + +export class SandboxPromise { + interrupted = false + constructor( + readonly fiber: Fiber.Fiber | undefined, + readonly immediate?: Effect.Effect, + ) {} +} + +export class SandboxDate { + constructor(readonly time: number) {} +} + +export class SandboxRegExp { + readonly regex: RegExp + constructor(pattern: string, flags: string) { + this.regex = new RegExp(pattern, flags) + } +} + +export class SandboxMap { + readonly map = new Map() +} + +export class SandboxSet { + readonly set = new Set() +} + +export const isSandboxValue = (value: unknown): value is SandboxDate | SandboxRegExp | SandboxMap | SandboxSet => + value instanceof SandboxDate || + value instanceof SandboxRegExp || + value instanceof SandboxMap || + value instanceof SandboxSet diff --git a/packages/codemode/test/codemode.test.ts b/packages/codemode/test/codemode.test.ts new file mode 100644 index 0000000000..eaa834e0a4 --- /dev/null +++ b/packages/codemode/test/codemode.test.ts @@ -0,0 +1,1110 @@ +import { describe, expect, test } from "bun:test" +import { Cause, Effect, Schema } from "effect" +import { + CodeMode, + ExecuteInputSchema, + ExecuteResultSchema, + Tool, + toolError, + type ExecutionLimits, +} from "../src/index.js" +import type { Definition } from "../src/tool.js" + +const run = (tool: Definition) => + Effect.runPromise(CodeMode.make({ tools: { host: { call: tool } } }).execute("return await tools.host.call({})")) + +class UnsafeHostError extends Schema.TaggedErrorClass()("UnsafeHostError", { + reason: Schema.String, +}) {} + +describe("CodeMode host failure boundary", () => { + test("preserves explicit safe tool failures", async () => { + const result = await run( + Tool.make({ + description: "Fail safely", + input: Schema.Struct({}), + output: Schema.String, + run: () => Effect.fail(toolError("Authorized request was refused")), + }), + ) + + expect(result.ok ? undefined : result.error).toStrictEqual({ + kind: "ToolFailure", + message: "Authorized request was refused", + }) + }) + + test("sanitizes unknown host failures and defects", async () => { + for (const failure of [ + Effect.fail(new UnsafeHostError({ reason: "Authorization: Bearer typed-secret" })), + Effect.die(new Error("postgres://user:defect-secret@example.invalid")), + ]) { + const result = await run( + Tool.make({ + description: "Fail internally", + input: Schema.Struct({}), + output: Schema.String, + run: () => failure, + }), + ) + + expect(result.ok ? undefined : result.error).toStrictEqual({ + kind: "ToolFailure", + message: "Tool execution failed", + }) + expect(JSON.stringify(result)).not.toMatch(/typed-secret|defect-secret|Authorization: Bearer/) + } + }) + + test("sanitizes invalid host output", async () => { + const secret = "invalid-output-secret" + const result = await run( + Tool.make({ + description: "Return invalid output", + input: Schema.Struct({}), + output: Schema.Struct({ safe: Schema.String }), + run: () => Effect.succeed({ safe: 1, secret } as unknown as { readonly safe: string }), + }), + ) + + expect(result.ok ? undefined : result.error).toStrictEqual({ + kind: "InvalidToolOutput", + message: "Invalid output from tool 'host.call'.", + }) + expect(JSON.stringify(result)).not.toMatch(/invalid-output-secret/) + }) + + test("sanitizes host output that throws while being copied", async () => { + const result = await run( + Tool.make({ + description: "Return hostile output", + input: Schema.Struct({}), + output: Schema.Unknown, + run: () => + Effect.succeed( + new Proxy( + {}, + { + ownKeys: () => { + throw new Error("host-output-secret") + }, + }, + ), + ), + }), + ) + + expect(result.ok ? undefined : result.error).toStrictEqual({ + kind: "InvalidToolOutput", + message: "Invalid output from tool 'host.call'.", + }) + expect(JSON.stringify(result)).not.toMatch(/host-output-secret/) + }) + + test("caught tool failures are Error values in-program", async () => { + const result = await Effect.runPromise( + CodeMode.make({ + tools: { + host: { + call: Tool.make({ + description: "Refuse", + input: Schema.Struct({}), + output: Schema.String, + run: () => Effect.fail(toolError("Refused")), + }), + }, + }, + }).execute(` + try { + await tools.host.call({}) + return "no" + } catch (e) { + return { isError: e instanceof Error, message: e.message } + } + `), + ) + + expect(result.ok).toBe(true) + if (result.ok) expect(result.value).toStrictEqual({ isError: true, message: "Refused" }) + }) + + test("propagates host interruption instead of returning a diagnostic", async () => { + const exit = await Effect.runPromiseExit( + CodeMode.make({ + tools: { + host: { + call: Tool.make({ + description: "Interrupt", + input: Schema.Struct({}), + output: Schema.String, + run: () => Effect.interrupt, + }), + }, + }, + }).execute("return await tools.host.call({})"), + ) + + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true) + } + }) +}) + +describe("CodeMode tool-call observation", () => { + test("reports the tools actually invoked with decoded input", async () => { + const calls: Array = [] + const lookup = Tool.make({ + description: "Look up a value", + input: Schema.Struct({ query: Schema.String }), + output: Schema.String, + run: ({ query }) => Effect.succeed(query), + }) + + const result = await Effect.runPromise( + CodeMode.make({ + tools: { context: { lookup } }, + onToolCallStart: (call) => Effect.sync(() => calls.push(call)), + }).execute(` + if (false) await tools.context.lookup({ query: "not called" }) + return await tools.context.lookup({ query: "deployment failure" }) + `), + ) + + expect(result.ok).toBe(true) + expect(calls).toStrictEqual([{ index: 0, name: "context.lookup", input: { query: "deployment failure" } }]) + }) + + test("observes settled calls with outcome and duration", async () => { + const events: Array<{ phase: string; index: number; name: string; outcome?: string; message?: string }> = [] + const lookup = Tool.make({ + description: "Look up a value", + input: Schema.Struct({ query: Schema.String }), + output: Schema.String, + run: ({ query }) => (query === "boom" ? Effect.fail(toolError("Lookup refused")) : Effect.succeed(query)), + }) + + const runtime = CodeMode.make({ + tools: { context: { lookup } }, + onToolCallStart: (call) => + Effect.sync(() => { + events.push({ phase: "start", index: call.index, name: call.name }) + }), + onToolCallEnd: (call) => + Effect.sync(() => { + expect(call.durationMs).toBeGreaterThanOrEqual(0) + events.push({ + phase: "end", + index: call.index, + name: call.name, + outcome: call.outcome, + ...(call.message === undefined ? {} : { message: call.message }), + }) + }), + }) + + const success = await Effect.runPromise(runtime.execute(`return await tools.context.lookup({ query: "ok" })`)) + expect(success.ok).toBe(true) + const failure = await Effect.runPromise(runtime.execute(`return await tools.context.lookup({ query: "boom" })`)) + expect(failure.ok).toBe(false) + + expect(events).toStrictEqual([ + { phase: "start", index: 0, name: "context.lookup" }, + { phase: "end", index: 0, name: "context.lookup", outcome: "success" }, + { phase: "start", index: 0, name: "context.lookup" }, + { phase: "end", index: 0, name: "context.lookup", outcome: "failure", message: "Lookup refused" }, + ]) + }) +}) + +describe("CodeMode console capture", () => { + test("captures console output as bounded result logs", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + const returned = console.log("Thread info:", { name: "Demo", count: 2 }) + console.warn("careful") + return returned + `, + }), + ) + + expect(result).toStrictEqual({ + ok: true, + value: null, + logs: ['Thread info: {"name":"Demo","count":2}', "[warn] careful"], + toolCalls: [], + }) + expect(Schema.decodeUnknownSync(ExecuteResultSchema)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) + }) + + test("keeps logs captured before failures", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + console.log("before failure") + throw new Error("boom") + `, + }), + ) + + expect(result.ok ? undefined : result.logs).toStrictEqual(["before failure"]) + expect(result.ok ? undefined : result.error.message).toBe("Uncaught: boom") + }) + + test("prints NaN and Infinity literally instead of the JSON null", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + console.log(NaN) + console.log(Infinity, -Infinity) + console.log({ ratio: NaN, bounds: [Infinity] }) + return null + `, + }), + ) + + expect(result.ok).toBe(true) + expect(result.logs).toStrictEqual(["NaN", "Infinity -Infinity", '{"ratio":NaN,"bounds":[Infinity]}']) + }) + + test("renders sandbox values nested inside logged containers", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + console.log({ m: new Map([["a", 1]]), when: new Date(0), r: /ab/g, s: new Set([1, 2]) }) + console.log([new Date(0)]) + return null + `, + }), + ) + + expect(result.ok).toBe(true) + expect(result.logs).toStrictEqual([ + '{"m":Map(1) [["a",1]],"when":1970-01-01T00:00:00.000Z,"r":/ab/g,"s":Set(2) [1,2]}', + "[1970-01-01T00:00:00.000Z]", + ]) + }) + + test("console formatting is total: cycles and opaque references render as markers", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + const m = new Map() + m.set("self", m) + console.log({ box: m }) + console.log({ fn: (x) => x, ok: 1 }) + return null + `, + }), + ) + + expect(result.ok).toBe(true) + expect(result.logs).toStrictEqual(['{"box":Map(1) [["self",[Circular]]]}', '{"fn":[CodeMode reference],"ok":1}']) + }) + + test("console.table renders sandbox value cells", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + console.table([{ when: new Date(0), n: NaN }]) + return null + `, + }), + ) + + expect(result.ok).toBe(true) + expect(result.logs).toStrictEqual(["(index)\twhen\tn\n0\t1970-01-01T00:00:00.000Z\tNaN"]) + }) + + test("captures console.dir and console.table output", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + console.dir({ nested: { ok: true } }) + console.table([ + { name: "Kit", count: 1, hidden: "x" }, + { name: "Olive", count: 2, hidden: "y" } + ], ["name", "count"]) + return "done" + `, + }), + ) + + expect(result).toStrictEqual({ + ok: true, + value: "done", + logs: ['{"nested":{"ok":true}}', "(index)\tname\tcount\n0\tKit\t1\n1\tOlive\t2"], + toolCalls: [], + }) + }) +}) + +describe("CodeMode output budget", () => { + test("absent maxOutputBytes means no truncation at all", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: `console.log("z".repeat(50_000)); return "x".repeat(100_000)`, + }), + ) + + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.truncated).toBeUndefined() + expect(result.value).toBe("x".repeat(100_000)) + expect(result.logs).toStrictEqual(["z".repeat(50_000)]) + }) + + test("truncates an oversized result value with a marker instead of failing", async () => { + const limits: ExecutionLimits = { maxOutputBytes: 40 } + const result = await Effect.runPromise( + CodeMode.execute({ + code: `return { data: "${"x".repeat(200)}" }`, + limits, + }), + ) + + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.truncated).toBe(true) + expect(typeof result.value).toBe("string") + expect(result.value).toMatch( + /^\{"data":"x+ \[result truncated: \d+ bytes exceeds the 40-byte output limit; return a smaller value\]$/, + ) + expect(Schema.decodeUnknownSync(ExecuteResultSchema)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) + }) + + test("keeps leading logs within the remaining budget and marks the cut", async () => { + const limits: ExecutionLimits = { maxOutputBytes: 40 } + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + console.log("first line") + console.log("${"y".repeat(200)}") + return "ok" + `, + limits, + }), + ) + + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("ok") + expect(result.truncated).toBe(true) + expect(result.logs).toStrictEqual(["first line", "[logs truncated: showing 1 of 2 lines]"]) + }) + + test("does not mark results within the budget", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: ` + console.log("fits") + return { fits: true } + `, + }), + ) + expect(result).toStrictEqual({ + ok: true, + value: { fits: true }, + logs: ["fits"], + toolCalls: [], + }) + }) +}) + +describe("CodeMode schema flexibility", () => { + test("accepts render-only JSON Schema input and omitted output", async () => { + const observed: Array = [] + const call = Tool.make({ + description: "Call an adapter-described tool", + input: { + type: "object", + properties: { id: { type: "string" }, count: { type: "number" } }, + required: ["id"], + }, + run: (input) => + Effect.sync(() => { + observed.push(input) + return { echoed: input } + }), + }) + const runtime = CodeMode.make({ tools: { adapter: { call } } }) + + expect(runtime.catalog()).toStrictEqual([ + { + path: "adapter.call", + description: "Call an adapter-described tool", + signature: "tools.adapter.call(input: { id: string; count?: number }): Promise", + }, + ]) + + // JSON Schema is render-only: mistyped input passes through unvalidated. + const result = await Effect.runPromise(runtime.execute(`return await tools.adapter.call({ id: 42 })`)) + expect(result.ok).toBe(true) + if (result.ok) expect(result.value).toStrictEqual({ echoed: { id: 42 } }) + expect(observed).toStrictEqual([{ id: 42 }]) + }) + + test("renders JSON Schema outputs and $defs references", async () => { + const lookup = Tool.make({ + description: "Look up a user", + input: { type: "object", properties: { login: { type: "string" } }, required: ["login"] }, + output: { + $ref: "#/$defs/User", + $defs: { + User: { + type: "object", + properties: { login: { type: "string" }, id: { type: "number" } }, + required: ["login", "id"], + }, + }, + }, + run: () => Effect.succeed({ login: "kit", id: 7 }), + }) + const runtime = CodeMode.make({ tools: { users: { lookup } } }) + + expect(runtime.catalog()).toStrictEqual([ + { + path: "users.lookup", + description: "Look up a user", + signature: "tools.users.lookup(input: { login: string }): Promise<{ login: string; id: number }>", + }, + ]) + + const result = await Effect.runPromise(runtime.execute(`return await tools.users.lookup({ login: "kit" })`)) + expect(result.ok).toBe(true) + if (result.ok) expect(result.value).toStrictEqual({ login: "kit", id: 7 }) + }) + + test("Effect Schema output without an input transform still renders unknown when omitted", async () => { + const ping = Tool.make({ + description: "Ping", + input: Schema.Struct({ host: Schema.String }), + run: () => Effect.succeed("pong"), + }) + const runtime = CodeMode.make({ tools: { net: { ping } } }) + expect(runtime.catalog()[0]?.signature).toBe("tools.net.ping(input: { host: string }): Promise") + + const result = await Effect.runPromise(runtime.execute(`return await tools.net.ping({ host: "example.test" })`)) + expect(result.ok).toBe(true) + if (result.ok) expect(result.value).toBe("pong") + }) +}) + +describe("CodeMode public contract", () => { + const lookup = Tool.make({ + description: "Look up an order by ID", + input: Schema.Struct({ id: Schema.String }), + output: Schema.Struct({ id: Schema.String, status: Schema.String }), + run: ({ id }) => Effect.succeed({ id, status: "open" }), + }) + const tools = { orders: { lookup } } + const source = `return await tools.orders.lookup({ id: "order_42" })` + + test("keeps one-shot, reusable, and agent-tool execution equivalent", async () => { + const runtime = CodeMode.make({ tools }) + const agentTool = runtime.agentTool() + const [oneShot, reusable, projected] = await Promise.all([ + Effect.runPromise(CodeMode.execute({ tools, code: source })), + Effect.runPromise(runtime.execute(source)), + Effect.runPromise(agentTool.execute({ code: source })), + ]) + + expect(reusable).toStrictEqual(oneShot) + expect(projected).toStrictEqual(oneShot) + expect(agentTool.name).toBe("code") + expect(agentTool.input).toBe(ExecuteInputSchema) + expect(agentTool.output).toBe(ExecuteResultSchema) + expect(agentTool.description).toBe(runtime.instructions()) + expect(Schema.decodeUnknownSync(ExecuteResultSchema)(JSON.parse(JSON.stringify(projected)))).toStrictEqual( + projected, + ) + }) + + test("inlines a COMPLETE small catalog and keeps search registered but unadvertised", async () => { + const runtime = CodeMode.make({ tools }) + expect(runtime.catalog()).toStrictEqual([ + { + path: "orders.lookup", + description: "Look up an order by ID", + signature: "tools.orders.lookup(input: { id: string }): Promise<{ id: string; status: string }>", + }, + ]) + expect(runtime.instructions()).toContain("Available tools (COMPLETE list") + expect(runtime.instructions()).toContain("- orders (1 tool)") + expect(runtime.instructions()).toContain( + " - tools.orders.lookup(input: { id: string }): Promise<{ id: string; status: string }> // Look up an order by ID", + ) + // A fully inlined catalog does not advertise search in the instructions... + expect(runtime.instructions()).not.toMatch(/\$codemode/) + + // ...but the search tool stays registered, so a speculative call still works. Search + // results carry the pretty multiline signature; the inline catalog stays compact. + const result = await Effect.runPromise(runtime.execute(`return await tools.$codemode.search({ query: "order" })`)) + expect(result.ok).toBe(true) + if (result.ok) { + expect(result.value).toStrictEqual({ + items: [ + { + path: "tools.orders.lookup", + description: "Look up an order by ID", + signature: "tools.orders.lookup(input: {\n id: string\n}): Promise<{\n id: string\n status: string\n}>", + }, + ], + total: 1, + }) + } + }) + + test("renders bracket notation for tool names that are not JavaScript identifiers", async () => { + const resolveLibrary = Tool.make({ + description: "Resolve a library ID", + input: Schema.Struct({ libraryName: Schema.String }), + output: Schema.String, + run: ({ libraryName }) => Effect.succeed(`/resolved/${libraryName}`), + }) + const runtime = CodeMode.make({ tools: { context7: { "resolve-library-id": resolveLibrary } } }) + + expect(runtime.catalog()).toStrictEqual([ + { + path: "context7.resolve-library-id", + description: "Resolve a library ID", + signature: 'tools.context7["resolve-library-id"](input: { libraryName: string }): Promise', + }, + ]) + expect(runtime.instructions()).toContain( + 'tools.context7["resolve-library-id"](input: { libraryName: string }): Promise', + ) + + const search = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: "resolve library id" })`), + ) + expect(search.ok).toBe(true) + if (search.ok) { + expect(search.value).toStrictEqual({ + items: [ + { + path: 'tools.context7["resolve-library-id"]', + description: "Resolve a library ID", + signature: 'tools.context7["resolve-library-id"](input: {\n libraryName: string\n}): Promise', + }, + ], + total: 1, + }) + } + + const call = await Effect.runPromise( + runtime.execute(`return await tools.context7["resolve-library-id"]({ libraryName: "TypeScript" })`), + ) + expect(call.ok).toBe(true) + if (call.ok) expect(call.value).toBe("/resolved/TypeScript") + + const exact = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: 'tools.context7["resolve-library-id"]' })`), + ) + expect(exact.ok).toBe(true) + if (exact.ok) expect((exact.value as { total: number }).total).toBe(1) + }) + + test("instructions use markdown sections with placeholder-only call forms", () => { + const runtime = CodeMode.make({ tools }) + const instructions = runtime.instructions() + // Sections in order: workflow at the top, catalog at the bottom. + expect(instructions).toContain("## Workflow") + expect(instructions).toContain("## Rules") + expect(instructions).toContain("## Syntax") + expect(instructions.indexOf("## Workflow")).toBeLessThan(instructions.indexOf("## Rules")) + expect(instructions.indexOf("## Rules")).toBeLessThan(instructions.indexOf("## Syntax")) + expect(instructions.indexOf("## Syntax")).toBeLessThan(instructions.indexOf("\n## Available tools (COMPLETE list")) + // The workflow carries the result-shape guidance; Rules only add content beyond it. + expect(instructions).toContain( + '`const data = typeof res === "string" ? JSON.parse(res) : res` - most tools return JSON as a string', + ) + expect(instructions).toContain("Return only the fields you need") + expect(instructions).toContain("raw payloads get truncated and waste context") + expect(instructions).toContain("`const res = await tools..(input)`") + expect(instructions).toContain("surrounding agent tools are not available unless listed here") + expect(instructions).toContain("Only tools listed here are available inside `tools`") + expect(instructions).toContain("bracket notation may appear for names that are not JavaScript identifiers") + // Placeholders use the ./ style ONLY - no fabricated tool + // names, and no real catalog tools cherry-picked into example lines. + expect(instructions).toContain("`return { : data. }`") + expect(instructions).not.toContain("total_count") + expect(instructions).not.toContain("list_issues") + expect(instructions).not.toContain("tools.orders.lookup({") + // COMPLETE: step 1 picks from the inlined list; search is not advertised. + expect(instructions).toContain("1. Pick a tool from the list under `## Available tools`") + expect(instructions).not.toContain("Browse one namespace") + + const partial = CodeMode.make({ tools, discovery: { maxInlineCatalogTokens: 0 } }).instructions() + // PARTIAL: the workflow starts with search (with query-style guidance that is clearly + // a query string, never a tool name) and the browse-namespace rule appears. + expect(partial).toContain( + '1. Find a tool (skip when it is already listed below): `const { items } = await tools.$codemode.search({ query: "" })` - short phrases like "list issues" work best.', + ) + expect(partial).toContain( + "Only tools listed here or returned by `tools.$codemode.search` are available inside `tools`", + ) + expect(partial).toContain( + '- Browse one namespace: `await tools.$codemode.search({ query: "", namespace: "" })`.', + ) + expect(partial).not.toContain("total_count") + expect(partial).not.toContain("tools.orders.lookup({") + }) + + test("the syntax section names what is unusual or missing, not an allowlist", () => { + const instructions = CodeMode.make({ tools }).instructions() + // Models already know JavaScript; the section leads with that. + expect(instructions).toContain("Standard modern JavaScript works") + expect(instructions).toContain("TypeScript type annotations are allowed and stripped before execution") + // The not-supported list is derived from (and verified against) the interpreter. + expect(instructions).toContain("Not supported") + for (const missing of ["classes", "generators", "for await...of", ".then/.catch/.finally"]) { + expect(instructions).toContain(missing) + } + // Implemented by the DSL-expansion pass, so no longer listed as missing. + expect(instructions).not.toContain("instanceof Error") + expect(instructions).not.toContain("splice") + // The data-boundary note survives. + expect(instructions).toContain( + "Dates serialize to ISO strings at data boundaries; Map/Set/RegExp serialize to `{}`.", + ) + }) + + test("zero tools keep minimal sections and the no-tools notice", () => { + const runtime = CodeMode.make({}) + const instructions = runtime.instructions() + expect(instructions).toContain("No tools are currently available.") + expect(instructions).toContain("## Syntax") + expect(instructions).toContain("## Available tools") + expect(instructions).not.toContain("## Workflow") + expect(instructions).not.toContain("## Rules") + expect(instructions).not.toMatch(/\$codemode/) + }) + + test("uses one ranked search returning complete definitions for large catalogs", async () => { + const upload = Tool.make({ + description: "Upload one readable local file to the current Discord thread", + input: Schema.Struct({ path: Schema.String }), + output: Schema.Struct({ sent: Schema.Boolean }), + run: () => Effect.succeed({ sent: true }), + }) + const generate = Tool.make({ + description: "Generate an image and upload it to the current Discord thread", + input: Schema.Struct({ prompt: Schema.String }), + output: Schema.Struct({ sent: Schema.Boolean }), + run: () => Effect.succeed({ sent: true }), + }) + const runtime = CodeMode.make({ + tools: { thread: { uploadFile: upload, generateImage: generate }, orders: { lookup } }, + discovery: { maxInlineCatalogTokens: 0 }, + }) + expect(runtime.instructions()).toContain( + "Available tools (PARTIAL - 0 of 3 shown; find the rest with tools.$codemode.search)", + ) + expect(runtime.instructions()).toContain("- thread (2 tools, none shown)") + expect(runtime.instructions()).toContain("- orders (1 tool, none shown)") + expect(runtime.instructions()).toMatch(/\$codemode\.search/) + expect(runtime.instructions()).not.toMatch(/tools\.thread\.uploadFile\(input/) + + const result = await Effect.runPromise( + runtime.execute(` + return await tools.$codemode.search({ + query: "send message attachment upload file to current Discord thread", + limit: 2 + }) + `), + ) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toStrictEqual({ + items: [ + { + path: "tools.thread.uploadFile", + description: "Upload one readable local file to the current Discord thread", + signature: "tools.thread.uploadFile(input: {\n path: string\n}): Promise<{\n sent: boolean\n}>", + }, + { + path: "tools.thread.generateImage", + description: "Generate an image and upload it to the current Discord thread", + signature: "tools.thread.generateImage(input: {\n prompt: string\n}): Promise<{\n sent: boolean\n}>", + }, + ], + total: 2, + }) + expect(result.toolCalls).toStrictEqual([{ name: "$codemode.search" }]) + + const variants = await Effect.runPromise( + runtime.execute(` + return await Promise.all([ + tools.$codemode.search({ query: "file" }), + tools.$codemode.search({ query: "image" }) + ]) + `), + ) + expect(variants.ok).toBe(true) + if (variants.ok) { + expect((variants.value as Array<{ items: Array<{ path: string }> }>)[0]?.items[0]?.path).toBe( + "tools.thread.uploadFile", + ) + expect((variants.value as Array<{ items: Array<{ path: string }> }>)[1]?.items[0]?.path).toBe( + "tools.thread.generateImage", + ) + } + + const removed = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.describe({ path: "thread.uploadFile" })`), + ) + expect(removed.ok).toBe(false) + if (!removed.ok) expect(removed.error.kind).toBe("UnknownTool") + }) + + test("search defaults to 10 results and resolves exact tool paths", async () => { + const tool = (index: number) => + Tool.make({ + description: `Numbered tool ${index}`, + input: Schema.Struct({ id: Schema.String }), + output: Schema.String, + run: () => Effect.succeed("ok"), + }) + const runtime = CodeMode.make({ + tools: { + many: Object.fromEntries(Array.from({ length: 14 }, (_, index) => [`tool${index}`, tool(index)])), + }, + }) + + const browse = await Effect.runPromise(runtime.execute(`return await tools.$codemode.search({})`)) + expect(browse.ok).toBe(true) + if (browse.ok) { + const value = browse.value as { items: Array<{ path: string }>; total: number } + expect(value.items).toHaveLength(10) + expect(value.total).toBe(14) + } + + for (const query of ["many.tool13", "tools.many.tool13"]) { + const exact = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: ${JSON.stringify(query)} })`), + ) + expect(exact.ok).toBe(true) + if (exact.ok) { + expect(exact.value).toStrictEqual({ + items: [ + { + path: "tools.many.tool13", + description: "Numbered tool 13", + signature: "tools.many.tool13(input: {\n id: string\n}): Promise", + }, + ], + total: 1, + }) + } + } + }) + + test("scopes search to one namespace and browses it alphabetically", async () => { + const simple = (description: string) => + Tool.make({ + description, + input: Schema.Struct({ id: Schema.String }), + output: Schema.String, + run: () => Effect.succeed("ok"), + }) + const runtime = CodeMode.make({ + tools: { + github: { list_issues: simple("List issues"), create_issue: simple("Create an issue") }, + linear: { list_issues: simple("List Linear issues") }, + }, + }) + + // Empty query + namespace browses just that namespace, alphabetical by path. + const browse = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: "", namespace: "github" })`), + ) + expect(browse.ok).toBe(true) + if (browse.ok) { + const value = browse.value as { items: Array<{ path: string }>; total: number } + expect(value.total).toBe(2) + expect(value.items.map((item) => item.path)).toStrictEqual([ + "tools.github.create_issue", + "tools.github.list_issues", + ]) + } + + // A query + namespace ranks within that namespace only. + const scoped = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: "issues", namespace: "linear" })`), + ) + expect(scoped.ok).toBe(true) + if (scoped.ok) { + const value = scoped.value as { items: Array<{ path: string }>; total: number } + expect(value.total).toBe(1) + expect(value.items[0]?.path).toBe("tools.linear.list_issues") + } + + const invalid = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: "issues", namespace: 7 })`), + ) + expect(invalid.ok).toBe(false) + if (!invalid.ok) expect(invalid.error.kind).toBe("InvalidToolInput") + }) + + test("matches input parameter names and partial-word substrings", async () => { + const upload = Tool.make({ + description: "Send a document to the workspace", + input: { + type: "object", + properties: { attachment: { type: "string", description: "Local path of the payload to send" } }, + required: ["attachment"], + }, + run: () => Effect.succeed("ok"), + }) + const other = Tool.make({ + description: "Rename the workspace", + input: Schema.Struct({ name: Schema.String }), + output: Schema.String, + run: () => Effect.succeed("ok"), + }) + const runtime = CodeMode.make({ tools: { files: { upload, other } } }) + + // "attachment" appears in neither path nor description - only in the input schema's + // property names, which the searchable text includes. + const byParameter = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: "attachment" })`), + ) + expect(byParameter.ok).toBe(true) + if (byParameter.ok) { + const value = byParameter.value as { items: Array<{ path: string }>; total: number } + expect(value.total).toBe(1) + expect(value.items[0]?.path).toBe("tools.files.upload") + } + + // Substring matching: a partial word ("docum") still hits the description. + const bySubstring = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: "docum" })`), + ) + expect(bySubstring.ok).toBe(true) + if (bySubstring.ok) { + const value = bySubstring.value as { items: Array<{ path: string }>; total: number } + expect(value.total).toBe(1) + expect(value.items[0]?.path).toBe("tools.files.upload") + } + }) + + test("a plural query term matches singular-only tool text", async () => { + const simple = (description: string) => + Tool.make({ + description, + input: Schema.Struct({ id: Schema.String }), + output: Schema.String, + run: () => Effect.succeed("ok"), + }) + const runtime = CodeMode.make({ + tools: { + // Neither path nor description contains "issues" - only the singular "issue". + tracker: { fetch_all: simple("Fetch every open issue in the project") }, + github: { list_issues: simple("List issues") }, + misc: { rename: simple("Rename the workspace") }, + }, + }) + + // "issues" still finds the singular-only tool (term OR singular(term) per field)... + const plural = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: "issues", namespace: "tracker" })`), + ) + expect(plural.ok).toBe(true) + if (plural.ok) { + const value = plural.value as { items: Array<{ path: string }>; total: number } + expect(value.total).toBe(1) + expect(value.items[0]?.path).toBe("tools.tracker.fetch_all") + } + + // ...while a true "issues" path match still outranks the singular-only description match. + const ranked = await Effect.runPromise(runtime.execute(`return await tools.$codemode.search({ query: "issues" })`)) + expect(ranked.ok).toBe(true) + if (ranked.ok) { + const value = ranked.value as { items: Array<{ path: string }>; total: number } + expect(value.total).toBe(2) + expect(value.items.map((item) => item.path)).toStrictEqual([ + "tools.github.list_issues", + "tools.tracker.fetch_all", + ]) + } + }) + + test("empty query lists everything alphabetically by path", async () => { + const simple = (description: string) => + Tool.make({ + description, + input: Schema.Struct({}), + output: Schema.String, + run: () => Effect.succeed("ok"), + }) + // Deliberately declared out of alphabetical order. + const runtime = CodeMode.make({ + tools: { + zeta: { last: simple("Last") }, + alpha: { beta: simple("Middle"), aardvark: simple("First") }, + }, + }) + const browse = await Effect.runPromise(runtime.execute(`return await tools.$codemode.search({})`)) + expect(browse.ok).toBe(true) + if (browse.ok) { + const value = browse.value as { items: Array<{ path: string }>; total: number } + expect(value.items.map((item) => item.path)).toStrictEqual([ + "tools.alpha.aardvark", + "tools.alpha.beta", + "tools.zeta.last", + ]) + } + }) + + test("inlines round-robin across namespaces so one expensive namespace cannot starve the rest", () => { + const cheap = Tool.make({ + description: "Cheap", + input: Schema.Struct({ q: Schema.String }), + output: Schema.String, + run: () => Effect.succeed("ok"), + }) + const expensive = Tool.make({ + description: + "An expensive tool whose description alone consumes far more than the remaining inline catalog byte budget for this runtime", + input: Schema.Struct({ + someRatherLongParameterName: Schema.String, + anotherEvenLongerParameterName: Schema.Number, + }), + output: Schema.String, + run: () => Effect.succeed("ok"), + }) + // Round 1 places alpha.cheap (~17 estimated tokens) and beta.cheap (~17); in round 2 + // alpha.expensive does not fit, which marks only alpha done - it must NOT prevent + // other namespaces from inlining (beta already got its line in the same round). + const runtime = CodeMode.make({ + tools: { alpha: { cheap, expensive }, beta: { cheap } }, + discovery: { maxInlineCatalogTokens: 40 }, + }) + + const instructions = runtime.instructions() + expect(instructions).toContain( + "Available tools (PARTIAL - 2 of 3 shown; find the rest with tools.$codemode.search)", + ) + expect(instructions).toContain("- alpha (2 tools, 1 shown)") + expect(instructions).toContain(" - tools.alpha.cheap(input: { q: string }): Promise // Cheap") + expect(instructions).not.toContain("tools.alpha.expensive(") + // Fully shown namespaces read cleanly (no "shown" annotation). + expect(instructions).toContain("- beta (1 tool)") + expect(instructions).toContain(" - tools.beta.cheap(input: { q: string }): Promise // Cheap") + expect(instructions).toMatch(/\$codemode\.search/) + }) + + test("decodes tool input and output before exposing either side", async () => { + const observed: Array = [] + const transformed = Tool.make({ + description: "Double a number", + input: Schema.Struct({ value: Schema.NumberFromString }), + output: Schema.NumberFromString, + run: ({ value }) => + Effect.sync(() => { + observed.push(value) + return String(value * 2) + }), + }) + const runtime = CodeMode.make({ + tools: { math: { double: transformed } }, + onToolCallStart: (call) => Effect.sync(() => observed.push(call.input)), + }) + + const success = await Effect.runPromise(runtime.execute(`return await tools.math.double({ value: "21" })`)) + expect(success).toStrictEqual({ ok: true, value: 42, toolCalls: [{ name: "math.double" }] }) + expect(observed).toStrictEqual([{ value: 21 }, 21]) + + const invalid = await Effect.runPromise(runtime.execute(`return await tools.math.double({ value: 21 })`)) + expect(invalid.ok).toBe(false) + if (invalid.ok) return + expect(invalid.error.kind).toBe("InvalidToolInput") + expect(observed).toStrictEqual([{ value: 21 }, 21]) + }) + + test("returns JSON-safe data and normalizes undefined to null", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ + code: `return { top: undefined, nested: [1, undefined] }`, + }), + ) + expect(result).toStrictEqual({ + ok: true, + value: { top: null, nested: [1, null] }, + toolCalls: [], + }) + expect(Schema.decodeUnknownSync(ExecuteResultSchema)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) + }) + + test("rejects invalid configuration and discovery limits", async () => { + expect(() => CodeMode.execute({ code: "return 1", limits: { timeoutMs: 0 } })).toThrow(RangeError) + expect(() => CodeMode.execute({ code: "return 1", limits: { timeoutMs: Number.POSITIVE_INFINITY } })).toThrow( + RangeError, + ) + expect(() => CodeMode.execute({ code: "return 1", limits: { maxToolCalls: -1 } })).toThrow(RangeError) + expect(() => CodeMode.execute({ code: "return 1", limits: { maxOutputBytes: -1 } })).toThrow(RangeError) + + expect(() => CodeMode.make({ tools, discovery: { maxInlineCatalogTokens: -1 } })).toThrow(RangeError) + + const result = await Effect.runPromise( + CodeMode.make({ + tools, + discovery: { maxInlineCatalogTokens: 0 }, + }).execute(`return await tools.$codemode.search({ query: "order", limit: 0.5 })`), + ) + expect(result.ok).toBe(false) + if (result.ok) return + expect(result.error.kind).toBe("InvalidToolInput") + }) + + test("enforces the tool-call limit as a diagnostic", async () => { + const result = await Effect.runPromise(CodeMode.execute({ tools, code: source, limits: { maxToolCalls: 0 } })) + expect(result.ok).toBe(false) + if (!result.ok) expect(result.error.kind).toBe("ToolCallLimitExceeded") + }) + + test("timeoutMs and maxToolCalls have no defaults: absent means unlimited", async () => { + // 150 tool calls would have exceeded the old default cap of 100; with no limits + // provided, there is no cap and no timeout - budgets are host policy. + const counter = Tool.make({ + description: "Count invocations", + input: Schema.Struct({}), + output: Schema.Number, + run: () => Effect.succeed(1), + }) + const result = await Effect.runPromise( + CodeMode.execute({ + tools: { host: { count: counter } }, + code: ` + let total = 0 + for (let i = 0; i < 150; i += 1) total += await tools.host.count({}) + return total + `, + }), + ) + expect(result).toMatchObject({ ok: true, value: 150 }) + if (result.ok) expect(result.toolCalls.length).toBe(150) + }) + + test("the timeout interrupts a busy loop without any operation budget", async () => { + // Regression: timeout interruption must not depend on interpreter-side work accounting. + // The Effect fiber runtime auto-yields between interpreter steps, so a pure `while + // (true) {}` loop is interrupted by `timeoutMs` alone. + const startedAt = Date.now() + const result = await Effect.runPromise(CodeMode.execute({ code: "while (true) {}", limits: { timeoutMs: 200 } })) + const elapsedMs = Date.now() - startedAt + + expect(result.ok).toBe(false) + if (!result.ok) { + expect(result.error.kind).toBe("TimeoutExceeded") + expect(result.error.message).toContain("timed out after 200ms") + } + expect(elapsedMs).toBeLessThan(3_000) + }) + + test("reserves the discovery namespace", () => { + expect(() => CodeMode.make({ tools: { $codemode: { lookup } } })).toThrow(/reserved for CodeMode discovery tools/) + }) +}) diff --git a/packages/codemode/test/enumeration.test.ts b/packages/codemode/test/enumeration.test.ts new file mode 100644 index 0000000000..87c075a792 --- /dev/null +++ b/packages/codemode/test/enumeration.test.ts @@ -0,0 +1,159 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Schema } from "effect" +import { CodeMode, Tool } from "../src/index.js" + +// Key enumeration: Object.keys and for...in share one surface over plain objects, arrays +// (index strings), and tool references (namespace/tool names from the host tool tree), so a +// model can discover what it may call instead of guessing names from the instructions. The +// motivating transcript: `Object.keys(tools)` failed with the generic plain-objects-only +// message and `for (const key in tools)` was unsupported syntax, forcing blind guesses. + +const echo = (description: string) => + Tool.make({ + description, + input: Schema.Struct({ value: Schema.String }), + output: Schema.String, + run: ({ value }) => Effect.succeed(value), + }) + +const tools = { + github: { list_issues: echo("List issues"), get_issue: echo("Get one issue") }, + memory: { search: echo("Search memory") }, + playwright: { navigate: echo("Navigate somewhere") }, +} + +const run = (code: string) => Effect.runPromise(CodeMode.execute({ tools, code })) +const value = async (code: string) => { + const result = await run(code) + if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) + return result.value +} +const error = async (code: string) => { + const result = await run(code) + if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) + return result.error +} + +describe("Object.keys over tool references", () => { + test("enumerates top-level namespaces (the transcript program)", async () => { + expect( + await value(` + const namespaces = Object.keys(tools) + return { namespaces, count: namespaces.length } + `), + ).toEqual({ namespaces: ["github", "memory", "playwright"], count: 3 }) + }) + + test("enumerates tool names at a nested namespace", async () => { + expect(await value(`return Object.keys(tools.github)`)).toEqual(["list_issues", "get_issue"]) + }) + + test("a callable tool is a leaf and enumerates as []", async () => { + expect(await value(`return Object.keys(tools.github.list_issues)`)).toEqual([]) + }) + + test("the virtual discovery namespace enumerates its callable surface", async () => { + expect(await value(`return Object.keys(tools.$codemode)`)).toEqual(["search"]) + }) + + test("an unknown namespace is an UnknownTool error pointing at the discovery idioms", async () => { + const failure = await error(`return Object.keys(tools.nonexistent)`) + expect(failure.kind).toBe("UnknownTool") + expect(failure.message).toContain("Unknown tool namespace 'nonexistent'") + expect(failure.suggestions?.join(" ")).toContain("Object.keys(tools)") + }) + + test("Object.values/entries on a tool reference explain the working idioms", async () => { + for (const method of ["values", "entries"] as const) { + const failure = await error(`return Object.${method}(tools)`) + expect(failure.kind).toBe("InvalidDataValue") + expect(failure.message).toContain( + `Object.${method}(...) cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or tools.$codemode.search({ query }) for signatures.`, + ) + } + const nested = await error(`return Object.entries(tools.github)`) + expect(nested.message).toContain("Use Object.keys(tools) for names") + }) +}) + +describe("Object.keys over arrays", () => { + test("returns index strings, like JS", async () => { + expect(await value(`return Object.keys(["a", "b", "c"])`)).toEqual(["0", "1", "2"]) + expect(await value(`return Object.keys([])`)).toEqual([]) + }) + + test("objects keep their own enumerable keys", async () => { + expect(await value(`return Object.keys({ a: 1, b: 2 })`)).toEqual(["a", "b"]) + }) + + test("non-object inputs still fail clearly", async () => { + const failure = await error(`return Object.keys("nope")`) + expect(failure.message).toContain("Object.keys expects a data object or array") + }) +}) + +describe("for...in", () => { + test("iterates own enumerable keys of a plain object with break/continue", async () => { + expect( + await value(` + const seen = [] + for (const key in { a: 1, b: 2, c: 3, d: 4 }) { + if (key === "b") continue + if (key === "d") break + seen.push(key) + } + return seen + `), + ).toEqual(["a", "c"]) + }) + + test("iterates index strings over arrays", async () => { + expect( + await value(` + const indexes = [] + for (const i in ["x", "y", "z"]) { + if (i === "2") break + indexes.push(i) + } + return indexes + `), + ).toEqual(["0", "1"]) + }) + + test("supports let declarations and bare identifiers", async () => { + expect( + await value(` + let last = "" + for (let key in { a: 1, b: 2 }) last = key + return last + `), + ).toBe("b") + expect( + await value(` + let key = "before" + for (key in { only: 1 }) {} + return key + `), + ).toBe("only") + }) + + test("enumerates namespaces and tools from the host tool tree", async () => { + expect( + await value(` + const names = [] + for (const ns in tools) { + for (const name in tools[ns]) names.push(ns + "." + name) + } + return names + `), + ).toEqual(["github.list_issues", "github.get_issue", "memory.search", "playwright.navigate"]) + }) + + test("unsupported values fail with a hint at for...of and Object.keys", async () => { + for (const expression of [`"text"`, "new Map([[1, 2]])", "new Set([1])", "42", "null"]) { + const failure = await error(`for (const key in ${expression}) {}; return "no"`) + expect(failure.message).toContain("for...in requires a plain object, array, or tools reference") + expect(failure.message).toContain("Use for...of for arrays/strings/Maps/Sets, or Object.keys(value)") + } + }) +}) diff --git a/packages/codemode/test/parity.test.ts b/packages/codemode/test/parity.test.ts new file mode 100644 index 0000000000..e5c1d83822 --- /dev/null +++ b/packages/codemode/test/parity.test.ts @@ -0,0 +1,425 @@ +import { describe, expect, test } from "bun:test" +import { Effect } from "effect" +import { CodeMode } from "../src/index.js" +import { ToolRuntime } from "../src/tool-runtime.js" + +// Runs a CodeMode program with no host tools and returns the ExecuteResult. These tests pin the +// JS-parity behaviors for the "99% of ordinary defensive JavaScript just works" goal: cases where +// a strict interpreter would throw but idiomatic JS yields undefined / succeeds. +// +// Note on the result boundary: this package normalizes a bare `undefined` result to `null` when +// it crosses out of the sandbox (results are JSON data), so tests asserting an in-sandbox +// `undefined` read check `=== undefined` inside the program and `null` at the boundary. +const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) +const value = async (code: string) => { + const result = await run(code) + if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) + return result.value +} +const error = async (code: string) => { + const result = await run(code) + if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) + return result.error +} + +describe("H2: string property access reads as undefined (not a throw)", () => { + test("unknown property on a string is undefined", async () => { + expect(await value(`const s = "hi"; return s.login === undefined`)).toBe(true) + expect(await value(`const s = "hi"; return s.login`)).toBeNull() + }) + + test("optional chaining + fallback on a string does not throw", async () => { + expect(await value(`const s = "hi"; return s?.login ?? "fallback"`)).toBe("fallback") + }) + + test("the real MCP pattern: result is a JSON string, defensive read falls through", async () => { + // me.result is a string; me.result?.login is undefined, so we fall back to the raw string. + expect(await value(`const me = { result: '{"login":"x"}' }; return me.result?.login ?? me.result`)).toBe( + '{"login":"x"}', + ) + }) + + test("unknown property on a number is undefined", async () => { + expect(await value(`return (5).foo ?? "n"`)).toBe("n") + }) + + test("supported string methods still work", async () => { + expect(await value(`return "AB".toLowerCase()`)).toBe("ab") + expect(await value(`return "hello".length`)).toBe(5) + }) +}) + +describe("H3: array property access reads as undefined (not a throw)", () => { + test("unknown property on an array is undefined", async () => { + expect(await value(`return [1,2,3].foo === undefined`)).toBe(true) + expect(await value(`return [1,2,3].foo`)).toBeNull() + }) + + test("optional chaining on an array does not throw", async () => { + expect(await value(`return [1,2,3]?.foo ?? "fb"`)).toBe("fb") + }) + + test("unknown property reads stay undefined for methods CodeMode does not implement", async () => { + expect(await value(`return [1,2,3].toSpliced === undefined`)).toBe(true) + }) + + test("supported array methods and indexing still work", async () => { + expect(await value(`return [1,2,3].map(x => x + 1)`)).toEqual([2, 3, 4]) + expect(await value(`return [1,2,3][9] === undefined`)).toBe(true) + expect(await value(`return [1,2,3][9]`)).toBeNull() + }) +}) + +describe("H6: object spread of null/undefined is a no-op", () => { + test("spreading null is a no-op", async () => { + expect(await value(`const o = null; return { ...o, a: 1 }`)).toEqual({ a: 1 }) + }) + + test("spreading an absent argument merges cleanly", async () => { + expect(await value(`function f(opts){ return { ...opts, a: 1 } } return f(undefined)`)).toEqual({ a: 1 }) + }) + + test("spreading a real object still works", async () => { + expect(await value(`const o = { a: 1 }; return { ...o, b: 2 }`)).toEqual({ a: 1, b: 2 }) + }) + + test("spreading an array into an object still errors", async () => { + const err = await error(`return { ...[1,2], a: 1 }`) + expect(err.kind).toBe("InvalidDataValue") + }) +}) + +describe("H4: typeof on an undeclared identifier is 'undefined'", () => { + test("feature-detection guard does not throw", async () => { + expect(await value(`return typeof foo === "undefined" ? "safe" : "no"`)).toBe("safe") + }) + + test("typeof of a declared binding is unaffected", async () => { + expect(await value(`const x = 5; return typeof x`)).toBe("number") + expect(await value(`const s = "a"; return typeof s`)).toBe("string") + }) + + test("referencing an undeclared identifier outside typeof still throws", async () => { + const err = await error(`return foo + 1`) + expect(err.message).toContain("foo") + }) +}) + +describe("H1: NaN/Infinity flow as intermediates and normalize to null at the boundary", () => { + test("guards run instead of the program crashing on a transient NaN", async () => { + expect(await value(`return parseInt("abc") || 0`)).toBe(0) + expect(await value(`const x = Number("abc"); return Number.isNaN(x) ? 0 : x`)).toBe(0) + expect(await value(`const o = {}; o.count = (o.count || 0) + 1; return o.count`)).toBe(1) + // average of an empty list, guarded - the classic divide-by-zero that used to throw pre-guard + expect(await value(`const a = []; return a.length ? a.reduce((s,x)=>s+x,0)/a.length : 0`)).toBe(0) + }) + + test("a non-finite value becomes null when it leaves the sandbox", async () => { + expect(await value(`return 5/0`)).toBeNull() + expect(await value(`return 0/0`)).toBeNull() + expect(await value(`return Math.max()`)).toBeNull() + // nested, too - normalization walks the returned structure + expect(await value(`return { a: Number("x"), b: 2, c: [1/0] }`)).toEqual({ a: null, b: 2, c: [null] }) + }) + + test("NaN and Infinity are usable identifiers and inspectable in-sandbox", async () => { + expect(await value(`return Number.isNaN(NaN)`)).toBe(true) + expect(await value(`return Infinity > 1e9`)).toBe(true) + expect(await value(`return Number.isFinite(1/0)`)).toBe(false) + expect(await value(`return [3,1,2].reduce((a,b)=>Math.max(a,b), -Infinity)`)).toBe(3) + // JSON.stringify inside the sandbox matches JS: non-finite serializes to null + expect(await value(`return JSON.stringify({ x: Number("z") })`)).toBe('{"x":null}') + }) + + test("copyOut normalizes non-finite numbers to null (the shared return + tool-arg boundary)", () => { + // Tool-call arguments funnel through copyOut too, so this one function pins both boundaries. + expect(ToolRuntime.copyOut(NaN)).toBeNull() + expect(ToolRuntime.copyOut(Infinity)).toBeNull() + expect(ToolRuntime.copyOut(-Infinity)).toBeNull() + expect(ToolRuntime.copyOut(42)).toBe(42) + expect(ToolRuntime.copyOut({ a: NaN, b: [Infinity, 1] })).toEqual({ a: null, b: [null, 1] }) + }) +}) + +describe("Error values and instanceof", () => { + test("new Error carries name/message and is instanceof Error", async () => { + expect(await value(`const e = new Error("boom"); return [e instanceof Error, e.name, e.message]`)).toEqual([ + true, + "Error", + "boom", + ]) + }) + + test("Error without new behaves like new Error", async () => { + expect(await value(`const e = Error("plain"); return [e instanceof Error, e.name, e.message]`)).toEqual([ + true, + "Error", + "plain", + ]) + expect(await value(`const e = new Error(); return [e.name, e.message, e instanceof Error]`)).toEqual([ + "Error", + "", + true, + ]) + }) + + test("specific error types are instanceof themselves and Error, not each other", async () => { + expect( + await value( + `const e = new TypeError("t"); return [e instanceof TypeError, e instanceof Error, e instanceof RangeError]`, + ), + ).toEqual([true, true, false]) + expect(await value(`return new Error("e") instanceof TypeError`)).toBe(false) + }) + + test("thrown errors keep instanceof through try/catch", async () => { + expect(await value(`try { throw new Error("x") } catch (e) { return [e instanceof Error, e.message] }`)).toEqual([ + true, + "x", + ]) + }) + + test("interpreter runtime failures are caught as Error values", async () => { + expect(await value(`try { JSON.parse("nope") } catch (e) { return e instanceof Error }`)).toBe(true) + expect(await value(`try { undeclared() } catch (e) { return e instanceof Error }`)).toBe(true) + }) + + test("caught failures carry the constructor name the real-JS failure would have", async () => { + // JSON.parse throws SyntaxError: name and specific-instanceof both carry through, and the + // message keeps the engine's position detail. + expect( + await value(` + try { JSON.parse("{oops") } catch (e) { + return [e.name, e instanceof SyntaxError, e instanceof Error, e instanceof TypeError, e.message.includes("JSON")] + } + `), + ).toEqual(["SyntaxError", true, true, false, true]) + expect(await value(`try { undeclared() } catch (e) { return [e.name, e instanceof ReferenceError] }`)).toEqual([ + "ReferenceError", + true, + ]) + expect(await value(`try { const c = 1; c = 2 } catch (e) { return [e.name, e instanceof TypeError] }`)).toEqual([ + "TypeError", + true, + ]) + expect(await value(`try { "a".normalize("NOPE") } catch (e) { return [e.name, e instanceof RangeError] }`)).toEqual( + ["RangeError", true], + ) + expect(await value(`try { "a".match("(") } catch (e) { return [e.name, e instanceof SyntaxError] }`)).toEqual([ + "SyntaxError", + true, + ]) + expect(await value(`try { new RegExp("(") } catch (e) { return [e.name, e instanceof SyntaxError] }`)).toEqual([ + "SyntaxError", + true, + ]) + }) + + test("diagnostics without a specific real-JS analogue are named plain Error", async () => { + expect(await value(`try { JSON.parse(5) } catch (e) { return [e.name, e instanceof Error] }`)).toEqual([ + "Error", + true, + ]) + }) + + test("Promise.allSettled rejection reasons are Error values", async () => { + expect( + await value(` + const settled = await Promise.allSettled([Promise.reject(new Error("b"))]) + return [settled[0].reason instanceof Error, settled[0].reason.message] + `), + ).toEqual([true, "b"]) + }) + + test("non-error thrown values are not instanceof Error", async () => { + expect(await value(`try { throw "raw" } catch (e) { return e instanceof Error }`)).toBe(false) + expect(await value(`try { throw { message: "shaped" } } catch (e) { return e instanceof Error }`)).toBe(false) + }) + + test("plain data is never instanceof Error", async () => { + expect(await value(`return [({}) instanceof Error, "s" instanceof Error, null instanceof Error]`)).toEqual([ + false, + false, + false, + ]) + }) + + test("error values still serialize as plain { name, message } data", async () => { + expect(await value(`return new Error("m")`)).toEqual({ name: "Error", message: "m" }) + expect(await value(`return JSON.stringify(new Error("m"))`)).toBe('{"name":"Error","message":"m"}') + expect(await value(`try { throw new Error("m") } catch (e) { return Object.keys(e) }`)).toEqual(["name", "message"]) + }) + + test("spreading an error loses the brand, like losing the prototype in JS", async () => { + expect(await value(`const e = new Error("m"); return ({ ...e }) instanceof Error`)).toBe(false) + expect(await value(`const e = new Error("m"); return { ...e }`)).toEqual({ name: "Error", message: "m" }) + }) + + test("typeof Error is function; an unknown instanceof right-hand side is a catchable error", async () => { + expect(await value(`return typeof Error`)).toBe("function") + expect(await value(`try { return 1 instanceof 5 } catch (e) { return "caught" }`)).toBe("caught") + const err = await error(`return 1 instanceof 5`) + expect(err.message).toContain("right-hand side of 'instanceof'") + }) +}) + +describe("array methods: splice, fill, copyWithin, keys/values/entries", () => { + test("splice removes in place and returns the removed elements", async () => { + expect(await value(`const a = [1,2,3,4]; const removed = a.splice(1, 2); return { removed, a }`)).toEqual({ + removed: [2, 3], + a: [1, 4], + }) + }) + + test("splice inserts new elements at the cut", async () => { + expect(await value(`const a = ["a","d"]; a.splice(1, 0, "b", "c"); return a`)).toEqual(["a", "b", "c", "d"]) + expect(await value(`const a = [1,2,3]; const removed = a.splice(1, 1, "x"); return { removed, a }`)).toEqual({ + removed: [2], + a: [1, "x", 3], + }) + }) + + test("splice with one argument removes to the end; negative start counts back", async () => { + expect(await value(`const a = [1,2,3]; const removed = a.splice(1); return { removed, a }`)).toEqual({ + removed: [2, 3], + a: [1], + }) + expect(await value(`const a = [1,2,3]; const removed = a.splice(-1); return { removed, a }`)).toEqual({ + removed: [3], + a: [1, 2], + }) + }) + + test("splice rejects inserting a container into itself", async () => { + const err = await error(`const a = [1]; a.splice(0, 0, [a]); return a`) + expect(err.kind).toBe("InvalidDataValue") + expect(err.message).toContain("circular") + }) + + test("fill overwrites a range and returns the mutated array", async () => { + expect(await value(`const a = [1,2,3,4]; return a.fill(0, 1, 3)`)).toEqual([1, 0, 0, 4]) + expect(await value(`return [1,2,3].fill("z")`)).toEqual(["z", "z", "z"]) + }) + + test("copyWithin copies a range in place", async () => { + expect(await value(`return [1,2,3,4,5].copyWithin(0, 3)`)).toEqual([4, 5, 3, 4, 5]) + }) + + test("keys/values/entries return arrays usable with for...of and spread", async () => { + expect(await value(`return [...["x","y","z"].keys()]`)).toEqual([0, 1, 2]) + expect(await value(`return ["x","y"].values()`)).toEqual(["x", "y"]) + expect( + await value(` + const out = [] + for (const [index, item] of ["a","b"].entries()) out.push(index + ":" + item) + return out + `), + ).toEqual(["0:a", "1:b"]) + expect(await value(`return [...[7].entries()]`)).toEqual([[0, 7]]) + }) +}) + +describe("string methods: localeCompare, normalize, trim aliases", () => { + test("localeCompare orders strings for sorting", async () => { + expect(await value(`return ["b","a","c"].sort((x, y) => x.localeCompare(y))`)).toEqual(["a", "b", "c"]) + expect(await value(`return "a".localeCompare("a")`)).toBe(0) + }) + + test("normalize applies unicode normalization forms", async () => { + expect(await value(`return "\\u0065\\u0301".normalize("NFC").length`)).toBe(1) + expect(await value(`return "\\u00e9".normalize("NFD").length`)).toBe(2) + expect(await value(`return "x".normalize() === "x"`)).toBe(true) + }) + + test("an invalid normalize form is a clear catchable error", async () => { + expect(await value(`try { "x".normalize("nope"); return "no" } catch (e) { return e.message }`)).toContain('"NFC"') + }) + + test("trimLeft/trimRight alias trimStart/trimEnd", async () => { + expect(await value(`return " x ".trimLeft()`)).toBe("x ") + expect(await value(`return " x ".trimRight()`)).toBe(" x") + }) +}) + +describe("compound assignment matches its binary operator", () => { + // `x op= y` must behave exactly like `x = x op y`, sharing the binary operator's coercion + // semantics (Dates string-coerce for `+` and use their time value for arithmetic; data + // objects/arrays coerce to their JS string form). + const pair = async (compound: string, expanded: string) => { + const [a, b] = await Promise.all([value(compound), value(expanded)]) + expect(a).toEqual(b) + return a + } + + test("sandbox Date += concatenates its string form, like d = d + 1", async () => { + const result = await pair(`let d = new Date(1000); d += 1; return d`, `let d = new Date(1000); d = d + 1; return d`) + expect(result).toBe("1970-01-01T00:00:01.000Z1") + }) + + test("sandbox Date numeric compound ops use its time value", async () => { + expect( + await pair(`let d = new Date(1000); d -= 400; return d`, `let d = new Date(1000); d = d - 400; return d`), + ).toBe(600) + expect(await pair(`let d = new Date(1000); d /= 4; return d`, `let d = new Date(1000); d = d / 4; return d`)).toBe( + 250, + ) + }) + + test("string += object/array matches x = x + obj", async () => { + expect(await pair(`let x = "a"; x += { b: 1 }; return x`, `let x = "a"; x = x + { b: 1 }; return x`)).toBe( + "a[object Object]", + ) + expect(await pair(`let x = "a"; x += [1, 2]; return x`, `let x = "a"; x = x + [1, 2]; return x`)).toBe("a1,2") + }) + + test("compound assignment through a member target coerces the same way", async () => { + expect( + await pair( + `const o = { s: "t" }; o.s += new Date(0); return o.s`, + `const o = { s: "t" }; o.s = o.s + new Date(0); return o.s`, + ), + ).toBe("t1970-01-01T00:00:00.000Z") + }) + + test("numeric and string compound operators sweep identically to their expansions", async () => { + const cases: Array<[string, number | string]> = [ + [`let x = 7; x += 3; return x`, 7 + 3], + [`let x = 7; x -= 3; return x`, 7 - 3], + [`let x = 7; x *= 3; return x`, 7 * 3], + [`let x = 7; x /= 2; return x`, 7 / 2], + [`let x = 7; x %= 3; return x`, 7 % 3], + [`let x = 7; x **= 2; return x`, 7 ** 2], + [`let x = 7; x &= 3; return x`, 7 & 3], + [`let x = 7; x |= 8; return x`, 7 | 8], + [`let x = 7; x ^= 2; return x`, 7 ^ 2], + [`let x = 7; x <<= 2; return x`, 7 << 2], + [`let x = -7; x >>= 1; return x`, -7 >> 1], + [`let x = -7; x >>>= 1; return x`, -7 >>> 1], + [`let x = "a"; x += "b"; return x`, "ab"], + ] + for (const [compound, expected] of cases) { + expect(await value(compound)).toBe(expected) + expect(await value(compound.replace(/x (\S+)= /, (_, op) => `x = x ${op} `))).toBe(expected) + } + }) +}) + +describe("H5: builtin coercion functions work as array callbacks", () => { + test("filter(Boolean) drops falsy values", async () => { + expect(await value(`return [0, 1, "", 2, null, 3].filter(Boolean)`)).toEqual([1, 2, 3]) + }) + + test("map(String) coerces each element", async () => { + expect(await value(`return [1, 2, 3].map(String)`)).toEqual(["1", "2", "3"]) + }) + + test("arrow callbacks still work (no regression)", async () => { + expect(await value(`return [1, 2, 3, 4].filter(x => x % 2 === 0)`)).toEqual([2, 4]) + expect(await value(`return [1, 2, 3].reduce((a, b) => a + b, 0)`)).toBe(6) + }) + + test("a non-callable callback is still rejected", async () => { + const err = await error(`return [1,2,3].map(42)`) + expect(err.message).toContain("callback") + }) +}) diff --git a/packages/codemode/test/promise.test.ts b/packages/codemode/test/promise.test.ts new file mode 100644 index 0000000000..952b2fdc50 --- /dev/null +++ b/packages/codemode/test/promise.test.ts @@ -0,0 +1,453 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Schema } from "effect" +import { CodeMode, Tool, toolError, type ExecuteResult, type ExecutionLimits } from "../src/index.js" + +// Wave 5 acceptance suite: first-class promise values. Un-awaited tool calls start eagerly on +// supervised fibers, `await` settles them, and Promise.all/allSettled/race/resolve/reject are +// ordinary functions over arbitrary arrays mixing promises and plain values. + +type Trace = { + starts: Array + active: number + maxActive: number + completed: number + interrupted: number +} + +const makeTrace = (): Trace => ({ starts: [], active: 0, maxActive: 0, completed: 0, interrupted: 0 }) + +/** Echoes `id` after `ms` milliseconds, recording start order, live concurrency, and interruption. */ +const sleepyTool = (trace: Trace) => + Tool.make({ + description: "Echo an id after a delay", + input: Schema.Struct({ id: Schema.Number, ms: Schema.optionalKey(Schema.Number) }), + output: Schema.Number, + run: ({ id, ms }) => + Effect.gen(function* () { + trace.starts.push(id) + trace.active += 1 + trace.maxActive = Math.max(trace.maxActive, trace.active) + yield* Effect.sleep(ms ?? 20) + trace.active -= 1 + trace.completed += 1 + return id + }).pipe( + Effect.onInterrupt(() => + Effect.sync(() => { + trace.active -= 1 + trace.interrupted += 1 + }), + ), + ), + }) + +const failingTool = Tool.make({ + description: "Always refuse", + input: Schema.Struct({}), + output: Schema.String, + run: () => Effect.fail(toolError("Lookup refused")), +}) + +const run = (code: string, options: { trace?: Trace; limits?: ExecutionLimits } = {}): Promise => { + const trace = options.trace ?? makeTrace() + return Effect.runPromise( + CodeMode.execute({ + tools: { host: { sleepy: sleepyTool(trace), fail: failingTool } }, + code, + ...(options.limits ? { limits: options.limits } : {}), + }), + ) +} + +const value = async (code: string, options: { trace?: Trace; limits?: ExecutionLimits } = {}) => { + const result = await run(code, options) + if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) + return result.value +} + +const error = async (code: string, options: { trace?: Trace; limits?: ExecutionLimits } = {}) => { + const result = await run(code, options) + if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) + return result.error +} + +describe("first-class promise values", () => { + test("an un-awaited tool call starts eagerly, in call order, before any await", async () => { + const trace = makeTrace() + const result = await value( + ` + const a = tools.host.sleepy({ id: 1, ms: 40 }) + const b = tools.host.sleepy({ id: 2, ms: 40 }) + const rb = await b + const ra = await a + return [ra, rb] + `, + { trace }, + ) + expect(result).toEqual([1, 2]) + expect(trace.starts).toEqual([1, 2]) + // Both calls overlapped even though they were awaited sequentially. + expect(trace.maxActive).toBeGreaterThan(1) + }) + + test("awaiting the same promise twice settles once and never re-runs the call", async () => { + const result = await run(` + const p = tools.host.sleepy({ id: 7 }) + const x = await p + const y = await p + return [x, y] + `) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toEqual([7, 7]) + expect(result.toolCalls).toStrictEqual([{ name: "host.sleepy" }]) + }) + + test("await of a non-promise value is a passthrough no-op", async () => { + expect(await value(`return await 42`)).toBe(42) + expect(await value(`const x = await "s"; return x`)).toBe("s") + expect(await value(`return await null`)).toBeNull() + expect(await value(`return (await [1, 2]).length`)).toBe(2) + }) + + test("returning an un-awaited tool call resolves it (async-function return semantics)", async () => { + expect(await value(`return tools.host.sleepy({ id: 9 })`)).toBe(9) + }) + + test("typeof a promise is 'object', and console.log renders it sensibly", async () => { + const result = await run(` + const p = Promise.resolve(1) + console.log(p) + return typeof p + `) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("object") + expect(result.logs).toStrictEqual(["[Promise (await it to get its value)]"]) + }) + + test("an awaited failure is catchable exactly like a synchronous throw", async () => { + expect( + await value(` + const p = tools.host.fail({}) + try { + await p + return "no" + } catch (e) { + return e.message + } + `), + ).toBe("Lookup refused") + }) + + test("a fire-and-forget call completes before the execution ends", async () => { + const trace = makeTrace() + const result = await value( + ` + tools.host.sleepy({ id: 1, ms: 30 }) + return "done" + `, + { trace }, + ) + expect(result).toBe("done") + expect(trace.completed).toBe(1) + expect(trace.interrupted).toBe(0) + }) + + test("a never-awaited failing call surfaces as an unhandled-rejection diagnostic", async () => { + const diagnostic = await error(` + tools.host.fail({}) + return "done" + `) + expect(diagnostic.kind).toBe("ToolFailure") + expect(diagnostic.message).toContain("Unhandled rejection from an un-awaited tool call") + expect(diagnostic.message).toContain("Lookup refused") + expect(diagnostic.suggestions?.join(" ")).toContain("await tools.ns.tool(...)") + }) +}) + +describe("promises at data boundaries", () => { + test("returning an un-awaited promise inside data is a clear await-hinting diagnostic", async () => { + const diagnostic = await error(`return { result: tools.host.sleepy({ id: 1 }) }`) + expect(diagnostic.kind).toBe("InvalidDataValue") + expect(diagnostic.message).toContain("un-awaited Promise") + expect(diagnostic.message).toContain("await tools.ns.tool(...)") + }) + + test("passing an un-awaited promise as a tool argument is a clear diagnostic", async () => { + const diagnostic = await error(`return await tools.host.sleepy({ id: tools.host.sleepy({ id: 1 }) })`) + expect(diagnostic.kind).toBe("InvalidDataValue") + expect(diagnostic.message).toContain("un-awaited Promise") + }) + + test("JSON.stringify of a promise is a diagnostic, not '{}'", async () => { + const diagnostic = await error(`return JSON.stringify(Promise.resolve(1))`) + expect(diagnostic.kind).toBe("InvalidDataValue") + expect(diagnostic.message).toContain("un-awaited Promise") + }) + + test("operators reject promise operands", async () => { + const diagnostic = await error(`return Promise.resolve(1) + 1`) + expect(diagnostic.kind).toBe("InvalidDataValue") + }) +}) + +describe("Promise.all over arbitrary arrays", () => { + test("mixes promises and plain values, preserving order", async () => { + expect( + await value(` + return await Promise.all([tools.host.sleepy({ id: 1 }), "plain", tools.host.sleepy({ id: 2 }), 42]) + `), + ).toEqual([1, "plain", 2, 42]) + }) + + test("accepts arrays built beforehand, passed as identifiers, and spread elements", async () => { + expect( + await value(` + const calls = [] + calls.push(tools.host.sleepy({ id: 1 })) + calls.push(7) + const more = [tools.host.sleepy({ id: 2 })] + const batch = [...calls, ...more, "x"] + return await Promise.all(batch) + `), + ).toEqual([1, 7, 2, "x"]) + }) + + test("runs items.map tool calls in parallel", async () => { + const trace = makeTrace() + const result = await value( + ` + const ids = [1, 2, 3, 4] + return await Promise.all(ids.map((id) => tools.host.sleepy({ id, ms: 40 }))) + `, + { trace }, + ) + expect(result).toEqual([1, 2, 3, 4]) + // maxActive counts truly-overlapping live executions, so > 1 proves real + // parallelism deterministically - no wall-clock assertion needed. + expect(trace.maxActive).toBeGreaterThan(1) + }) + + test("caps live tool-call concurrency at the fixed internal constant (8)", async () => { + const trace = makeTrace() + const result = await value( + ` + const ids = [] + for (let i = 0; i < 20; i += 1) ids.push(i) + const results = await Promise.all(ids.map((id) => tools.host.sleepy({ id, ms: 10 }))) + return results.length + `, + { trace }, + ) + expect(result).toBe(20) + expect(trace.maxActive).toBeGreaterThan(1) + expect(trace.maxActive).toBeLessThanOrEqual(8) + }) + + test("resolves the empty array", async () => { + expect(await value(`return await Promise.all([])`)).toEqual([]) + }) + + test("rejects with the first failure, catchable in-program", async () => { + expect( + await value(` + try { + await Promise.all([tools.host.sleepy({ id: 1 }), tools.host.fail({})]) + return "no" + } catch (e) { + return e.message + } + `), + ).toBe("Lookup refused") + }) + + test("a non-collection argument is a clear error", async () => { + const diagnostic = await error(`return await Promise.all(42)`) + expect(diagnostic.message).toContain("Promise.all expects an array") + }) + + test("exceeding maxToolCalls inside Promise.all is a ToolCallLimitExceeded diagnostic", async () => { + const diagnostic = await error( + `return await Promise.all([tools.host.sleepy({ id: 1 }), tools.host.sleepy({ id: 2 }), tools.host.sleepy({ id: 3 })])`, + { limits: { maxToolCalls: 2 } }, + ) + expect(diagnostic.kind).toBe("ToolCallLimitExceeded") + }) +}) + +describe("Promise.allSettled", () => { + test("reports fulfilled and rejected outcomes with catch-normalized reasons", async () => { + expect( + await value(` + return await Promise.allSettled([ + tools.host.sleepy({ id: 5 }), + tools.host.fail({}), + "plain", + Promise.reject(new Error("boom")), + ]) + `), + ).toEqual([ + { status: "fulfilled", value: 5 }, + { status: "rejected", reason: { name: "Error", message: "Lookup refused" } }, + { status: "fulfilled", value: "plain" }, + { status: "rejected", reason: { name: "Error", message: "boom" } }, + ]) + }) + + test("never rejects for program-level failures", async () => { + const result = await run(` + const settled = await Promise.allSettled([tools.host.fail({}), tools.host.fail({})]) + return settled.filter((s) => s.status === "rejected").length + `) + expect(result.ok).toBe(true) + if (result.ok) expect(result.value).toBe(2) + }) +}) + +describe("Promise.race", () => { + test("first settlement wins and losers are interrupted", async () => { + const trace = makeTrace() + const result = await value( + ` + const fast = tools.host.sleepy({ id: 1, ms: 10 }) + const slow = tools.host.sleepy({ id: 2, ms: 5000 }) + return await Promise.race([fast, slow]) + `, + { trace }, + ) + expect(result).toBe(1) + expect(trace.interrupted).toBe(1) + expect(trace.completed).toBe(1) + }) + + test("awaiting an interrupted loser afterwards is a catchable program failure", async () => { + expect( + await value(` + const fast = tools.host.sleepy({ id: 1, ms: 10 }) + const slow = tools.host.sleepy({ id: 2, ms: 5000 }) + const winner = await Promise.race([fast, slow]) + try { + await slow + return "no" + } catch (e) { + return { winner, caught: e.message } + } + `), + ).toEqual({ + winner: 1, + caught: "This tool call was interrupted because another value settled a Promise.race first.", + }) + }) + + test("a rejection can win the race", async () => { + expect( + await value(` + try { + await Promise.race([tools.host.fail({}), tools.host.sleepy({ id: 1, ms: 5000 })]) + return "no" + } catch (e) { + return e.message + } + `), + ).toBe("Lookup refused") + }) + + test("a plain value wins over pending promises", async () => { + const trace = makeTrace() + expect( + await value(`return await Promise.race([tools.host.sleepy({ id: 1, ms: 5000 }), "immediate"])`, { trace }), + ).toBe("immediate") + expect(trace.interrupted).toBe(1) + }) + + test("an empty race is a clear error instead of hanging", async () => { + const diagnostic = await error(`return await Promise.race([])`) + expect(diagnostic.message).toContain("never settle") + }) +}) + +describe("Promise.resolve / Promise.reject", () => { + test("resolve wraps plain values and passes promises through", async () => { + expect(await value(`return await Promise.resolve(42)`)).toBe(42) + expect(await value(`return await Promise.resolve(Promise.resolve("nested"))`)).toBe("nested") + expect(await value(`return await Promise.resolve(tools.host.sleepy({ id: 3 }))`)).toBe(3) + }) + + test("reject produces a promise whose await throws the reason", async () => { + expect( + await value(` + try { + await Promise.reject("nope") + return "no" + } catch (e) { + return e + } + `), + ).toBe("nope") + }) +}) + +describe("timeout interruption of forked calls", () => { + test("the execution timeout interrupts in-flight forked fibers", async () => { + const trace = makeTrace() + const result = await run( + ` + const a = tools.host.sleepy({ id: 1, ms: 60000 }) + const b = tools.host.sleepy({ id: 2, ms: 60000 }) + return await a + `, + { trace, limits: { timeoutMs: 100 } }, + ) + expect(result.ok).toBe(false) + if (result.ok) return + expect(result.error.kind).toBe("TimeoutExceeded") + // Both calls started; neither escaped the timeout - the awaited one AND the abandoned one. + expect(trace.starts).toEqual([1, 2]) + expect(trace.interrupted).toBe(2) + expect(trace.completed).toBe(0) + }) + + test("the timeout also interrupts calls inside Promise.all", async () => { + const trace = makeTrace() + const result = await run( + `return await Promise.all([tools.host.sleepy({ id: 1, ms: 60000 }), tools.host.sleepy({ id: 2, ms: 60000 })])`, + { trace, limits: { timeoutMs: 100 } }, + ) + expect(result.ok).toBe(false) + if (result.ok) return + expect(result.error.kind).toBe("TimeoutExceeded") + expect(trace.interrupted).toBe(2) + }) +}) + +describe("unsupported promise surface", () => { + test(".then/.catch/.finally give a clear await-instead error", async () => { + for (const method of ["then", "catch", "finally"]) { + const diagnostic = await error(`return tools.host.sleepy({ id: 1 }).${method}((x) => x)`) + expect(diagnostic.kind).toBe("UnsupportedSyntax") + expect(diagnostic.message).toContain(`Promise.prototype.${method} is not supported`) + expect(diagnostic.message).toContain("await") + } + }) + + test("other property reads on a promise hint at the missing await", async () => { + const diagnostic = await error(`return tools.host.sleepy({ id: 1 }).value`) + expect(diagnostic.kind).toBe("InvalidDataValue") + expect(diagnostic.message).toContain("un-awaited Promise") + expect(diagnostic.message).toContain("await it first") + }) + + test("unknown Promise statics list what is available", async () => { + const diagnostic = await error(`return await Promise.any([tools.host.sleepy({ id: 1 })])`) + expect(diagnostic.message).toContain("Promise.any is not available") + expect(diagnostic.message).toContain("Promise.allSettled") + }) + + test("new Promise(...) points at tool calls instead", async () => { + const diagnostic = await error(`return new Promise((resolve) => resolve(1))`) + expect(diagnostic.kind).toBe("UnsupportedSyntax") + expect(diagnostic.message).toContain("new Promise(...) is not supported") + expect(diagnostic.message).toContain("already return promises") + }) +}) diff --git a/packages/codemode/test/signature.test.ts b/packages/codemode/test/signature.test.ts new file mode 100644 index 0000000000..9c45371d93 --- /dev/null +++ b/packages/codemode/test/signature.test.ts @@ -0,0 +1,341 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Schema } from "effect" +import { CodeMode } from "../src/index.js" +import { Tool, inputTypeScript, jsonSchemaToTypeScript, outputTypeScript } from "../src/tool.js" + +// A raw JSON Schema tool in the shape an MCP adapter produces: render-only input schema +// whose property descriptions and constraints must surface as JSDoc in pretty signatures. +const listIssues = Tool.make({ + description: "List issues in a repository", + input: { + type: "object", + properties: { + owner: { type: "string", description: "Repository owner" }, + after: { type: "string", description: "Cursor from the previous response's pageInfo" }, + perPage: { type: "number", description: "Results per page", default: 30 }, + labels: { type: "array", items: { type: "string" }, description: "Filter by labels", minItems: 1, maxItems: 10 }, + state: { type: "string", enum: ["open", "closed"] }, + }, + required: ["owner"], + }, + run: () => Effect.succeed("[]"), +}) + +// An Effect Schema tool whose field annotations must flow through the emitted JSON Schema. +const lookupOrder = Tool.make({ + description: "Look up an order", + input: Schema.Struct({ + id: Schema.String.annotate({ description: "Order identifier" }), + verbose: Schema.optionalKey(Schema.Boolean), + }), + output: Schema.Struct({ + status: Schema.String.annotate({ description: "Current order status" }), + }), + run: () => Effect.succeed({ status: "open" }), +}) + +describe("pretty signature rendering", () => { + test("described fields get JSDoc comments; undescribed and untagged fields get none", () => { + expect(inputTypeScript(listIssues, true)).toBe( + [ + "{", + " /** Repository owner */", + " owner: string", + " /** Cursor from the previous response's pageInfo */", + " after?: string", + " /**", + " * Results per page", + " * @default 30", + " */", + " perPage?: number", + " /**", + " * Filter by labels", + " * @minItems 1", + " * @maxItems 10", + " */", + " labels?: Array", + ' state?: "open" | "closed"', + "}", + ].join("\n"), + ) + }) + + test("compact mode output is unchanged by the pretty machinery", () => { + expect(inputTypeScript(listIssues)).toBe( + '{ owner: string; after?: string; perPage?: number; labels?: Array; state?: "open" | "closed" }', + ) + expect(inputTypeScript(lookupOrder)).toBe("{ id: string; verbose?: boolean }") + expect(outputTypeScript(lookupOrder)).toBe("{ status: string }") + }) + + test("nested objects recurse with increasing indent and their own JSDoc", () => { + const pretty = jsonSchemaToTypeScript( + { + type: "object", + properties: { + filter: { + type: "object", + description: "Search filter", + properties: { state: { type: "string", description: "Issue state" } }, + }, + }, + }, + true, + ) + expect(pretty).toBe( + ["{", " /** Search filter */", " filter?: {", " /** Issue state */", " state?: string", " }", "}"].join( + "\n", + ), + ) + }) + + test("Effect Schema annotations become JSDoc on input and output fields", () => { + expect(inputTypeScript(lookupOrder, true)).toBe( + ["{", " /** Order identifier */", " id: string", " verbose?: boolean", "}"].join("\n"), + ) + expect(outputTypeScript(lookupOrder, true)).toBe( + ["{", " /** Current order status */", " status: string", "}"].join("\n"), + ) + }) + + test("constraints TypeScript cannot express surface as JSDoc tags", () => { + const pretty = jsonSchemaToTypeScript( + { + type: "object", + properties: { + legacy: { type: "string", deprecated: true }, + homepage: { type: "string", format: "uri" }, + tags: { type: "array", items: { type: "string" }, minItems: 2, maxItems: 5, default: ["a", "b"] }, + }, + }, + true, + ) + expect(pretty).toContain(" /** @deprecated */\n legacy?: string") + expect(pretty).toContain(" /** @format uri */\n homepage?: string") + expect(pretty).toContain( + [ + " /**", + ' * @default ["a","b"]', + " * @minItems 2", + " * @maxItems 5", + " */", + " tags?: Array", + ].join("\n"), + ) + }) + + test("skips an unserializable default rather than emitting a broken tag", () => { + const pretty = jsonSchemaToTypeScript( + { type: "object", properties: { size: { type: "number", default: 1n } } }, + true, + ) + expect(pretty).toBe(["{", " size?: number", "}"].join("\n")) + }) + + test("neutralizes */ inside descriptions so nothing closes the comment early", () => { + const pretty = jsonSchemaToTypeScript( + { type: "object", properties: { note: { type: "string", description: "Ends */ early" } } }, + true, + ) + expect(pretty).toContain(" /** Ends * / early */") + expect(pretty).not.toContain("Ends */") + }) + + test("multiline descriptions become *-prefixed blocks with blank edges trimmed", () => { + const pretty = jsonSchemaToTypeScript( + { + type: "object", + properties: { query: { type: "string", description: "\nFirst line\n\nSecond line\n" } }, + }, + true, + ) + expect(pretty).toBe( + ["{", " /**", " * First line", " *", " * Second line", " */", " query?: string", "}"].join("\n"), + ) + }) + + test("stays total on cyclic $refs and pathological nesting in both modes", () => { + const cyclic = { + $ref: "#/$defs/Node", + $defs: { Node: { type: "object", properties: { child: { $ref: "#/$defs/Node" }, name: { type: "string" } } } }, + } as const + expect(jsonSchemaToTypeScript(cyclic)).toBe("{ child?: Node; name?: string }") + expect(jsonSchemaToTypeScript(cyclic, true)).toContain("child?: Node") + + let deep: Record = { type: "string" } + for (let level = 0; level < 12; level += 1) deep = { type: "object", properties: { next: deep } } + for (const pretty of [false, true]) { + const rendered = jsonSchemaToTypeScript(deep, pretty) + expect(rendered).toContain("unknown") + expect(rendered).toContain("next?:") + } + }) +}) + +describe("non-identifier property names render as quoted keys", () => { + // MCP-style schemas routinely carry property names that are not bare TS identifiers + // (`foo-bar`, `@type`, dotted names); the rendered signature must quote them so the + // model sees a valid TypeScript object type. Bare identifiers stay unquoted. + const rawSchema = { + type: "object", + properties: { + "foo-bar": { type: "string" }, + "@type": { type: "string" }, + "x.y": { type: "number", description: "Dotted name" }, + "123": { type: "number" }, + plain: { type: "boolean" }, + }, + required: ["@type"], + } as const + + test("compact rendering quotes non-identifier keys and leaves identifiers bare", () => { + expect(jsonSchemaToTypeScript(rawSchema)).toBe( + '{ "123"?: number; "foo-bar"?: string; "@type": string; "x.y"?: number; plain?: boolean }', + ) + }) + + test("pretty rendering quotes non-identifier keys and keeps their JSDoc", () => { + expect(jsonSchemaToTypeScript(rawSchema, true)).toBe( + [ + "{", + ' "123"?: number', + ' "foo-bar"?: string', + ' "@type": string', + " /** Dotted name */", + ' "x.y"?: number', + " plain?: boolean", + "}", + ].join("\n"), + ) + }) + + test("JSON Schema input and output signatures of a tool both quote", () => { + const tool = Tool.make({ + description: "Adapter tool with awkward field names", + input: rawSchema, + output: { + type: "object", + properties: { "content-type": { type: "string" } }, + required: ["content-type"], + } as const, + run: () => Effect.succeed({ "content-type": "text/plain" }), + }) + expect(inputTypeScript(tool)).toContain('"foo-bar"?: string') + expect(outputTypeScript(tool)).toBe('{ "content-type": string }') + expect(outputTypeScript(tool, true)).toBe(["{", ' "content-type": string', "}"].join("\n")) + }) + + test("Effect Schema structs with non-identifier field names quote too", () => { + const tool = Tool.make({ + description: "Schema tool with awkward field names", + input: Schema.Struct({ "foo-bar": Schema.String, plain: Schema.optionalKey(Schema.Number) }), + run: () => Effect.succeed(null), + }) + expect(inputTypeScript(tool)).toBe('{ "foo-bar": string; plain?: number }') + expect(inputTypeScript(tool, true)).toBe(["{", ' "foo-bar": string', " plain?: number", "}"].join("\n")) + }) +}) + +describe("union schemas render every alternative", () => { + test("anyOf with a number branch keeps sibling alternatives", () => { + const schema = { + anyOf: [{ type: "string" }, { type: "number" }], + } as const + expect(jsonSchemaToTypeScript(schema)).toBe("string | number") + expect(jsonSchemaToTypeScript(schema, true)).toBe("string | number") + }) + + test("nullable numeric unions keep null", () => { + const schema = { + oneOf: [{ type: "number" }, { type: "null" }], + } as const + expect(jsonSchemaToTypeScript(schema)).toBe("number | null") + expect(jsonSchemaToTypeScript(schema, true)).toBe("number | null") + }) + + test("tool input and output signatures preserve numeric unions", () => { + const tool = Tool.make({ + description: "Tool with numeric unions", + input: { + type: "object", + properties: { + value: { anyOf: [{ type: "string" }, { type: "number" }] }, + }, + } as const, + output: { anyOf: [{ type: "number" }, { type: "boolean" }] } as const, + run: () => Effect.succeed(1), + }) + expect(inputTypeScript(tool)).toBe("{ value?: string | number }") + expect(outputTypeScript(tool)).toBe("number | boolean") + }) +}) + +describe("pretty signatures in search results", () => { + const runtime = CodeMode.make({ tools: { github: { list_issues: listIssues }, orders: { lookup: lookupOrder } } }) + + const search = async (query: string) => { + const result = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: ${JSON.stringify(query)} })`), + ) + expect(result.ok).toBe(true) + if (!result.ok) throw new Error("search failed") + return result.value as { items: Array<{ path: string; signature: string }>; total: number } + } + + test("a raw JSON Schema (MCP-style) tool's result signature carries field JSDoc and tags", async () => { + const { items } = await search("list issues repository") + const item = items.find(({ path }) => path === "tools.github.list_issues")! + expect(item.signature).toBe( + [ + "tools.github.list_issues(input: {", + " /** Repository owner */", + " owner: string", + " /** Cursor from the previous response's pageInfo */", + " after?: string", + " /**", + " * Results per page", + " * @default 30", + " */", + " perPage?: number", + " /**", + " * Filter by labels", + " * @minItems 1", + " * @maxItems 10", + " */", + " labels?: Array", + ' state?: "open" | "closed"', + "}): Promise", + ].join("\n"), + ) + }) + + test("an annotated Effect Schema tool's result signature carries field JSDoc (exact-path lookup too)", async () => { + for (const query of ["look up order", "tools.orders.lookup"]) { + const { items } = await search(query) + const item = items.find(({ path }) => path === "tools.orders.lookup")! + expect(item.signature).toBe( + [ + "tools.orders.lookup(input: {", + " /** Order identifier */", + " id: string", + " verbose?: boolean", + "}): Promise<{", + " /** Current order status */", + " status: string", + "}>", + ].join("\n"), + ) + } + }) + + test("the inline catalog line for the same tool stays single-line compact", () => { + const instructions = runtime.instructions() + expect(instructions).toContain( + ' - tools.github.list_issues(input: { owner: string; after?: string; perPage?: number; labels?: Array; state?: "open" | "closed" }): Promise // List issues in a repository', + ) + expect(instructions).toContain( + " - tools.orders.lookup(input: { id: string; verbose?: boolean }): Promise<{ status: string }> // Look up an order", + ) + expect(instructions).not.toContain("/**") + }) +}) diff --git a/packages/codemode/test/stdlib.test.ts b/packages/codemode/test/stdlib.test.ts new file mode 100644 index 0000000000..ac0e8e2e79 --- /dev/null +++ b/packages/codemode/test/stdlib.test.ts @@ -0,0 +1,495 @@ +import { describe, expect, test } from "bun:test" +import { Effect } from "effect" +import { CodeMode, Tool } from "../src/index.js" + +// Standard-library value types: Date, RegExp, Map, Set. Programs use them as ordinary JS; +// intra-sandbox checkpoints (Object.* helpers, spread, coercion inputs) preserve the live +// values, while at the host boundary (final result, tool arguments, JSON.stringify) they +// serialize exactly as JSON.stringify would: Date -> ISO string (invalid -> null), +// RegExp/Map/Set -> {}. +const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) +const value = async (code: string) => { + const result = await run(code) + if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) + return result.value +} +const error = async (code: string) => { + const result = await run(code) + if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) + return result.error +} + +describe("Date", () => { + test("Date.now() returns a number", async () => { + expect(await value(`return typeof Date.now()`)).toBe("number") + }) + + test("epoch construction and ISO rendering", async () => { + expect(await value(`return new Date(0).toISOString()`)).toBe("1970-01-01T00:00:00.000Z") + }) + + test("string parsing round-trips", async () => { + expect(await value(`return new Date("2024-01-02T03:04:05.000Z").getTime()`)).toBe(1704164645000) + expect(await value(`return Date.parse("2024-01-02T03:04:05.000Z")`)).toBe(1704164645000) + }) + + test("date arithmetic and comparison use the time value", async () => { + expect(await value(`const a = new Date(1000); const b = new Date(3000); return b - a`)).toBe(2000) + expect(await value(`const a = new Date(1000); const b = new Date(3000); return a < b`)).toBe(true) + expect(await value(`return +new Date(42)`)).toBe(42) + }) + + test("UTC getters read calendar components", async () => { + expect( + await value( + `const d = new Date("2024-03-05T06:07:08.009Z"); return [d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()]`, + ), + ).toEqual([2024, 2, 5, 6, 7, 8, 9]) + }) + + test("invalid dates yield NaN times, guardable in-sandbox", async () => { + expect(await value(`return Number.isNaN(new Date("garbage").getTime())`)).toBe(true) + expect(await value(`return new Date("garbage").toJSON()`)).toBeNull() + }) + + test("toISOString on an invalid date is a catchable error", async () => { + expect(await value(`try { new Date("garbage").toISOString(); return "no" } catch { return "caught" }`)).toBe( + "caught", + ) + }) + + test("template interpolation renders the ISO form", async () => { + expect(await value("return `at ${new Date(0)}`")).toBe("at 1970-01-01T00:00:00.000Z") + }) + + test("dates serialize to ISO strings at the boundary, direct and nested", async () => { + expect(await value(`return new Date(0)`)).toBe("1970-01-01T00:00:00.000Z") + expect(await value(`return { when: new Date(0), tags: [new Date(1000)] }`)).toEqual({ + when: "1970-01-01T00:00:00.000Z", + tags: ["1970-01-01T00:00:01.000Z"], + }) + expect(await value(`return JSON.stringify({ d: new Date(0) })`)).toBe('{"d":"1970-01-01T00:00:00.000Z"}') + }) + + test("coercions: Number is the time, String is ISO, Boolean is true", async () => { + expect(await value(`return Number(new Date(5))`)).toBe(5) + expect(await value(`return String(new Date(0))`)).toBe("1970-01-01T00:00:00.000Z") + expect(await value(`return Boolean(new Date(0))`)).toBe(true) + }) + + test("sorting dates with a numeric comparator", async () => { + expect( + await value(` + const dates = [new Date(3000), new Date(1000), new Date(2000)] + return dates.sort((a, b) => a - b).map((d) => d.getTime()) + `), + ).toEqual([1000, 2000, 3000]) + }) + + test("new Date(year, month, day) accepts component form", async () => { + expect(await value(`const d = new Date(2024, 0, 2); return [d.getFullYear(), d.getMonth(), d.getDate()]`)).toEqual([ + 2024, 0, 2, + ]) + }) + + test("typeof and unknown properties are forgiving", async () => { + expect(await value(`return typeof new Date(0)`)).toBe("object") + expect(await value(`return new Date(0).nope === undefined`)).toBe(true) + }) +}) + +describe("RegExp", () => { + test("literal test", async () => { + expect(await value(`return /ab+c/.test("xabbbc")`)).toBe(true) + expect(await value(`return /ab+c/.test("nope")`)).toBe(false) + }) + + test("exec exposes captures and index", async () => { + expect(await value(`const m = /a(b+)/.exec("xxabbc"); return { full: m[0], group: m[1], index: m.index }`)).toEqual( + { + full: "abb", + group: "bb", + index: 2, + }, + ) + expect(await value(`return /a/.exec("zzz")`)).toBeNull() + }) + + test("named groups read through", async () => { + expect( + await value(`const m = /(?[a-z]+)-(?\\d+)/.exec("id ab-42"); return m.groups.word + m.groups.num`), + ).toBe("ab42") + }) + + test("global exec advances lastIndex across calls", async () => { + expect( + await value(` + const r = /\\d+/g + const first = r.exec("a1b22c") + const second = r.exec("a1b22c") + return [first[0], second[0]] + `), + ).toEqual(["1", "22"]) + }) + + test("string match: non-global carries index, global lists all matches", async () => { + expect(await value(`const m = "a1b22".match(/\\d+/); return [m[0], m.index]`)).toEqual(["1", 1]) + expect(await value(`return "a1b22".match(/\\d+/g)`)).toEqual(["1", "22"]) + expect(await value(`return "abc".match(/\\d/)`)).toBeNull() + }) + + test("matchAll materializes match arrays with captures", async () => { + expect(await value(`return "a1b22".matchAll(/(\\d+)/g).map((m) => m[1])`)).toEqual(["1", "22"]) + }) + + test("replace and replaceAll with patterns and $1 substitution", async () => { + expect(await value(`return "a1b2".replace(/\\d/, "#")`)).toBe("a#b2") + expect(await value(`return "a1b2".replace(/\\d/g, "#")`)).toBe("a#b#") + expect(await value(`return "a1b2".replaceAll(/\\d/g, "#")`)).toBe("a#b#") + expect(await value(`return "hi bob".replace(/b(o)b/, "[$1]")`)).toBe("hi [o]") + }) + + test("replaceAll without the g flag is a catchable error", async () => { + expect(await value(`try { "a".replaceAll(/a/, "b"); return "no" } catch { return "caught" }`)).toBe("caught") + }) + + test("split and search accept patterns", async () => { + expect(await value(`return "a1b22c".split(/\\d+/)`)).toEqual(["a", "b", "c"]) + expect(await value(`return "ab42".search(/\\d/)`)).toBe(2) + expect(await value(`return "ab".search(/\\d/)`)).toBe(-1) + }) + + test("new RegExp constructs from strings; invalid patterns are catchable", async () => { + expect(await value(`return new RegExp("a+", "i").test("AAA")`)).toBe(true) + expect(await value(`try { new RegExp("("); return "no" } catch { return "caught" }`)).toBe("caught") + expect(await value(`return [/a/ instanceof RegExp, /a/.source]`)).toEqual([true, "a"]) + }) + + test("invalid patterns fail with actionable messages", async () => { + const fromString = await error(`return "abc".match("(")`) + expect(fromString.message).toContain('String.match received the string "("') + expect(fromString.message).toContain("escape them with a backslash") + + const fromConstructor = await error(`return new RegExp("(")`) + expect(fromConstructor.message).toContain('new RegExp(...) received "("') + expect(fromConstructor.message).toContain("escape them with a backslash") + + const fromFlags = await error(`return new RegExp("a", "xz")`) + expect(fromFlags.message).toContain('invalid flags "xz"') + expect(fromFlags.message).toContain("Valid flags are") + }) + + test("missing g-flag errors say how to fix the call", async () => { + expect((await error(`return "aa".replaceAll(/a/, "b")`)).message).toContain("write /a/g, or use String.replace") + expect((await error(`return "aa".matchAll(/a/)`)).message).toContain("write /a/g, or use String.match") + }) + + test("a non-pattern argument names the expected shapes", async () => { + const err = await error(`return "abc".match(42)`) + expect(err.message).toContain("expects a regular expression") + expect(err.message).toContain("not number") + }) + + test("source and flags properties read through", async () => { + expect(await value(`const r = /ab/gi; return { source: r.source, flags: r.flags, global: r.global }`)).toEqual({ + source: "ab", + flags: "gi", + global: true, + }) + }) + + test("regexes serialize to {} at the boundary, like JSON", async () => { + expect(await value(`return /a/`)).toEqual({}) + expect(await value(`return JSON.stringify({ r: /a/g })`)).toBe('{"r":{}}') + }) + + test("template interpolation renders the literal form", async () => { + expect(await value("return `${/ab/g}`")).toBe("/ab/g") + }) +}) + +describe("Map", () => { + test("get/set/has/size with chaining", async () => { + expect( + await value(` + const m = new Map() + m.set("a", 1).set("b", 2) + return { a: m.get("a"), b: m.get("b"), has: m.has("a"), miss: m.get("zz") === undefined, size: m.size } + `), + ).toEqual({ a: 1, b: 2, has: true, miss: true, size: 5 - 3 }) + }) + + test("object keys use identity", async () => { + expect( + await value(` + const key = { id: 1 } + const m = new Map() + m.set(key, "hit") + return [m.get(key), m.get({ id: 1 }) === undefined] + `), + ).toEqual(["hit", true]) + }) + + test("construction from entry pairs and another Map", async () => { + expect(await value(`const m = new Map([["a", 1], ["b", 2]]); return m.get("b")`)).toBe(2) + expect( + await value( + `const m = new Map([["a", 1]]); const n = new Map(m); n.set("b", 2); return [n.get("a"), n.get("b"), m.has("b")]`, + ), + ).toEqual([1, 2, false]) + expect((await error(`return new Map("nope")`)).message).toMatch(/\[key, value\] pairs/) + expect((await error(`return new Map(["flat"])`)).message).toMatch(/\[key, value\] pairs/) + }) + + test("keys/values/entries return arrays", async () => { + expect( + await value(` + const m = new Map([["a", 1], ["b", 2]]) + return { keys: m.keys(), values: m.values(), entries: m.entries() } + `), + ).toEqual({ + keys: ["a", "b"], + values: [1, 2], + entries: [ + ["a", 1], + ["b", 2], + ], + }) + }) + + test("Object.fromEntries(map) and Array.from(map)", async () => { + expect(await value(`return Object.fromEntries(new Map([["a", 1], ["b", 2]]))`)).toEqual({ a: 1, b: 2 }) + expect(await value(`return Array.from(new Map([["a", 1]]))`)).toEqual([["a", 1]]) + }) + + test("for...of iterates [key, value] pairs with destructuring", async () => { + expect( + await value(` + const m = new Map([["a", 1], ["b", 2]]) + let total = 0 + let names = "" + for (const [key, count] of m) { names += key; total += count } + return names + total + `), + ).toBe("ab3") + }) + + test("spread produces entry pairs", async () => { + expect(await value(`return [...new Map([["a", 1]])]`)).toEqual([["a", 1]]) + }) + + test("forEach passes (value, key)", async () => { + expect( + await value(` + const m = new Map([["a", 1], ["b", 2]]) + const seen = [] + m.forEach((count, key) => seen.push(key + count)) + return seen + `), + ).toEqual(["a1", "b2"]) + }) + + test("delete and clear", async () => { + expect( + await value(` + const m = new Map([["a", 1], ["b", 2]]) + const removed = m.delete("a") + const missed = m.delete("zz") + const sizeAfterDelete = m.size + m.clear() + return [removed, missed, sizeAfterDelete, m.size] + `), + ).toEqual([true, false, 1, 0]) + }) + + test("counting idiom: grouped tallies", async () => { + expect( + await value(` + const words = ["a", "b", "a", "c", "a"] + const counts = new Map() + for (const word of words) counts.set(word, (counts.get(word) ?? 0) + 1) + return Object.fromEntries(counts) + `), + ).toEqual({ a: 3, b: 1, c: 1 }) + }) + + test("maps serialize to {} at the boundary, like JSON", async () => { + expect(await value(`return new Map([["a", 1]])`)).toEqual({}) + expect(await value(`return JSON.stringify(new Map([["a", 1]]))`)).toBe("{}") + }) + + test("console.log renders map contents for debugging", async () => { + const result = await run(`console.log(new Map([["a", 1]])); return null`) + expect(result.ok).toBe(true) + expect(result.logs?.[0]).toBe(`Map(1) [["a",1]]`) + }) +}) + +describe("Set", () => { + test("add/has/delete/size with chaining", async () => { + expect( + await value(` + const s = new Set() + s.add(1).add(2).add(1) + const removed = s.delete(2) + return [s.size, s.has(1), s.has(2), removed] + `), + ).toEqual([1, true, false, true]) + }) + + test("dedupe idiom: [...new Set(items)]", async () => { + expect(await value(`return [...new Set([1, 2, 2, 3, 1])]`)).toEqual([1, 2, 3]) + }) + + test("construction from strings and other Sets", async () => { + expect(await value(`return [...new Set("aba")]`)).toEqual(["a", "b"]) + expect(await value(`return Array.from(new Set(new Set([1, 2])))`)).toEqual([1, 2]) + }) + + test("SameValueZero: NaN is findable", async () => { + expect(await value(`const s = new Set([NaN]); return s.has(NaN)`)).toBe(true) + }) + + test("for...of iterates values", async () => { + expect( + await value(` + let total = 0 + for (const n of new Set([1, 2, 3])) total += n + return total + `), + ).toBe(6) + }) + + test("sets serialize to {} at the boundary, like JSON", async () => { + expect(await value(`return { s: new Set([1]) }`)).toEqual({ s: {} }) + }) +}) + +describe("stdlib integration", () => { + test("typeof reports constructors as functions and never throws", async () => { + expect(await value(`return typeof Map`)).toBe("function") + expect(await value(`return typeof ((x) => x)`)).toBe("function") + expect(await value(`return typeof Math`)).toBe("object") + expect(await value(`return typeof tools`)).toBe("object") + }) + + test("negation works on any value", async () => { + expect(await value(`return !new Map()`)).toBe(false) + expect(await value(`const fn = () => 1; return !fn`)).toBe(false) + }) + + test("object spread of sandbox values is a no-op, like JS", async () => { + expect(await value(`return { ...new Map([["a", 1]]), kept: true }`)).toEqual({ kept: true }) + }) + + test("dates inside Map values survive in-sandbox reads", async () => { + expect( + await value(` + const m = new Map([["start", new Date(1000)]]) + return m.get("start").getTime() + `), + ).toBe(1000) + }) + + test("instanceof recognizes the stdlib value types", async () => { + expect( + await value( + `return [new Date(0) instanceof Date, /a/ instanceof RegExp, new Map() instanceof Map, new Set() instanceof Set]`, + ), + ).toEqual([true, true, true, true]) + expect( + await value(`return [[1] instanceof Array, [1] instanceof Object, ({}) instanceof Object, 5 instanceof Object]`), + ).toEqual([true, true, true, false]) + expect(await value(`return [new Map() instanceof Set, "s" instanceof Date]`)).toEqual([false, false]) + expect( + await value(`const p = Promise.resolve(1); const isPromise = p instanceof Promise; await p; return isPromise`), + ).toBe(true) + }) + + test("realistic pipeline: parse, extract with regex, dedupe, count by day", async () => { + expect( + await value(` + const raw = '[{"at":"2024-01-01T05:00:00Z","tag":"a b"},{"at":"2024-01-01T09:00:00Z","tag":"b c"},{"at":"2024-01-02T01:00:00Z","tag":"a"}]' + const rows = JSON.parse(raw) + const tags = new Set() + const byDay = new Map() + for (const row of rows) { + for (const m of row.tag.matchAll(/[a-z]+/g)) tags.add(m[0]) + const day = new Date(row.at).toISOString().slice(0, 10) + byDay.set(day, (byDay.get(day) ?? 0) + 1) + } + return { tags: [...tags].sort((a, b) => (a < b ? -1 : 1)), byDay: Object.fromEntries(byDay) } + `), + ).toEqual({ tags: ["a", "b", "c"], byDay: { "2024-01-01": 2, "2024-01-02": 1 } }) + }) +}) + +describe("sandbox values at intra-sandbox checkpoints", () => { + test("Object.values/entries keep Dates usable", async () => { + expect(await value(`return Object.values({ d: new Date(0) })[0].getTime()`)).toBe(0) + expect(await value(`const [key, d] = Object.entries({ d: new Date(0) })[0]; return key + ":" + d.getTime()`)).toBe( + "d:0", + ) + }) + + test("Object.assign keeps Maps usable", async () => { + expect(await value(`const merged = Object.assign({}, { m: new Map([["a", 1]]) }); return merged.m.get("a")`)).toBe( + 1, + ) + }) + + test("object and array spread keep sandbox values usable", async () => { + expect( + await value(` + const src = { m: new Map([["a", 1]]) } + const copy = { ...src } + copy.m.set("b", 2) + return [copy.m.get("a"), src.m.get("b")] + `), + ).toEqual([1, 2]) + expect(await value(`const list = [new Date(1000)]; const copy = [...list]; return copy[0].getTime()`)).toBe(1000) + }) + + test("Array.from over arrays keeps nested sandbox values usable", async () => { + expect(await value(`return Array.from([new Date(5)])[0].getTime()`)).toBe(5) + }) + + test("regexes stay callable through Object.values", async () => { + expect(await value(`return Object.values({ r: /ab+/ })[0].test("abb")`)).toBe(true) + }) + + test("Object.* helpers see sandbox values as empty objects, never internals", async () => { + expect(await value(`return Object.keys(new Map([["a", 1]]))`)).toEqual([]) + expect(await value(`return Object.values(new Date(0))`)).toEqual([]) + expect(await value(`return Object.entries(new Set([1]))`)).toEqual([]) + expect(await value(`return Object.assign({}, new Map([["a", 1]]))`)).toEqual({}) + expect(await value(`return Object.hasOwn(new Date(0), "time")`)).toBe(false) + }) + + test("the host boundary still serializes JSON forms: results, JSON.stringify, and tool arguments", async () => { + expect(await value(`return { d: new Date(0), m: new Map([["a", 1]]) }`)).toEqual({ + d: "1970-01-01T00:00:00.000Z", + m: {}, + }) + expect(await value(`return JSON.stringify({ d: new Date(0) })`)).toBe('{"d":"1970-01-01T00:00:00.000Z"}') + + const observed: Array = [] + const capture = Tool.make({ + description: "Capture the exact input the host receives", + input: { type: "object" }, + run: (input) => + Effect.sync(() => { + observed.push(input) + return "ok" + }), + }) + const result = await Effect.runPromise( + CodeMode.execute({ + tools: { host: { capture } }, + code: `return await tools.host.capture({ when: new Date(0), tags: new Map([["a", 1]]) })`, + }), + ) + expect(result.ok).toBe(true) + expect(observed).toStrictEqual([{ when: "1970-01-01T00:00:00.000Z", tags: {} }]) + }) +}) diff --git a/packages/codemode/tsconfig.json b/packages/codemode/tsconfig.json new file mode 100644 index 0000000000..fe5c4d217b --- /dev/null +++ b/packages/codemode/tsconfig.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@tsconfig/bun/tsconfig.json", + "compilerOptions": { + "noUncheckedIndexedAccess": false + } +} From 5fc4e18b82d5fd15341f41bc370b15581792da46 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 3 Jul 2026 11:10:49 -0500 Subject: [PATCH 06/82] test(core): cover when AND semantics and multiselect neq (#35182) --- packages/core/test/form.test.ts | 73 +++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/packages/core/test/form.test.ts b/packages/core/test/form.test.ts index 7ea351df3a..e032cf6c71 100644 --- a/packages/core/test/form.test.ts +++ b/packages/core/test/form.test.ts @@ -92,6 +92,79 @@ describe("Form", () => { }), ) + it.effect("requires every when condition to match and treats empty when as active", () => + Effect.gen(function* () { + const service = yield* Form.Service + const created = yield* service.create({ + sessionID: "global", + mode: "form", + fields: [ + { key: "a", type: "boolean" }, + { key: "b", type: "boolean" }, + { + key: "x", + type: "string", + required: true, + when: [ + { key: "a", op: "eq", value: true }, + { key: "b", op: "eq", value: true }, + ], + }, + { key: "z", type: "string", required: true, when: [] }, + ], + }) + + const missingX = yield* service.reply({ id: created.id, answer: { a: true, b: true, z: "ok" } }).pipe(Effect.flip) + expect(missingX).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Missing required form field: x" })) + + const inactiveX = yield* service + .reply({ id: created.id, answer: { a: true, b: false, x: "nope", z: "ok" } }) + .pipe(Effect.flip) + expect(inactiveX).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Form field is not active: x" })) + + const missingZ = yield* service.reply({ id: created.id, answer: { a: true, b: false } }).pipe(Effect.flip) + expect(missingZ).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Missing required form field: z" })) + + yield* service.reply({ id: created.id, answer: { a: true, b: false, z: "ok" } }) + expect(yield* service.state(created.id)).toEqual({ status: "answered", answer: { a: true, b: false, z: "ok" } }) + }), + ) + + it.effect("evaluates neq against multiselect answers as non-inclusion", () => + Effect.gen(function* () { + const service = yield* Form.Service + const options = [ + { value: "go", label: "Go" }, + { value: "ts", label: "TypeScript" }, + ] + const created = yield* service.create({ + sessionID: "global", + mode: "form", + fields: [ + { key: "langs", type: "multiselect", options }, + { key: "note", type: "string", required: true, when: [{ key: "langs", op: "neq", value: "go" }] }, + ], + }) + + const missing = yield* service.reply({ id: created.id, answer: { langs: ["ts"] } }).pipe(Effect.flip) + expect(missing).toEqual( + new Form.InvalidAnswerError({ id: created.id, message: "Missing required form field: note" }), + ) + + // an answered-but-empty multiselect also satisfies neq + const missingEmpty = yield* service.reply({ id: created.id, answer: { langs: [] } }).pipe(Effect.flip) + expect(missingEmpty).toEqual( + new Form.InvalidAnswerError({ id: created.id, message: "Missing required form field: note" }), + ) + + const inactive = yield* service.reply({ id: created.id, answer: { langs: ["go"], note: "x" } }).pipe(Effect.flip) + expect(inactive).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Form field is not active: note" })) + + yield* service.reply({ id: created.id, answer: { langs: ["go"] } }) + expect(yield* service.state(created.id)).toEqual({ status: "answered", answer: { langs: ["go"] } }) + }), + ) + it.effect("treats unanswered when references as false and cascades inactivity", () => Effect.gen(function* () { const service = yield* Form.Service From bd8d858bf7fafc8bb9b5d1ac88001e83bede430e Mon Sep 17 00:00:00 2001 From: James Long Date: Fri, 3 Jul 2026 12:19:09 -0400 Subject: [PATCH 07/82] feat(core): implement V2 session.shell (#35183) --- .../client/src/effect/generated/client.ts | 137 ++++++++++-------- .../client/src/promise/generated/client.ts | 14 ++ .../client/src/promise/generated/types.ts | 8 + packages/core/src/session.ts | 70 ++++++++- packages/core/test/session-create.test.ts | 56 +++++-- .../plugin/src/v2/effect/generated/api.ts | 132 +++++++++-------- packages/protocol/src/groups/session.ts | 20 +++ packages/sdk/js/src/v2/gen/sdk.gen.ts | 39 +++++ packages/sdk/js/src/v2/gen/types.gen.ts | 38 +++++ packages/server/src/handlers/session.ts | 18 +++ packages/tui/src/component/prompt/index.tsx | 7 +- packages/tui/src/routes/session/index.tsx | 27 +++- 12 files changed, 414 insertions(+), 152 deletions(-) diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index f25557c0de..a9a91eb8c6 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -208,23 +208,35 @@ const Endpoint4_11 = (raw: RawClient["server.session"]) => (input: Endpoint4_11I payload: { text: input["text"], description: input["description"], metadata: input["metadata"] }, }).pipe(Effect.mapError(mapClientError)) -type Endpoint4_12Request = Parameters[0] -type Endpoint4_12Input = { readonly sessionID: Endpoint4_12Request["params"]["sessionID"] } +type Endpoint4_12Request = Parameters[0] +type Endpoint4_12Input = { + readonly sessionID: Endpoint4_12Request["params"]["sessionID"] + readonly id?: Endpoint4_12Request["payload"]["id"] + readonly command: Endpoint4_12Request["payload"]["command"] +} const Endpoint4_12 = (raw: RawClient["server.session"]) => (input: Endpoint4_12Input) => - raw["session.compact"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) + raw["session.shell"]({ + params: { sessionID: input["sessionID"] }, + payload: { id: input["id"], command: input["command"] }, + }).pipe(Effect.mapError(mapClientError)) -type Endpoint4_13Request = Parameters[0] +type Endpoint4_13Request = Parameters[0] type Endpoint4_13Input = { readonly sessionID: Endpoint4_13Request["params"]["sessionID"] } const Endpoint4_13 = (raw: RawClient["server.session"]) => (input: Endpoint4_13Input) => + raw["session.compact"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) + +type Endpoint4_14Request = Parameters[0] +type Endpoint4_14Input = { readonly sessionID: Endpoint4_14Request["params"]["sessionID"] } +const Endpoint4_14 = (raw: RawClient["server.session"]) => (input: Endpoint4_14Input) => raw["session.wait"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) -type Endpoint4_14Request = Parameters[0] -type Endpoint4_14Input = { - readonly sessionID: Endpoint4_14Request["params"]["sessionID"] - readonly messageID: Endpoint4_14Request["payload"]["messageID"] - readonly files?: Endpoint4_14Request["payload"]["files"] +type Endpoint4_15Request = Parameters[0] +type Endpoint4_15Input = { + readonly sessionID: Endpoint4_15Request["params"]["sessionID"] + readonly messageID: Endpoint4_15Request["payload"]["messageID"] + readonly files?: Endpoint4_15Request["payload"]["files"] } -const Endpoint4_14 = (raw: RawClient["server.session"]) => (input: Endpoint4_14Input) => +const Endpoint4_15 = (raw: RawClient["server.session"]) => (input: Endpoint4_15Input) => raw["session.revert.stage"]({ params: { sessionID: input["sessionID"] }, payload: { messageID: input["messageID"], files: input["files"] }, @@ -233,61 +245,61 @@ const Endpoint4_14 = (raw: RawClient["server.session"]) => (input: Endpoint4_14I Effect.map((value) => value.data), ) -type Endpoint4_15Request = Parameters[0] -type Endpoint4_15Input = { readonly sessionID: Endpoint4_15Request["params"]["sessionID"] } -const Endpoint4_15 = (raw: RawClient["server.session"]) => (input: Endpoint4_15Input) => - raw["session.revert.clear"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) - -type Endpoint4_16Request = Parameters[0] +type Endpoint4_16Request = Parameters[0] type Endpoint4_16Input = { readonly sessionID: Endpoint4_16Request["params"]["sessionID"] } const Endpoint4_16 = (raw: RawClient["server.session"]) => (input: Endpoint4_16Input) => - raw["session.revert.commit"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) + raw["session.revert.clear"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) -type Endpoint4_17Request = Parameters[0] +type Endpoint4_17Request = Parameters[0] type Endpoint4_17Input = { readonly sessionID: Endpoint4_17Request["params"]["sessionID"] } const Endpoint4_17 = (raw: RawClient["server.session"]) => (input: Endpoint4_17Input) => + raw["session.revert.commit"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) + +type Endpoint4_18Request = Parameters[0] +type Endpoint4_18Input = { readonly sessionID: Endpoint4_18Request["params"]["sessionID"] } +const Endpoint4_18 = (raw: RawClient["server.session"]) => (input: Endpoint4_18Input) => raw["session.context"]({ params: { sessionID: input["sessionID"] } }).pipe( Effect.mapError(mapClientError), Effect.map((value) => value.data), ) -type Endpoint4_18Request = Parameters[0] -type Endpoint4_18Input = { readonly sessionID: Endpoint4_18Request["params"]["sessionID"] } -const Endpoint4_18 = (raw: RawClient["server.session"]) => (input: Endpoint4_18Input) => +type Endpoint4_19Request = Parameters[0] +type Endpoint4_19Input = { readonly sessionID: Endpoint4_19Request["params"]["sessionID"] } +const Endpoint4_19 = (raw: RawClient["server.session"]) => (input: Endpoint4_19Input) => raw["session.context.entry.list"]({ params: { sessionID: input["sessionID"] } }).pipe( Effect.mapError(mapClientError), Effect.map((value) => value.data), ) -type Endpoint4_19Request = Parameters[0] -type Endpoint4_19Input = { - readonly sessionID: Endpoint4_19Request["params"]["sessionID"] - readonly key: Endpoint4_19Request["params"]["key"] - readonly value: Endpoint4_19Request["payload"]["value"] +type Endpoint4_20Request = Parameters[0] +type Endpoint4_20Input = { + readonly sessionID: Endpoint4_20Request["params"]["sessionID"] + readonly key: Endpoint4_20Request["params"]["key"] + readonly value: Endpoint4_20Request["payload"]["value"] } -const Endpoint4_19 = (raw: RawClient["server.session"]) => (input: Endpoint4_19Input) => +const Endpoint4_20 = (raw: RawClient["server.session"]) => (input: Endpoint4_20Input) => raw["session.context.entry.put"]({ params: { sessionID: input["sessionID"], key: input["key"] }, payload: { value: input["value"] }, }).pipe(Effect.mapError(mapClientError)) -type Endpoint4_20Request = Parameters[0] -type Endpoint4_20Input = { - readonly sessionID: Endpoint4_20Request["params"]["sessionID"] - readonly key: Endpoint4_20Request["params"]["key"] +type Endpoint4_21Request = Parameters[0] +type Endpoint4_21Input = { + readonly sessionID: Endpoint4_21Request["params"]["sessionID"] + readonly key: Endpoint4_21Request["params"]["key"] } -const Endpoint4_20 = (raw: RawClient["server.session"]) => (input: Endpoint4_20Input) => +const Endpoint4_21 = (raw: RawClient["server.session"]) => (input: Endpoint4_21Input) => raw["session.context.entry.remove"]({ params: { sessionID: input["sessionID"], key: input["key"] } }).pipe( Effect.mapError(mapClientError), ) -type Endpoint4_21Request = Parameters[0] -type Endpoint4_21Input = { - readonly sessionID: Endpoint4_21Request["params"]["sessionID"] - readonly after?: Endpoint4_21Request["query"]["after"] - readonly follow?: Endpoint4_21Request["query"]["follow"] +type Endpoint4_22Request = Parameters[0] +type Endpoint4_22Input = { + readonly sessionID: Endpoint4_22Request["params"]["sessionID"] + readonly after?: Endpoint4_22Request["query"]["after"] + readonly follow?: Endpoint4_22Request["query"]["follow"] } -const Endpoint4_21 = (raw: RawClient["server.session"]) => (input: Endpoint4_21Input) => +const Endpoint4_22 = (raw: RawClient["server.session"]) => (input: Endpoint4_22Input) => Stream.unwrap( raw["session.log"]({ params: { sessionID: input["sessionID"] }, @@ -298,22 +310,22 @@ const Endpoint4_21 = (raw: RawClient["server.session"]) => (input: Endpoint4_21I ), ) -type Endpoint4_22Request = Parameters[0] -type Endpoint4_22Input = { readonly sessionID: Endpoint4_22Request["params"]["sessionID"] } -const Endpoint4_22 = (raw: RawClient["server.session"]) => (input: Endpoint4_22Input) => - raw["session.interrupt"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) - -type Endpoint4_23Request = Parameters[0] +type Endpoint4_23Request = Parameters[0] type Endpoint4_23Input = { readonly sessionID: Endpoint4_23Request["params"]["sessionID"] } const Endpoint4_23 = (raw: RawClient["server.session"]) => (input: Endpoint4_23Input) => + raw["session.interrupt"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) + +type Endpoint4_24Request = Parameters[0] +type Endpoint4_24Input = { readonly sessionID: Endpoint4_24Request["params"]["sessionID"] } +const Endpoint4_24 = (raw: RawClient["server.session"]) => (input: Endpoint4_24Input) => raw["session.background"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) -type Endpoint4_24Request = Parameters[0] -type Endpoint4_24Input = { - readonly sessionID: Endpoint4_24Request["params"]["sessionID"] - readonly messageID: Endpoint4_24Request["params"]["messageID"] +type Endpoint4_25Request = Parameters[0] +type Endpoint4_25Input = { + readonly sessionID: Endpoint4_25Request["params"]["sessionID"] + readonly messageID: Endpoint4_25Request["params"]["messageID"] } -const Endpoint4_24 = (raw: RawClient["server.session"]) => (input: Endpoint4_24Input) => +const Endpoint4_25 = (raw: RawClient["server.session"]) => (input: Endpoint4_25Input) => raw["session.message"]({ params: { sessionID: input["sessionID"], messageID: input["messageID"] } }).pipe( Effect.mapError(mapClientError), Effect.map((value) => value.data), @@ -332,19 +344,20 @@ const adaptGroup4 = (raw: RawClient["server.session"]) => ({ command: Endpoint4_9(raw), skill: Endpoint4_10(raw), synthetic: Endpoint4_11(raw), - compact: Endpoint4_12(raw), - wait: Endpoint4_13(raw), - revertStage: Endpoint4_14(raw), - revertClear: Endpoint4_15(raw), - revertCommit: Endpoint4_16(raw), - context: Endpoint4_17(raw), - listContextEntries: Endpoint4_18(raw), - putContextEntry: Endpoint4_19(raw), - removeContextEntry: Endpoint4_20(raw), - log: Endpoint4_21(raw), - interrupt: Endpoint4_22(raw), - background: Endpoint4_23(raw), - message: Endpoint4_24(raw), + shell: Endpoint4_12(raw), + compact: Endpoint4_13(raw), + wait: Endpoint4_14(raw), + revertStage: Endpoint4_15(raw), + revertClear: Endpoint4_16(raw), + revertCommit: Endpoint4_17(raw), + context: Endpoint4_18(raw), + listContextEntries: Endpoint4_19(raw), + putContextEntry: Endpoint4_20(raw), + removeContextEntry: Endpoint4_21(raw), + log: Endpoint4_22(raw), + interrupt: Endpoint4_23(raw), + background: Endpoint4_24(raw), + message: Endpoint4_25(raw), }) type Endpoint5_0Request = Parameters[0] diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index ee752f23ef..79368764c7 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -29,6 +29,8 @@ import type { SessionSkillOutput, SessionSyntheticInput, SessionSyntheticOutput, + SessionShellInput, + SessionShellOutput, SessionCompactInput, SessionCompactOutput, SessionWaitInput, @@ -525,6 +527,18 @@ export function make(options: ClientOptions) { }, requestOptions, ), + shell: (input: SessionShellInput, requestOptions?: RequestOptions) => + request( + { + method: "POST", + path: `/api/session/${encodeURIComponent(input.sessionID)}/shell`, + body: { id: input["id"], command: input["command"] }, + successStatus: 204, + declaredStatuses: [404, 400, 401], + empty: true, + }, + requestOptions, + ), compact: (input: SessionCompactInput, requestOptions?: RequestOptions) => request( { diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index d858ded933..6c8286fc52 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -865,6 +865,14 @@ export type SessionSyntheticInput = { export type SessionSyntheticOutput = void +export type SessionShellInput = { + readonly sessionID: { readonly sessionID: string }["sessionID"] + readonly id?: { readonly id?: string | undefined; readonly command: string }["id"] + readonly command: { readonly id?: string | undefined; readonly command: string }["command"] +} + +export type SessionShellOutput = void + export type SessionCompactInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } export type SessionCompactOutput = void diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 4f1be4151c..acae2691c8 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -41,6 +41,9 @@ import type { EventLog } from "@opencode-ai/schema/event-log" import { SkillV2 } from "./skill" import { Job } from "./job" import { CommandV2 } from "./command" +import { Identifier } from "./util/identifier" +import { Shell } from "./shell" +import { KeyedMutex } from "./effect/keyed-mutex" export const RevertState = Revert.State export type RevertState = Revert.State @@ -106,7 +109,7 @@ export class NotFoundError extends Schema.TaggedErrorClass()("Ses export class OperationUnavailableError extends Schema.TaggedErrorClass()( "Session.OperationUnavailableError", { - operation: Schema.Literals(["move", "shell", "skill", "switchAgent", "compact"]), + operation: Schema.Literals(["move", "skill", "switchAgent", "compact"]), }, ) {} @@ -208,8 +211,7 @@ export interface Interface { id?: EventV2.ID sessionID: SessionSchema.ID command: string - resume?: boolean - }) => Effect.Effect + }) => Effect.Effect readonly skill: (input: { id?: SessionMessage.ID sessionID: SessionSchema.ID @@ -255,6 +257,8 @@ const layer = Layer.effect( const locations = yield* LocationServiceMap.Service const jobs = yield* Job.Service const scope = yield* Scope.Scope + const activeShells = new Set() + const shellLocks = KeyedMutex.makeUnsafe() const decodeMessage = Schema.decodeUnknownEffect(SessionMessage.Message) const isDurableSessionEvent = Schema.is(SessionEvent.Durable) const decode = (row: typeof SessionMessageTable.$inferSelect) => @@ -268,6 +272,19 @@ const layer = Layer.effect( ), ) + // Session shell is user-initiated and synchronous at the API boundary, while + // the Location shell service owns process lifecycle and file-backed output. + const runShellCommand = (command: string, cwd: string) => + Effect.gen(function* () { + const shell = yield* Shell.Service + const info = yield* shell.create({ command, cwd }) + yield* shell.wait(info.id) + const output = yield* shell.output(info.id, { limit: SHELL_MAX_CAPTURE_BYTES }) + return output.output || "(no output)" + }).pipe( + Effect.catchTag("Shell.NotFoundError", () => Effect.succeed("Shell command output is no longer available.")), + ) + const result = Service.of({ create: Effect.fn("V2Session.create")(function* (input) { const sessionID = input.id ?? SessionSchema.ID.create() @@ -489,7 +506,10 @@ const layer = Layer.effect( ) if (!SessionInput.equivalent(admitted, expected)) return yield* new PromptConflictError({ sessionID: input.sessionID, messageID }) - if (input.resume !== false) yield* execution.wake(admitted.sessionID) + if (input.resume !== false) { + if (activeShells.has(admitted.sessionID)) return admitted + yield* execution.wake(admitted.sessionID) + } return admitted }), ), @@ -525,8 +545,43 @@ const layer = Layer.effect( resume: input.resume, }) }), - shell: Effect.fn("V2Session.shell")(function* () { - return yield* new OperationUnavailableError({ operation: "shell" }) + shell: Effect.fn("V2Session.shell")(function* (input) { + const session = yield* result.get(input.sessionID) + yield* shellLocks.withLock(input.sessionID)( + Effect.gen(function* () { + activeShells.add(input.sessionID) + if ((yield* execution.active).has(input.sessionID)) yield* execution.awaitIdle(input.sessionID) + const messageID = SessionMessage.ID.create() + const callID = Identifier.ascending() + yield* events.publish( + SessionEvent.Shell.Started, + { + sessionID: input.sessionID, + messageID, + callID, + command: input.command, + timestamp: yield* DateTime.now, + }, + { id: input.id }, + ) + const output = yield* runShellCommand(input.command, session.location.directory).pipe( + Effect.provide(locations.get(session.location)), + ) + yield* events.publish(SessionEvent.Shell.Ended, { + sessionID: input.sessionID, + callID, + output, + timestamp: yield* DateTime.now, + }) + }).pipe( + Effect.ensuring( + Effect.gen(function* () { + activeShells.delete(input.sessionID) + yield* execution.wake(input.sessionID) + }), + ), + ), + ) }), skill: Effect.fn("V2Session.skill")(function* (input) { const session = yield* result.get(input.sessionID) @@ -679,6 +734,9 @@ const resolvePrompt = (input: PromptInput.Prompt) => }), }) +// Mirrors the shell tool's in-memory preview safety limit. +const SHELL_MAX_CAPTURE_BYTES = 1024 * 1024 + export const node = makeGlobalNode({ service: Service, layer: layer.pipe(Layer.orDie), diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index 9c41d1d9ac..b22c65ec97 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -17,11 +17,11 @@ import { AbsolutePath } from "@opencode-ai/core/schema" import { SessionV2 } from "@opencode-ai/core/session" import { SessionV1 } from "@opencode-ai/core/v1/session" import { Prompt } from "@opencode-ai/core/session/prompt" +import { SessionMessage } from "@opencode-ai/core/session/message" import { SessionProjector } from "@opencode-ai/core/session/projector" import { SessionExecution } from "@opencode-ai/core/session/execution" import { SessionInput } from "@opencode-ai/core/session/input" import { SessionEvent } from "@opencode-ai/core/session/event" -import { SessionMessage } from "@opencode-ai/core/session/message" import { SessionTable } from "@opencode-ai/core/session/sql" import { SessionStore } from "@opencode-ai/core/session/store" import { WorkspaceV2 } from "@opencode-ai/core/workspace" @@ -62,6 +62,13 @@ const assertCreateInputTypes = (session: SessionV2.Interface) => { } void assertCreateInputTypes +function withTmp(f: (directory: string) => Effect.Effect) { + return Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe(Effect.flatMap((tmp) => f(tmp.path))) +} + describe("SessionV2.create", () => { it.effect("creates a fresh projected session when the ID is omitted", () => Effect.gen(function* () { @@ -476,20 +483,41 @@ describe("SessionV2.create", () => { }), ) - it.effect("reports unfinished Session operations as unavailable", () => - Effect.gen(function* () { - const session = yield* SessionV2.Service - const created = yield* session.create({ location }) - const unavailable = ( - effect: Effect.Effect, - ) => - effect.pipe( - Effect.flip, - Effect.map((error) => (error instanceof SessionV2.OperationUnavailableError ? error.operation : "not-found")), - ) + it.live("runs a shell command and projects the started/ended shell message", () => + withTmp((directory) => + Effect.gen(function* () { + const session = yield* SessionV2.Service + const created = yield* session.create({ + location: Location.Ref.make({ directory: AbsolutePath.make(directory) }), + }) - expect(yield* unavailable(session.shell({ sessionID: created.id, command: "pwd" }))).toBe("shell") - }), + yield* session.shell({ sessionID: created.id, command: "echo hello" }) + + const messages = yield* session.messages({ sessionID: created.id, order: "asc" }) + const shell = messages.find((message): message is SessionMessage.Shell => message.type === "shell") + expect(shell).toMatchObject({ type: "shell", command: "echo hello" }) + expect(shell?.output).toContain("hello") + expect(shell?.time.completed).toBeDefined() + }), + ), + ) + + it.live("still emits shell ended for a failing command", () => + withTmp((directory) => + Effect.gen(function* () { + const session = yield* SessionV2.Service + const created = yield* session.create({ + location: Location.Ref.make({ directory: AbsolutePath.make(directory) }), + }) + + yield* session.shell({ sessionID: created.id, command: "false" }) + + const messages = yield* session.messages({ sessionID: created.id, order: "asc" }) + const shell = messages.find((message): message is SessionMessage.Shell => message.type === "shell") + expect(shell).toMatchObject({ type: "shell", command: "false" }) + expect(shell?.time.completed).toBeDefined() + }), + ), ) it.effect("switches the selected agent through the durable Session event", () => diff --git a/packages/plugin/src/v2/effect/generated/api.ts b/packages/plugin/src/v2/effect/generated/api.ts index 049ca7486c..8e764daa82 100644 --- a/packages/plugin/src/v2/effect/generated/api.ts +++ b/packages/plugin/src/v2/effect/generated/api.ts @@ -153,96 +153,105 @@ export type Endpoint4_11Input = { export type Endpoint4_11Output = EffectValue> export type SessionSyntheticOperation = (input: Endpoint4_11Input) => Effect.Effect -type Endpoint4_12Request = Parameters[0] -export type Endpoint4_12Input = { readonly sessionID: Endpoint4_12Request["params"]["sessionID"] } -export type Endpoint4_12Output = EffectValue> -export type SessionCompactOperation = (input: Endpoint4_12Input) => Effect.Effect - -type Endpoint4_13Request = Parameters[0] -export type Endpoint4_13Input = { readonly sessionID: Endpoint4_13Request["params"]["sessionID"] } -export type Endpoint4_13Output = EffectValue> -export type SessionWaitOperation = (input: Endpoint4_13Input) => Effect.Effect - -type Endpoint4_14Request = Parameters[0] -export type Endpoint4_14Input = { - readonly sessionID: Endpoint4_14Request["params"]["sessionID"] - readonly messageID: Endpoint4_14Request["payload"]["messageID"] - readonly files?: Endpoint4_14Request["payload"]["files"] +type Endpoint4_12Request = Parameters[0] +export type Endpoint4_12Input = { + readonly sessionID: Endpoint4_12Request["params"]["sessionID"] + readonly id?: Endpoint4_12Request["payload"]["id"] + readonly command: Endpoint4_12Request["payload"]["command"] } -export type Endpoint4_14Output = EffectValue>["data"] -export type SessionRevertStageOperation = (input: Endpoint4_14Input) => Effect.Effect +export type Endpoint4_12Output = EffectValue> +export type SessionShellOperation = (input: Endpoint4_12Input) => Effect.Effect -type Endpoint4_15Request = Parameters[0] -export type Endpoint4_15Input = { readonly sessionID: Endpoint4_15Request["params"]["sessionID"] } -export type Endpoint4_15Output = EffectValue> -export type SessionRevertClearOperation = (input: Endpoint4_15Input) => Effect.Effect +type Endpoint4_13Request = Parameters[0] +export type Endpoint4_13Input = { readonly sessionID: Endpoint4_13Request["params"]["sessionID"] } +export type Endpoint4_13Output = EffectValue> +export type SessionCompactOperation = (input: Endpoint4_13Input) => Effect.Effect -type Endpoint4_16Request = Parameters[0] +type Endpoint4_14Request = Parameters[0] +export type Endpoint4_14Input = { readonly sessionID: Endpoint4_14Request["params"]["sessionID"] } +export type Endpoint4_14Output = EffectValue> +export type SessionWaitOperation = (input: Endpoint4_14Input) => Effect.Effect + +type Endpoint4_15Request = Parameters[0] +export type Endpoint4_15Input = { + readonly sessionID: Endpoint4_15Request["params"]["sessionID"] + readonly messageID: Endpoint4_15Request["payload"]["messageID"] + readonly files?: Endpoint4_15Request["payload"]["files"] +} +export type Endpoint4_15Output = EffectValue>["data"] +export type SessionRevertStageOperation = (input: Endpoint4_15Input) => Effect.Effect + +type Endpoint4_16Request = Parameters[0] export type Endpoint4_16Input = { readonly sessionID: Endpoint4_16Request["params"]["sessionID"] } -export type Endpoint4_16Output = EffectValue> -export type SessionRevertCommitOperation = (input: Endpoint4_16Input) => Effect.Effect +export type Endpoint4_16Output = EffectValue> +export type SessionRevertClearOperation = (input: Endpoint4_16Input) => Effect.Effect -type Endpoint4_17Request = Parameters[0] +type Endpoint4_17Request = Parameters[0] export type Endpoint4_17Input = { readonly sessionID: Endpoint4_17Request["params"]["sessionID"] } -export type Endpoint4_17Output = EffectValue>["data"] -export type SessionContextOperation = (input: Endpoint4_17Input) => Effect.Effect +export type Endpoint4_17Output = EffectValue> +export type SessionRevertCommitOperation = (input: Endpoint4_17Input) => Effect.Effect -type Endpoint4_18Request = Parameters[0] +type Endpoint4_18Request = Parameters[0] export type Endpoint4_18Input = { readonly sessionID: Endpoint4_18Request["params"]["sessionID"] } -export type Endpoint4_18Output = EffectValue< +export type Endpoint4_18Output = EffectValue>["data"] +export type SessionContextOperation = (input: Endpoint4_18Input) => Effect.Effect + +type Endpoint4_19Request = Parameters[0] +export type Endpoint4_19Input = { readonly sessionID: Endpoint4_19Request["params"]["sessionID"] } +export type Endpoint4_19Output = EffectValue< ReturnType >["data"] export type SessionListContextEntriesOperation = ( - input: Endpoint4_18Input, -) => Effect.Effect - -type Endpoint4_19Request = Parameters[0] -export type Endpoint4_19Input = { - readonly sessionID: Endpoint4_19Request["params"]["sessionID"] - readonly key: Endpoint4_19Request["params"]["key"] - readonly value: Endpoint4_19Request["payload"]["value"] -} -export type Endpoint4_19Output = EffectValue> -export type SessionPutContextEntryOperation = ( input: Endpoint4_19Input, ) => Effect.Effect -type Endpoint4_20Request = Parameters[0] +type Endpoint4_20Request = Parameters[0] export type Endpoint4_20Input = { readonly sessionID: Endpoint4_20Request["params"]["sessionID"] readonly key: Endpoint4_20Request["params"]["key"] + readonly value: Endpoint4_20Request["payload"]["value"] } -export type Endpoint4_20Output = EffectValue> -export type SessionRemoveContextEntryOperation = ( +export type Endpoint4_20Output = EffectValue> +export type SessionPutContextEntryOperation = ( input: Endpoint4_20Input, ) => Effect.Effect -type Endpoint4_21Request = Parameters[0] +type Endpoint4_21Request = Parameters[0] export type Endpoint4_21Input = { readonly sessionID: Endpoint4_21Request["params"]["sessionID"] - readonly after?: Endpoint4_21Request["query"]["after"] - readonly follow?: Endpoint4_21Request["query"]["follow"] + readonly key: Endpoint4_21Request["params"]["key"] } -export type Endpoint4_21Output = StreamValue>> -export type SessionLogOperation = (input: Endpoint4_21Input) => Stream.Stream +export type Endpoint4_21Output = EffectValue> +export type SessionRemoveContextEntryOperation = ( + input: Endpoint4_21Input, +) => Effect.Effect -type Endpoint4_22Request = Parameters[0] -export type Endpoint4_22Input = { readonly sessionID: Endpoint4_22Request["params"]["sessionID"] } -export type Endpoint4_22Output = EffectValue> -export type SessionInterruptOperation = (input: Endpoint4_22Input) => Effect.Effect +type Endpoint4_22Request = Parameters[0] +export type Endpoint4_22Input = { + readonly sessionID: Endpoint4_22Request["params"]["sessionID"] + readonly after?: Endpoint4_22Request["query"]["after"] + readonly follow?: Endpoint4_22Request["query"]["follow"] +} +export type Endpoint4_22Output = StreamValue>> +export type SessionLogOperation = (input: Endpoint4_22Input) => Stream.Stream -type Endpoint4_23Request = Parameters[0] +type Endpoint4_23Request = Parameters[0] export type Endpoint4_23Input = { readonly sessionID: Endpoint4_23Request["params"]["sessionID"] } -export type Endpoint4_23Output = EffectValue> -export type SessionBackgroundOperation = (input: Endpoint4_23Input) => Effect.Effect +export type Endpoint4_23Output = EffectValue> +export type SessionInterruptOperation = (input: Endpoint4_23Input) => Effect.Effect -type Endpoint4_24Request = Parameters[0] -export type Endpoint4_24Input = { - readonly sessionID: Endpoint4_24Request["params"]["sessionID"] - readonly messageID: Endpoint4_24Request["params"]["messageID"] +type Endpoint4_24Request = Parameters[0] +export type Endpoint4_24Input = { readonly sessionID: Endpoint4_24Request["params"]["sessionID"] } +export type Endpoint4_24Output = EffectValue> +export type SessionBackgroundOperation = (input: Endpoint4_24Input) => Effect.Effect + +type Endpoint4_25Request = Parameters[0] +export type Endpoint4_25Input = { + readonly sessionID: Endpoint4_25Request["params"]["sessionID"] + readonly messageID: Endpoint4_25Request["params"]["messageID"] } -export type Endpoint4_24Output = EffectValue>["data"] -export type SessionMessageOperation = (input: Endpoint4_24Input) => Effect.Effect +export type Endpoint4_25Output = EffectValue>["data"] +export type SessionMessageOperation = (input: Endpoint4_25Input) => Effect.Effect export interface SessionApi { readonly list: SessionListOperation @@ -257,6 +266,7 @@ export interface SessionApi { readonly command: SessionCommandOperation readonly skill: SessionSkillOperation readonly synthetic: SessionSyntheticOperation + readonly shell: SessionShellOperation readonly compact: SessionCompactOperation readonly wait: SessionWaitOperation readonly revertStage: SessionRevertStageOperation diff --git a/packages/protocol/src/groups/session.ts b/packages/protocol/src/groups/session.ts index d2114ddee9..527dcc6f61 100644 --- a/packages/protocol/src/groups/session.ts +++ b/packages/protocol/src/groups/session.ts @@ -349,6 +349,26 @@ export const makeSessionGroup = (sessionLo }), ), ) + .add( + HttpApiEndpoint.post("session.shell", "/api/session/:sessionID/shell", { + params: { sessionID: Session.ID }, + payload: Schema.Struct({ + id: Event.ID.pipe(Schema.optional), + command: Schema.String, + }), + success: HttpApiSchema.NoContent, + error: SessionNotFoundError, + }) + .middleware(sessionLocationMiddleware) + .annotateMerge( + OpenApi.annotations({ + identifier: "v2.session.shell", + summary: "Run shell command", + description: + "Execute one shell command in the session's working directory. Emits a shell.started event before execution and a shell.ended event with the merged output after.", + }), + ), + ) .add( HttpApiEndpoint.post("session.compact", "/api/session/:sessionID/compact", { params: { sessionID: Session.ID }, diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index 1c896d80a3..ae8318d78e 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -422,6 +422,8 @@ import type { V2SessionRevertCommitResponses, V2SessionRevertStageErrors, V2SessionRevertStageResponses, + V2SessionShellErrors, + V2SessionShellResponses, V2SessionSkillErrors, V2SessionSkillResponses, V2SessionSwitchAgentErrors, @@ -6240,6 +6242,43 @@ export class Session3 extends HeyApiClient { }) } + /** + * Run shell command + * + * Execute one shell command in the session's working directory. Emits a shell.started event before execution and a shell.ended event with the merged output after. + */ + public shell( + parameters: { + sessionID: string + id?: string | null + command?: string + }, + options?: Options, + ) { + const params = buildClientParams( + [parameters], + [ + { + args: [ + { in: "path", key: "sessionID" }, + { in: "body", key: "id" }, + { in: "body", key: "command" }, + ], + }, + ], + ) + return (options?.client ?? this.client).post({ + url: "/api/session/{sessionID}/shell", + ...options, + ...params, + headers: { + "Content-Type": "application/json", + ...options?.headers, + ...params.headers, + }, + }) + } + /** * Compact session * diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 13fbacae2b..2f476f2844 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -16686,6 +16686,44 @@ export type V2SessionSyntheticResponses = { export type V2SessionSyntheticResponse = V2SessionSyntheticResponses[keyof V2SessionSyntheticResponses] +export type V2SessionShellData = { + body: { + id?: string | null + command: string + } + path: { + sessionID: string + } + query?: never + url: "/api/session/{sessionID}/shell" +} + +export type V2SessionShellErrors = { + /** + * InvalidRequestError + */ + 400: InvalidRequestErrorV2 + /** + * UnauthorizedError + */ + 401: UnauthorizedErrorV2 + /** + * SessionNotFoundError + */ + 404: SessionNotFoundErrorV2 +} + +export type V2SessionShellError = V2SessionShellErrors[keyof V2SessionShellErrors] + +export type V2SessionShellResponses = { + /** + * + */ + 204: void +} + +export type V2SessionShellResponse = V2SessionShellResponses[keyof V2SessionShellResponses] + export type V2SessionCompactData = { body?: never path: { diff --git a/packages/server/src/handlers/session.ts b/packages/server/src/handlers/session.ts index f6dbabdbf8..8a3cf1b130 100644 --- a/packages/server/src/handlers/session.ts +++ b/packages/server/src/handlers/session.ts @@ -323,6 +323,24 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl return HttpApiSchema.NoContent.make() }), ) + .handle( + "session.shell", + Effect.fn(function* (ctx) { + yield* session + .shell({ sessionID: ctx.params.sessionID, id: ctx.payload.id, command: ctx.payload.command }) + .pipe( + Effect.catchTag("Session.NotFoundError", (error) => + Effect.fail( + new SessionNotFoundError({ + sessionID: error.sessionID, + message: `Session not found: ${error.sessionID}`, + }), + ), + ), + ) + return HttpApiSchema.NoContent.make() + }), + ) .handle( "session.compact", Effect.fn(function* (ctx) { diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index 7b0724e5dc..9fad2eb21c 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -1101,13 +1101,8 @@ export function Prompt(props: PromptProps) { if (store.mode === "shell") { move.startSubmit() - void sdk.client.session.shell({ + void sdk.client.v2.session.shell({ sessionID, - agent: agent.id, - model: { - providerID: selectedModel.providerID, - modelID: selectedModel.modelID, - }, command: inputText, }) setStore("mode", "normal") diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index fc7c2d3a0e..d406fe664e 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -1068,9 +1068,7 @@ function SessionMessageView(props: { message: SessionMessage }) { - - {props.message.type === "shell" ? `$ ${props.message.command}\n${props.message.output}` : ""} - + } /> @@ -1346,6 +1344,29 @@ function RevertMessage(props: { ) } +function ShellMessage(props: { message: Extract }) { + const { theme } = useTheme() + const output = createMemo(() => stripAnsi(props.message.output.trim())) + + return ( + + $ {props.message.command} + + {output()} + + + ) +} + function UserMessage(props: { message: SessionMessageUser }) { const ctx = use() const data = useData() From de476aa51b768e390809f343bff41df9c2d5d4d5 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 12:35:35 -0400 Subject: [PATCH 08/82] refactor(schema): declare event durability at definition level (#35172) --- .../client/src/promise/generated/types.ts | 242 ++--- packages/core/src/event.ts | 3 +- packages/core/src/session/projector.ts | 4 +- packages/core/test/event.test.ts | 14 +- packages/core/test/session-log.test.ts | 2 +- .../test/cli/run/noninteractive.test.ts | 12 +- .../test/cli/run/stream-v2.transport.test.ts | 114 ++- .../test/v2/session-message-updater.test.ts | 15 + packages/protocol/src/groups/event.ts | 1 - packages/schema/src/agent.ts | 4 +- packages/schema/src/catalog.ts | 4 +- packages/schema/src/command.ts | 4 +- packages/schema/src/durable-event-manifest.ts | 7 +- packages/schema/src/event-manifest.ts | 8 +- packages/schema/src/event.ts | 82 +- packages/schema/src/filesystem-watcher.ts | 4 +- packages/schema/src/filesystem.ts | 4 +- packages/schema/src/form.ts | 16 +- packages/schema/src/ide-event.ts | 2 +- packages/schema/src/installation-event.ts | 4 +- packages/schema/src/integration.ts | 6 +- packages/schema/src/lsp-event.ts | 2 +- packages/schema/src/mcp-event.ts | 6 +- packages/schema/src/models-dev.ts | 4 +- packages/schema/src/permission.ts | 6 +- packages/schema/src/plugin.ts | 4 +- packages/schema/src/project-directories.ts | 4 +- packages/schema/src/project.ts | 4 +- packages/schema/src/pty.ts | 10 +- packages/schema/src/question.ts | 8 +- packages/schema/src/reference.ts | 4 +- packages/schema/src/server-event.ts | 4 +- .../schema/src/session-compaction-event.ts | 2 +- packages/schema/src/session-event.ts | 110 +-- packages/schema/src/session-status-event.ts | 4 +- packages/schema/src/session-todo.ts | 4 +- packages/schema/src/shell.ts | 8 +- packages/schema/src/skill.ts | 4 +- packages/schema/src/tui-event.ts | 8 +- packages/schema/src/v1/legacy-event.ts | 4 +- packages/schema/src/v1/permission.ts | 6 +- packages/schema/src/v1/question.ts | 8 +- packages/schema/src/v1/session.ts | 22 +- packages/schema/src/vcs-event.ts | 2 +- packages/schema/src/workspace-event.ts | 6 +- packages/schema/src/worktree-event.ts | 4 +- packages/schema/test/event-manifest.test.ts | 69 +- packages/schema/test/event.test.ts | 10 +- packages/sdk-next/test/embedded.test.ts | 2 +- packages/sdk/js/src/v2/gen/types.gen.ts | 930 ++++-------------- .../test/cli/cmd/tui/notifications.test.ts | 12 +- packages/tui/test/cli/tui/data.test.tsx | 22 +- specs/v2/schema-changelog.md | 20 + 53 files changed, 700 insertions(+), 1165 deletions(-) diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 6c8286fc52..798155e88e 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -1109,7 +1109,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.agent.switched" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1122,7 +1122,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.model.switched" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1135,7 +1135,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.moved" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1148,7 +1148,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.renamed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number; readonly sessionID: string; readonly title: string } } @@ -1156,7 +1156,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.forked" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1169,7 +1169,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.prompted" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1196,7 +1196,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.prompt.admitted" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1223,7 +1223,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.context.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1236,7 +1236,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.synthetic" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1251,7 +1251,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.skill.activated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1265,7 +1265,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.shell.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1279,7 +1279,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.shell.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1292,7 +1292,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.step.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1307,7 +1307,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.step.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1329,7 +1329,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.step.failed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1342,7 +1342,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.text.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1355,7 +1355,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.text.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1365,11 +1365,40 @@ export type SessionLogOutput = readonly text: string } } + | { + readonly id: string + readonly metadata?: { readonly [x: string]: unknown } + readonly type: "session.next.reasoning.started" + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly location?: { readonly directory: string; readonly workspaceID?: string } + readonly data: { + readonly timestamp: number + readonly sessionID: string + readonly assistantMessageID: string + readonly reasoningID: string + readonly providerMetadata?: { readonly [x: string]: { readonly [x: string]: unknown } } + } + } + | { + readonly id: string + readonly metadata?: { readonly [x: string]: unknown } + readonly type: "session.next.reasoning.ended" + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly location?: { readonly directory: string; readonly workspaceID?: string } + readonly data: { + readonly timestamp: number + readonly sessionID: string + readonly assistantMessageID: string + readonly reasoningID: string + readonly text: string + readonly providerMetadata?: { readonly [x: string]: { readonly [x: string]: unknown } } + } + } | { readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.input.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1383,7 +1412,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.input.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1397,7 +1426,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.called" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1416,7 +1445,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.progress" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1434,7 +1463,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.success" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1458,7 +1487,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.failed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1473,40 +1502,11 @@ export type SessionLogOutput = } } } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.reasoning.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly assistantMessageID: string - readonly reasoningID: string - readonly providerMetadata?: { readonly [x: string]: { readonly [x: string]: unknown } } - } - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.reasoning.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly assistantMessageID: string - readonly reasoningID: string - readonly text: string - readonly providerMetadata?: { readonly [x: string]: { readonly [x: string]: unknown } } - } - } | { readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.retried" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1526,7 +1526,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.compaction.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1539,7 +1539,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.compaction.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1554,7 +1554,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.revert.staged" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -1578,7 +1578,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.revert.cleared" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number; readonly sessionID: string } } @@ -1586,7 +1586,7 @@ export type SessionLogOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.revert.committed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number; readonly sessionID: string; readonly messageID: string } } @@ -3773,7 +3773,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "models-dev.refreshed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: {} } @@ -3781,7 +3780,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "integration.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: {} } @@ -3789,7 +3787,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "integration.connection.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly integrationID: string } } @@ -3797,7 +3794,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "catalog.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: {} } @@ -3805,7 +3801,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "agent.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: {} } @@ -3813,7 +3808,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.created" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -3874,7 +3869,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -3935,7 +3930,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.deleted" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -3996,7 +3991,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "message.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -4100,7 +4095,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "message.removed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string; readonly messageID: string } } @@ -4108,7 +4103,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "message.part.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -4346,7 +4341,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "message.part.removed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string; readonly messageID: string; readonly partID: string } } @@ -4354,7 +4349,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.agent.switched" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4367,7 +4362,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.model.switched" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4380,7 +4375,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.moved" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4393,7 +4388,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.renamed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number; readonly sessionID: string; readonly title: string } } @@ -4401,7 +4396,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.forked" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4414,7 +4409,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.prompted" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4441,7 +4436,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.prompt.admitted" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4468,7 +4463,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.execution.settled" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4481,7 +4475,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.context.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4494,7 +4488,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.synthetic" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4509,7 +4503,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.skill.activated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4523,7 +4517,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.shell.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4537,7 +4531,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.shell.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4550,7 +4544,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.step.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4565,7 +4559,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.step.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4587,7 +4581,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.step.failed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4600,7 +4594,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.text.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4613,7 +4607,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.text.delta" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4627,7 +4620,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.text.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4641,7 +4634,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.reasoning.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4655,7 +4648,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.reasoning.delta" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4669,7 +4661,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.reasoning.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4684,7 +4676,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.input.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4698,7 +4690,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.input.delta" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4712,7 +4703,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.input.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4726,7 +4717,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.called" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4745,7 +4736,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.progress" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4763,7 +4754,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.success" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4787,7 +4778,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.tool.failed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4806,7 +4797,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.retried" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4826,7 +4817,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.compaction.started" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4839,7 +4830,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.compaction.delta" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4852,7 +4842,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.compaction.ended" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4867,7 +4857,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.revert.staged" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number @@ -4891,7 +4881,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.revert.cleared" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number; readonly sessionID: string } } @@ -4899,7 +4889,7 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.next.revert.committed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly timestamp: number; readonly sessionID: string; readonly messageID: string } } @@ -4907,7 +4897,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "file.edited" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly file: string } } @@ -4915,7 +4904,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "reference.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: {} } @@ -4923,7 +4911,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "permission.v2.asked" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string @@ -4939,7 +4926,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "permission.v2.replied" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -4951,7 +4937,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "plugin.added" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string } } @@ -4959,7 +4944,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "project.directories.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly projectID: string } } @@ -4967,7 +4951,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "command.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: {} } @@ -4975,7 +4958,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "skill.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: {} } @@ -4983,7 +4965,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "file.watcher.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly file: string; readonly event: "add" | "change" | "unlink" } } @@ -4991,7 +4972,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "pty.created" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly info: { @@ -5010,7 +4990,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "pty.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly info: { @@ -5029,7 +5008,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "pty.exited" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string; readonly exitCode: number } } @@ -5037,7 +5015,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "pty.deleted" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string } } @@ -5045,7 +5022,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "shell.created" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly info: { @@ -5066,7 +5042,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "shell.exited" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string @@ -5078,7 +5053,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "shell.deleted" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string } } @@ -5086,7 +5060,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.v2.asked" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string @@ -5105,7 +5078,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.v2.replied" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -5117,7 +5089,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.v2.rejected" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string; readonly requestID: string } } @@ -5125,7 +5096,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "form.created" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly form: @@ -5240,7 +5210,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "form.replied" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string @@ -5252,7 +5221,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "form.cancelled" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string; readonly sessionID: string } } @@ -5260,7 +5228,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "todo.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -5271,7 +5238,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.status" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -5298,7 +5264,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.idle" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string } } @@ -5306,7 +5271,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "tui.prompt.append" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly text: string } } @@ -5314,7 +5278,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "tui.command.execute" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly command: @@ -5342,7 +5305,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "tui.toast.show" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly title?: string @@ -5355,7 +5317,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "tui.session.select" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string } } @@ -5363,7 +5324,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "installation.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly version: string } } @@ -5371,7 +5331,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "installation.update-available" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly version: string } } @@ -5379,7 +5338,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "vcs.branch.updated" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly branch?: string } } @@ -5387,7 +5345,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "mcp.status.changed" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly server: string } } @@ -5395,7 +5352,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "permission.asked" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string @@ -5411,7 +5367,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "permission.replied" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -5423,7 +5378,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.asked" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string @@ -5442,7 +5396,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.replied" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string @@ -5454,7 +5407,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.rejected" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID: string; readonly requestID: string } } @@ -5462,7 +5414,6 @@ export type EventSubscribeOutput = readonly id: string readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.error" - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly sessionID?: string | undefined @@ -5503,7 +5454,6 @@ export type EventSubscribeOutput = | { readonly id: string readonly metadata?: { readonly [x: string]: unknown } | undefined - readonly durable?: { readonly aggregateID: string; readonly seq: number; readonly version: number } | undefined readonly location?: { readonly directory: string; readonly workspaceID?: string } | undefined readonly type: "server.connected" readonly data: {} diff --git a/packages/core/src/event.ts b/packages/core/src/event.ts index 66ee91c6c6..dd0aa43181 100644 --- a/packages/core/src/event.ts +++ b/packages/core/src/event.ts @@ -92,8 +92,9 @@ export class SubscriberOverflowError extends Schema.TaggedErrorClass +type MessageEvent = Exclude const decodeMessage = Schema.decodeUnknownSync(SessionMessage.Message) const encodeMessage = Schema.encodeSync(SessionMessage.Message) @@ -417,7 +417,7 @@ function run(db: DatabaseService, event: MessageEvent) { }) } -function insertMessage(db: DatabaseService, event: SessionEvent.Event, message: SessionMessage.Message) { +function insertMessage(db: DatabaseService, event: SessionEvent.DurableEvent, message: SessionMessage.Message) { if (event.durable === undefined) return Effect.die("Durable Session event is missing aggregate sequence") const encoded = encodeMessage(message) const { id, type, ...data } = encoded diff --git a/packages/core/test/event.test.ts b/packages/core/test/event.test.ts index b40f088c5d..a9220df422 100644 --- a/packages/core/test/event.test.ts +++ b/packages/core/test/event.test.ts @@ -22,14 +22,14 @@ const locationLayer = Layer.succeed( location({ directory: AbsolutePath.make("project"), workspaceID: WorkspaceV2.ID.make("wrk_test") }), ), ) -const Message = EventV2.define({ +const Message = EventV2.ephemeral({ type: "test.message", schema: { text: Schema.String, }, }) -const SyncMessage = EventV2.define({ +const SyncMessage = EventV2.durable({ type: "test.sync", durable: { version: 1, @@ -41,7 +41,7 @@ const SyncMessage = EventV2.define({ }, }) -const SyncSent = EventV2.define({ +const SyncSent = EventV2.durable({ type: "test.sent", durable: { version: 1, @@ -53,14 +53,14 @@ const SyncSent = EventV2.define({ }, }) -const GlobalMessage = EventV2.define({ +const GlobalMessage = EventV2.ephemeral({ type: "test.global", schema: { text: Schema.String, }, }) -const VersionedMessage = EventV2.define({ +const VersionedMessage = EventV2.durable({ type: "test.versioned", durable: { version: 2, @@ -129,12 +129,12 @@ describe("EventV2", () => { it.effect("selects the latest durable definition independent of declaration order", () => Effect.sync(() => { - const latest = EventV2.define({ + const latest = EventV2.durable({ type: "test.out-of-order", durable: { version: 2, aggregate: "id" }, schema: { id: Schema.String }, }) - const historical = EventV2.define({ + const historical = EventV2.durable({ type: "test.out-of-order", durable: { version: 1, aggregate: "id" }, schema: { id: Schema.String }, diff --git a/packages/core/test/session-log.test.ts b/packages/core/test/session-log.test.ts index b80dd2c206..3b9229589c 100644 --- a/packages/core/test/session-log.test.ts +++ b/packages/core/test/session-log.test.ts @@ -78,7 +78,7 @@ describe("SessionV2.log", () => { it.effect("reads across undecodable gaps in aggregate order and marks the true log position", () => Effect.gen(function* () { - const GapEvent = EventV2.define({ + const GapEvent = EventV2.durable({ type: "test.session.log.gap", durable: { aggregate: "sessionID", version: 1 }, schema: { sessionID: SessionV2.ID, value: Schema.String }, diff --git a/packages/opencode/test/cli/run/noninteractive.test.ts b/packages/opencode/test/cli/run/noninteractive.test.ts index 15cf799c75..d8bff61a73 100644 --- a/packages/opencode/test/cli/run/noninteractive.test.ts +++ b/packages/opencode/test/cli/run/noninteractive.test.ts @@ -25,6 +25,7 @@ function prompted(messageID: string): V2Event { return { id: "evt_prompted", type: "session.next.prompted", + durable: { aggregateID: "ses_1", seq: 0, version: 1 }, data: { timestamp: 1, sessionID: "ses_1", messageID, prompt: { text: "hello" }, delivery: "steer" }, } } @@ -39,11 +40,7 @@ function settled(outcome: "success" | "interrupted" = "success"): V2Event { // Runs one non-interactive prompt against a mocked SDK. `turn` produces the // live events the prompt admission triggers, keyed by the generated message ID. -async function run(input: { - turn: (messageID: string) => V2Event[] - pendingForms?: FormInfo[] - attached?: boolean -}) { +async function run(input: { turn: (messageID: string) => V2Event[]; pendingForms?: FormInfo[]; attached?: boolean }) { const sdk = new OpencodeClient() const values: V2Event[] = [{ id: "evt_connected", type: "server.connected", data: {} }] let wake: (() => void) | undefined @@ -64,8 +61,9 @@ async function run(input: { ) spyOn(sdk.v2.session.permission, "list").mockImplementation(() => ok({ data: [] }) as never) spyOn(sdk.v2.session.question, "list").mockImplementation(() => ok({ data: [] }) as never) - spyOn(sdk.v2.session.form, "list").mockImplementation((request) => - ok({ data: input.pendingForms?.filter((item) => item.sessionID === request.sessionID) ?? [] }) as never, + spyOn(sdk.v2.session.form, "list").mockImplementation( + (request) => + ok({ data: input.pendingForms?.filter((item) => item.sessionID === request.sessionID) ?? [] }) as never, ) spyOn(sdk.v2.session.form, "cancel").mockImplementation(() => ok(undefined) as never) spyOn(sdk.v2.session, "prompt").mockImplementation((request) => { diff --git a/packages/opencode/test/cli/run/stream-v2.transport.test.ts b/packages/opencode/test/cli/run/stream-v2.transport.test.ts index 7c2fc9f70e..2f78d106cf 100644 --- a/packages/opencode/test/cli/run/stream-v2.transport.test.ts +++ b/packages/opencode/test/cli/run/stream-v2.transport.test.ts @@ -53,6 +53,10 @@ function connected(id = "evt_connected") { return { id, type: "server.connected", data: {} } satisfies RunV2Event } +function durable(sessionID: string, seq = 0, version = 1) { + return { aggregateID: sessionID, seq, version } +} + function footer() { const commits: StreamCommit[] = [] const events: FooterEvent[] = [] @@ -94,7 +98,10 @@ function sdk(input: { const client = new OpencodeClient() let subscription = 0 spyOn(client.v2.event, "subscribe").mockImplementation( - () => Promise.resolve({ stream: input.streams[subscription++]?.stream ?? feed().stream }) as ReturnType, + () => + Promise.resolve({ stream: input.streams[subscription++]?.stream ?? feed().stream }) as ReturnType< + typeof client.v2.event.subscribe + >, ) spyOn(client.v2.session, "messages").mockImplementation((request) => ok({ @@ -193,32 +200,33 @@ describe("V2 mini transport", () => { }) while (!admitted) await Bun.sleep(0) events.push({ - id: "evt_prompted", - type: "session.next.prompted", - data: { - timestamp: 2, - sessionID: "ses_1", - messageID: "msg_prompt", - prompt: { text: "hello" }, - delivery: "steer", - }, - }) - events.push({ - id: "evt_text", - type: "session.next.text.delta", - data: { - timestamp: 3, - sessionID: "ses_1", - assistantMessageID: "msg_assistant", - textID: "txt_1", - delta: "answer", - }, - }) - events.push({ - id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 4, sessionID: "ses_1", outcome: "success" }, - }) + id: "evt_prompted", + type: "session.next.prompted", + durable: durable("ses_1"), + data: { + timestamp: 2, + sessionID: "ses_1", + messageID: "msg_prompt", + prompt: { text: "hello" }, + delivery: "steer", + }, + }) + events.push({ + id: "evt_text", + type: "session.next.text.delta", + data: { + timestamp: 3, + sessionID: "ses_1", + assistantMessageID: "msg_assistant", + textID: "txt_1", + delta: "answer", + }, + }) + events.push({ + id: "evt_settled", + type: "session.next.execution.settled", + data: { timestamp: 4, sessionID: "ses_1", outcome: "success" }, + }) await turn expect(ui.commits.map((item) => item.text)).toEqual(["previous prompt", "answer"]) @@ -245,9 +253,7 @@ describe("V2 mini transport", () => { limits: () => ({}), footer: ui.api, }) - let request: - | Parameters[0] - | undefined + let request: Parameters[0] | undefined // The generated method has conditional return types for throwOnError; this mock represents the successful branch. // @ts-expect-error successful SDK response is valid for both modes at runtime spyOn(client.v2.session, "prompt").mockImplementation((input) => { @@ -256,6 +262,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", type: "session.next.prompted", + durable: durable("ses_1"), data: { timestamp: 2, sessionID: "ses_1", @@ -341,9 +348,7 @@ describe("V2 mini transport", () => { limits: () => ({}), footer: ui.api, }) - let request: - | Parameters[0] - | undefined + let request: Parameters[0] | undefined // The generated method has conditional return types for throwOnError; this mock represents the successful branch. // @ts-expect-error successful SDK response is valid for both modes at runtime spyOn(client.v2.session, "prompt").mockImplementation((input) => { @@ -352,6 +357,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", type: "session.next.prompted", + durable: durable("ses_1"), data: { timestamp: 2, sessionID: "ses_1", @@ -440,9 +446,7 @@ describe("V2 mini transport", () => { limits: () => ({}), footer: ui.api, }) - let request: - | Parameters[0] - | undefined + let request: Parameters[0] | undefined // The generated method has conditional return types for throwOnError; this mock represents the successful branch. // @ts-expect-error successful SDK response is valid for both modes at runtime spyOn(client.v2.session, "prompt").mockImplementation((input) => { @@ -451,6 +455,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", type: "session.next.prompted", + durable: durable("ses_1"), data: { timestamp: 2, sessionID: "ses_1", @@ -593,7 +598,9 @@ describe("V2 mini transport", () => { const messageID = request.id ?? "msg_prompt" const prompt = request.prompt ?? { text: "" } admitted = true - return ok({ data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 } }) + return ok({ + data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 }, + }) }) const turn = transport.runPromptTurn({ @@ -663,7 +670,9 @@ describe("V2 mini transport", () => { const messageID = request.id ?? "msg_prompt" const prompt = request.prompt ?? { text: "" } admitted = true - return ok({ data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 } }) + return ok({ + data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 }, + }) }) const turn = transport.runPromptTurn({ @@ -805,6 +814,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_reasoning", type: "session.next.reasoning.ended", + durable: durable("ses_1"), data: { timestamp: 3, sessionID: "ses_1", @@ -841,7 +851,9 @@ describe("V2 mini transport", () => { const messageID = request.id ?? "msg_prompt" const prompt = request.prompt ?? { text: "" } admitted = true - return ok({ data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 } }) + return ok({ + data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 }, + }) }) const interrupted = spyOn(client.v2.session, "interrupt").mockImplementation(() => ok(undefined)) @@ -896,7 +908,9 @@ describe("V2 mini transport", () => { const messageID = request.id ?? "msg_prompt" const prompt = request.prompt ?? { text: "" } admitted = true - return ok({ data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 } }) + return ok({ + data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 }, + }) }) const turn = transport.runPromptTurn({ @@ -911,6 +925,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", type: "session.next.prompted", + durable: durable("ses_1"), data: { timestamp: 2, sessionID: "ses_1", @@ -952,7 +967,9 @@ describe("V2 mini transport", () => { const messageID = request.id ?? "msg_prompt" const prompt = request.prompt ?? { text: "" } admitted = true - return ok({ data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 } }) + return ok({ + data: { admittedSeq: 1, id: messageID, sessionID: "ses_1", prompt, delivery: "steer" as const, timeCreated: 2 }, + }) }) const interrupted = spyOn(client.v2.session, "interrupt").mockImplementation(() => ok(undefined)) const controller = new AbortController() @@ -969,6 +986,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", type: "session.next.prompted", + durable: durable("ses_1"), data: { timestamp: 2, sessionID: "ses_1", @@ -1031,13 +1049,13 @@ describe("V2 mini transport", () => { limits: () => ({}), footer: ui.api, }) - const states = () => - ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) + const states = () => ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) transport.selectSubagent("ses_child") events.push({ id: "evt_child_step", type: "session.next.step.started", + durable: durable("ses_child"), data: { timestamp: 2, sessionID: "ses_child", @@ -1107,13 +1125,13 @@ describe("V2 mini transport", () => { limits: () => ({}), footer: ui.api, }) - const states = () => - ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) + const states = () => ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) // Both events arrive while session.get is still in flight. events.push({ id: "evt_child_step", type: "session.next.step.started", + durable: durable("ses_child"), data: { timestamp: 2, sessionID: "ses_child", @@ -1165,13 +1183,13 @@ describe("V2 mini transport", () => { limits: () => ({}), footer: ui.api, }) - const states = () => - ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) + const states = () => ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) // Child event arrives first and gets buffered behind the gated session.get. events.push({ id: "evt_child_step", type: "session.next.step.started", + durable: durable("ses_child"), data: { timestamp: 2, sessionID: "ses_child", @@ -1184,6 +1202,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_parent_call", type: "session.next.tool.called", + durable: durable("ses_1"), data: { timestamp: 3, sessionID: "ses_1", @@ -1197,6 +1216,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_parent_success", type: "session.next.tool.success", + durable: durable("ses_1", 1), data: { timestamp: 4, sessionID: "ses_1", diff --git a/packages/opencode/test/v2/session-message-updater.test.ts b/packages/opencode/test/v2/session-message-updater.test.ts index 668a353f67..e85afaeeff 100644 --- a/packages/opencode/test/v2/session-message-updater.test.ts +++ b/packages/opencode/test/v2/session-message-updater.test.ts @@ -9,6 +9,10 @@ import { SessionEvent } from "@opencode-ai/core/session/event" import { SessionMessageUpdater } from "@opencode-ai/core/session/message-updater" import { SessionMessage } from "@opencode-ai/core/session/message" +function durable(sessionID: SessionID, seq = 0, version = 1) { + return { aggregateID: sessionID, seq: EventV2.Seq.make(seq), version: EventV2.Version.make(version) } +} + test.skip("step snapshots carry over to assistant messages", () => { const state: SessionMessageUpdater.MemoryState = { messages: [] } const sessionID = SessionID.make("session") @@ -18,6 +22,7 @@ test.skip("step snapshots carry over to assistant messages", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.step.started", + durable: durable(sessionID), data: { sessionID, assistantMessageID, @@ -39,6 +44,7 @@ test.skip("step snapshots carry over to assistant messages", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.step.ended", + durable: durable(sessionID, 1, 2), data: { sessionID, assistantMessageID, @@ -71,6 +77,7 @@ test.skip("text ended populates assistant text content", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.step.started", + durable: durable(sessionID), data: { sessionID, assistantMessageID, @@ -89,6 +96,7 @@ test.skip("text ended populates assistant text content", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.text.started", + durable: durable(sessionID, 1), data: { sessionID, assistantMessageID, @@ -102,6 +110,7 @@ test.skip("text ended populates assistant text content", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.text.ended", + durable: durable(sessionID, 2), data: { sessionID, assistantMessageID, @@ -127,6 +136,7 @@ test.skip("tool completion stores completed timestamp", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.step.started", + durable: durable(sessionID), data: { sessionID, assistantMessageID, @@ -145,6 +155,7 @@ test.skip("tool completion stores completed timestamp", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.tool.input.started", + durable: durable(sessionID, 1), data: { sessionID, assistantMessageID, @@ -159,6 +170,7 @@ test.skip("tool completion stores completed timestamp", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.tool.called", + durable: durable(sessionID, 2), data: { sessionID, assistantMessageID, @@ -175,6 +187,7 @@ test.skip("tool completion stores completed timestamp", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.tool.success", + durable: durable(sessionID, 3), data: { sessionID, assistantMessageID, @@ -205,6 +218,7 @@ test("compaction events reduce to compaction message only when completed", () => SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id, type: "session.next.compaction.started", + durable: durable(sessionID), data: { sessionID, messageID: compactionID, @@ -246,6 +260,7 @@ test("compaction events reduce to compaction message only when completed", () => SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), type: "session.next.compaction.ended", + durable: durable(sessionID, 1), data: { sessionID, messageID: compactionID, diff --git a/packages/protocol/src/groups/event.ts b/packages/protocol/src/groups/event.ts index f5a0c0c7bb..9860aa0cad 100644 --- a/packages/protocol/src/groups/event.ts +++ b/packages/protocol/src/groups/event.ts @@ -9,7 +9,6 @@ import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/un const fields = { id: Event.ID, metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), - durable: Schema.optional(Schema.Struct({ aggregateID: Schema.String, seq: Event.Seq, version: Event.Version })), location: Schema.optional(Location.Ref), } diff --git a/packages/schema/src/agent.ts b/packages/schema/src/agent.ts index 3d8068b89a..eb84cf500b 100644 --- a/packages/schema/src/agent.ts +++ b/packages/schema/src/agent.ts @@ -1,14 +1,14 @@ export * as Agent from "./agent.js" import { Schema } from "effect" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { optional } from "./schema.js" import { Model } from "./model.js" import { Permission } from "./permission.js" import { Provider } from "./provider.js" import { PositiveInt, statics } from "./schema.js" -const Updated = define({ type: "agent.updated", schema: {} }) +const Updated = ephemeral({ type: "agent.updated", schema: {} }) export const ID = Schema.String.pipe(Schema.brand("AgentV2.ID")) export type ID = typeof ID.Type diff --git a/packages/schema/src/catalog.ts b/packages/schema/src/catalog.ts index 19e2c26b9f..58545cd86b 100644 --- a/packages/schema/src/catalog.ts +++ b/packages/schema/src/catalog.ts @@ -1,6 +1,6 @@ export * as Catalog from "./catalog.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" -const Updated = define({ type: "catalog.updated", schema: {} }) +const Updated = ephemeral({ type: "catalog.updated", schema: {} }) export const Event = { Updated, Definitions: inventory(Updated) } diff --git a/packages/schema/src/command.ts b/packages/schema/src/command.ts index fb88087dbd..81e37157c6 100644 --- a/packages/schema/src/command.ts +++ b/packages/schema/src/command.ts @@ -1,11 +1,11 @@ export * as Command from "./command.js" import { Schema } from "effect" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { optional } from "./schema.js" import { Model } from "./model.js" -const Updated = define({ type: "command.updated", schema: {} }) +const Updated = ephemeral({ type: "command.updated", schema: {} }) export interface Info extends Schema.Schema.Type {} export const Info = Schema.Struct({ diff --git a/packages/schema/src/durable-event-manifest.ts b/packages/schema/src/durable-event-manifest.ts index 6b481dcfb9..8f8870f581 100644 --- a/packages/schema/src/durable-event-manifest.ts +++ b/packages/schema/src/durable-event-manifest.ts @@ -5,11 +5,8 @@ import { SessionEvent } from "./session-event.js" import { SessionV1 } from "./session-v1.js" export const SessionDurable = { - definitions: Event.durable(SessionEvent.DurableDefinitions), + definitions: Event.durableMap(SessionEvent.Definitions), schema: SessionEvent.Durable, } as const -export const Durable = Event.durable([ - ...SessionV1.Event.Definitions.filter((definition) => definition.durable !== undefined), - ...SessionEvent.DurableDefinitions, -]) +export const Durable = Event.durableMap([...SessionV1.Event.Definitions, ...SessionEvent.Definitions]) diff --git a/packages/schema/src/event-manifest.ts b/packages/schema/src/event-manifest.ts index 19fca5e79d..e17ff96bc9 100644 --- a/packages/schema/src/event-manifest.ts +++ b/packages/schema/src/event-manifest.ts @@ -36,8 +36,12 @@ import { VcsEvent } from "./vcs-event.js" import { WorkspaceEvent } from "./workspace-event.js" import { WorktreeEvent } from "./worktree-event.js" -const sessionV1DurableDefinitions = SessionV1.Event.Definitions.filter((definition) => definition.durable !== undefined) -const sessionV1LiveDefinitions = SessionV1.Event.Definitions.filter((definition) => definition.durable === undefined) +const sessionV1DurableDefinitions = SessionV1.Event.Definitions.filter( + (definition) => definition.durability === "durable", +) +const sessionV1LiveDefinitions = SessionV1.Event.Definitions.filter( + (definition) => definition.durability === "ephemeral", +) const coreDefinitions = Event.inventory(...sessionV1DurableDefinitions, ...SessionEvent.Definitions) diff --git a/packages/schema/src/event.ts b/packages/schema/src/event.ts index 1157a2bc44..aac2f0315e 100644 --- a/packages/schema/src/event.ts +++ b/packages/schema/src/event.ts @@ -24,50 +24,70 @@ export type Seq = typeof Seq.Type export const Version = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(Schema.brand("Event.Version")) export type Version = typeof Version.Type -export type Definition< +const DurableEnvelope = Schema.Struct({ aggregateID: Schema.String, seq: Seq, version: Version }) +export type DurableEnvelope = typeof DurableEnvelope.Type + +export type DurableDefinition< Type extends string = string, DataSchema extends Schema.Codec = Schema.Codec, > = Schema.Top & { readonly type: Type - readonly durable?: { + readonly durability: "durable" + readonly durable: { readonly version: number readonly aggregate: string } readonly data: DataSchema } +export type EphemeralDefinition< + Type extends string = string, + DataSchema extends Schema.Codec = Schema.Codec, +> = Schema.Top & { + readonly type: Type + readonly durability: "ephemeral" + readonly durable?: never + readonly data: DataSchema +} + +export type Definition< + Type extends string = string, + DataSchema extends Schema.Codec = Schema.Codec, +> = DurableDefinition | EphemeralDefinition + export type Data = Schema.Schema.Type -export type Payload = { +type PayloadBase = { readonly id: ID readonly type: D["type"] readonly data: Data - readonly durable?: { - readonly aggregateID: string - readonly seq: Seq - readonly version: Version - } readonly location?: Location.Ref readonly metadata?: Record } -export function define< - const Type extends string, - const Fields extends Readonly>>, ->(input: { +export type Payload = D extends DurableDefinition + ? PayloadBase & { readonly durable: DurableEnvelope } + : PayloadBase & { readonly durable?: never } + +type Input>>> = { readonly type: Type readonly durable?: { readonly version: number readonly aggregate: string } readonly schema: Fields -}) { +} + +export function durable< + const Type extends string, + const Fields extends Readonly>>, +>(input: Input & { readonly durable: NonNullable["durable"]> }) { const data = Schema.Struct(input.schema) return Schema.Struct({ id: ID, metadata: optional(Schema.Record(Schema.String, Schema.Unknown)), type: Schema.Literal(input.type), - durable: optional(Schema.Struct({ aggregateID: Schema.String, seq: Seq, version: Version })), + durable: DurableEnvelope, location: optional(Location.Ref), data, }) @@ -75,10 +95,34 @@ export function define< .pipe( statics(() => ({ type: input.type, - ...(input.durable === undefined ? {} : { durable: input.durable }), + durability: "durable" as const, + durable: input.durable, data, })), - ) satisfies Definition + ) satisfies DurableDefinition +} + +export function ephemeral< + const Type extends string, + const Fields extends Readonly>>, +>(input: Omit, "durable">) { + const data = Schema.Struct(input.schema) + return Schema.Struct({ + id: ID, + metadata: optional(Schema.Record(Schema.String, Schema.Unknown)), + type: Schema.Literal(input.type), + location: optional(Location.Ref), + data, + }) + .annotate({ identifier: input.type }) + .pipe( + statics(() => ({ + type: input.type, + durability: "ephemeral" as const, + durable: undefined, + data, + })), + ) satisfies EphemeralDefinition } export function inventory>(...definitions: Definitions) { @@ -107,15 +151,15 @@ export function versionedType(type: string, version: number) { return `${type}.${version}` } -export function durable>(definitions: Definitions) { +export function durableMap>(definitions: Definitions) { return readonlyMap( definitions.reduce((result, definition) => { - if (!definition.durable) return result + if (definition.durability !== "durable") return result const key = versionedType(definition.type, definition.durable.version) if (result.has(key)) throw new Error(`Duplicate durable event definition for ${key}`) result.set(key, definition) return result - }, new Map()), + }, new Map()), ) } diff --git a/packages/schema/src/filesystem-watcher.ts b/packages/schema/src/filesystem-watcher.ts index e1e1d557d6..debe0914d1 100644 --- a/packages/schema/src/filesystem-watcher.ts +++ b/packages/schema/src/filesystem-watcher.ts @@ -1,9 +1,9 @@ export * as FileSystemWatcher from "./filesystem-watcher.js" import { Schema } from "effect" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" -const Updated = define({ +const Updated = ephemeral({ type: "file.watcher.updated", schema: { file: Schema.String, diff --git a/packages/schema/src/filesystem.ts b/packages/schema/src/filesystem.ts index 882c3f0abf..3599e48c7c 100644 --- a/packages/schema/src/filesystem.ts +++ b/packages/schema/src/filesystem.ts @@ -2,10 +2,10 @@ export * as FileSystem from "./filesystem.js" import { Schema } from "effect" import { optional } from "./schema.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { NonNegativeInt, PositiveInt, RelativePath } from "./schema.js" -const Edited = define({ +const Edited = ephemeral({ type: "file.edited", schema: { file: Schema.String }, }) diff --git a/packages/schema/src/form.ts b/packages/schema/src/form.ts index 820192d06f..df9d455f13 100644 --- a/packages/schema/src/form.ts +++ b/packages/schema/src/form.ts @@ -1,7 +1,7 @@ export * as Form from "./form.js" import { Schema } from "effect" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { ascending } from "./identifier.js" import { NonNegativeInt, optional, statics } from "./schema.js" @@ -127,9 +127,11 @@ export interface UrlInfo extends Schema.Schema.Type {} export const Info = Schema.Union([FormInfo, UrlInfo]).pipe(Schema.toTaggedUnion("mode")) export type Info = FormInfo | UrlInfo -export const Value = Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Array(Schema.String)]).annotate({ - identifier: "Form.Value", -}) +export const Value = Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Array(Schema.String)]).annotate( + { + identifier: "Form.Value", + }, +) export type Value = typeof Value.Type export const Answer = Schema.Record(Schema.String, Value).annotate({ identifier: "Form.Answer" }) @@ -149,8 +151,8 @@ export const Reply = Schema.Struct({ }).annotate({ identifier: "Form.Reply" }) export interface Reply extends Schema.Schema.Type {} -const Created = define({ type: "form.created", schema: { form: Info } }) -const Replied = define({ type: "form.replied", schema: { id: ID, sessionID: Schema.String, answer: Answer } }) -const Cancelled = define({ type: "form.cancelled", schema: { id: ID, sessionID: Schema.String } }) +const Created = ephemeral({ type: "form.created", schema: { form: Info } }) +const Replied = ephemeral({ type: "form.replied", schema: { id: ID, sessionID: Schema.String, answer: Answer } }) +const Cancelled = ephemeral({ type: "form.cancelled", schema: { id: ID, sessionID: Schema.String } }) export const Event = { Created, Replied, Cancelled, Definitions: inventory(Created, Replied, Cancelled) } diff --git a/packages/schema/src/ide-event.ts b/packages/schema/src/ide-event.ts index ec01d9fa36..dd88975b38 100644 --- a/packages/schema/src/ide-event.ts +++ b/packages/schema/src/ide-event.ts @@ -3,7 +3,7 @@ export * as IdeEvent from "./ide-event.js" import { Schema } from "effect" import { Event } from "./event.js" -export const Installed = Event.define({ +export const Installed = Event.ephemeral({ type: "ide.installed", schema: { ide: Schema.String, diff --git a/packages/schema/src/installation-event.ts b/packages/schema/src/installation-event.ts index dde53f7b72..f36a2dfc14 100644 --- a/packages/schema/src/installation-event.ts +++ b/packages/schema/src/installation-event.ts @@ -3,14 +3,14 @@ export * as InstallationEvent from "./installation-event.js" import { Schema } from "effect" import { Event } from "./event.js" -export const Updated = Event.define({ +export const Updated = Event.ephemeral({ type: "installation.updated", schema: { version: Schema.String, }, }) -export const UpdateAvailable = Event.define({ +export const UpdateAvailable = Event.ephemeral({ type: "installation.update-available", schema: { version: Schema.String, diff --git a/packages/schema/src/integration.ts b/packages/schema/src/integration.ts index f1d9c63784..329bf8207f 100644 --- a/packages/schema/src/integration.ts +++ b/packages/schema/src/integration.ts @@ -2,7 +2,7 @@ export * as Integration from "./integration.js" import { Schema } from "effect" import { optional } from "./schema.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { Connection } from "./connection.js" import { ascending } from "./identifier.js" import { statics } from "./schema.js" @@ -76,11 +76,11 @@ export type Method = typeof Method.Type export const Inputs = Schema.Record(Schema.String, Schema.String).annotate({ identifier: "Integration.Inputs" }) export type Inputs = typeof Inputs.Type -const Updated = define({ +const Updated = ephemeral({ type: "integration.updated", schema: {}, }) -const ConnectionUpdated = define({ +const ConnectionUpdated = ephemeral({ type: "integration.connection.updated", schema: { integrationID: ID }, }) diff --git a/packages/schema/src/lsp-event.ts b/packages/schema/src/lsp-event.ts index 68f31fbc6c..7928fa00a0 100644 --- a/packages/schema/src/lsp-event.ts +++ b/packages/schema/src/lsp-event.ts @@ -2,6 +2,6 @@ export * as LspEvent from "./lsp-event.js" import { Event } from "./event.js" -export const Updated = Event.define({ type: "lsp.updated", schema: {} }) +export const Updated = Event.ephemeral({ type: "lsp.updated", schema: {} }) export const Definitions = Event.inventory(Updated) diff --git a/packages/schema/src/mcp-event.ts b/packages/schema/src/mcp-event.ts index 70be7a91d8..f4221335e9 100644 --- a/packages/schema/src/mcp-event.ts +++ b/packages/schema/src/mcp-event.ts @@ -3,14 +3,14 @@ export * as McpEvent from "./mcp-event.js" import { Schema } from "effect" import { Event } from "./event.js" -export const ToolsChanged = Event.define({ +export const ToolsChanged = Event.ephemeral({ type: "mcp.tools.changed", schema: { server: Schema.String, }, }) -export const BrowserOpenFailed = Event.define({ +export const BrowserOpenFailed = Event.ephemeral({ type: "mcp.browser.open.failed", schema: { mcpName: Schema.String, @@ -20,7 +20,7 @@ export const BrowserOpenFailed = Event.define({ // Emitted whenever a server's connection status settles (connected, failed, needs_auth, closed) so // observers can refresh status without polling. -export const StatusChanged = Event.define({ +export const StatusChanged = Event.ephemeral({ type: "mcp.status.changed", schema: { server: Schema.String, diff --git a/packages/schema/src/models-dev.ts b/packages/schema/src/models-dev.ts index 60d630ecfa..925639aef3 100644 --- a/packages/schema/src/models-dev.ts +++ b/packages/schema/src/models-dev.ts @@ -1,8 +1,8 @@ export * as ModelsDev from "./models-dev.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" -const Refreshed = define({ +const Refreshed = ephemeral({ type: "models-dev.refreshed", schema: {}, }) diff --git a/packages/schema/src/permission.ts b/packages/schema/src/permission.ts index de86fd1b1e..ca79081eda 100644 --- a/packages/schema/src/permission.ts +++ b/packages/schema/src/permission.ts @@ -2,7 +2,7 @@ export * as Permission from "./permission.js" import { Schema } from "effect" import { optional } from "./schema.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { ascending } from "./identifier.js" import { SessionID } from "./session-id.js" import { statics } from "./schema.js" @@ -40,8 +40,8 @@ export interface Request extends Schema.Schema.Type {} export const Reply = Schema.Literals(["once", "always", "reject"]).annotate({ identifier: "PermissionV2.Reply" }) export type Reply = typeof Reply.Type -const Asked = define({ type: "permission.v2.asked", schema: Request.fields }) -const Replied = define({ +const Asked = ephemeral({ type: "permission.v2.asked", schema: Request.fields }) +const Replied = ephemeral({ type: "permission.v2.replied", schema: { sessionID: SessionID, diff --git a/packages/schema/src/plugin.ts b/packages/schema/src/plugin.ts index 3a9b8b55b1..40379e3051 100644 --- a/packages/schema/src/plugin.ts +++ b/packages/schema/src/plugin.ts @@ -1,7 +1,7 @@ export * as Plugin from "./plugin.js" import { Schema } from "effect" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" export const ID = Schema.String.pipe(Schema.brand("Plugin.ID")) export type ID = typeof ID.Type @@ -11,7 +11,7 @@ export const Info = Schema.Struct({ id: ID, }).annotate({ identifier: "Plugin.Info" }) -const Added = define({ +const Added = ephemeral({ type: "plugin.added", schema: { id: ID }, }) diff --git a/packages/schema/src/project-directories.ts b/packages/schema/src/project-directories.ts index d80322287c..aa5d51f0cf 100644 --- a/packages/schema/src/project-directories.ts +++ b/packages/schema/src/project-directories.ts @@ -1,9 +1,9 @@ export * as ProjectDirectories from "./project-directories.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { Project } from "./project.js" -const Updated = define({ +const Updated = ephemeral({ type: "project.directories.updated", schema: { projectID: Project.ID }, }) diff --git a/packages/schema/src/project.ts b/packages/schema/src/project.ts index fce8d19ebf..e8524300a9 100644 --- a/packages/schema/src/project.ts +++ b/packages/schema/src/project.ts @@ -1,7 +1,7 @@ export * as Project from "./project.js" import { Schema } from "effect" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { AbsolutePath, NonNegativeInt, optional } from "./schema.js" import { ProjectID } from "./project-id.js" @@ -56,5 +56,5 @@ export const Info = Schema.Struct({ }).annotate({ identifier: "Project" }) export interface Info extends Schema.Schema.Type {} -const Updated = define({ type: "project.updated", schema: Info.fields }) +const Updated = ephemeral({ type: "project.updated", schema: Info.fields }) export const Event = { Updated, Definitions: inventory(Updated) } diff --git a/packages/schema/src/pty.ts b/packages/schema/src/pty.ts index 58dc9cb833..b2da9093f0 100644 --- a/packages/schema/src/pty.ts +++ b/packages/schema/src/pty.ts @@ -2,7 +2,7 @@ export * as Pty from "./pty.js" import { Schema } from "effect" import { optional } from "./schema.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { ascending } from "./identifier.js" import { NonNegativeInt, PositiveInt, statics } from "./schema.js" @@ -31,10 +31,10 @@ export const Info = Schema.Struct({ }).annotate({ identifier: "Pty" }) export interface Info extends Schema.Schema.Type {} -const Created = define({ type: "pty.created", schema: { info: Info } }) -const Updated = define({ type: "pty.updated", schema: { info: Info } }) -const Exited = define({ type: "pty.exited", schema: { id: ID, exitCode: NonNegativeInt } }) -const Deleted = define({ type: "pty.deleted", schema: { id: ID } }) +const Created = ephemeral({ type: "pty.created", schema: { info: Info } }) +const Updated = ephemeral({ type: "pty.updated", schema: { info: Info } }) +const Exited = ephemeral({ type: "pty.exited", schema: { id: ID, exitCode: NonNegativeInt } }) +const Deleted = ephemeral({ type: "pty.deleted", schema: { id: ID } }) export const Event = { Created, Updated, Exited, Deleted, Definitions: inventory(Created, Updated, Exited, Deleted) } export const CreateInput = Schema.Struct({ diff --git a/packages/schema/src/question.ts b/packages/schema/src/question.ts index 56fa7a277b..617ad2a895 100644 --- a/packages/schema/src/question.ts +++ b/packages/schema/src/question.ts @@ -2,7 +2,7 @@ export * as Question from "./question.js" import { Schema } from "effect" import { optional } from "./schema.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { ascending } from "./identifier.js" import { SessionID } from "./session-id.js" import { statics } from "./schema.js" @@ -67,8 +67,8 @@ export const Reply = Schema.Struct({ }).annotate({ identifier: "QuestionV2.Reply" }) export interface Reply extends Schema.Schema.Type {} -const Asked = define({ type: "question.v2.asked", schema: Request.fields }) -const Replied = define({ +const Asked = ephemeral({ type: "question.v2.asked", schema: Request.fields }) +const Replied = ephemeral({ type: "question.v2.replied", schema: { sessionID: SessionID, @@ -76,7 +76,7 @@ const Replied = define({ answers: Schema.Array(Answer), }, }) -const Rejected = define({ +const Rejected = ephemeral({ type: "question.v2.rejected", schema: { sessionID: SessionID, diff --git a/packages/schema/src/reference.ts b/packages/schema/src/reference.ts index 5d63bea9df..9dd277f62b 100644 --- a/packages/schema/src/reference.ts +++ b/packages/schema/src/reference.ts @@ -2,10 +2,10 @@ export * as Reference from "./reference.js" import { Schema } from "effect" import { optional } from "./schema.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { AbsolutePath } from "./schema.js" -const Updated = define({ type: "reference.updated", schema: {} }) +const Updated = ephemeral({ type: "reference.updated", schema: {} }) export const Event = { Updated, Definitions: inventory(Updated) } export interface LocalSource extends Schema.Schema.Type {} diff --git a/packages/schema/src/server-event.ts b/packages/schema/src/server-event.ts index ec8599ad32..4f4963cfbf 100644 --- a/packages/schema/src/server-event.ts +++ b/packages/schema/src/server-event.ts @@ -2,7 +2,7 @@ export * as ServerEvent from "./server-event.js" import { Event } from "./event.js" -export const Connected = Event.define({ type: "server.connected", schema: {} }) -export const Disposed = Event.define({ type: "global.disposed", schema: {} }) +export const Connected = Event.ephemeral({ type: "server.connected", schema: {} }) +export const Disposed = Event.ephemeral({ type: "global.disposed", schema: {} }) export const Definitions = Event.inventory(Connected, Disposed) diff --git a/packages/schema/src/session-compaction-event.ts b/packages/schema/src/session-compaction-event.ts index 56782fd5d5..a9c0144c98 100644 --- a/packages/schema/src/session-compaction-event.ts +++ b/packages/schema/src/session-compaction-event.ts @@ -3,7 +3,7 @@ export * as SessionCompactionEvent from "./session-compaction-event.js" import { Event } from "./event.js" import { SessionID } from "./session-id.js" -export const Compacted = Event.define({ +export const Compacted = Event.ephemeral({ type: "session.compacted", schema: { sessionID: SessionID, diff --git a/packages/schema/src/session-event.ts b/packages/schema/src/session-event.ts index df78fa1493..fe1a698555 100644 --- a/packages/schema/src/session-event.ts +++ b/packages/schema/src/session-event.ts @@ -51,7 +51,7 @@ const stepSettlementOptions = { export const UnknownError = SessionMessage.UnknownError export type UnknownError = SessionMessage.UnknownError -export const AgentSwitched = Event.define({ +export const AgentSwitched = Event.durable({ type: "session.next.agent.switched", ...options, schema: { @@ -62,7 +62,7 @@ export const AgentSwitched = Event.define({ }) export type AgentSwitched = typeof AgentSwitched.Type -export const ModelSwitched = Event.define({ +export const ModelSwitched = Event.durable({ type: "session.next.model.switched", ...options, schema: { @@ -73,7 +73,7 @@ export const ModelSwitched = Event.define({ }) export type ModelSwitched = typeof ModelSwitched.Type -export const Moved = Event.define({ +export const Moved = Event.durable({ type: "session.next.moved", ...options, schema: { @@ -84,7 +84,7 @@ export const Moved = Event.define({ }) export type Moved = typeof Moved.Type -export const Renamed = Event.define({ +export const Renamed = Event.durable({ type: "session.next.renamed", ...options, schema: { @@ -94,7 +94,7 @@ export const Renamed = Event.define({ }) export type Renamed = typeof Renamed.Type -export const Forked = Event.define({ +export const Forked = Event.durable({ type: "session.next.forked", ...options, schema: { @@ -105,21 +105,21 @@ export const Forked = Event.define({ }) export type Forked = typeof Forked.Type -export const Prompted = Event.define({ +export const Prompted = Event.durable({ type: "session.next.prompted", ...options, schema: PromptFields, }) export type Prompted = typeof Prompted.Type -export const PromptAdmitted = Event.define({ +export const PromptAdmitted = Event.durable({ type: "session.next.prompt.admitted", ...options, schema: PromptFields, }) export type PromptAdmitted = typeof PromptAdmitted.Type -export const ExecutionSettled = Event.define({ +export const ExecutionSettled = Event.ephemeral({ type: "session.next.execution.settled", schema: { ...Base, @@ -129,7 +129,7 @@ export const ExecutionSettled = Event.define({ }) export type ExecutionSettled = typeof ExecutionSettled.Type -export const ContextUpdated = Event.define({ +export const ContextUpdated = Event.durable({ type: "session.next.context.updated", ...options, schema: { @@ -140,7 +140,7 @@ export const ContextUpdated = Event.define({ }) export type ContextUpdated = typeof ContextUpdated.Type -export const Synthetic = Event.define({ +export const Synthetic = Event.durable({ type: "session.next.synthetic", ...options, schema: { @@ -154,7 +154,7 @@ export const Synthetic = Event.define({ export type Synthetic = typeof Synthetic.Type export namespace Skill { - export const Activated = Event.define({ + export const Activated = Event.durable({ type: "session.next.skill.activated", ...options, schema: { @@ -168,7 +168,7 @@ export namespace Skill { } export namespace Shell { - export const Started = Event.define({ + export const Started = Event.durable({ type: "session.next.shell.started", ...options, schema: { @@ -180,7 +180,7 @@ export namespace Shell { }) export type Started = typeof Started.Type - export const Ended = Event.define({ + export const Ended = Event.durable({ type: "session.next.shell.ended", ...options, schema: { @@ -193,7 +193,7 @@ export namespace Shell { } export namespace Step { - export const Started = Event.define({ + export const Started = Event.durable({ type: "session.next.step.started", ...options, schema: { @@ -206,7 +206,7 @@ export namespace Step { }) export type Started = typeof Started.Type - export const Ended = Event.define({ + export const Ended = Event.durable({ type: "session.next.step.ended", ...stepSettlementOptions, schema: { @@ -229,7 +229,7 @@ export namespace Step { }) export type Ended = typeof Ended.Type - export const Failed = Event.define({ + export const Failed = Event.durable({ type: "session.next.step.failed", ...stepSettlementOptions, schema: { @@ -242,7 +242,7 @@ export namespace Step { } export namespace Text { - export const Started = Event.define({ + export const Started = Event.durable({ type: "session.next.text.started", ...options, schema: { @@ -254,7 +254,7 @@ export namespace Text { export type Started = typeof Started.Type // Stream fragments are live-only; Text.Ended is the replayable full-value boundary. - export const Delta = Event.define({ + export const Delta = Event.ephemeral({ type: "session.next.text.delta", schema: { ...Base, @@ -265,7 +265,7 @@ export namespace Text { }) export type Delta = typeof Delta.Type - export const Ended = Event.define({ + export const Ended = Event.durable({ type: "session.next.text.ended", ...options, schema: { @@ -279,7 +279,7 @@ export namespace Text { } export namespace Reasoning { - export const Started = Event.define({ + export const Started = Event.durable({ type: "session.next.reasoning.started", ...options, schema: { @@ -292,7 +292,7 @@ export namespace Reasoning { export type Started = typeof Started.Type // Stream fragments are live-only; Reasoning.Ended is the replayable full-value boundary. - export const Delta = Event.define({ + export const Delta = Event.ephemeral({ type: "session.next.reasoning.delta", schema: { ...Base, @@ -303,7 +303,7 @@ export namespace Reasoning { }) export type Delta = typeof Delta.Type - export const Ended = Event.define({ + export const Ended = Event.durable({ type: "session.next.reasoning.ended", ...options, schema: { @@ -325,7 +325,7 @@ export namespace Tool { } export namespace Input { - export const Started = Event.define({ + export const Started = Event.durable({ type: "session.next.tool.input.started", ...options, schema: { @@ -336,7 +336,7 @@ export namespace Tool { export type Started = typeof Started.Type // Stream fragments are live-only; Input.Ended is the replayable raw-input boundary. - export const Delta = Event.define({ + export const Delta = Event.ephemeral({ type: "session.next.tool.input.delta", schema: { ...ToolBase, @@ -345,7 +345,7 @@ export namespace Tool { }) export type Delta = typeof Delta.Type - export const Ended = Event.define({ + export const Ended = Event.durable({ type: "session.next.tool.input.ended", ...options, schema: { @@ -356,7 +356,7 @@ export namespace Tool { export type Ended = typeof Ended.Type } - export const Called = Event.define({ + export const Called = Event.durable({ type: "session.next.tool.called", ...options, schema: { @@ -375,7 +375,7 @@ export namespace Tool { * Replayable bounded running-tool state. Tools should checkpoint semantic * transitions or at a bounded cadence, not persist every stdout/stderr chunk. */ - export const Progress = Event.define({ + export const Progress = Event.durable({ type: "session.next.tool.progress", ...options, schema: { @@ -386,7 +386,7 @@ export namespace Tool { }) export type Progress = typeof Progress.Type - export const Success = Event.define({ + export const Success = Event.durable({ type: "session.next.tool.success", ...options, schema: { @@ -403,7 +403,7 @@ export namespace Tool { }) export type Success = typeof Success.Type - export const Failed = Event.define({ + export const Failed = Event.durable({ type: "session.next.tool.failed", ...options, schema: { @@ -431,7 +431,7 @@ export const RetryError = Schema.Struct({ }) export interface RetryError extends Schema.Schema.Type {} -export const Retried = Event.define({ +export const Retried = Event.durable({ type: "session.next.retried", ...options, schema: { @@ -443,7 +443,7 @@ export const Retried = Event.define({ export type Retried = typeof Retried.Type export namespace Compaction { - export const Started = Event.define({ + export const Started = Event.durable({ type: "session.next.compaction.started", ...options, schema: { @@ -454,7 +454,7 @@ export namespace Compaction { }) export type Started = typeof Started.Type - export const Delta = Event.define({ + export const Delta = Event.ephemeral({ type: "session.next.compaction.delta", schema: { ...Base, @@ -464,7 +464,7 @@ export namespace Compaction { }) export type Delta = typeof Delta.Type - export const Ended = Event.define({ + export const Ended = Event.durable({ type: "session.next.compaction.ended", ...options, schema: { @@ -479,53 +479,19 @@ export namespace Compaction { } export namespace RevertEvent { - export const Staged = Event.define({ + export const Staged = Event.durable({ type: "session.next.revert.staged", ...options, schema: { ...Base, revert: Revert.State }, }) - export const Cleared = Event.define({ type: "session.next.revert.cleared", ...options, schema: Base }) - export const Committed = Event.define({ + export const Cleared = Event.durable({ type: "session.next.revert.cleared", ...options, schema: Base }) + export const Committed = Event.durable({ type: "session.next.revert.committed", ...options, schema: { ...Base, messageID: SessionMessage.ID }, }) } -export const DurableDefinitions = Event.inventory( - AgentSwitched, - ModelSwitched, - Moved, - Renamed, - Forked, - Prompted, - PromptAdmitted, - ContextUpdated, - Synthetic, - Skill.Activated, - Shell.Started, - Shell.Ended, - Step.Started, - Step.Ended, - Step.Failed, - Text.Started, - Text.Ended, - Tool.Input.Started, - Tool.Input.Ended, - Tool.Called, - Tool.Progress, - Tool.Success, - Tool.Failed, - Reasoning.Started, - Reasoning.Ended, - Retried, - Compaction.Started, - Compaction.Ended, - RevertEvent.Staged, - RevertEvent.Cleared, - RevertEvent.Committed, -) - export const Definitions = Event.inventory( AgentSwitched, ModelSwitched, @@ -565,6 +531,10 @@ export const Definitions = Event.inventory( RevertEvent.Committed, ) +export const DurableDefinitions = Event.inventory( + ...Definitions.filter((definition) => definition.durability === "durable"), +) + export const Durable = Schema.Union(DurableDefinitions, { mode: "oneOf" }) .pipe(Schema.toTaggedUnion("type")) .annotate({ identifier: "SessionDurableEvent" }) diff --git a/packages/schema/src/session-status-event.ts b/packages/schema/src/session-status-event.ts index 331c58ba1c..03e6940215 100644 --- a/packages/schema/src/session-status-event.ts +++ b/packages/schema/src/session-status-event.ts @@ -32,7 +32,7 @@ export const Info = Schema.Union([ ]).annotate({ identifier: "SessionStatus" }) export type Info = Schema.Schema.Type -export const Status = Event.define({ +export const Status = Event.ephemeral({ type: "session.status", schema: { sessionID: SessionID, @@ -41,7 +41,7 @@ export const Status = Event.define({ }) // deprecated -export const Idle = Event.define({ +export const Idle = Event.ephemeral({ type: "session.idle", schema: { sessionID: SessionID, diff --git a/packages/schema/src/session-todo.ts b/packages/schema/src/session-todo.ts index f72abcd17e..f4d68268ff 100644 --- a/packages/schema/src/session-todo.ts +++ b/packages/schema/src/session-todo.ts @@ -1,7 +1,7 @@ export * as SessionTodo from "./session-todo.js" import { Schema } from "effect" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { SessionID } from "./session-id.js" export const Info = Schema.Struct({ @@ -15,7 +15,7 @@ export const Info = Schema.Struct({ }).annotate({ identifier: "Todo" }) export interface Info extends Schema.Schema.Type {} -const Updated = define({ +const Updated = ephemeral({ type: "todo.updated", schema: { sessionID: SessionID, diff --git a/packages/schema/src/shell.ts b/packages/schema/src/shell.ts index a627a15950..fbe877c974 100644 --- a/packages/schema/src/shell.ts +++ b/packages/schema/src/shell.ts @@ -2,7 +2,7 @@ export * as Shell from "./shell.js" import { Schema } from "effect" import { optional } from "./schema.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" import { ascending } from "./identifier.js" import { NonNegativeInt, statics } from "./schema.js" @@ -49,9 +49,9 @@ export const Info = Schema.Struct({ }).annotate({ identifier: "Shell" }) export interface Info extends Schema.Schema.Type {} -const Created = define({ type: "shell.created", schema: { info: Info } }) -const Exited = define({ type: "shell.exited", schema: { id: ID, exit: optional(Schema.Number), status: Status } }) -const Deleted = define({ type: "shell.deleted", schema: { id: ID } }) +const Created = ephemeral({ type: "shell.created", schema: { info: Info } }) +const Exited = ephemeral({ type: "shell.exited", schema: { id: ID, exit: optional(Schema.Number), status: Status } }) +const Deleted = ephemeral({ type: "shell.deleted", schema: { id: ID } }) export const Event = { Created, Exited, Deleted, Definitions: inventory(Created, Exited, Deleted) } export const CreateInput = Schema.Struct({ diff --git a/packages/schema/src/skill.ts b/packages/schema/src/skill.ts index bf0dd7aa2b..184266f2ad 100644 --- a/packages/schema/src/skill.ts +++ b/packages/schema/src/skill.ts @@ -3,7 +3,7 @@ export * as Skill from "./skill.js" import { Schema } from "effect" import { optional } from "./schema.js" import { AbsolutePath } from "./schema.js" -import { define, inventory } from "./event.js" +import { ephemeral, inventory } from "./event.js" export interface DirectorySource extends Schema.Schema.Type {} export const DirectorySource = Schema.Struct({ @@ -27,7 +27,7 @@ export const Info = Schema.Struct({ content: Schema.String, }).annotate({ identifier: "SkillV2.Info" }) -const Updated = define({ type: "skill.updated", schema: {} }) +const Updated = ephemeral({ type: "skill.updated", schema: {} }) export const Event = { Updated, Definitions: inventory(Updated) } export interface EmbeddedSource extends Schema.Schema.Type {} diff --git a/packages/schema/src/tui-event.ts b/packages/schema/src/tui-event.ts index 0de2b6e369..ba9fd29ef8 100644 --- a/packages/schema/src/tui-event.ts +++ b/packages/schema/src/tui-event.ts @@ -8,9 +8,9 @@ import { SessionID } from "./session-id.js" const DEFAULT_TOAST_DURATION = 5000 -export const PromptAppend = Event.define({ type: "tui.prompt.append", schema: { text: Schema.String } }) +export const PromptAppend = Event.ephemeral({ type: "tui.prompt.append", schema: { text: Schema.String } }) -export const CommandExecute = Event.define({ +export const CommandExecute = Event.ephemeral({ type: "tui.command.execute", schema: { command: Schema.Union([ @@ -38,7 +38,7 @@ export const CommandExecute = Event.define({ }, }) -export const ToastShow = Event.define({ +export const ToastShow = Event.ephemeral({ type: "tui.toast.show", schema: { title: optional(Schema.String), @@ -50,7 +50,7 @@ export const ToastShow = Event.define({ }, }) -export const SessionSelect = Event.define({ +export const SessionSelect = Event.ephemeral({ type: "tui.session.select", schema: { sessionID: SessionID.annotate({ description: "Session ID to navigate to" }), diff --git a/packages/schema/src/v1/legacy-event.ts b/packages/schema/src/v1/legacy-event.ts index 12037e104f..ac22fff5e3 100644 --- a/packages/schema/src/v1/legacy-event.ts +++ b/packages/schema/src/v1/legacy-event.ts @@ -1,11 +1,11 @@ export * as LegacyEvent from "./legacy-event.js" import { Schema } from "effect" -import { define, inventory } from "../event.js" +import { ephemeral, inventory } from "../event.js" import { SessionID } from "../session-id.js" import { SessionV1 } from "./session.js" -export const CommandExecuted = define({ +export const CommandExecuted = ephemeral({ type: "command.executed", schema: { name: Schema.String, diff --git a/packages/schema/src/v1/permission.ts b/packages/schema/src/v1/permission.ts index af1d0098b8..1faa46a508 100644 --- a/packages/schema/src/v1/permission.ts +++ b/packages/schema/src/v1/permission.ts @@ -1,7 +1,7 @@ export * as PermissionV1 from "./permission.js" import { Schema } from "effect" -import { define, inventory } from "../event.js" +import { ephemeral, inventory } from "../event.js" import { ascending } from "../identifier.js" import { Project } from "../project.js" import { statics } from "../schema.js" @@ -58,8 +58,8 @@ export const ReplyInput = Schema.Struct({ requestID: ID, ...ReplyBody.fields }). }) export type ReplyInput = typeof ReplyInput.Type -const Asked = define({ type: "permission.asked", schema: Request.fields }) -const Replied = define({ +const Asked = ephemeral({ type: "permission.asked", schema: Request.fields }) +const Replied = ephemeral({ type: "permission.replied", schema: { sessionID: SessionID, requestID: ID, reply: Reply }, }) diff --git a/packages/schema/src/v1/question.ts b/packages/schema/src/v1/question.ts index 557646c44e..da47f37ffd 100644 --- a/packages/schema/src/v1/question.ts +++ b/packages/schema/src/v1/question.ts @@ -1,7 +1,7 @@ export * as QuestionV1 from "./question.js" import { Schema } from "effect" -import { define, inventory } from "../event.js" +import { ephemeral, inventory } from "../event.js" import { ascending } from "../identifier.js" import { statics } from "../schema.js" import { SessionID } from "../session-id.js" @@ -55,9 +55,9 @@ export const Rejected = Schema.Struct({ sessionID: SessionID, requestID: ID }).a identifier: "QuestionRejected", }) -const Asked = define({ type: "question.asked", schema: Request.fields }) -const RepliedEvent = define({ type: "question.replied", schema: Replied.fields }) -const RejectedEvent = define({ type: "question.rejected", schema: Rejected.fields }) +const Asked = ephemeral({ type: "question.asked", schema: Request.fields }) +const RepliedEvent = ephemeral({ type: "question.replied", schema: Replied.fields }) +const RejectedEvent = ephemeral({ type: "question.rejected", schema: Rejected.fields }) export const Event = { Asked, Replied: RepliedEvent, diff --git a/packages/schema/src/v1/session.ts b/packages/schema/src/v1/session.ts index 452ba3a186..1c2827f0d8 100644 --- a/packages/schema/src/v1/session.ts +++ b/packages/schema/src/v1/session.ts @@ -1,7 +1,7 @@ export * as SessionV1 from "./session.js" import { Effect, Schema, Types } from "effect" -import { define, inventory } from "../event.js" +import { durable, ephemeral, inventory } from "../event.js" import { FileDiff } from "../file-diff.js" import { Project } from "../project.js" import { Provider } from "../provider.js" @@ -569,7 +569,7 @@ export const SessionInfo = Schema.Struct({ export type SessionInfo = typeof SessionInfo.Type const events = { - Created: define({ + Created: durable({ type: "session.created", ...options, schema: { @@ -577,7 +577,7 @@ const events = { info: SessionInfo, }, }), - Updated: define({ + Updated: durable({ type: "session.updated", ...options, schema: { @@ -585,7 +585,7 @@ const events = { info: SessionInfo, }, }), - Deleted: define({ + Deleted: durable({ type: "session.deleted", ...options, schema: { @@ -593,7 +593,7 @@ const events = { info: SessionInfo, }, }), - MessageUpdated: define({ + MessageUpdated: durable({ type: "message.updated", ...options, schema: { @@ -601,7 +601,7 @@ const events = { info: Info, }, }), - MessageRemoved: define({ + MessageRemoved: durable({ type: "message.removed", ...options, schema: { @@ -609,7 +609,7 @@ const events = { messageID: MessageID, }, }), - PartUpdated: define({ + PartUpdated: durable({ type: "message.part.updated", ...options, schema: { @@ -618,7 +618,7 @@ const events = { time: Schema.Finite, }, }), - PartRemoved: define({ + PartRemoved: durable({ type: "message.part.removed", ...options, schema: { @@ -629,7 +629,7 @@ const events = { }), } -export const PartDelta = define({ +export const PartDelta = ephemeral({ type: "message.part.delta", schema: { sessionID: SessionID, @@ -640,7 +640,7 @@ export const PartDelta = define({ }, }) -export const Diff = define({ +export const Diff = ephemeral({ type: "session.diff", schema: { sessionID: SessionID, @@ -648,7 +648,7 @@ export const Diff = define({ }, }) -export const Error = define({ +export const Error = ephemeral({ type: "session.error", schema: { sessionID: Schema.optional(SessionID), diff --git a/packages/schema/src/vcs-event.ts b/packages/schema/src/vcs-event.ts index 2428b432b4..5ece3cd844 100644 --- a/packages/schema/src/vcs-event.ts +++ b/packages/schema/src/vcs-event.ts @@ -4,7 +4,7 @@ import { Schema } from "effect" import { optional } from "./schema.js" import { Event } from "./event.js" -export const BranchUpdated = Event.define({ +export const BranchUpdated = Event.ephemeral({ type: "vcs.branch.updated", schema: { branch: optional(Schema.String), diff --git a/packages/schema/src/workspace-event.ts b/packages/schema/src/workspace-event.ts index 6468a4410c..2b6a752ef5 100644 --- a/packages/schema/src/workspace-event.ts +++ b/packages/schema/src/workspace-event.ts @@ -10,21 +10,21 @@ export const ConnectionStatus = Schema.Struct({ }).annotate({ identifier: "WorkspaceEvent.ConnectionStatus" }) export interface ConnectionStatus extends Schema.Schema.Type {} -export const Ready = Event.define({ +export const Ready = Event.ephemeral({ type: "workspace.ready", schema: { name: Schema.String, }, }) -export const Failed = Event.define({ +export const Failed = Event.ephemeral({ type: "workspace.failed", schema: { message: Schema.String, }, }) -export const Status = Event.define({ +export const Status = Event.ephemeral({ type: "workspace.status", schema: ConnectionStatus.fields, }) diff --git a/packages/schema/src/worktree-event.ts b/packages/schema/src/worktree-event.ts index 2acb72fe7e..db80d794e5 100644 --- a/packages/schema/src/worktree-event.ts +++ b/packages/schema/src/worktree-event.ts @@ -4,7 +4,7 @@ import { Schema } from "effect" import { optional } from "./schema.js" import { Event } from "./event.js" -export const Ready = Event.define({ +export const Ready = Event.ephemeral({ type: "worktree.ready", schema: { name: Schema.String, @@ -12,7 +12,7 @@ export const Ready = Event.define({ }, }) -export const Failed = Event.define({ +export const Failed = Event.ephemeral({ type: "worktree.failed", schema: { message: Schema.String, diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 452b0ac149..4e0c6eaa18 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -1,5 +1,15 @@ import { describe, expect, test } from "bun:test" -import { Agent, FileSystem, Form, Integration, Permission, Project, Reference, Session, Workspace } from "../src/index.js" +import { + Agent, + FileSystem, + Form, + Integration, + Permission, + Project, + Reference, + Session, + Workspace, +} from "../src/index.js" import { EventManifest } from "../src/event-manifest.js" import { IdeEvent } from "../src/ide-event.js" import { SessionEvent } from "../src/session-event.js" @@ -9,11 +19,11 @@ import { WorkspaceEvent } from "../src/workspace-event.js" describe("public event manifest", () => { test("owns the complete public event surface", () => { - expect(EventManifest.ServerDefinitions.filter((definition) => definition.type !== "agent.updated").length).toBe(86) + expect(EventManifest.ServerDefinitions).toContain(Agent.Event.Updated) expect(EventManifest.ServerDefinitions.filter((definition) => definition.type === "agent.updated")).toEqual([ Agent.Event.Updated, ]) - expect(EventManifest.Definitions.filter((definition) => definition.type !== "agent.updated").length).toBe(101) + expect(EventManifest.Definitions).toContain(Agent.Event.Updated) expect(EventManifest.Definitions.filter((definition) => definition.type === "agent.updated")).toEqual([ Agent.Event.Updated, ]) @@ -29,7 +39,9 @@ describe("public event manifest", () => { SessionV1.Event.Diff, SessionV1.Event.Error, ]) - expect(Array.from(EventManifest.Latest.keys()).filter((type) => type !== "agent.updated").length).toBe(101) + expect(Array.from(EventManifest.Latest.keys())).toEqual( + EventManifest.Definitions.map((definition) => definition.type), + ) expect(EventManifest.Latest.get("agent.updated")).toBe(Agent.Event.Updated) expect(Agent.Event.Updated.durable).toBeUndefined() expect(EventManifest.Durable.has("agent.updated")).toBe(false) @@ -62,4 +74,53 @@ describe("public event manifest", () => { expect(EventManifest.Durable.has("session.next.step.ended.1")).toBe(false) expect(EventManifest.Durable.get("session.next.step.ended.2")).toBe(SessionEvent.Step.Ended) }) + + test("derives durable definitions from explicit definition durability", () => { + expect(Array.from(EventManifest.Durable.keys()).toSorted()).toEqual( + [ + "session.created.1", + "session.updated.1", + "session.deleted.1", + "message.updated.1", + "message.removed.1", + "message.part.updated.1", + "message.part.removed.1", + "session.next.agent.switched.1", + "session.next.model.switched.1", + "session.next.moved.1", + "session.next.renamed.1", + "session.next.forked.1", + "session.next.prompted.1", + "session.next.prompt.admitted.1", + "session.next.context.updated.1", + "session.next.synthetic.1", + "session.next.skill.activated.1", + "session.next.shell.started.1", + "session.next.shell.ended.1", + "session.next.step.started.1", + "session.next.step.ended.2", + "session.next.step.failed.2", + "session.next.text.started.1", + "session.next.text.ended.1", + "session.next.tool.input.started.1", + "session.next.tool.input.ended.1", + "session.next.tool.called.1", + "session.next.tool.progress.1", + "session.next.tool.success.1", + "session.next.tool.failed.1", + "session.next.reasoning.started.1", + "session.next.reasoning.ended.1", + "session.next.retried.1", + "session.next.compaction.started.1", + "session.next.compaction.ended.1", + "session.next.revert.staged.1", + "session.next.revert.cleared.1", + "session.next.revert.committed.1", + ].toSorted(), + ) + expect(SessionEvent.DurableDefinitions).toEqual( + SessionEvent.Definitions.filter((definition) => definition.durability === "durable"), + ) + expect(EventManifest.Definitions.every((definition) => definition.durability !== undefined)).toBe(true) + }) }) diff --git a/packages/schema/test/event.test.ts b/packages/schema/test/event.test.ts index a05dca0c6e..404b49aa74 100644 --- a/packages/schema/test/event.test.ts +++ b/packages/schema/test/event.test.ts @@ -6,17 +6,17 @@ import { EventLog } from "../src/event-log.js" describe("public event schemas", () => { test("definition is pure", () => { const definitions = Event.inventory() - Event.define({ type: "test.pure", schema: { value: Schema.String } }) + Event.ephemeral({ type: "test.pure", schema: { value: Schema.String } }) expect(definitions).toEqual([]) }) test("latest selection is independent of declaration order", () => { - const historical = Event.define({ + const historical = Event.durable({ type: "test.versioned", durable: { aggregate: "id", version: 1 }, schema: { id: Schema.String }, }) - const current = Event.define({ + const current = Event.durable({ type: "test.versioned", durable: { aggregate: "id", version: 2 }, schema: { id: Schema.String, value: Schema.String }, @@ -27,13 +27,13 @@ describe("public event schemas", () => { }) test("durable definitions are indexed by type and version", () => { - const definition = Event.define({ + const definition = Event.durable({ type: "test.durable", durable: { aggregate: "id", version: 1 }, schema: { id: Schema.String }, }) - expect(Event.durable([definition]).get("test.durable.1")).toBe(definition) + expect(Event.durableMap([definition]).get("test.durable.1")).toBe(definition) }) test("synced marker encodes the captured watermark", () => { diff --git a/packages/sdk-next/test/embedded.test.ts b/packages/sdk-next/test/embedded.test.ts index 572cdd9665..81f3d480ad 100644 --- a/packages/sdk-next/test/embedded.test.ts +++ b/packages/sdk-next/test/embedded.test.ts @@ -149,7 +149,7 @@ it.live( const opencode = yield* fixture.sdk.OpenCode.create() const id = sessionID(fixture) const connected = yield* Latch.make(false) - const prompted = yield* Deferred.make() + const prompted = yield* Deferred.make>() yield* opencode.events.subscribe().pipe( Stream.runForEach((event) => diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 2f476f2844..a1ba35e5ae 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -2928,14 +2928,14 @@ export type SessionDurableEvent = | SessionNextStepFailed | SessionNextTextStarted | SessionNextTextEnded + | SessionNextReasoningStarted + | SessionNextReasoningEnded | SessionNextToolInputStarted | SessionNextToolInputEnded | SessionNextToolCalled | SessionNextToolProgress | SessionNextToolSuccess | SessionNextToolFailed - | SessionNextReasoningStarted - | SessionNextReasoningEnded | SessionNextRetried | SessionNextCompactionStarted | SessionNextCompactionEnded @@ -3020,11 +3020,6 @@ export type SessionStatus2 = { [key: string]: unknown } type: "session.status" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -3038,11 +3033,6 @@ export type QuestionReplied2 = { [key: string]: unknown } type: "question.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -3057,11 +3047,6 @@ export type QuestionRejected2 = { [key: string]: unknown } type: "question.rejected" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -4634,7 +4619,7 @@ export type SessionNextAgentSwitched = { [key: string]: unknown } type: "session.next.agent.switched" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4654,7 +4639,7 @@ export type SessionNextModelSwitched = { [key: string]: unknown } type: "session.next.model.switched" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4674,7 +4659,7 @@ export type SessionNextMoved = { [key: string]: unknown } type: "session.next.moved" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4694,7 +4679,7 @@ export type SessionNextRenamed = { [key: string]: unknown } type: "session.next.renamed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4713,7 +4698,7 @@ export type SessionNextForked = { [key: string]: unknown } type: "session.next.forked" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4733,7 +4718,7 @@ export type SessionNextPrompted = { [key: string]: unknown } type: "session.next.prompted" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4754,7 +4739,7 @@ export type SessionNextPromptAdmitted = { [key: string]: unknown } type: "session.next.prompt.admitted" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4775,7 +4760,7 @@ export type SessionNextContextUpdated = { [key: string]: unknown } type: "session.next.context.updated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4795,7 +4780,7 @@ export type SessionNextSynthetic = { [key: string]: unknown } type: "session.next.synthetic" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4819,7 +4804,7 @@ export type SessionNextSkillActivated = { [key: string]: unknown } type: "session.next.skill.activated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4840,7 +4825,7 @@ export type SessionNextShellStarted = { [key: string]: unknown } type: "session.next.shell.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4861,7 +4846,7 @@ export type SessionNextShellEnded = { [key: string]: unknown } type: "session.next.shell.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4881,7 +4866,7 @@ export type SessionNextStepStarted = { [key: string]: unknown } type: "session.next.step.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4903,7 +4888,7 @@ export type SessionNextStepEnded = { [key: string]: unknown } type: "session.next.step.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4935,7 +4920,7 @@ export type SessionNextStepFailed = { [key: string]: unknown } type: "session.next.step.failed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4955,7 +4940,7 @@ export type SessionNextTextStarted = { [key: string]: unknown } type: "session.next.text.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4975,7 +4960,7 @@ export type SessionNextTextEnded = { [key: string]: unknown } type: "session.next.text.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -4990,13 +4975,56 @@ export type SessionNextTextEnded = { } } +export type SessionNextReasoningStarted = { + id: string + metadata?: { + [key: string]: unknown + } + type: "session.next.reasoning.started" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + timestamp: number + sessionID: string + assistantMessageID: string + reasoningID: string + providerMetadata?: LlmProviderMetadata + } +} + +export type SessionNextReasoningEnded = { + id: string + metadata?: { + [key: string]: unknown + } + type: "session.next.reasoning.ended" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + timestamp: number + sessionID: string + assistantMessageID: string + reasoningID: string + text: string + providerMetadata?: LlmProviderMetadata + } +} + export type SessionNextToolInputStarted = { id: string metadata?: { [key: string]: unknown } type: "session.next.tool.input.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5017,7 +5045,7 @@ export type SessionNextToolInputEnded = { [key: string]: unknown } type: "session.next.tool.input.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5038,7 +5066,7 @@ export type SessionNextToolCalled = { [key: string]: unknown } type: "session.next.tool.called" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5066,7 +5094,7 @@ export type SessionNextToolProgress = { [key: string]: unknown } type: "session.next.tool.progress" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5090,7 +5118,7 @@ export type SessionNextToolSuccess = { [key: string]: unknown } type: "session.next.tool.success" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5120,7 +5148,7 @@ export type SessionNextToolFailed = { [key: string]: unknown } type: "session.next.tool.failed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5140,56 +5168,13 @@ export type SessionNextToolFailed = { } } -export type SessionNextReasoningStarted = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.reasoning.started" - durable?: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - timestamp: number - sessionID: string - assistantMessageID: string - reasoningID: string - providerMetadata?: LlmProviderMetadata - } -} - -export type SessionNextReasoningEnded = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.reasoning.ended" - durable?: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - timestamp: number - sessionID: string - assistantMessageID: string - reasoningID: string - text: string - providerMetadata?: LlmProviderMetadata - } -} - export type SessionNextRetried = { id: string metadata?: { [key: string]: unknown } type: "session.next.retried" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5209,7 +5194,7 @@ export type SessionNextCompactionStarted = { [key: string]: unknown } type: "session.next.compaction.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5229,7 +5214,7 @@ export type SessionNextCompactionEnded = { [key: string]: unknown } type: "session.next.compaction.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5251,7 +5236,7 @@ export type SessionNextRevertStaged = { [key: string]: unknown } type: "session.next.revert.staged" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5270,7 +5255,7 @@ export type SessionNextRevertCleared = { [key: string]: unknown } type: "session.next.revert.cleared" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5288,7 +5273,7 @@ export type SessionNextRevertCommitted = { [key: string]: unknown } type: "session.next.revert.committed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5634,11 +5619,6 @@ export type ModelsDevRefreshed = { [key: string]: unknown } type: "models-dev.refreshed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -5651,11 +5631,6 @@ export type IntegrationUpdated = { [key: string]: unknown } type: "integration.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -5668,11 +5643,6 @@ export type IntegrationConnectionUpdated = { [key: string]: unknown } type: "integration.connection.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { integrationID: string @@ -5685,11 +5655,6 @@ export type CatalogUpdated = { [key: string]: unknown } type: "catalog.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -5702,11 +5667,6 @@ export type AgentUpdated = { [key: string]: unknown } type: "agent.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -5719,7 +5679,7 @@ export type SessionCreated = { [key: string]: unknown } type: "session.created" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5737,7 +5697,7 @@ export type SessionUpdated = { [key: string]: unknown } type: "session.updated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5755,7 +5715,7 @@ export type SessionDeleted = { [key: string]: unknown } type: "session.deleted" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5773,7 +5733,7 @@ export type MessageUpdated = { [key: string]: unknown } type: "message.updated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5791,7 +5751,7 @@ export type MessageRemoved = { [key: string]: unknown } type: "message.removed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5809,7 +5769,7 @@ export type MessagePartUpdated = { [key: string]: unknown } type: "message.part.updated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5828,7 +5788,7 @@ export type MessagePartRemoved = { [key: string]: unknown } type: "message.part.removed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -5847,11 +5807,6 @@ export type SessionNextExecutionSettled = { [key: string]: unknown } type: "session.next.execution.settled" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { timestamp: number @@ -5867,11 +5822,6 @@ export type SessionNextTextDelta = { [key: string]: unknown } type: "session.next.text.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { timestamp: number @@ -5888,11 +5838,6 @@ export type SessionNextReasoningDelta = { [key: string]: unknown } type: "session.next.reasoning.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { timestamp: number @@ -5909,11 +5854,6 @@ export type SessionNextToolInputDelta = { [key: string]: unknown } type: "session.next.tool.input.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { timestamp: number @@ -5930,11 +5870,6 @@ export type SessionNextCompactionDelta = { [key: string]: unknown } type: "session.next.compaction.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { timestamp: number @@ -5950,11 +5885,6 @@ export type MessagePartDelta = { [key: string]: unknown } type: "message.part.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -5971,11 +5901,6 @@ export type SessionDiff = { [key: string]: unknown } type: "session.diff" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -5989,11 +5914,6 @@ export type SessionError = { [key: string]: unknown } type: "session.error" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID?: string @@ -6015,11 +5935,6 @@ export type InstallationUpdated = { [key: string]: unknown } type: "installation.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { version: string @@ -6032,11 +5947,6 @@ export type InstallationUpdateAvailable = { [key: string]: unknown } type: "installation.update-available" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { version: string @@ -6049,11 +5959,6 @@ export type FileEdited = { [key: string]: unknown } type: "file.edited" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { file: string @@ -6066,11 +5971,6 @@ export type ReferenceUpdated = { [key: string]: unknown } type: "reference.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -6083,11 +5983,6 @@ export type PermissionV2Asked = { [key: string]: unknown } type: "permission.v2.asked" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6108,11 +6003,6 @@ export type PermissionV2Replied = { [key: string]: unknown } type: "permission.v2.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -6127,11 +6017,6 @@ export type PluginAdded = { [key: string]: unknown } type: "plugin.added" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6144,11 +6029,6 @@ export type ProjectDirectoriesUpdated = { [key: string]: unknown } type: "project.directories.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { projectID: string @@ -6161,11 +6041,6 @@ export type CommandUpdated = { [key: string]: unknown } type: "command.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -6178,11 +6053,6 @@ export type SkillUpdated = { [key: string]: unknown } type: "skill.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -6195,11 +6065,6 @@ export type FileWatcherUpdated = { [key: string]: unknown } type: "file.watcher.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { file: string @@ -6213,11 +6078,6 @@ export type PtyCreated = { [key: string]: unknown } type: "pty.created" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { info: Pty @@ -6230,11 +6090,6 @@ export type PtyUpdated = { [key: string]: unknown } type: "pty.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { info: Pty @@ -6247,11 +6102,6 @@ export type PtyExited = { [key: string]: unknown } type: "pty.exited" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6265,11 +6115,6 @@ export type PtyDeleted = { [key: string]: unknown } type: "pty.deleted" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6282,11 +6127,6 @@ export type ShellCreated = { [key: string]: unknown } type: "shell.created" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { info: Shell1 @@ -6299,11 +6139,6 @@ export type ShellExited = { [key: string]: unknown } type: "shell.exited" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6318,11 +6153,6 @@ export type ShellDeleted = { [key: string]: unknown } type: "shell.deleted" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6335,11 +6165,6 @@ export type QuestionV2Asked = { [key: string]: unknown } type: "question.v2.asked" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6358,11 +6183,6 @@ export type QuestionV2Replied = { [key: string]: unknown } type: "question.v2.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -6377,11 +6197,6 @@ export type QuestionV2Rejected = { [key: string]: unknown } type: "question.v2.rejected" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -6425,11 +6240,6 @@ export type FormCreated = { [key: string]: unknown } type: "form.created" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { form: FormFormInfo | FormUrlInfo @@ -6444,11 +6254,6 @@ export type FormReplied = { [key: string]: unknown } type: "form.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6463,11 +6268,6 @@ export type FormCancelled = { [key: string]: unknown } type: "form.cancelled" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6481,11 +6281,6 @@ export type TodoUpdated = { [key: string]: unknown } type: "todo.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -6499,11 +6294,6 @@ export type LspUpdated = { [key: string]: unknown } type: "lsp.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -6516,11 +6306,6 @@ export type PermissionAsked = { [key: string]: unknown } type: "permission.asked" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6544,11 +6329,6 @@ export type PermissionReplied = { [key: string]: unknown } type: "permission.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -6563,11 +6343,6 @@ export type TuiPromptAppend = { [key: string]: unknown } type: "tui.prompt.append" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { text: string @@ -6580,11 +6355,6 @@ export type TuiCommandExecute = { [key: string]: unknown } type: "tui.command.execute" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { command: @@ -6615,11 +6385,6 @@ export type TuiToastShow = { [key: string]: unknown } type: "tui.toast.show" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { title?: string @@ -6635,11 +6400,6 @@ export type TuiSessionSelect = { [key: string]: unknown } type: "tui.session.select" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { /** @@ -6655,11 +6415,6 @@ export type McpToolsChanged = { [key: string]: unknown } type: "mcp.tools.changed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { server: string @@ -6672,11 +6427,6 @@ export type McpBrowserOpenFailed = { [key: string]: unknown } type: "mcp.browser.open.failed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { mcpName: string @@ -6690,11 +6440,6 @@ export type McpStatusChanged = { [key: string]: unknown } type: "mcp.status.changed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { server: string @@ -6707,11 +6452,6 @@ export type CommandExecuted = { [key: string]: unknown } type: "command.executed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { name: string @@ -6727,11 +6467,6 @@ export type ProjectUpdated = { [key: string]: unknown } type: "project.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6751,11 +6486,6 @@ export type SessionIdle = { [key: string]: unknown } type: "session.idle" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -6768,11 +6498,6 @@ export type QuestionAsked = { [key: string]: unknown } type: "question.asked" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { id: string @@ -6791,11 +6516,6 @@ export type SessionCompacted = { [key: string]: unknown } type: "session.compacted" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { sessionID: string @@ -6808,11 +6528,6 @@ export type VcsBranchUpdated = { [key: string]: unknown } type: "vcs.branch.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { branch?: string @@ -6825,11 +6540,6 @@ export type WorkspaceReady = { [key: string]: unknown } type: "workspace.ready" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { name: string @@ -6842,11 +6552,6 @@ export type WorkspaceFailed = { [key: string]: unknown } type: "workspace.failed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { message: string @@ -6859,11 +6564,6 @@ export type WorkspaceStatus = { [key: string]: unknown } type: "workspace.status" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { workspaceID: string @@ -6877,11 +6577,6 @@ export type WorktreeReady = { [key: string]: unknown } type: "worktree.ready" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { name: string @@ -6895,11 +6590,6 @@ export type WorktreeFailed = { [key: string]: unknown } type: "worktree.failed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { message: string @@ -6912,11 +6602,6 @@ export type ServerConnected = { [key: string]: unknown } type: "server.connected" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -6929,11 +6614,6 @@ export type GlobalDisposed = { [key: string]: unknown } type: "global.disposed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef data: { [key: string]: unknown @@ -8627,7 +8307,7 @@ export type SessionNextAgentSwitched2 = { [key: string]: unknown } type: "session.next.agent.switched" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8647,7 +8327,7 @@ export type SessionNextModelSwitched2 = { [key: string]: unknown } type: "session.next.model.switched" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8667,7 +8347,7 @@ export type SessionNextMoved2 = { [key: string]: unknown } type: "session.next.moved" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8687,7 +8367,7 @@ export type SessionNextRenamed2 = { [key: string]: unknown } type: "session.next.renamed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8706,7 +8386,7 @@ export type SessionNextForked2 = { [key: string]: unknown } type: "session.next.forked" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8726,7 +8406,7 @@ export type SessionNextPrompted2 = { [key: string]: unknown } type: "session.next.prompted" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8747,7 +8427,7 @@ export type SessionNextPromptAdmitted2 = { [key: string]: unknown } type: "session.next.prompt.admitted" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8768,7 +8448,7 @@ export type SessionNextContextUpdated2 = { [key: string]: unknown } type: "session.next.context.updated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8788,7 +8468,7 @@ export type SessionNextSynthetic2 = { [key: string]: unknown } type: "session.next.synthetic" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8812,7 +8492,7 @@ export type SessionNextSkillActivated2 = { [key: string]: unknown } type: "session.next.skill.activated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8833,7 +8513,7 @@ export type SessionNextShellStarted2 = { [key: string]: unknown } type: "session.next.shell.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8854,7 +8534,7 @@ export type SessionNextShellEnded2 = { [key: string]: unknown } type: "session.next.shell.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8874,7 +8554,7 @@ export type SessionNextStepStarted2 = { [key: string]: unknown } type: "session.next.step.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8896,7 +8576,7 @@ export type SessionNextStepEnded2 = { [key: string]: unknown } type: "session.next.step.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8928,7 +8608,7 @@ export type SessionNextStepFailed2 = { [key: string]: unknown } type: "session.next.step.failed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8948,7 +8628,7 @@ export type SessionNextTextStarted2 = { [key: string]: unknown } type: "session.next.text.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8968,7 +8648,7 @@ export type SessionNextTextEnded2 = { [key: string]: unknown } type: "session.next.text.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -8983,13 +8663,68 @@ export type SessionNextTextEnded2 = { } } +export type LlmProviderMetadata3 = { + [key: string]: { + [key: string]: unknown + } +} + +export type SessionNextReasoningStarted2 = { + id: string + metadata?: { + [key: string]: unknown + } + type: "session.next.reasoning.started" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef2 + data: { + timestamp: number + sessionID: string + assistantMessageID: string + reasoningID: string + providerMetadata?: LlmProviderMetadata3 + } +} + +export type LlmProviderMetadata4 = { + [key: string]: { + [key: string]: unknown + } +} + +export type SessionNextReasoningEnded2 = { + id: string + metadata?: { + [key: string]: unknown + } + type: "session.next.reasoning.ended" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef2 + data: { + timestamp: number + sessionID: string + assistantMessageID: string + reasoningID: string + text: string + providerMetadata?: LlmProviderMetadata4 + } +} + export type SessionNextToolInputStarted2 = { id: string metadata?: { [key: string]: unknown } type: "session.next.tool.input.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9010,7 +8745,7 @@ export type SessionNextToolInputEnded2 = { [key: string]: unknown } type: "session.next.tool.input.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9025,7 +8760,7 @@ export type SessionNextToolInputEnded2 = { } } -export type LlmProviderMetadata3 = { +export type LlmProviderMetadata5 = { [key: string]: { [key: string]: unknown } @@ -9037,7 +8772,7 @@ export type SessionNextToolCalled2 = { [key: string]: unknown } type: "session.next.tool.called" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9054,7 +8789,7 @@ export type SessionNextToolCalled2 = { } provider: { executed: boolean - metadata?: LlmProviderMetadata3 + metadata?: LlmProviderMetadata5 } } } @@ -9065,7 +8800,7 @@ export type SessionNextToolProgress2 = { [key: string]: unknown } type: "session.next.tool.progress" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9083,7 +8818,7 @@ export type SessionNextToolProgress2 = { } } -export type LlmProviderMetadata4 = { +export type LlmProviderMetadata6 = { [key: string]: { [key: string]: unknown } @@ -9095,7 +8830,7 @@ export type SessionNextToolSuccess2 = { [key: string]: unknown } type: "session.next.tool.success" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9114,12 +8849,12 @@ export type SessionNextToolSuccess2 = { result?: unknown provider: { executed: boolean - metadata?: LlmProviderMetadata4 + metadata?: LlmProviderMetadata6 } } } -export type LlmProviderMetadata5 = { +export type LlmProviderMetadata7 = { [key: string]: { [key: string]: unknown } @@ -9131,7 +8866,7 @@ export type SessionNextToolFailed2 = { [key: string]: unknown } type: "session.next.tool.failed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9146,66 +8881,11 @@ export type SessionNextToolFailed2 = { result?: unknown provider: { executed: boolean - metadata?: LlmProviderMetadata5 + metadata?: LlmProviderMetadata7 } } } -export type LlmProviderMetadata6 = { - [key: string]: { - [key: string]: unknown - } -} - -export type SessionNextReasoningStarted2 = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.reasoning.started" - durable?: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef2 - data: { - timestamp: number - sessionID: string - assistantMessageID: string - reasoningID: string - providerMetadata?: LlmProviderMetadata6 - } -} - -export type LlmProviderMetadata7 = { - [key: string]: { - [key: string]: unknown - } -} - -export type SessionNextReasoningEnded2 = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.reasoning.ended" - durable?: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef2 - data: { - timestamp: number - sessionID: string - assistantMessageID: string - reasoningID: string - text: string - providerMetadata?: LlmProviderMetadata7 - } -} - export type SessionNextRetryError2 = { message: string statusCode?: number @@ -9225,7 +8905,7 @@ export type SessionNextRetried2 = { [key: string]: unknown } type: "session.next.retried" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9245,7 +8925,7 @@ export type SessionNextCompactionStarted2 = { [key: string]: unknown } type: "session.next.compaction.started" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9265,7 +8945,7 @@ export type SessionNextCompactionEnded2 = { [key: string]: unknown } type: "session.next.compaction.ended" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9287,7 +8967,7 @@ export type SessionNextRevertStaged2 = { [key: string]: unknown } type: "session.next.revert.staged" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9306,7 +8986,7 @@ export type SessionNextRevertCleared2 = { [key: string]: unknown } type: "session.next.revert.cleared" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9324,7 +9004,7 @@ export type SessionNextRevertCommitted2 = { [key: string]: unknown } type: "session.next.revert.committed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -9355,14 +9035,14 @@ export type SessionDurableEventV2 = | SessionNextStepFailed2 | SessionNextTextStarted2 | SessionNextTextEnded2 + | SessionNextReasoningStarted2 + | SessionNextReasoningEnded2 | SessionNextToolInputStarted2 | SessionNextToolInputEnded2 | SessionNextToolCalled2 | SessionNextToolProgress2 | SessionNextToolSuccess2 | SessionNextToolFailed2 - | SessionNextReasoningStarted2 - | SessionNextReasoningEnded2 | SessionNextRetried2 | SessionNextCompactionStarted2 | SessionNextCompactionEnded2 @@ -9889,11 +9569,6 @@ export type ModelsDevRefreshed2 = { [key: string]: unknown } type: "models-dev.refreshed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: | { @@ -9908,11 +9583,6 @@ export type IntegrationUpdated2 = { [key: string]: unknown } type: "integration.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: | { @@ -9927,11 +9597,6 @@ export type IntegrationConnectionUpdated2 = { [key: string]: unknown } type: "integration.connection.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { integrationID: string @@ -9944,11 +9609,6 @@ export type CatalogUpdated2 = { [key: string]: unknown } type: "catalog.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: | { @@ -9963,11 +9623,6 @@ export type AgentUpdated2 = { [key: string]: unknown } type: "agent.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: | { @@ -10053,7 +9708,7 @@ export type SessionCreated2 = { [key: string]: unknown } type: "session.created" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -10071,7 +9726,7 @@ export type SessionUpdated2 = { [key: string]: unknown } type: "session.updated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -10089,7 +9744,7 @@ export type SessionDeleted2 = { [key: string]: unknown } type: "session.deleted" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -10263,7 +9918,7 @@ export type MessageUpdated2 = { [key: string]: unknown } type: "message.updated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -10281,7 +9936,7 @@ export type MessageRemoved2 = { [key: string]: unknown } type: "message.removed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -10562,7 +10217,7 @@ export type MessagePartUpdated2 = { [key: string]: unknown } type: "message.part.updated" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -10581,7 +10236,7 @@ export type MessagePartRemoved2 = { [key: string]: unknown } type: "message.part.removed" - durable?: { + durable: { aggregateID: string seq: number version: number @@ -10600,11 +10255,6 @@ export type SessionNextExecutionSettled2 = { [key: string]: unknown } type: "session.next.execution.settled" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { timestamp: number @@ -10620,11 +10270,6 @@ export type SessionNextTextDelta2 = { [key: string]: unknown } type: "session.next.text.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { timestamp: number @@ -10641,11 +10286,6 @@ export type SessionNextReasoningDelta2 = { [key: string]: unknown } type: "session.next.reasoning.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { timestamp: number @@ -10662,11 +10302,6 @@ export type SessionNextToolInputDelta2 = { [key: string]: unknown } type: "session.next.tool.input.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { timestamp: number @@ -10683,11 +10318,6 @@ export type SessionNextCompactionDelta2 = { [key: string]: unknown } type: "session.next.compaction.delta" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { timestamp: number @@ -10703,11 +10333,6 @@ export type FileEdited2 = { [key: string]: unknown } type: "file.edited" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { file: string @@ -10720,11 +10345,6 @@ export type ReferenceUpdated2 = { [key: string]: unknown } type: "reference.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: | { @@ -10739,11 +10359,6 @@ export type PermissionV2Asked2 = { [key: string]: unknown } type: "permission.v2.asked" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -10764,11 +10379,6 @@ export type PermissionV2Replied2 = { [key: string]: unknown } type: "permission.v2.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -10783,11 +10393,6 @@ export type PluginAdded2 = { [key: string]: unknown } type: "plugin.added" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -10800,11 +10405,6 @@ export type ProjectDirectoriesUpdated2 = { [key: string]: unknown } type: "project.directories.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { projectID: string @@ -10817,11 +10417,6 @@ export type CommandUpdated2 = { [key: string]: unknown } type: "command.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: | { @@ -10836,11 +10431,6 @@ export type SkillUpdated2 = { [key: string]: unknown } type: "skill.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: | { @@ -10855,11 +10445,6 @@ export type FileWatcherUpdated2 = { [key: string]: unknown } type: "file.watcher.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { file: string @@ -10884,11 +10469,6 @@ export type PtyCreated2 = { [key: string]: unknown } type: "pty.created" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { info: PtyV2 @@ -10901,11 +10481,6 @@ export type PtyUpdated2 = { [key: string]: unknown } type: "pty.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { info: PtyV2 @@ -10918,11 +10493,6 @@ export type PtyExited2 = { [key: string]: unknown } type: "pty.exited" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -10936,11 +10506,6 @@ export type PtyDeleted2 = { [key: string]: unknown } type: "pty.deleted" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -10971,11 +10536,6 @@ export type ShellCreated2 = { [key: string]: unknown } type: "shell.created" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { info: ShellV2 @@ -10988,11 +10548,6 @@ export type ShellExited2 = { [key: string]: unknown } type: "shell.exited" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -11007,11 +10562,6 @@ export type ShellDeleted2 = { [key: string]: unknown } type: "shell.deleted" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -11057,11 +10607,6 @@ export type QuestionV2Asked2 = { [key: string]: unknown } type: "question.v2.asked" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -11082,11 +10627,6 @@ export type QuestionV2Replied2 = { [key: string]: unknown } type: "question.v2.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -11101,11 +10641,6 @@ export type QuestionV2Rejected2 = { [key: string]: unknown } type: "question.v2.rejected" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -11212,11 +10747,6 @@ export type FormCreated2 = { [key: string]: unknown } type: "form.created" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { form: FormFormInfo1 | FormUrlInfo1 @@ -11235,11 +10765,6 @@ export type FormReplied2 = { [key: string]: unknown } type: "form.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -11254,11 +10779,6 @@ export type FormCancelled2 = { [key: string]: unknown } type: "form.cancelled" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -11287,11 +10807,6 @@ export type TodoUpdated2 = { [key: string]: unknown } type: "todo.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -11327,11 +10842,6 @@ export type SessionStatusV22 = { [key: string]: unknown } type: "session.status" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -11345,11 +10855,6 @@ export type SessionIdle2 = { [key: string]: unknown } type: "session.idle" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -11362,11 +10867,6 @@ export type TuiPromptAppend2 = { [key: string]: unknown } type: "tui.prompt.append" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { text: string @@ -11379,11 +10879,6 @@ export type TuiCommandExecute2 = { [key: string]: unknown } type: "tui.command.execute" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { command: @@ -11414,11 +10909,6 @@ export type TuiToastShow2 = { [key: string]: unknown } type: "tui.toast.show" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { title?: string @@ -11434,11 +10924,6 @@ export type TuiSessionSelect2 = { [key: string]: unknown } type: "tui.session.select" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { /** @@ -11454,11 +10939,6 @@ export type InstallationUpdated2 = { [key: string]: unknown } type: "installation.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { version: string @@ -11471,11 +10951,6 @@ export type InstallationUpdateAvailable2 = { [key: string]: unknown } type: "installation.update-available" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { version: string @@ -11488,11 +10963,6 @@ export type VcsBranchUpdated2 = { [key: string]: unknown } type: "vcs.branch.updated" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { branch?: string @@ -11505,11 +10975,6 @@ export type McpStatusChanged2 = { [key: string]: unknown } type: "mcp.status.changed" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { server: string @@ -11522,11 +10987,6 @@ export type PermissionAsked2 = { [key: string]: unknown } type: "permission.asked" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -11550,11 +11010,6 @@ export type PermissionReplied2 = { [key: string]: unknown } type: "permission.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -11608,11 +11063,6 @@ export type QuestionAsked2 = { [key: string]: unknown } type: "question.asked" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { id: string @@ -11633,11 +11083,6 @@ export type QuestionRepliedV2 = { [key: string]: unknown } type: "question.replied" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -11652,11 +11097,6 @@ export type QuestionRejectedV2 = { [key: string]: unknown } type: "question.rejected" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID: string @@ -11670,11 +11110,6 @@ export type SessionError2 = { [key: string]: unknown } type: "session.error" - durable?: { - aggregateID: string - seq: number - version: number - } location?: LocationRef2 data: { sessionID?: string | null @@ -11696,11 +11131,6 @@ export type V2EventServerConnected = { metadata?: { [key: string]: unknown } | null - durable?: { - aggregateID: string - seq: number - version: number - } | null location?: LocationRef2 | null type: "server.connected" data: diff --git a/packages/tui/test/cli/cmd/tui/notifications.test.ts b/packages/tui/test/cli/cmd/tui/notifications.test.ts index 1a19f7be25..a914b34dbc 100644 --- a/packages/tui/test/cli/cmd/tui/notifications.test.ts +++ b/packages/tui/test/cli/cmd/tui/notifications.test.ts @@ -33,10 +33,7 @@ async function setup() { }, }, event: { - on: ( - type: Type, - handler: (event: Extract) => void, - ) => { + on: (type: Type, handler: (event: Extract) => void) => { const list = handlers.get(type) ?? [] const wrapped = handler as (event: V2Event) => void list.push(wrapped) @@ -86,10 +83,15 @@ function permission(id: string, sessionID = "session"): PermissionRequest { } } +function durable(sessionID: string) { + return { aggregateID: sessionID, seq: 0, version: 1 } +} + function stepStarted(id: string, sessionID = "session"): V2Event { return { id, type: "session.next.step.started", + durable: durable(sessionID), data: { sessionID, assistantMessageID: `msg_${id}`, @@ -104,6 +106,7 @@ function stepEnded(id: string, sessionID = "session", finish = "stop"): V2Event return { id, type: "session.next.step.ended", + durable: durable(sessionID), data: { sessionID, assistantMessageID: `msg_${id}`, @@ -119,6 +122,7 @@ function stepFailed(id: string, sessionID = "session"): V2Event { return { id, type: "session.next.step.failed", + durable: durable(sessionID), data: { sessionID, assistantMessageID: `msg_${id}`, diff --git a/packages/tui/test/cli/tui/data.test.tsx b/packages/tui/test/cli/tui/data.test.tsx index fc7af6c8ed..b2bacfc0dd 100644 --- a/packages/tui/test/cli/tui/data.test.tsx +++ b/packages/tui/test/cli/tui/data.test.tsx @@ -21,6 +21,10 @@ function emitEvent(events: ReturnType, event: V2Event) events.emit({ ...event, location: { directory } }) } +function durable(sessionID: string, seq = 0, version = 1) { + return { aggregateID: sessionID, seq, version } +} + test("refreshes resources into reactive getters", async () => { const events = createEventStream() const location = { @@ -261,6 +265,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_started", type: "session.next.step.started", + durable: durable("session-live"), data: { sessionID: "session-live", assistantMessageID: "message-live", @@ -274,6 +279,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_ended", type: "session.next.step.ended", + durable: durable("session-live", 1, 2), data: { sessionID: "session-live", assistantMessageID: "message-live", @@ -303,6 +309,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_failed_step_started", type: "session.next.step.started", + durable: durable("session-failed"), data: { sessionID: "session-failed", assistantMessageID: "message-failed", @@ -316,6 +323,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_failed", type: "session.next.step.failed", + durable: durable("session-failed", 1, 2), data: { sessionID: "session-failed", assistantMessageID: "message-failed", @@ -548,7 +556,10 @@ test("keeps shell state scoped to location", async () => { if (url.pathname !== "/api/shell") return const requestDirectory = url.searchParams.get("location[directory]") return json({ - location: { directory: requestDirectory ?? directory, project: { id: "proj_test", directory: requestDirectory ?? directory } }, + location: { + directory: requestDirectory ?? directory, + project: { id: "proj_test", directory: requestDirectory ?? directory }, + }, data: [ { id: requestDirectory === other ? "sh_other" : "sh_default", @@ -773,11 +784,13 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_agent_1", type: "session.next.agent.switched", + durable: durable("session-1"), data: { sessionID: "session-1", messageID: "msg_agent_1", timestamp: 0, agent: "build" }, }) emitEvent(events, { id: "evt_model_1", type: "session.next.model.switched", + durable: durable("session-1", 1), data: { sessionID: "session-1", messageID: "msg_model_1", @@ -788,6 +801,7 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_step_started_1", type: "session.next.step.started", + durable: durable("session-1", 2), data: { sessionID: "session-1", assistantMessageID: "msg_explicit_assistant_9", @@ -799,6 +813,7 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_input_1", type: "session.next.tool.input.started", + durable: durable("session-1", 3), data: { sessionID: "session-1", assistantMessageID: "msg_explicit_assistant_9", @@ -810,6 +825,7 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_called_1", type: "session.next.tool.called", + durable: durable("session-1", 4), data: { sessionID: "session-1", timestamp: 2, @@ -823,6 +839,7 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_failed_1", type: "session.next.tool.failed", + durable: durable("session-1", 5), data: { sessionID: "session-1", timestamp: 3, @@ -912,6 +929,7 @@ test("renders admitted prompts immediately with queued marker and clears when pr emitEvent(events, { id: "evt_admitted_1", type: "session.next.prompt.admitted", + durable: durable(sessionID), data: { sessionID, messageID, @@ -930,6 +948,7 @@ test("renders admitted prompts immediately with queued marker and clears when pr emitEvent(events, { id: "evt_prompted_1", type: "session.next.prompted", + durable: durable(sessionID, 1), data: { sessionID, messageID, @@ -989,6 +1008,7 @@ test("projects live context updates with their message ID", async () => { emitEvent(events, { id: "evt_context_1", type: "session.next.context.updated", + durable: durable("session-1"), data: { sessionID: "session-1", messageID: "msg_context_1", diff --git a/specs/v2/schema-changelog.md b/specs/v2/schema-changelog.md index 794db93c95..d526b5d8e7 100644 --- a/specs/v2/schema-changelog.md +++ b/specs/v2/schema-changelog.md @@ -1,5 +1,25 @@ # V2 Schema Changelog +## 2026-07-03: Require Durable Envelope On Durable Events + +- Make the wire `durable` envelope required on durable event definitions. +- Remove the `durable` envelope field from live-only event definitions. + +Compatibility: + +- No stored event row, database, or runtime publish behavior change; runtime already attaches the envelope only after durable commit/replay. +- Generated clients now model the existing invariant: durable events carry `durable`, live-only events do not. + +## 2026-07-03: Declare Event Durability At Definition Level + +- Add explicit `Event.durable(...)` and `Event.ephemeral(...)` definition constructors. +- Preserve the existing durable and live-only event classifications while deriving durable inventories from definition metadata instead of hand-maintained lists. + +Compatibility: + +- No wire payload, stored event row, database, or behavior change. +- Generated clients were regenerated from the unchanged public event schemas. + ## 2026-07-02: Rename Session Log Replay Marker - Rename the replay boundary marker from `log.caught_up` / `EventLog.CaughtUp` to `log.synced` / `EventLog.Synced`. From dd768e30e2c9c3e67f709132a7f7ca455816c7c2 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 12:36:46 -0400 Subject: [PATCH 09/82] refactor(client): namespace service exports and share the registration contract --- packages/cli/src/commands/handlers/api.ts | 3 +- packages/cli/src/commands/handlers/default.ts | 3 +- packages/cli/src/commands/handlers/serve.ts | 29 +++++----- packages/cli/src/services/service-config.ts | 2 +- packages/cli/src/tui.ts | 4 +- packages/client/src/effect/index.ts | 1 - packages/client/src/effect/service.ts | 54 +++++++++---------- packages/client/src/promise/index.ts | 1 - 8 files changed, 47 insertions(+), 50 deletions(-) diff --git a/packages/cli/src/commands/handlers/api.ts b/packages/cli/src/commands/handlers/api.ts index 82d273c25d..de4d1a2b87 100644 --- a/packages/cli/src/commands/handlers/api.ts +++ b/packages/cli/src/commands/handlers/api.ts @@ -4,7 +4,6 @@ import { Commands } from "../commands" import { Runtime } from "../../framework/runtime" import { Service } from "@opencode-ai/client/effect" import { ServiceConfig } from "../../services/service-config" -import type { Transport } from "@opencode-ai/client/effect" const methods = new Set(["delete", "get", "head", "options", "patch", "post", "put"]) @@ -61,7 +60,7 @@ export function rawRequest(input: readonly string[]) { } function resolveRequest( - transport: Transport, + transport: Service.Transport, input: readonly string[], params: Record, ) { diff --git a/packages/cli/src/commands/handlers/default.ts b/packages/cli/src/commands/handlers/default.ts index 98b0c9b3c9..32e542e634 100644 --- a/packages/cli/src/commands/handlers/default.ts +++ b/packages/cli/src/commands/handlers/default.ts @@ -3,7 +3,6 @@ import { Commands } from "../commands" import { Runtime } from "../../framework/runtime" import { Effect, Option } from "effect" import { Service } from "@opencode-ai/client/effect" -import type { Transport } from "@opencode-ai/client/effect" import { ServiceConfig } from "../../services/service-config" import { Standalone } from "../../services/standalone" import { Updater } from "../../services/updater" @@ -23,7 +22,7 @@ export default Runtime.handler(Commands, (input) => return { url: server, headers: password ? { authorization: "Basic " + btoa("opencode:" + password) } : undefined, - } satisfies Transport + } satisfies Service.Transport } if (input.standalone) return yield* Standalone.transport() const options = yield* ServiceConfig.options() diff --git a/packages/cli/src/commands/handlers/serve.ts b/packages/cli/src/commands/handlers/serve.ts index 80cf6cba9f..d6b6938ee3 100644 --- a/packages/cli/src/commands/handlers/serve.ts +++ b/packages/cli/src/commands/handlers/serve.ts @@ -14,6 +14,7 @@ import { InstallationVersion } from "@opencode-ai/core/installation/version" import { createOpencodeClient } from "@opencode-ai/sdk/v2/client" import { Commands } from "../commands" import { Runtime } from "../../framework/runtime" +import { Service } from "@opencode-ai/client/effect" import { ServiceConfig } from "../../services/service-config" import { Updater } from "../../services/updater" import { randomBytes, randomUUID } from "crypto" @@ -63,8 +64,11 @@ export default Runtime.handler( // not a startup lock: the atomic rename elects the latest writer, the watcher // self-evicts losers, and the finalizer id-guard keeps an exiting server from // deleting its successor's registration. -const RegistrationId = Schema.Struct({ id: Schema.optional(Schema.String) }) -const decodeRegistrationId = Schema.decodeUnknownEffect(Schema.fromJsonString(RegistrationId)) +// Written and read through Service.Info so the file the server registers is +// provably the contract clients discover with. +const infoJson = Schema.fromJsonString(Service.Info) +const encodeInfo = Schema.encodeEffect(infoJson) +const decodeInfo = Schema.decodeUnknownEffect(infoJson) const register = Effect.fnUntraced(function* (address: HttpServer.Address) { const fs = yield* FileSystem.FileSystem @@ -73,20 +77,17 @@ const register = Effect.fnUntraced(function* (address: HttpServer.Address) { const secret = yield* ServiceConfig.password() const temp = file + "." + id + ".tmp" yield* fs.makeDirectory(path.dirname(file), { recursive: true }) - yield* fs.writeFileString( - temp, - JSON.stringify({ - id, - version: InstallationVersion, - url: HttpServer.formatAddress(address), - pid: process.pid, - password: secret, - }), - { mode: 0o600 }, - ) + const encoded = yield* encodeInfo({ + id, + version: InstallationVersion, + url: HttpServer.formatAddress(address), + pid: process.pid, + password: secret, + }) + yield* fs.writeFileString(temp, encoded, { mode: 0o600 }) yield* fs.rename(temp, file) const currentID = fs.readFileString(file).pipe( - Effect.flatMap(decodeRegistrationId), + Effect.flatMap(decodeInfo), Effect.map((info) => info.id), Effect.orElseSucceed(() => undefined), ) diff --git a/packages/cli/src/services/service-config.ts b/packages/cli/src/services/service-config.ts index 356472e359..ecdd5bf19a 100644 --- a/packages/cli/src/services/service-config.ts +++ b/packages/cli/src/services/service-config.ts @@ -5,7 +5,7 @@ import { Effect, FileSystem, Schema } from "effect" import { randomBytes } from "crypto" import path from "path" -// The CLI's service configuration file, plus the ServiceOptions binding that +// The CLI's service configuration file, plus the Service.Options binding that // points the client package's service operations at this CLI: which // registration file (by channel), which version, and how to spawn opencode. diff --git a/packages/cli/src/tui.ts b/packages/cli/src/tui.ts index 577a7be493..a535309d42 100644 --- a/packages/cli/src/tui.ts +++ b/packages/cli/src/tui.ts @@ -5,11 +5,11 @@ import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { Global } from "@opencode-ai/core/global" import { loadBuiltinPlugins } from "@opencode-ai/tui/builtins" import { OpenCode } from "@opencode-ai/client/promise" -import type { Transport } from "@opencode-ai/client/effect" +import type { Service } from "@opencode-ai/client/effect" import { createOpencodeClient } from "@opencode-ai/sdk/v2/client" import type { Args } from "@opencode-ai/tui/context/args" -export function runTui(transport: Transport, args: Args, discover?: () => Promise) { +export function runTui(transport: Service.Transport, args: Args, discover?: () => Promise) { const config = TuiConfig.resolve({}, { terminalSuspend: false }) let disposeSlots: (() => void) | undefined return Effect.gen(function* () { diff --git a/packages/client/src/effect/index.ts b/packages/client/src/effect/index.ts index 1a69a358cc..23e6d55c74 100644 --- a/packages/client/src/effect/index.ts +++ b/packages/client/src/effect/index.ts @@ -2,7 +2,6 @@ // Core or Server. Preserve these datatype exports so internal model reorganizations do not require caller migrations. export * from "./generated/index" export { Service } from "./service.js" -export type { Transport, ServiceOptions } from "./service.js" export { Agent } from "@opencode-ai/schema/agent" export { Command } from "@opencode-ai/schema/command" export { Credential } from "@opencode-ai/schema/credential" diff --git a/packages/client/src/effect/service.ts b/packages/client/src/effect/service.ts index 93cbdd03fc..ca428f5aa6 100644 --- a/packages/client/src/effect/service.ts +++ b/packages/client/src/effect/service.ts @@ -16,7 +16,7 @@ export type Transport = { readonly headers?: RequestInit["headers"] } -export type ServiceOptions = { +export type Options = { // Absolute path to the service registration file. Defaults to // opencode/service.json in the XDG state directory. readonly file?: string @@ -30,21 +30,21 @@ export type ServiceOptions = { // Read-only lookup: registration file plus health check and version gate. // Never spawns; escalation to start() is the caller's policy. -export const discover = Effect.fn("service.discover")(function* (options: ServiceOptions = {}) { - const registration = yield* read(options.file) - if (registration === undefined) return undefined - if (options.version !== undefined && registration.version !== options.version) return undefined - const found = yield* probe(registration) +export const discover = Effect.fn("service.discover")(function* (options: Options = {}) { + const info = yield* read(options.file) + if (info === undefined) return undefined + if (options.version !== undefined && info.version !== options.version) return undefined + const found = yield* probe(info) return found?.transport }) // Idempotent ensure-running: reuses a healthy compatible server, replaces a // version-mismatched one, and otherwise spawns the service command detached. -export const start = Effect.fn("service.start")(function* (options: ServiceOptions = {}) { +export const start = Effect.fn("service.start")(function* (options: Options = {}) { const compatible = yield* discover(options) if (compatible !== undefined) return compatible const mismatched = yield* find(options) - if (mismatched !== undefined) yield* kill(mismatched.registration, options).pipe(Effect.ignore) + if (mismatched !== undefined) yield* kill(mismatched.info, options).pipe(Effect.ignore) const [command, ...args] = options.command ?? ["opencode", "serve", "--service"] if (command === undefined) return yield* Effect.fail(new Error("Missing service command")) @@ -64,10 +64,10 @@ export const start = Effect.fn("service.start")(function* (options: ServiceOptio ) }) -export const stop = Effect.fn("service.stop")(function* (options: ServiceOptions = {}) { +export const stop = Effect.fn("service.stop")(function* (options: Options = {}) { const fs = yield* FileSystem.FileSystem const existing = yield* find(options) - if (existing !== undefined) yield* kill(existing.registration, options) + if (existing !== undefined) yield* kill(existing.info, options) yield* fs.remove(options.file ?? fallback()).pipe(Effect.ignore) }) @@ -80,18 +80,18 @@ function auth(password: string): RequestInit["headers"] { return { authorization: "Basic " + btoa("opencode:" + password) } } -const Registration = Schema.Struct({ +export const Info = Schema.Struct({ id: Schema.optional(Schema.String), version: Schema.optional(Schema.String), url: Schema.String, pid: Schema.Int.check(Schema.isGreaterThan(0)), password: Schema.optional(Schema.String), }) -type Registration = typeof Registration.Type +export type Info = typeof Info.Type -const decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Registration)) +const decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Info)) -// A missing or corrupt file means no valid registration; callers treat both +// A missing or corrupt file means no valid info; callers treat both // the same (the registering server self-evicts, clients rediscover). const read = Effect.fnUntraced(function* (file?: string) { const fs = yield* FileSystem.FileSystem @@ -101,14 +101,14 @@ const read = Effect.fnUntraced(function* (file?: string) { }) type LocalService = { - readonly registration: Registration + readonly info: Info readonly transport: Transport } -const probe = Effect.fnUntraced(function* (registration: Registration) { - const headers = registration.password === undefined ? undefined : auth(registration.password) +const probe = Effect.fnUntraced(function* (info: Info) { + const headers = info.password === undefined ? undefined : auth(info.password) const healthy = yield* Effect.tryPromise(() => - fetch(new URL("/api/health", registration.url), { + fetch(new URL("/api/health", info.url), { headers, signal: AbortSignal.timeout(2_000), }), @@ -117,15 +117,15 @@ const probe = Effect.fnUntraced(function* (registration: Registration) { Effect.orElseSucceed(() => false), ) if (!healthy) return undefined - return { registration, transport: { url: registration.url, headers } } satisfies LocalService + return { info, transport: { url: info.url, headers } } satisfies LocalService }) // Health-checked lookup without the version gate: lifecycle operations must be // able to see (and replace or stop) a server from a different version. -const find = Effect.fnUntraced(function* (options: ServiceOptions) { - const registration = yield* read(options.file) - if (registration === undefined) return undefined - return yield* probe(registration) +const find = Effect.fnUntraced(function* (options: Options) { + const info = yield* read(options.file) + if (info === undefined) return undefined + return yield* probe(info) }) // 50ms cadence bounded at ~5s, shared by stop escalation and start readiness. @@ -142,22 +142,22 @@ const stopped = Effect.fnUntraced(function* (pid: number) { return yield* Effect.fail(new Error(`Server process ${pid} is still running`)) }) -function same(left: Registration, right: Registration) { +function same(left: Info, right: Info) { return left.id === right.id && left.version === right.version && left.url === right.url && left.pid === right.pid } -const kill = Effect.fnUntraced(function* (info: Registration, options: ServiceOptions) { +const kill = Effect.fnUntraced(function* (info: Info, options: Options) { // A stale registration may point at a PID that has since been reused by // another process. Only signal the PID after authenticating the server. const current = yield* find(options) - if (current === undefined || !same(current.registration, info)) return + if (current === undefined || !same(current.info, info)) return yield* signal(info.pid, "SIGTERM") const done = yield* stopped(info.pid).pipe(Effect.retry(poll), Effect.option) if (Option.isSome(done)) return const latest = yield* find(options) - if (latest === undefined || !same(latest.registration, info)) return + if (latest === undefined || !same(latest.info, info)) return yield* signal(info.pid, "SIGKILL") yield* stopped(info.pid).pipe(Effect.retry(poll)) }) diff --git a/packages/client/src/promise/index.ts b/packages/client/src/promise/index.ts index 61bdcdf888..e9e848b160 100644 --- a/packages/client/src/promise/index.ts +++ b/packages/client/src/promise/index.ts @@ -1,4 +1,3 @@ export * from "./generated/index" -export type { Transport } from "../effect/service.js" export type { EventSubscribeOutput as OpenCodeEvent } from "./generated/types" export type OpenCodeClient = ReturnType From 6f47459c68cb6db4e9df0afa431bfad968bc2e1c Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 12:42:09 -0400 Subject: [PATCH 10/82] chore: update lockfile --- bun.lock | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/bun.lock b/bun.lock index be72ef8802..5eca1724f1 100644 --- a/bun.lock +++ b/bun.lock @@ -126,6 +126,7 @@ "@opencode-ai/schema": "workspace:*", }, "devDependencies": { + "@effect/platform-node": "catalog:", "@opencode-ai/core": "workspace:*", "@opencode-ai/httpapi-codegen": "workspace:*", "@opencode-ai/server": "workspace:*", @@ -597,7 +598,6 @@ "@octokit/rest": "catalog:", "@openauthjs/openauth": "catalog:", "@opencode-ai/client": "workspace:*", - "@opencode-ai/codemode": "workspace:*", "@opencode-ai/llm": "workspace:*", "@opencode-ai/plugin": "workspace:*", "@opencode-ai/protocol": "workspace:*", @@ -7078,8 +7078,6 @@ "opencode-gitlab-auth/open/wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], - "openid-client/lru-cache/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], - "p-locate/p-limit/yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], "pkg-dir/find-up/locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="], From aad8d90dd182c43b1c06e670c00d02233e9c160c Mon Sep 17 00:00:00 2001 From: James Long Date: Fri, 3 Jul 2026 13:25:38 -0400 Subject: [PATCH 11/82] refactor(core): move path resolve into fs service (#35201) --- packages/core/src/fs-util.ts | 10 ++++++++++ packages/core/src/instruction-context.ts | 24 ++++++++++++----------- packages/core/src/project/copy.ts | 2 +- packages/core/src/session/instructions.ts | 2 +- packages/core/src/tool/read.ts | 6 +++--- packages/core/src/tool/shell.ts | 14 ++++++++----- 6 files changed, 37 insertions(+), 21 deletions(-) diff --git a/packages/core/src/fs-util.ts b/packages/core/src/fs-util.ts index ff71477d70..124ac6d702 100644 --- a/packages/core/src/fs-util.ts +++ b/packages/core/src/fs-util.ts @@ -38,6 +38,7 @@ export namespace FSUtil { readonly ensureDir: (path: string) => Effect.Effect readonly writeWithDirs: (path: string, content: string | Uint8Array, mode?: number) => Effect.Effect readonly readDirectoryEntries: (path: string) => Effect.Effect + readonly resolve: (path: string) => Effect.Effect readonly findUp: (target: string, start: string, stop?: string) => Effect.Effect readonly up: (options: { targets: string[]; start: string; stop?: string }) => Effect.Effect readonly globUp: (pattern: string, start: string, stop?: string) => Effect.Effect @@ -89,6 +90,14 @@ export namespace FSUtil { }) }) + const resolve = Effect.fn("FileSystem.resolve")(function* (path: string) { + const resolved = pathResolve(windowsPath(path)) + return yield* fs.realPath(resolved).pipe( + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(resolved)), + Effect.orDie, + ) + }) + const readJson = Effect.fn("FileSystem.readJson")(function* (path: string) { const text = yield* fs.readFileString(path) return yield* Effect.try({ @@ -187,6 +196,7 @@ export namespace FSUtil { isDir, isFile, readDirectoryEntries, + resolve, readJson, writeJson, ensureDir, diff --git a/packages/core/src/instruction-context.ts b/packages/core/src/instruction-context.ts index 94d9e787ce..66d9e14c01 100644 --- a/packages/core/src/instruction-context.ts +++ b/packages/core/src/instruction-context.ts @@ -43,22 +43,24 @@ const layer = Layer.effect( }) const observe = Effect.fn("InstructionContext.observe")(function* () { - const start = FSUtil.resolve(location.directory) - const stop = FSUtil.resolve(location.project.directory) + const start = yield* fs.resolve(location.directory) + const stop = yield* fs.resolve(location.project.directory) const fromProject = relative(stop, start) const insideProject = fromProject === "" || (fromProject !== ".." && !fromProject.startsWith(`..${sep}`) && !isAbsolute(fromProject)) const discovered = new Set( - (Flag.OPENCODE_DISABLE_PROJECT_CONFIG || !insideProject - ? [] - : yield* fs.up({ - targets: ["AGENTS.md"], - start, - stop, - }) - ).map(FSUtil.resolve), + yield* Effect.forEach( + Flag.OPENCODE_DISABLE_PROJECT_CONFIG || !insideProject + ? [] + : yield* fs.up({ + targets: ["AGENTS.md"], + start, + stop, + }), + fs.resolve, + ), ) - const paths = Array.dedupe([FSUtil.resolve(join(global.config, "AGENTS.md")), ...discovered]) + const paths = Array.dedupe([yield* fs.resolve(join(global.config, "AGENTS.md")), ...discovered]) const files = yield* Effect.forEach( paths, (path) => diff --git a/packages/core/src/project/copy.ts b/packages/core/src/project/copy.ts index b42df4045c..0980ef44f7 100644 --- a/packages/core/src/project/copy.ts +++ b/packages/core/src/project/copy.ts @@ -139,7 +139,7 @@ const layer = Layer.effect( }) const canonical = Effect.fnUntraced(function* (input: AbsolutePath) { - const resolved = AbsolutePath.make(FSUtil.resolve(input)) + const resolved = AbsolutePath.make(yield* fs.resolve(input)) if (!(yield* fs.isDir(resolved))) return yield* new DirectoryUnavailableError({ directory: input }) return resolved }) diff --git a/packages/core/src/session/instructions.ts b/packages/core/src/session/instructions.ts index 3e2eb27147..913f5c7334 100644 --- a/packages/core/src/session/instructions.ts +++ b/packages/core/src/session/instructions.ts @@ -35,7 +35,7 @@ const layer = Layer.effect( // Resolved once for the Location layer; the synthetic text and dedup ledger keep // absolute paths, but the human-facing description shows paths relative to the project // root so opening a subdirectory still describes paths from the project root. - const root = FSUtil.resolve(location.project.directory) + const root = yield* fs.resolve(location.project.directory) // Same-turn parallel reads settle concurrently, so an in-memory claim guards each // Session/path pair before any filesystem work. The durable history check below covers // paths injected in earlier turns after this Location layer was reopened. diff --git a/packages/core/src/tool/read.ts b/packages/core/src/tool/read.ts index 028456a4e1..16e229d97d 100644 --- a/packages/core/src/tool/read.ts +++ b/packages/core/src/tool/read.ts @@ -97,8 +97,8 @@ export const Plugin = { // skipped, and discovery failures never fail the read. yield* Effect.gen(function* () { if (target.externalDirectory !== undefined) return - const resolved = FSUtil.resolve(target.canonical) - const root = FSUtil.resolve(location.directory) + const resolved = yield* fs.resolve(target.canonical) + const root = yield* fs.resolve(location.directory) // up() searches its stop directory, so the Location-root AGENTS.md (already // supplied by the core/instructions baseline) is dropped by the dirname filter. const discovered = yield* fs.up({ @@ -106,7 +106,7 @@ export const Plugin = { start: type === "directory" ? resolved : dirname(resolved), stop: root, }) - const candidates = discovered.map(FSUtil.resolve).filter((file) => dirname(file) !== root) + const candidates = (yield* Effect.forEach(discovered, fs.resolve)).filter((file) => dirname(file) !== root) if (candidates.length === 0) return yield* sessionInstructions.load({ sessionID: context.sessionID, paths: candidates }) }).pipe( diff --git a/packages/core/src/tool/shell.ts b/packages/core/src/tool/shell.ts index e86f960ba5..cb7edb3113 100644 --- a/packages/core/src/tool/shell.ts +++ b/packages/core/src/tool/shell.ts @@ -80,17 +80,21 @@ const modelOutput = (output: Output): string | undefined => { const shellTokens = (command: string) => command.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) ?? [] const unquote = (value: string) => value.replace(/^(['"])(.*)\1$/, "$2") -const externalCommandDirectories = (command: string, cwd: string) => { +const externalCommandDirectories = Effect.fn("ShellTool.externalCommandDirectories")(function* ( + fs: FSUtil.Interface, + command: string, + cwd: string, +) { const directories = new Set() for (const token of shellTokens(command)) { const value = unquote(token).replace(/[;,|&]+$/, "") if (!path.isAbsolute(value)) continue - const resolved = FSUtil.resolve(value) + const resolved = yield* fs.resolve(value) if (FSUtil.contains(cwd, resolved)) continue - directories.add(FSUtil.resolve(path.dirname(resolved))) + directories.add(yield* fs.resolve(path.dirname(resolved))) } return [...directories] -} +}) export const Plugin = { id: "core-shell-tool", @@ -168,7 +172,7 @@ export const Plugin = { agent: context.agent, source, }) - const warnings = externalCommandDirectories(input.command, target.canonical).map( + const warnings = (yield* externalCommandDirectories(fsUtil, input.command, target.canonical)).map( (directory) => `Command argument references external directory ${path.join(directory, "*").replaceAll("\\", "/")}. Shell runs with host-user filesystem, process, and network authority; this scan is advisory only.`, ) From c6a52a39b5f1e1d3bb0165d47259afa8c2b5e297 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 13:33:25 -0400 Subject: [PATCH 12/82] fix(cli): read OPENCODE_PASSWORD for explicit server auth --- packages/cli/src/commands/handlers/default.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/src/commands/handlers/default.ts b/packages/cli/src/commands/handlers/default.ts index 32e542e634..ca4c6469b4 100644 --- a/packages/cli/src/commands/handlers/default.ts +++ b/packages/cli/src/commands/handlers/default.ts @@ -18,7 +18,7 @@ export default Runtime.handler(Commands, (input) => return yield* Effect.fail(new Error("--server and --standalone cannot be combined")) const transport = yield* Effect.gen(function* () { if (server !== undefined) { - const password = process.env["OPENCODE_SERVER_PASSWORD"] + const password = process.env["OPENCODE_PASSWORD"] return { url: server, headers: password ? { authorization: "Basic " + btoa("opencode:" + password) } : undefined, From c22793d5f6aac55252fe251c21da65f412235de6 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 13:34:11 -0400 Subject: [PATCH 13/82] feat(cli): validate explicit server before starting the tui --- packages/cli/src/commands/handlers/default.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/commands/handlers/default.ts b/packages/cli/src/commands/handlers/default.ts index ca4c6469b4..addafa634f 100644 --- a/packages/cli/src/commands/handlers/default.ts +++ b/packages/cli/src/commands/handlers/default.ts @@ -19,10 +19,26 @@ export default Runtime.handler(Commands, (input) => const transport = yield* Effect.gen(function* () { if (server !== undefined) { const password = process.env["OPENCODE_PASSWORD"] - return { + const explicit = { url: server, headers: password ? { authorization: "Basic " + btoa("opencode:" + password) } : undefined, } satisfies Service.Transport + // Fail loudly before entering the TUI: an explicit server that is + // unreachable or rejects auth should not present as reconnect churn. + const response = yield* Effect.tryPromise(() => + fetch(new URL("/api/health", server), { headers: explicit.headers, signal: AbortSignal.timeout(5_000) }), + ).pipe(Effect.mapError((cause) => new Error(`Could not reach server at ${server}`, { cause }))) + if (response.status === 401) + return yield* Effect.fail( + new Error( + password + ? `Server at ${server} rejected the password` + : `Server at ${server} requires a password; set OPENCODE_PASSWORD`, + ), + ) + if (!response.ok) + return yield* Effect.fail(new Error(`Server at ${server} responded with status ${response.status}`)) + return explicit } if (input.standalone) return yield* Standalone.transport() const options = yield* ServiceConfig.options() From 24d26365e6403fd8add79fec45ed63f2fb20381e Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 13:37:12 -0400 Subject: [PATCH 14/82] refactor(cli): manage environment variables with effect config --- packages/cli/src/commands/handlers/default.ts | 9 ++++++--- packages/cli/src/commands/handlers/serve.ts | 11 ++++++++--- packages/cli/src/env.ts | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 6 deletions(-) create mode 100644 packages/cli/src/env.ts diff --git a/packages/cli/src/commands/handlers/default.ts b/packages/cli/src/commands/handlers/default.ts index addafa634f..5521af8fe6 100644 --- a/packages/cli/src/commands/handlers/default.ts +++ b/packages/cli/src/commands/handlers/default.ts @@ -1,8 +1,9 @@ import { NodeFileSystem } from "@effect/platform-node" import { Commands } from "../commands" import { Runtime } from "../../framework/runtime" -import { Effect, Option } from "effect" +import { Effect, Option, Redacted } from "effect" import { Service } from "@opencode-ai/client/effect" +import { Env } from "../../env" import { ServiceConfig } from "../../services/service-config" import { Standalone } from "../../services/standalone" import { Updater } from "../../services/updater" @@ -18,10 +19,12 @@ export default Runtime.handler(Commands, (input) => return yield* Effect.fail(new Error("--server and --standalone cannot be combined")) const transport = yield* Effect.gen(function* () { if (server !== undefined) { - const password = process.env["OPENCODE_PASSWORD"] + const password = Option.getOrUndefined(yield* Env.password) const explicit = { url: server, - headers: password ? { authorization: "Basic " + btoa("opencode:" + password) } : undefined, + headers: password + ? { authorization: "Basic " + btoa("opencode:" + Redacted.value(password)) } + : undefined, } satisfies Service.Transport // Fail loudly before entering the TUI: an explicit server that is // unreachable or rejects auth should not present as reconnect churn. diff --git a/packages/cli/src/commands/handlers/serve.ts b/packages/cli/src/commands/handlers/serve.ts index d6b6938ee3..2b00b297a3 100644 --- a/packages/cli/src/commands/handlers/serve.ts +++ b/packages/cli/src/commands/handlers/serve.ts @@ -4,7 +4,7 @@ import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { PermissionSaved } from "@opencode-ai/core/permission/saved" import { Global } from "@opencode-ai/core/global" -import { Context, FileSystem, Layer, Option, Schedule, Schema } from "effect" +import { Context, FileSystem, Layer, Option, Redacted, Schedule, Schema } from "effect" import * as Effect from "effect/Effect" import { HttpRouter, HttpServer } from "effect/unstable/http" import { createServer } from "node:http" @@ -15,6 +15,7 @@ import { createOpencodeClient } from "@opencode-ai/sdk/v2/client" import { Commands } from "../commands" import { Runtime } from "../../framework/runtime" import { Service } from "@opencode-ai/client/effect" +import { Env } from "../../env" import { ServiceConfig } from "../../services/service-config" import { Updater } from "../../services/updater" import { randomBytes, randomUUID } from "crypto" @@ -26,12 +27,16 @@ export default Runtime.handler( if (input.service) yield* Effect.sync(() => process.chdir(Global.Path.home)) return yield* Effect.scoped( Effect.gen(function* () { - const standalonePassword = process.env.OPENCODE_SERVER_PASSWORD + const standalonePassword = Option.getOrUndefined(yield* Env.serverPassword) + // Keep the lease credential out of the environment inherited by any + // process this server spawns. if (input.stdio) delete process.env.OPENCODE_SERVER_PASSWORD const config = input.service ? yield* ServiceConfig.read() : {} const password = input.service ? yield* ServiceConfig.password() - : standalonePassword || randomBytes(32).toString("base64url") + : standalonePassword + ? Redacted.value(standalonePassword) + : randomBytes(32).toString("base64url") if (!password) return yield* Effect.fail(new Error("Missing server password")) const hostname = Option.getOrUndefined(input.hostname) ?? config.hostname ?? "127.0.0.1" const port = Option.isSome(input.port) diff --git a/packages/cli/src/env.ts b/packages/cli/src/env.ts new file mode 100644 index 0000000000..914abac644 --- /dev/null +++ b/packages/cli/src/env.ts @@ -0,0 +1,18 @@ +import { Config } from "effect" + +// Every environment variable the CLI reads, in one place. Consumers yield +// these instead of touching process.env so the full surface stays visible, +// typed, and redacted where secret. + +// Client-side password for an explicit --server target. The legacy name is +// still honored; it also remains the variable a standalone child inherits. +export const password = Config.redacted("OPENCODE_PASSWORD").pipe( + Config.orElse(() => Config.redacted("OPENCODE_SERVER_PASSWORD")), + Config.option, +) + +// Server-side lease password: set by the standalone spawner for its child, +// or preset for a manually managed `opencode serve`. +export const serverPassword = Config.redacted("OPENCODE_SERVER_PASSWORD").pipe(Config.option) + +export * as Env from "./env" From 08293e74a0edd22dfd335ce86b47bcc95bf2acf0 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 13:41:15 -0400 Subject: [PATCH 15/82] refactor(cli): single password config with legacy fallback --- packages/cli/src/commands/handlers/default.ts | 2 +- packages/cli/src/commands/handlers/serve.ts | 7 +++++-- packages/cli/src/env.ts | 11 ++++------- packages/cli/src/services/standalone.ts | 4 +++- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/packages/cli/src/commands/handlers/default.ts b/packages/cli/src/commands/handlers/default.ts index 5521af8fe6..1f8ebe89c4 100644 --- a/packages/cli/src/commands/handlers/default.ts +++ b/packages/cli/src/commands/handlers/default.ts @@ -19,7 +19,7 @@ export default Runtime.handler(Commands, (input) => return yield* Effect.fail(new Error("--server and --standalone cannot be combined")) const transport = yield* Effect.gen(function* () { if (server !== undefined) { - const password = Option.getOrUndefined(yield* Env.password) + const password = yield* Env.password const explicit = { url: server, headers: password diff --git a/packages/cli/src/commands/handlers/serve.ts b/packages/cli/src/commands/handlers/serve.ts index 2b00b297a3..11483189c3 100644 --- a/packages/cli/src/commands/handlers/serve.ts +++ b/packages/cli/src/commands/handlers/serve.ts @@ -27,10 +27,13 @@ export default Runtime.handler( if (input.service) yield* Effect.sync(() => process.chdir(Global.Path.home)) return yield* Effect.scoped( Effect.gen(function* () { - const standalonePassword = Option.getOrUndefined(yield* Env.serverPassword) + const standalonePassword = yield* Env.password // Keep the lease credential out of the environment inherited by any // process this server spawns. - if (input.stdio) delete process.env.OPENCODE_SERVER_PASSWORD + if (input.stdio) { + delete process.env.OPENCODE_PASSWORD + delete process.env.OPENCODE_SERVER_PASSWORD + } const config = input.service ? yield* ServiceConfig.read() : {} const password = input.service ? yield* ServiceConfig.password() diff --git a/packages/cli/src/env.ts b/packages/cli/src/env.ts index 914abac644..6cc76b793f 100644 --- a/packages/cli/src/env.ts +++ b/packages/cli/src/env.ts @@ -4,15 +4,12 @@ import { Config } from "effect" // these instead of touching process.env so the full surface stays visible, // typed, and redacted where secret. -// Client-side password for an explicit --server target. The legacy name is -// still honored; it also remains the variable a standalone child inherits. +// The opencode server password: sent by clients connecting to an explicit +// --server, and adopted by a manually run or standalone server. The legacy +// name is still honored. export const password = Config.redacted("OPENCODE_PASSWORD").pipe( Config.orElse(() => Config.redacted("OPENCODE_SERVER_PASSWORD")), - Config.option, + Config.withDefault(undefined), ) -// Server-side lease password: set by the standalone spawner for its child, -// or preset for a manually managed `opencode serve`. -export const serverPassword = Config.redacted("OPENCODE_SERVER_PASSWORD").pipe(Config.option) - export * as Env from "./env" diff --git a/packages/cli/src/services/standalone.ts b/packages/cli/src/services/standalone.ts index b591a5deb1..285a433b55 100644 --- a/packages/cli/src/services/standalone.ts +++ b/packages/cli/src/services/standalone.ts @@ -15,7 +15,9 @@ function command(password: string) { if (!compiled && entrypoint.length === 0) throw new Error("Failed to resolve CLI entrypoint") return ChildProcess.make(process.execPath, [...entrypoint, "serve", "--stdio", "--port", "0"], { cwd: process.cwd(), - env: { OPENCODE_SERVER_PASSWORD: password }, + // Explicit entry wins over anything inherited, so a user-exported + // OPENCODE_PASSWORD cannot shadow the child's lease credential. + env: { OPENCODE_PASSWORD: password }, extendEnv: true, // The server treats EOF on this pipe as the end of its ownership lease. // The OS closes it even when the TUI is killed before Effect finalizers run. From 1b88ff8d5380d707548a06ef5100c993d209ce8f Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 13:54:13 -0400 Subject: [PATCH 16/82] fix(core): clean up Effect audit patterns (#35174) --- bun.lock | 29 +++++++++++----- package.json | 2 ++ packages/core/src/database/path.ts | 5 ++- packages/core/src/filesystem/watcher.ts | 3 +- packages/core/src/models-dev.ts | 17 ++++++++-- packages/core/src/plugin/provider/openai.ts | 34 ++++++++++--------- .../core/src/plugin/provider/sap-ai-core.ts | 17 +++++----- packages/core/src/project/copy.ts | 3 +- packages/core/src/ripgrep.ts | 6 ++-- packages/core/src/session/projector.ts | 2 +- .../core/src/session/runner/to-llm-message.ts | 15 ++++---- packages/server/src/handlers/credential.ts | 6 ++-- packages/server/src/handlers/fs.ts | 3 +- packages/server/src/handlers/permission.ts | 12 ++++--- packages/server/src/handlers/pty.ts | 3 +- packages/server/src/handlers/question.ts | 6 ++-- script/ast-grep/no-json-parse-cast.yml | 6 ++++ .../no-nested-effect-service-yield.yml | 11 ++++++ 18 files changed, 118 insertions(+), 62 deletions(-) create mode 100644 script/ast-grep/no-json-parse-cast.yml create mode 100644 script/ast-grep/no-nested-effect-service-yield.yml diff --git a/bun.lock b/bun.lock index 5eca1724f1..9c5bbb1591 100644 --- a/bun.lock +++ b/bun.lock @@ -14,6 +14,7 @@ }, "devDependencies": { "@actions/artifact": "5.0.1", + "@ast-grep/cli": "0.44.0", "@tsconfig/bun": "catalog:", "@types/mime-types": "3.0.1", "@typescript/native-preview": "catalog:", @@ -1236,6 +1237,22 @@ "@anycable/core": ["@anycable/core@0.9.2", "", { "dependencies": { "nanoevents": "^7.0.1" } }, "sha512-x5ZXDcW/N4cxWl93CnbHs/u7qq4793jS2kNPWm+duPrXlrva+ml2ZGT7X9tuOBKzyIHf60zWCdIK7TUgMPAwXA=="], + "@ast-grep/cli": ["@ast-grep/cli@0.44.0", "", { "dependencies": { "detect-libc": "2.1.2" }, "optionalDependencies": { "@ast-grep/cli-darwin-arm64": "0.44.0", "@ast-grep/cli-darwin-x64": "0.44.0", "@ast-grep/cli-linux-arm64-gnu": "0.44.0", "@ast-grep/cli-linux-x64-gnu": "0.44.0", "@ast-grep/cli-win32-arm64-msvc": "0.44.0", "@ast-grep/cli-win32-ia32-msvc": "0.44.0", "@ast-grep/cli-win32-x64-msvc": "0.44.0" }, "bin": { "sg": "sg", "ast-grep": "ast-grep" } }, "sha512-Jf4PuP7XjzsMa3m9gYxmzV8KyWZc4w1ZzKe/t0+90wWxmSasQJe6AtMkJxHEi98MGgfAF1nWziqjDd0/6EsBjA=="], + + "@ast-grep/cli-darwin-arm64": ["@ast-grep/cli-darwin-arm64@0.44.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-bF7euu/hF/cYg4510z8110vh60rrqfrBdsfRqVGd6xqNSPENu7CJnTVN/Z4Nk5U1NM8YKzUD+dYx1ySUJ0CUNQ=="], + + "@ast-grep/cli-darwin-x64": ["@ast-grep/cli-darwin-x64@0.44.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-0fI9caQGp1dFcmBATNlVytIRdAeYb91v1D2xjMIi1bSX+l8Uj846JUiaimUGBuBZmyFq+BScoWM4RnprEmZMpQ=="], + + "@ast-grep/cli-linux-arm64-gnu": ["@ast-grep/cli-linux-arm64-gnu@0.44.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-JB6EUnqEtGGtyg1GqNquld/++1CvaWD7r84IwwhddX1qx0NmDoHyn2mKd8vnQ24Z0RkV3g7y7foMLakELbGtDw=="], + + "@ast-grep/cli-linux-x64-gnu": ["@ast-grep/cli-linux-x64-gnu@0.44.0", "", { "os": "linux", "cpu": "x64" }, "sha512-rNL0LsI682D9EMzfaGVEtZa1xaqTtGb2I+Zk4ZzidX6u+fF7f79wdqyKahKjXzoIrGkuhkoL3gcyLKAtQd9+qg=="], + + "@ast-grep/cli-win32-arm64-msvc": ["@ast-grep/cli-win32-arm64-msvc@0.44.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-lqD0MhGQAddh2YoV/brKQ6GVcFLmRiTBwIElutwedaUvRCdasTGukFPYuSWk/iI8Kv19xom6s7l+mGuZ7v+xwQ=="], + + "@ast-grep/cli-win32-ia32-msvc": ["@ast-grep/cli-win32-ia32-msvc@0.44.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-ZJrnS+2OkNfwyr6yrN69glP67uybBxDvl9mqZvh1J44vB3OFn9U9c+cVAoZIAo7JD5F4rZNxwyu3gcy4+xuwEA=="], + + "@ast-grep/cli-win32-x64-msvc": ["@ast-grep/cli-win32-x64-msvc@0.44.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OJEo7f95YYaSuS1byUB7ZctbzxoA7/wCoAol+pt6pvfdW/8Wq+L1qU28glwx7dQ0HgTsnPZbWpXQwmZpCBHhZg=="], + "@astrojs/check": ["@astrojs/check@0.9.6", "", { "dependencies": { "@astrojs/language-server": "^2.16.1", "chokidar": "^4.0.1", "kleur": "^4.1.5", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": "^5.0.0" }, "bin": { "astro-check": "bin/astro-check.js" } }, "sha512-jlaEu5SxvSgmfGIFfNgcn5/f+29H61NJzEMfAZ82Xopr4XBchXB1GVlcJsE+elUlsYSbXlptZLX+JMG3b/wZEA=="], "@astrojs/cloudflare": ["@astrojs/cloudflare@12.6.3", "", { "dependencies": { "@astrojs/internal-helpers": "0.7.1", "@astrojs/underscore-redirects": "1.0.0", "@cloudflare/workers-types": "^4.20250507.0", "tinyglobby": "^0.2.13", "vite": "^6.3.5", "wrangler": "^4.14.1" }, "peerDependencies": { "astro": "^5.0.0" } }, "sha512-xhJptF5tU2k5eo70nIMyL1Udma0CqmUEnGSlGyFflLqSY82CRQI6nWZ/xZt0ZvmXuErUjIx0YYQNfZsz5CNjLQ=="], @@ -3490,7 +3507,7 @@ "destroy": ["destroy@1.2.0", "", {}, "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg=="], - "detect-libc": ["detect-libc@1.0.3", "", { "bin": { "detect-libc": "./bin/detect-libc.js" } }, "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg=="], + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], "detect-node": ["detect-node@2.1.0", "", {}, "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g=="], @@ -6048,6 +6065,8 @@ "@oxc-resolver/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="], + "@parcel/watcher/detect-libc": ["detect-libc@1.0.3", "", { "bin": { "detect-libc": "./bin/detect-libc.js" } }, "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg=="], + "@pierre/diffs/@shikijs/transformers": ["@shikijs/transformers@3.20.0", "", { "dependencies": { "@shikijs/core": "3.20.0", "@shikijs/types": "3.20.0" } }, "sha512-PrHHMRr3Q5W1qB/42kJW6laqFyWdhrPF2hNR9qjOm1xcSiAO3hAHo7HaVyHE6pMyevmy3i51O8kuGGXC78uK3g=="], "@pierre/diffs/diff": ["diff@8.0.3", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="], @@ -6114,8 +6133,6 @@ "@storybook/csf-plugin/unplugin": ["unplugin@2.3.11", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="], - "@tailwindcss/oxide/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="], @@ -6328,8 +6345,6 @@ "light-my-request/process-warning": ["process-warning@4.0.1", "", {}, "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q=="], - "lightningcss/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "matcher/escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], "md-to-react-email/marked": ["marked@7.0.4", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-t8eP0dXRJMtMvBojtkcsA7n48BkauktUKzfkPSCq85ZMTJ0v76Rke4DYz01omYpPTUh4p/f7HePgRo3ebG8+QQ=="], @@ -6360,8 +6375,6 @@ "node-gyp/undici": ["undici@6.26.0", "", {}, "sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A=="], - "node-gyp-build-optional-packages/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], "nypm/citty": ["citty@0.2.2", "", {}, "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w=="], @@ -6428,8 +6441,6 @@ "serialize-error/type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="], - "sharp/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "shiki/@shikijs/core": ["@shikijs/core@4.2.0", "", { "dependencies": { "@shikijs/primitive": "4.2.0", "@shikijs/types": "4.2.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-Hc87Ab1Ld/vEbZRCbwx344I5v+4RU8CVToUTRkqXL1+TjbuOp9U5Xa0M23V4GEWHxVn+yO5otb+HkQVm3ptWQQ=="], "shiki/@shikijs/types": ["@shikijs/types@4.2.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-VT/MKtlpOhEPZloSH3Pb9WCZEBDoQVMa9jedp5UAwmJOar1DVc9DRODAxmYPW9M93IK4ryuqRejFfmlvlVDemw=="], diff --git a/package.json b/package.json index 226a86ff2c..0810127669 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "dev:stats": "bun sst shell --stage=production -- bun run --cwd packages/stats/app dev", "dev:storybook": "bun --cwd packages/storybook storybook", "lint": "oxlint", + "lint:effect-patterns": "ast-grep scan --rule script/ast-grep/no-json-parse-cast.yml packages/core/src packages/server/src packages/protocol/src && ast-grep scan --rule script/ast-grep/no-nested-effect-service-yield.yml packages/core/src packages/server/src packages/protocol/src", "typecheck": "bun turbo typecheck", "upgrade-opentui": "bun run script/upgrade-opentui.ts", "postinstall": "bun run --cwd packages/core fix-node-pty", @@ -95,6 +96,7 @@ }, "devDependencies": { "@actions/artifact": "5.0.1", + "@ast-grep/cli": "0.44.0", "@tsconfig/bun": "catalog:", "@types/mime-types": "3.0.1", "@typescript/native-preview": "catalog:", diff --git a/packages/core/src/database/path.ts b/packages/core/src/database/path.ts index 379d5f8aa7..93fd2d5773 100644 --- a/packages/core/src/database/path.ts +++ b/packages/core/src/database/path.ts @@ -1,5 +1,6 @@ import nodePath from "path" import { customType } from "drizzle-orm/sqlite-core" +import { Schema } from "effect" import { AbsolutePath } from "../schema" function storagePath(input: string) { @@ -74,6 +75,8 @@ export const pathColumn = customType<{ }, }) +const decodeAbsoluteArray = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Array(Schema.String))) + export const absoluteArrayColumn = customType<{ data: AbsolutePath[] driverData: string @@ -86,6 +89,6 @@ export const absoluteArrayColumn = customType<{ return JSON.stringify(input.map(absolute)) }, fromDriver(input) { - return (JSON.parse(input) as string[]).map((item) => AbsolutePath.make(toPlatform(absolute(item)))) + return decodeAbsoluteArray(input).map((item) => AbsolutePath.make(toPlatform(absolute(item)))) }, }) diff --git a/packages/core/src/filesystem/watcher.ts b/packages/core/src/filesystem/watcher.ts index fe7a5b2594..1efc9d6907 100644 --- a/packages/core/src/filesystem/watcher.ts +++ b/packages/core/src/filesystem/watcher.ts @@ -113,7 +113,8 @@ const layer = Layer.effect( ) } - const config = (yield* (yield* Config.Service).entries()) + const configService = yield* Config.Service + const config = (yield* configService.entries()) .filter((entry): entry is Config.Document => entry.type === "document") .flatMap((item) => item.info.watcher?.ignore ?? []) yield* Effect.forkScoped( diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index cf2991168a..8a3fb965bf 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -47,7 +47,7 @@ const Cost = Schema.Struct({ const ReasoningOption = Schema.Union([ Schema.Struct({ type: Schema.Literal("effort"), - values: Schema.Array(Schema.String), + values: Schema.Array(Schema.Union([Schema.String, Schema.Null])), }), Schema.Struct({ type: Schema.Literal("toggle"), @@ -125,6 +125,10 @@ export const Provider = Schema.Struct({ export type Provider = Schema.Schema.Type +const Providers = Schema.Record(Schema.String, Provider) +const decodeProviders = Schema.decodeUnknownEffect(Schema.fromJsonString(Providers)) +const decodeProvidersUnknown = Schema.decodeUnknownEffect(Providers) + export const Event = ModelsDev.Event declare const OPENCODE_MODELS_DEV: Record | undefined @@ -176,6 +180,7 @@ const layer = Layer.effect( }) const loadFromDisk = fs.readJson(Flag.OPENCODE_MODELS_PATH ?? filepath).pipe( + Effect.flatMap(decodeProvidersUnknown), Effect.catch((error) => { if ( Flag.OPENCODE_MODELS_PATH === undefined && @@ -186,11 +191,17 @@ const layer = Layer.effect( } return Effect.succeed(undefined) }), - Effect.map((v) => v as Record | undefined), ) const loadSnapshot = Effect.sync(() => typeof OPENCODE_MODELS_DEV === "undefined" ? undefined : OPENCODE_MODELS_DEV, + ).pipe( + Effect.flatMap((snapshot) => + snapshot === undefined ? Effect.succeed(undefined) : decodeProvidersUnknown(snapshot), + ), + Effect.catch((cause) => + Effect.logWarning("bundled models snapshot failed schema decode", { cause }).pipe(Effect.as(undefined)), + ), ) const fetchAndWrite = Effect.fn("ModelsDev.fetchAndWrite")(function* () { @@ -221,7 +232,7 @@ const layer = Layer.effect( return yield* fetchAndWrite() }), ) - return JSON.parse(text) as Record + return yield* decodeProviders(text) }).pipe(Effect.withSpan("ModelsDev.populate"), Effect.orDie) const [cachedGet, invalidate] = yield* Effect.cachedInvalidateWithTTL(populate, Duration.infinity) diff --git a/packages/core/src/plugin/provider/openai.ts b/packages/core/src/plugin/provider/openai.ts index 82e2319a1b..e8974195a6 100644 --- a/packages/core/src/plugin/provider/openai.ts +++ b/packages/core/src/plugin/provider/openai.ts @@ -1,7 +1,7 @@ import { createServer } from "node:http" import type { IntegrationOAuthMethodRegistration } from "@opencode-ai/plugin/v2/effect/integration" import { define } from "@opencode-ai/plugin/v2/effect/plugin" -import { Deferred, Effect, Semaphore, Stream } from "effect" +import { Deferred, Effect, Option, Schema, Semaphore, Stream } from "effect" import type { Scope } from "effect" import { Credential } from "../../credential" import { EventV2 } from "../../event" @@ -32,11 +32,16 @@ type TokenResponse = { expires_in?: number } -type Claims = { - chatgpt_account_id?: string - organizations?: Array<{ id: string }> - "https://api.openai.com/auth"?: { chatgpt_account_id?: string } -} +const Claims = Schema.fromJsonString( + Schema.Struct({ + chatgpt_account_id: Schema.optional(Schema.String), + organizations: Schema.optional(Schema.Array(Schema.Struct({ id: Schema.String }))), + "https://api.openai.com/auth": Schema.optional( + Schema.Struct({ chatgpt_account_id: Schema.optional(Schema.String) }), + ), + }), +) +const decodeClaims = Schema.decodeUnknownOption(Claims) const browser = { integrationID: Integration.ID.make("openai"), @@ -315,14 +320,11 @@ function extractAccountID(tokens: TokenResponse) { function claim(token: string) { const part = token.split(".")[1] if (!part) return - try { - const claims = JSON.parse(Buffer.from(part, "base64url").toString()) as Claims - return ( - claims.chatgpt_account_id ?? - claims["https://api.openai.com/auth"]?.chatgpt_account_id ?? - claims.organizations?.[0]?.id - ) - } catch { - return - } + const claims = Option.getOrUndefined(decodeClaims(Buffer.from(part, "base64url").toString())) + if (!claims) return + return ( + claims.chatgpt_account_id ?? + claims["https://api.openai.com/auth"]?.chatgpt_account_id ?? + claims.organizations?.[0]?.id + ) } diff --git a/packages/core/src/plugin/provider/sap-ai-core.ts b/packages/core/src/plugin/provider/sap-ai-core.ts index 8c668d8b41..b6c3a540e6 100644 --- a/packages/core/src/plugin/provider/sap-ai-core.ts +++ b/packages/core/src/plugin/provider/sap-ai-core.ts @@ -19,17 +19,18 @@ export const SapAICorePlugin = define({ const installedPath = evt.package.startsWith("file://") ? evt.package : (yield* npm.add(evt.package).pipe(Effect.orDie)).entrypoint - if (!installedPath) throw new Error(`Package ${evt.package} has no import entrypoint`) + if (!installedPath) return yield* Effect.die(new Error(`Package ${evt.package} has no import entrypoint`)) - const mod = yield* Effect.promise(async () => { - return (await import( - installedPath.startsWith("file://") ? installedPath : pathToFileURL(installedPath).href - )) as Record any> - }).pipe(Effect.orDie) + const mod: Record = yield* Effect.promise( + () => import(installedPath.startsWith("file://") ? installedPath : pathToFileURL(installedPath).href), + ) const match = Object.keys(mod).find((name) => name.startsWith("create")) - if (!match) throw new Error(`Package ${evt.package} has no provider factory export`) + if (!match) return yield* Effect.die(new Error(`Package ${evt.package} has no provider factory export`)) + const factory = mod[match] + if (typeof factory !== "function") + return yield* Effect.die(new Error(`Package ${evt.package} provider factory export is not callable`)) - evt.sdk = mod[match]( + evt.sdk = factory( serviceKey ? { deploymentId: process.env.AICORE_DEPLOYMENT_ID, resourceGroup: process.env.AICORE_RESOURCE_GROUP } : {}, diff --git a/packages/core/src/project/copy.ts b/packages/core/src/project/copy.ts index 0980ef44f7..9183e26eb9 100644 --- a/packages/core/src/project/copy.ts +++ b/packages/core/src/project/copy.ts @@ -202,7 +202,8 @@ const layer = Layer.effect( const copyDirectory = yield* canonical(input.directory) const stored = yield* directories.get({ projectID: input.projectID, directory: copyDirectory }) if (!stored?.strategy) return yield* new InvalidDirectoryError({ directory: copyDirectory }) - yield* (yield* getStrategy(StrategyID.make(stored.strategy))).remove({ + const strategy = yield* getStrategy(StrategyID.make(stored.strategy)) + yield* strategy.remove({ directory: copyDirectory, force: input.force, }) diff --git a/packages/core/src/ripgrep.ts b/packages/core/src/ripgrep.ts index ac8ea52d93..7e1056c4d8 100644 --- a/packages/core/src/ripgrep.ts +++ b/packages/core/src/ripgrep.ts @@ -35,6 +35,7 @@ const RawMatch = Schema.Struct({ ), }), }) +const decodeJsonRecord = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString) type RawMatchData = (typeof RawMatch.Type)["data"] @@ -232,10 +233,7 @@ const layer = Layer.effect( parse: (line) => (Buffer.byteLength(line, "utf8") > MAX_RECORD_BYTES ? Effect.fail(failure(`Ripgrep JSON record exceeded ${MAX_RECORD_BYTES} bytes`)) - : Effect.try({ - try: () => JSON.parse(line) as unknown, - catch: (cause) => failure("Invalid ripgrep JSON output", cause), - }) + : decodeJsonRecord(line).pipe(Effect.mapError((cause) => failure("Invalid ripgrep JSON output", cause))) ).pipe( Effect.flatMap((json) => { if (!json || typeof json !== "object" || !("type" in json) || json.type !== "match") diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index c7145e8dba..5e2d112229 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -438,7 +438,7 @@ function insertMessage(db: DatabaseService, event: SessionEvent.DurableEvent, me const layer = Layer.effectDiscard( Effect.gen(function* () { const events = yield* EventV2.Service - const { db } = yield* Database.Service + const db = (yield* Database.Service).db yield* events.project(SessionV1.Event.Created, (event) => Effect.gen(function* () { const stored = yield* db diff --git a/packages/core/src/session/runner/to-llm-message.ts b/packages/core/src/session/runner/to-llm-message.ts index 8ddd7cce5c..0d9055e480 100644 --- a/packages/core/src/session/runner/to-llm-message.ts +++ b/packages/core/src/session/runner/to-llm-message.ts @@ -7,6 +7,7 @@ import { type Model, type ProviderMetadata, } from "@opencode-ai/llm" +import { Option, Schema } from "effect" import { SessionMessage } from "../message" import type { FileAttachment } from "../prompt" @@ -18,14 +19,12 @@ const media = (file: FileAttachment): ContentPart => ({ metadata: file.description === undefined ? undefined : { description: file.description }, }) -const toolInput = (tool: SessionMessage.AssistantTool) => { - if (tool.state.status !== "pending") return tool.state.input - try { - return JSON.parse(tool.state.input) as unknown - } catch { - return tool.state.input - } -} +const decodeToolInput = Schema.decodeUnknownOption(Schema.UnknownFromJsonString) + +const toolInput = (tool: SessionMessage.AssistantTool) => + tool.state.status === "pending" + ? Option.getOrElse(decodeToolInput(tool.state.input), () => tool.state.input) + : tool.state.input const toolCall = (tool: SessionMessage.AssistantTool, providerMetadata: ProviderMetadata | undefined): ContentPart => ToolCallPart.make({ diff --git a/packages/server/src/handlers/credential.ts b/packages/server/src/handlers/credential.ts index 7e138a5d5a..49e84d49ba 100644 --- a/packages/server/src/handlers/credential.ts +++ b/packages/server/src/handlers/credential.ts @@ -8,14 +8,16 @@ export const CredentialHandler = HttpApiBuilder.group(Api, "server.credential", .handle( "credential.update", Effect.fn(function* (ctx) { - yield* (yield* Integration.Service).connection.update(ctx.params.credentialID, { label: ctx.payload.label }) + const integration = yield* Integration.Service + yield* integration.connection.update(ctx.params.credentialID, { label: ctx.payload.label }) return HttpApiSchema.NoContent.make() }), ) .handle( "credential.remove", Effect.fn(function* (ctx) { - yield* (yield* Integration.Service).connection.remove(ctx.params.credentialID) + const integration = yield* Integration.Service + yield* integration.connection.remove(ctx.params.credentialID) return HttpApiSchema.NoContent.make() }), ), diff --git a/packages/server/src/handlers/fs.ts b/packages/server/src/handlers/fs.ts index c7d1d43bab..d623f2d7e6 100644 --- a/packages/server/src/handlers/fs.ts +++ b/packages/server/src/handlers/fs.ts @@ -11,7 +11,8 @@ export const FileSystemHandler = HttpApiBuilder.group(Api, "server.fs", (handler return handlers .handleRaw("fs.read", (ctx) => Effect.gen(function* () { - const file = yield* (yield* FileSystem.Service).read({ + const fs = yield* FileSystem.Service + const file = yield* fs.read({ path: RelativePath.make( decodeURIComponent(new URL(ctx.request.url, "http://localhost").pathname.slice(13)), ), diff --git a/packages/server/src/handlers/permission.ts b/packages/server/src/handlers/permission.ts index 0425c14996..cbc49180f6 100644 --- a/packages/server/src/handlers/permission.ts +++ b/packages/server/src/handlers/permission.ts @@ -17,7 +17,8 @@ export const PermissionHandler = HttpApiBuilder.group(Api, "server.permission", .handle( "permission.request.list", Effect.fn(function* () { - return yield* response((yield* PermissionV2.Service).list()) + const permission = yield* PermissionV2.Service + return yield* response(permission.list()) }), ) .handle( @@ -59,7 +60,8 @@ export const PermissionHandler = HttpApiBuilder.group(Api, "server.permission", .handle( "session.permission.get", Effect.fn(function* (ctx) { - const request = yield* (yield* PermissionV2.Service).get(ctx.params.requestID) + const permission = yield* PermissionV2.Service + const request = yield* permission.get(ctx.params.requestID) if (!request || request.sessionID !== ctx.params.sessionID) return yield* missingRequest(ctx.params.requestID) return { data: request } }), @@ -80,8 +82,9 @@ export const PermissionHandler = HttpApiBuilder.group(Api, "server.permission", "permission.saved.list", Effect.fn(function* (ctx) { const location = yield* Location.Service + const saved = yield* PermissionSaved.Service return { - data: yield* (yield* PermissionSaved.Service).list({ + data: yield* saved.list({ projectID: ctx.query.projectID ?? location.project.id, }), } @@ -90,7 +93,8 @@ export const PermissionHandler = HttpApiBuilder.group(Api, "server.permission", .handle( "permission.saved.remove", Effect.fn(function* (ctx) { - yield* (yield* PermissionSaved.Service).remove(ctx.params.id) + const saved = yield* PermissionSaved.Service + yield* saved.remove(ctx.params.id) return HttpApiSchema.NoContent.make() }), ) diff --git a/packages/server/src/handlers/pty.ts b/packages/server/src/handlers/pty.ts index cda2cf43e9..e2c5fcc568 100644 --- a/packages/server/src/handlers/pty.ts +++ b/packages/server/src/handlers/pty.ts @@ -32,7 +32,8 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) => .handle( "pty.list", Effect.fn(function* () { - return yield* response((yield* Pty.Service).list()) + const pty = yield* Pty.Service + return yield* response(pty.list()) }), ) .handle( diff --git a/packages/server/src/handlers/question.ts b/packages/server/src/handlers/question.ts index 954afe0df5..d8011dd269 100644 --- a/packages/server/src/handlers/question.ts +++ b/packages/server/src/handlers/question.ts @@ -26,13 +26,15 @@ export const QuestionHandler = HttpApiBuilder.group(Api, "server.question", (han .handle( "question.request.list", Effect.fn(function* () { - return yield* response((yield* QuestionV2.Service).list()) + const question = yield* QuestionV2.Service + return yield* response(question.list()) }), ) .handle( "session.question.list", Effect.fn(function* (ctx) { - const requests = yield* (yield* QuestionV2.Service).list() + const question = yield* QuestionV2.Service + const requests = yield* question.list() return { data: requests.filter((request) => request.sessionID === ctx.params.sessionID) } }), ) diff --git a/script/ast-grep/no-json-parse-cast.yml b/script/ast-grep/no-json-parse-cast.yml new file mode 100644 index 0000000000..923528d880 --- /dev/null +++ b/script/ast-grep/no-json-parse-cast.yml @@ -0,0 +1,6 @@ +id: no-json-parse-cast +language: TypeScript +message: Prefer Effect Schema JSON decoding over JSON.parse casts. +severity: error +rule: + pattern: JSON.parse($INPUT) as $TYPE diff --git a/script/ast-grep/no-nested-effect-service-yield.yml b/script/ast-grep/no-nested-effect-service-yield.yml new file mode 100644 index 0000000000..aaa6107a48 --- /dev/null +++ b/script/ast-grep/no-nested-effect-service-yield.yml @@ -0,0 +1,11 @@ +id: no-nested-effect-service-yield +language: TypeScript +message: Bind Effect services before calling methods instead of nesting service yields. +severity: error +rule: + any: + - pattern: (yield* $SERVICE).$METHOD($$$ARGS) + - pattern: (yield* $SERVICE).$PROPERTY.$METHOD($$$ARGS) +constraints: + SERVICE: + regex: \.Service$ From 14019015292f19bddd5665cc7bcdae93744e91ad Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 13:58:26 -0400 Subject: [PATCH 17/82] chore: effect pattern lint infrastructure (#35210) --- package.json | 3 +- .../cli/src/commands/handlers/debug/agents.ts | 2 +- .../cli/src/commands/handlers/mcp/list.ts | 2 +- packages/cli/src/commands/handlers/migrate.ts | 2 +- packages/cli/src/commands/handlers/serve.ts | 5 +- .../cli/src/commands/handlers/service/get.ts | 3 +- .../src/commands/handlers/service/restart.ts | 2 +- .../cli/src/commands/handlers/service/set.ts | 2 +- .../src/commands/handlers/service/start.ts | 2 +- .../src/commands/handlers/service/status.ts | 2 +- .../cli/src/commands/handlers/service/stop.ts | 2 +- .../src/commands/handlers/service/unset.ts | 2 +- packages/cli/src/framework/runtime.ts | 21 ++++-- packages/cli/src/framework/spec.ts | 2 +- packages/cli/src/index.ts | 13 ++-- packages/core/src/account.ts | 2 +- packages/core/src/config/experimental.ts | 10 +-- packages/core/src/cross-spawn-spawner.ts | 33 ++++----- packages/core/src/database/database.ts | 6 +- packages/core/src/database/migration.ts | 2 +- packages/core/src/database/sqlite.bun.ts | 23 +++--- packages/core/src/database/sqlite.node.ts | 23 +++--- packages/core/src/form.ts | 29 +++++--- packages/core/src/fs-util.ts | 14 ++-- packages/core/src/id/id.ts | 10 +-- packages/core/src/integration.ts | 11 +-- packages/core/src/location-services.ts | 2 +- packages/core/src/permission.ts | 72 +++++++++---------- packages/core/src/plugin.ts | 4 +- packages/core/src/plugin/host.ts | 6 +- packages/core/src/plugin/runtime.ts | 2 +- packages/core/src/policy.ts | 19 ++--- packages/core/src/project/sql.ts | 8 +-- packages/core/src/pty/pty.bun.ts | 8 ++- packages/core/src/pty/pty.node.ts | 1 + packages/core/src/pty/ticket.ts | 2 +- packages/core/src/session/compaction.ts | 12 ++-- .../core/src/session/context-checkpoint.ts | 4 +- packages/core/src/session/execution/local.ts | 2 +- packages/core/src/session/input.ts | 2 +- packages/core/src/session/projector.ts | 17 +++-- packages/core/src/session/runner/llm.ts | 4 +- packages/core/src/session/runner/model.ts | 3 + .../src/session/runner/publish-llm-event.ts | 44 ++++++------ packages/core/src/session/sql.ts | 6 +- packages/core/src/shell/select.ts | 6 +- packages/core/test/session-runner.test.ts | 14 ++-- packages/server/src/auth.ts | 9 +-- packages/server/src/handlers/event.ts | 2 +- packages/server/src/handlers/pty.ts | 2 +- packages/server/src/routes.ts | 4 +- .../no-drizzle-column-name-snapshot.yml | 12 ++++ .../no-effect-die-string-snapshot.yml | 30 ++++++++ .../no-import-alias-snapshot.yml | 42 +++++++++++ .../no-json-parse-cast-snapshot.yml | 8 +++ ...o-nested-effect-service-yield-snapshot.yml | 20 ++++++ .../__snapshots__/no-star-import-snapshot.yml | 22 ++++++ .../no-drizzle-column-name-test.yml | 14 ++++ .../rule-tests/no-effect-die-string-test.yml | 7 ++ .../rule-tests/no-import-alias-test.yml | 13 ++++ .../rule-tests/no-json-parse-cast-test.yml | 6 ++ .../no-nested-effect-service-yield-test.yml | 21 ++++++ .../rule-tests/no-star-import-test.yml | 8 +++ .../ast-grep/rules/no-drizzle-column-name.yml | 22 ++++++ .../ast-grep/rules/no-effect-die-string.yml | 22 ++++++ script/ast-grep/rules/no-import-alias.yml | 14 ++++ .../{ => rules}/no-json-parse-cast.yml | 0 .../no-nested-effect-service-yield.yml | 0 script/ast-grep/rules/no-star-import.yml | 10 +++ script/ast-grep/sgconfig.yml | 4 ++ 70 files changed, 524 insertions(+), 234 deletions(-) create mode 100644 script/ast-grep/rule-tests/__snapshots__/no-drizzle-column-name-snapshot.yml create mode 100644 script/ast-grep/rule-tests/__snapshots__/no-effect-die-string-snapshot.yml create mode 100644 script/ast-grep/rule-tests/__snapshots__/no-import-alias-snapshot.yml create mode 100644 script/ast-grep/rule-tests/__snapshots__/no-json-parse-cast-snapshot.yml create mode 100644 script/ast-grep/rule-tests/__snapshots__/no-nested-effect-service-yield-snapshot.yml create mode 100644 script/ast-grep/rule-tests/__snapshots__/no-star-import-snapshot.yml create mode 100644 script/ast-grep/rule-tests/no-drizzle-column-name-test.yml create mode 100644 script/ast-grep/rule-tests/no-effect-die-string-test.yml create mode 100644 script/ast-grep/rule-tests/no-import-alias-test.yml create mode 100644 script/ast-grep/rule-tests/no-json-parse-cast-test.yml create mode 100644 script/ast-grep/rule-tests/no-nested-effect-service-yield-test.yml create mode 100644 script/ast-grep/rule-tests/no-star-import-test.yml create mode 100644 script/ast-grep/rules/no-drizzle-column-name.yml create mode 100644 script/ast-grep/rules/no-effect-die-string.yml create mode 100644 script/ast-grep/rules/no-import-alias.yml rename script/ast-grep/{ => rules}/no-json-parse-cast.yml (100%) rename script/ast-grep/{ => rules}/no-nested-effect-service-yield.yml (100%) create mode 100644 script/ast-grep/rules/no-star-import.yml create mode 100644 script/ast-grep/sgconfig.yml diff --git a/package.json b/package.json index 0810127669..9da29ab6ba 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,8 @@ "dev:stats": "bun sst shell --stage=production -- bun run --cwd packages/stats/app dev", "dev:storybook": "bun --cwd packages/storybook storybook", "lint": "oxlint", - "lint:effect-patterns": "ast-grep scan --rule script/ast-grep/no-json-parse-cast.yml packages/core/src packages/server/src packages/protocol/src && ast-grep scan --rule script/ast-grep/no-nested-effect-service-yield.yml packages/core/src packages/server/src packages/protocol/src", + "lint:effect-patterns": "ast-grep scan -c script/ast-grep/sgconfig.yml packages/core/src packages/server/src packages/protocol/src packages/cli/src", + "test:lint-rules": "ast-grep test -c script/ast-grep/sgconfig.yml", "typecheck": "bun turbo typecheck", "upgrade-opentui": "bun run script/upgrade-opentui.ts", "postinstall": "bun run --cwd packages/core fix-node-pty", diff --git a/packages/cli/src/commands/handlers/debug/agents.ts b/packages/cli/src/commands/handlers/debug/agents.ts index ee241bcc1b..1dbaf4d801 100644 --- a/packages/cli/src/commands/handlers/debug/agents.ts +++ b/packages/cli/src/commands/handlers/debug/agents.ts @@ -1,5 +1,5 @@ import { EOL } from "os" -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { createOpencodeClient } from "@opencode-ai/sdk/v2/client" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" diff --git a/packages/cli/src/commands/handlers/mcp/list.ts b/packages/cli/src/commands/handlers/mcp/list.ts index 167509fb70..2d38a6aca0 100644 --- a/packages/cli/src/commands/handlers/mcp/list.ts +++ b/packages/cli/src/commands/handlers/mcp/list.ts @@ -1,5 +1,5 @@ import { EOL } from "node:os" -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { createOpencodeClient, type McpServer } from "@opencode-ai/sdk/v2/client" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" diff --git a/packages/cli/src/commands/handlers/migrate.ts b/packages/cli/src/commands/handlers/migrate.ts index c73c7750df..6ff6939aa1 100644 --- a/packages/cli/src/commands/handlers/migrate.ts +++ b/packages/cli/src/commands/handlers/migrate.ts @@ -1,4 +1,4 @@ -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { Commands } from "../commands" import { Runtime } from "../../framework/runtime" diff --git a/packages/cli/src/commands/handlers/serve.ts b/packages/cli/src/commands/handlers/serve.ts index 11483189c3..8a6b1c2ceb 100644 --- a/packages/cli/src/commands/handlers/serve.ts +++ b/packages/cli/src/commands/handlers/serve.ts @@ -4,8 +4,7 @@ import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { PermissionSaved } from "@opencode-ai/core/permission/saved" import { Global } from "@opencode-ai/core/global" -import { Context, FileSystem, Layer, Option, Redacted, Schedule, Schema } from "effect" -import * as Effect from "effect/Effect" +import { Context, Effect, FileSystem, Layer, Option, Redacted, Schedule, Schema } from "effect" import { HttpRouter, HttpServer } from "effect/unstable/http" import { createServer } from "node:http" import { createRoutes } from "@opencode-ai/server/routes" @@ -60,7 +59,7 @@ export default Runtime.handler( if (!input.service && !input.stdio && !standalonePassword) console.log(`server password ${password}`) const updater = yield* Updater.Service yield* updater.check().pipe(Effect.schedule(Schedule.spaced("10 minutes")), Effect.forkScoped) - return yield* (input.stdio ? waitForStdinClose() : Effect.never) + return yield* input.stdio ? waitForStdinClose() : Effect.never }).pipe(Effect.annotateLogs({ role: "server" })), ) }), diff --git a/packages/cli/src/commands/handlers/service/get.ts b/packages/cli/src/commands/handlers/service/get.ts index 1b85faf6e9..fd4b9af384 100644 --- a/packages/cli/src/commands/handlers/service/get.ts +++ b/packages/cli/src/commands/handlers/service/get.ts @@ -1,6 +1,5 @@ import { EOL } from "os" -import { Option } from "effect" -import * as Effect from "effect/Effect" +import { Effect, Option } from "effect" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" import { ServiceConfig } from "../../../services/service-config" diff --git a/packages/cli/src/commands/handlers/service/restart.ts b/packages/cli/src/commands/handlers/service/restart.ts index c78273ed0f..93b8836acd 100644 --- a/packages/cli/src/commands/handlers/service/restart.ts +++ b/packages/cli/src/commands/handlers/service/restart.ts @@ -1,5 +1,5 @@ import { EOL } from "os" -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { Service } from "@opencode-ai/client/effect" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" diff --git a/packages/cli/src/commands/handlers/service/set.ts b/packages/cli/src/commands/handlers/service/set.ts index 6ecde18d41..f761c02411 100644 --- a/packages/cli/src/commands/handlers/service/set.ts +++ b/packages/cli/src/commands/handlers/service/set.ts @@ -1,4 +1,4 @@ -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" import { ServiceConfig } from "../../../services/service-config" diff --git a/packages/cli/src/commands/handlers/service/start.ts b/packages/cli/src/commands/handlers/service/start.ts index a3a7200bf9..602a26ecf1 100644 --- a/packages/cli/src/commands/handlers/service/start.ts +++ b/packages/cli/src/commands/handlers/service/start.ts @@ -1,5 +1,5 @@ import { EOL } from "os" -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { Service } from "@opencode-ai/client/effect" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" diff --git a/packages/cli/src/commands/handlers/service/status.ts b/packages/cli/src/commands/handlers/service/status.ts index 807d7d749d..bf58968eef 100644 --- a/packages/cli/src/commands/handlers/service/status.ts +++ b/packages/cli/src/commands/handlers/service/status.ts @@ -1,5 +1,5 @@ import { EOL } from "os" -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { Service } from "@opencode-ai/client/effect" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" diff --git a/packages/cli/src/commands/handlers/service/stop.ts b/packages/cli/src/commands/handlers/service/stop.ts index 53ad3615c3..5bf45ccabc 100644 --- a/packages/cli/src/commands/handlers/service/stop.ts +++ b/packages/cli/src/commands/handlers/service/stop.ts @@ -1,4 +1,4 @@ -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { Service } from "@opencode-ai/client/effect" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" diff --git a/packages/cli/src/commands/handlers/service/unset.ts b/packages/cli/src/commands/handlers/service/unset.ts index ef5fdf9330..cc738125d3 100644 --- a/packages/cli/src/commands/handlers/service/unset.ts +++ b/packages/cli/src/commands/handlers/service/unset.ts @@ -1,4 +1,4 @@ -import * as Effect from "effect/Effect" +import { Effect } from "effect" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" import { ServiceConfig } from "../../../services/service-config" diff --git a/packages/cli/src/framework/runtime.ts b/packages/cli/src/framework/runtime.ts index 902c89d716..2108da415d 100644 --- a/packages/cli/src/framework/runtime.ts +++ b/packages/cli/src/framework/runtime.ts @@ -1,9 +1,8 @@ -import * as Effect from "effect/Effect" -import * as Command from "effect/unstable/cli/Command" +import { Effect, FileSystem, Scope } from "effect" +import { Command } from "effect/unstable/cli" import { Spec } from "./spec" import { Global } from "@opencode-ai/core/global" import { Updater } from "../services/updater" -import { FileSystem, Scope } from "effect" export type Input = Value extends Spec.Node @@ -12,11 +11,21 @@ export type Input = ? Input : never -type RuntimeHandler = (input: unknown) => Effect.Effect +type RuntimeHandler = ( + input: unknown, +) => Effect.Effect type Loader = () => Promise<{ - default: (input: Input) => Effect.Effect + default: ( + input: Input, + ) => Effect.Effect }> -type ProvidedCommand = Command.Command +type ProvidedCommand = Command.Command< + string, + unknown, + unknown, + unknown, + FileSystem.FileSystem | Global.Service | Updater.Service | Scope.Scope +> export type Handlers = keyof Node["commands"] extends never ? Loader diff --git a/packages/cli/src/framework/spec.ts b/packages/cli/src/framework/spec.ts index 3bb47e5e5e..345a0cfa85 100644 --- a/packages/cli/src/framework/spec.ts +++ b/packages/cli/src/framework/spec.ts @@ -1,4 +1,4 @@ -import * as Command from "effect/unstable/cli/Command" +import { Command } from "effect/unstable/cli" type Options> = { readonly description?: string diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 071fd37e1a..e515424183 100755 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,10 +1,7 @@ #!/usr/bin/env bun -import * as NodeRuntime from "@effect/platform-node/NodeRuntime" -import * as NodeServices from "@effect/platform-node/NodeServices" -import { NodeFileSystem } from "@effect/platform-node" -import * as Effect from "effect/Effect" -import { Layer, Logger, References } from "effect" +import { NodeFileSystem, NodeRuntime, NodeServices } from "@effect/platform-node" +import { Effect, Layer, Logger, References } from "effect" import { Commands } from "./commands/commands" import { Runtime } from "./framework/runtime" import { Logging } from "@opencode-ai/core/observability/logging" @@ -46,7 +43,11 @@ const Handlers = Runtime.handlers(Commands, { serve: () => import("./commands/handlers/serve"), }) -Effect.logInfo("cli starting", { version: InstallationVersion, channel: InstallationChannel, local: InstallationLocal }).pipe( +Effect.logInfo("cli starting", { + version: InstallationVersion, + channel: InstallationChannel, + local: InstallationLocal, +}).pipe( Effect.flatMap(() => Runtime.run(Commands, Handlers, { version: InstallationVersion })), Effect.annotateLogs({ role: "cli" }), Effect.provide(Updater.layer), diff --git a/packages/core/src/account.ts b/packages/core/src/account.ts index d364d6f344..7e81780e95 100644 --- a/packages/core/src/account.ts +++ b/packages/core/src/account.ts @@ -1,7 +1,7 @@ export * as AccountV2 from "./account" import { Schema } from "effect" -import type * as HttpClientError from "effect/unstable/http/HttpClientError" +import type { HttpClientError } from "effect/unstable/http" export const ID = Schema.String.pipe(Schema.brand("AccountID")) export type ID = Schema.Schema.Type diff --git a/packages/core/src/config/experimental.ts b/packages/core/src/config/experimental.ts index 12a02635db..8b38a225b4 100644 --- a/packages/core/src/config/experimental.ts +++ b/packages/core/src/config/experimental.ts @@ -2,17 +2,19 @@ export * as ConfigExperimental from "./experimental" import { Schema } from "effect" import { Catalog } from "../catalog" -import { Policy as PolicyV2 } from "../policy" +import { Policy } from "../policy" // Each core domain exports the policy actions it supports. Adding an action to // this union makes it valid in authored config while keeping Policy generic. export const PolicyAction = Schema.Union([Catalog.PolicyActions]) -export class Policy extends Schema.Class("ConfigV2.Experimental.Policy")({ - ...PolicyV2.Info.fields, +class PolicyConfig extends Schema.Class("ConfigV2.Experimental.Policy")({ + ...Policy.Info.fields, action: PolicyAction, }) {} +export { PolicyConfig as Policy } + export class Experimental extends Schema.Class("ConfigV2.Experimental")({ - policies: Policy.pipe(Schema.Array, Schema.optional), + policies: PolicyConfig.pipe(Schema.Array, Schema.optional), }) {} diff --git a/packages/core/src/cross-spawn-spawner.ts b/packages/core/src/cross-spawn-spawner.ts index 6ea9022acf..f6a04ffd93 100644 --- a/packages/core/src/cross-spawn-spawner.ts +++ b/packages/core/src/cross-spawn-spawner.ts @@ -1,26 +1,17 @@ -import type * as Arr from "effect/Array" -import { NodeFileSystem, NodeSink, NodeStream } from "@effect/platform-node" -import * as NodePath from "@effect/platform-node/NodePath" -import * as Deferred from "effect/Deferred" -import * as Effect from "effect/Effect" -import * as Exit from "effect/Exit" -import * as FileSystem from "effect/FileSystem" -import * as Layer from "effect/Layer" -import * as Path from "effect/Path" -import * as PlatformError from "effect/PlatformError" -import * as Predicate from "effect/Predicate" -import type * as Scope from "effect/Scope" -import * as Sink from "effect/Sink" -import * as Stream from "effect/Stream" -import * as ChildProcess from "effect/unstable/process/ChildProcess" -import type { ChildProcessHandle } from "effect/unstable/process/ChildProcessSpawner" +import type { NonEmptyReadonlyArray } from "effect/Array" +import { NodeFileSystem, NodePath, NodeSink, NodeStream } from "@effect/platform-node" +import { Deferred, Effect, Exit, FileSystem, Layer, Path, PlatformError, Predicate, Sink, Stream } from "effect" +import type { Scope } from "effect" +import { ChildProcess } from "effect/unstable/process" import { ChildProcessSpawner, ExitCode, - make as makeSpawner, + make, makeHandle, ProcessId, + type ChildProcessHandle, } from "effect/unstable/process/ChildProcessSpawner" +// ast-grep-ignore: no-star-import import * as NodeChildProcess from "node:child_process" import { PassThrough } from "node:stream" import launch from "cross-spawn" @@ -71,7 +62,7 @@ const flatten = (command: ChildProcess.Command) => { if (commands.length === 0) throw new Error("flatten produced empty commands array") const [head, ...tail] = commands return { - commands: [head, ...tail] as Arr.NonEmptyReadonlyArray, + commands: [head, ...tail] as NonEmptyReadonlyArray, opts, } } @@ -96,7 +87,7 @@ const toPlatformError = ( type ExitSignal = Deferred.Deferred -export const make = Effect.gen(function* () { +const makeCrossSpawnSpawner = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem const path = yield* Path.Path @@ -494,12 +485,12 @@ export const make = Effect.gen(function* () { }, ) - return makeSpawner(spawnCommand) + return make(spawnCommand) }) const layer: Layer.Layer = Layer.effect( ChildProcessSpawner, - make, + makeCrossSpawnSpawner, ) export const node = makeGlobalNode({ service: ChildProcessSpawner, layer, deps: [filesystem, path] }) diff --git a/packages/core/src/database/database.ts b/packages/core/src/database/database.ts index d61adf047e..f3cc8b3f9f 100644 --- a/packages/core/src/database/database.ts +++ b/packages/core/src/database/database.ts @@ -1,7 +1,7 @@ export * as Database from "./database" import { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite" -import { layer as sqliteLayer } from "#sqlite" +import { layer } from "#sqlite" import { Context, Effect, Layer } from "effect" import { Global } from "../global" import { Flag } from "../flag/flag" @@ -19,7 +19,7 @@ export interface Interface { export class Service extends Context.Service()("@opencode/v2/storage/Database") {} -const layer = Layer.effect( +const databaseLayer = Layer.effect( Service, Effect.gen(function* () { const db = yield* makeDatabase @@ -37,7 +37,7 @@ const layer = Layer.effect( ) export function layerFromPath(filename: string) { - return layer.pipe(Layer.provide(sqliteLayer({ filename }))) + return databaseLayer.pipe(Layer.provide(layer({ filename }))) } export function path() { diff --git a/packages/core/src/database/migration.ts b/packages/core/src/database/migration.ts index 90dee8acbf..17bf0a5c44 100644 --- a/packages/core/src/database/migration.ts +++ b/packages/core/src/database/migration.ts @@ -22,7 +22,7 @@ export function apply(db: Database) { sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`, ) if (tables.some((table) => table.name === "session")) return yield* applyOnly(db, migrations) - if (tables.length > 0) return yield* Effect.die("Database is not empty and has no session table") + if (tables.length > 0) return yield* Effect.die(new Error("Database is not empty and has no session table")) yield* db.transaction((tx) => Effect.gen(function* () { yield* schema.up(tx) diff --git a/packages/core/src/database/sqlite.bun.ts b/packages/core/src/database/sqlite.bun.ts index e15f4c117e..bbb3ad6143 100644 --- a/packages/core/src/database/sqlite.bun.ts +++ b/packages/core/src/database/sqlite.bun.ts @@ -1,18 +1,11 @@ import { Database } from "bun:sqlite" import { drizzle } from "drizzle-orm/bun-sqlite" -import * as Context from "effect/Context" -import * as Effect from "effect/Effect" -import * as Fiber from "effect/Fiber" +import { Context, Effect, Fiber, Layer, Scope, Semaphore, Stream } from "effect" import { identity } from "effect/Function" -import * as Layer from "effect/Layer" -import * as Scope from "effect/Scope" -import * as Semaphore from "effect/Semaphore" -import * as Stream from "effect/Stream" -import * as Reactivity from "effect/unstable/reactivity/Reactivity" -import * as Client from "effect/unstable/sql/SqlClient" +import { Reactivity } from "effect/unstable/reactivity" +import { SqlClient, Statement } from "effect/unstable/sql" import type { Connection } from "effect/unstable/sql/SqlConnection" import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError" -import * as Statement from "effect/unstable/sql/Statement" import { Sqlite } from "./sqlite" const ATTR_DB_SYSTEM_NAME = "db.system.name" @@ -20,7 +13,7 @@ const ATTR_DB_SYSTEM_NAME = "db.system.name" const TypeId = "~@opencode-ai/core/database/SqliteBun" as const type TypeId = typeof TypeId -interface SqliteClient extends Client.SqlClient { +interface SqliteClient extends SqlClient.SqlClient { readonly [TypeId]: TypeId readonly config: Config readonly export: Effect.Effect @@ -57,7 +50,7 @@ const make = (options: Config) => Effect.withFiber>, SqlError>((fiber) => { const statement = native.query(query) // @ts-ignore bun-types missing safeIntegers method, fixed in https://github.com/oven-sh/bun/pull/26627 - statement.safeIntegers(Context.get(fiber.context, Client.SafeIntegers)) + statement.safeIntegers(Context.get(fiber.context, SqlClient.SafeIntegers)) try { return Effect.succeed((statement.all(...(params as any)) ?? []) as Array>) } catch (cause) { @@ -73,7 +66,7 @@ const make = (options: Config) => Effect.withFiber, SqlError>((fiber) => { const statement = native.query(query) // @ts-ignore bun-types missing safeIntegers method, fixed in https://github.com/oven-sh/bun/pull/26627 - statement.safeIntegers(Context.get(fiber.context, Client.SafeIntegers)) + statement.safeIntegers(Context.get(fiber.context, SqlClient.SafeIntegers)) try { return Effect.succeed((statement.values(...(params as any)) ?? []) as Array) } catch (cause) { @@ -130,7 +123,7 @@ const make = (options: Config) => }) const client = Object.assign( - (yield* Client.make({ + (yield* SqlClient.make({ acquirer, compiler, transactionAcquirer, @@ -166,7 +159,7 @@ const nativeLayer = (config: Config) => }), ) -const sqliteLayer = (config: Config) => Layer.effect(Client.SqlClient, make(config)) +const sqliteLayer = (config: Config) => Layer.effect(SqlClient.SqlClient, make(config)) const drizzleLayer = Layer.effect( Sqlite.Drizzle, diff --git a/packages/core/src/database/sqlite.node.ts b/packages/core/src/database/sqlite.node.ts index 6eaecbee26..6fcbd76e4e 100644 --- a/packages/core/src/database/sqlite.node.ts +++ b/packages/core/src/database/sqlite.node.ts @@ -1,18 +1,11 @@ import { DatabaseSync, type SQLInputValue } from "node:sqlite" import { drizzle } from "drizzle-orm/node-sqlite" -import * as Context from "effect/Context" -import * as Effect from "effect/Effect" -import * as Fiber from "effect/Fiber" +import { Context, Effect, Fiber, Layer, Scope, Semaphore, Stream } from "effect" import { identity } from "effect/Function" -import * as Layer from "effect/Layer" -import * as Scope from "effect/Scope" -import * as Semaphore from "effect/Semaphore" -import * as Stream from "effect/Stream" -import * as Reactivity from "effect/unstable/reactivity/Reactivity" -import * as Client from "effect/unstable/sql/SqlClient" +import { Reactivity } from "effect/unstable/reactivity" +import { SqlClient, Statement } from "effect/unstable/sql" import type { Connection } from "effect/unstable/sql/SqlConnection" import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError" -import * as Statement from "effect/unstable/sql/Statement" import { Sqlite } from "./sqlite" const ATTR_DB_SYSTEM_NAME = "db.system.name" @@ -20,7 +13,7 @@ const ATTR_DB_SYSTEM_NAME = "db.system.name" const TypeId = "~@opencode-ai/core/database/SqliteNode" as const type TypeId = typeof TypeId -interface SqliteClient extends Client.SqlClient { +interface SqliteClient extends SqlClient.SqlClient { readonly [TypeId]: TypeId readonly config: Config readonly loadExtension: (path: string) => Effect.Effect @@ -56,7 +49,7 @@ const make = (options: Config) => const run = (query: string, params: ReadonlyArray = []) => Effect.withFiber>, SqlError>((fiber) => { const statement = native.prepare(query) - statement.setReadBigInts(Context.get(fiber.context, Client.SafeIntegers)) + statement.setReadBigInts(Context.get(fiber.context, SqlClient.SafeIntegers)) try { return Effect.succeed(statement.all(...(params as SQLInputValue[])) as Array>) } catch (cause) { @@ -71,7 +64,7 @@ const make = (options: Config) => const runValues = (query: string, params: ReadonlyArray = []) => Effect.withFiber>, SqlError>((fiber) => { const statement = native.prepare(query) - statement.setReadBigInts(Context.get(fiber.context, Client.SafeIntegers)) + statement.setReadBigInts(Context.get(fiber.context, SqlClient.SafeIntegers)) statement.setReturnArrays(true) try { return Effect.succeed( @@ -124,7 +117,7 @@ const make = (options: Config) => }) const client = Object.assign( - (yield* Client.make({ + (yield* SqlClient.make({ acquirer, compiler, transactionAcquirer, @@ -161,7 +154,7 @@ const nativeLayer = (config: Config) => }), ) -const sqliteLayer = (config: Config) => Layer.effect(Client.SqlClient, make(config)) +const sqliteLayer = (config: Config) => Layer.effect(SqlClient.SqlClient, make(config)) const drizzleLayer = Layer.effect( Sqlite.Drizzle, diff --git a/packages/core/src/form.ts b/packages/core/src/form.ts index 47a72ed23a..d49129b3b8 100644 --- a/packages/core/src/form.ts +++ b/packages/core/src/form.ts @@ -98,10 +98,14 @@ export const layer = Layer.effect( Service, Effect.gen(function* () { const events = yield* EventV2.Service - const forms = yield* Cache.makeWith(() => Effect.die("Form cache must be used via set/getSuccess, never get"), { - capacity: Number.MAX_SAFE_INTEGER, - timeToLive: (exit) => (Exit.isSuccess(exit) && exit.value.state.status === "pending" ? Duration.infinity : RETENTION), - }) + const forms = yield* Cache.makeWith( + () => Effect.die(new Error("Form cache must be used via set/getSuccess, never get")), + { + capacity: Number.MAX_SAFE_INTEGER, + timeToLive: (exit) => + Exit.isSuccess(exit) && exit.value.state.status === "pending" ? Duration.infinity : RETENTION, + }, + ) const find = Effect.fn("Form.find")(function* (id: ID) { return yield* Cache.getSuccess(forms, id).pipe( @@ -131,7 +135,9 @@ export const layer = Layer.effect( ...(input.metadata === undefined ? {} : { metadata: input.metadata }), } const form: Info = - input.mode === "form" ? { ...base, mode: "form", fields: input.fields } : { ...base, mode: "url", url: input.url } + input.mode === "form" + ? { ...base, mode: "form", fields: input.fields } + : { ...base, mode: "url", url: input.url } const entry: Entry = { form, state: { status: "pending" }, @@ -149,7 +155,9 @@ export const layer = Layer.effect( Effect.gen(function* () { const form = yield* create(input) const entry = yield* find(form.id).pipe(Effect.orDie) - return yield* restore(Deferred.await(entry.deferred)).pipe(Effect.onInterrupt(() => Effect.ignore(cancel(form.id)))) + return yield* restore(Deferred.await(entry.deferred)).pipe( + Effect.onInterrupt(() => Effect.ignore(cancel(form.id))), + ) }), ), ) @@ -301,7 +309,8 @@ function validateField(field: Form.Field, value: Form.Value): string | undefined return `Form field has invalid pattern: ${field.key}` } } - if (field.format === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return `Expected email for form field: ${field.key}` + if (field.format === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) + return `Expected email for form field: ${field.key}` if (field.format === "uri" && !isUri(value)) return `Expected URI for form field: ${field.key}` if (field.format === "date" && !isDate(value)) return `Expected date for form field: ${field.key}` if (field.format === "date-time" && !isDateTime(value)) return `Expected date-time for form field: ${field.key}` @@ -324,8 +333,10 @@ function validateField(field: Form.Field, value: Form.Value): string | undefined if (field.type === "multiselect") { if (!isStringArray(value)) return `Expected string array for form field: ${field.key}` if (field.required && value.length === 0) return `Missing required form field: ${field.key}` - if (field.minItems !== undefined && value.length < field.minItems) return `Too few selections for form field: ${field.key}` - if (field.maxItems !== undefined && value.length > field.maxItems) return `Too many selections for form field: ${field.key}` + if (field.minItems !== undefined && value.length < field.minItems) + return `Too few selections for form field: ${field.key}` + if (field.maxItems !== undefined && value.length > field.maxItems) + return `Too many selections for form field: ${field.key}` if (!field.custom && value.some((item) => !field.options.some((option) => option.value === item))) { return `Invalid option for form field: ${field.key}` } diff --git a/packages/core/src/fs-util.ts b/packages/core/src/fs-util.ts index 124ac6d702..b6edce6657 100644 --- a/packages/core/src/fs-util.ts +++ b/packages/core/src/fs-util.ts @@ -1,7 +1,7 @@ import { NodeFileSystem } from "@effect/platform-node" -import { dirname, isAbsolute, join, relative, resolve as pathResolve, sep } from "path" +import path, { dirname, isAbsolute, join, relative, sep } from "path" import { realpathSync } from "fs" -import * as NFS from "fs/promises" +import { readdir } from "fs/promises" import { lookup } from "mime-types" import { Context, Effect, FileSystem, Layer, Schema } from "effect" import type { PlatformError } from "effect/PlatformError" @@ -78,7 +78,7 @@ export namespace FSUtil { const readDirectoryEntries = Effect.fn("FileSystem.readDirectoryEntries")(function* (dirPath: string) { return yield* Effect.tryPromise({ try: async () => { - const entries = await NFS.readdir(dirPath, { withFileTypes: true }) + const entries = await readdir(dirPath, { withFileTypes: true }) return entries.map( (e): DirEntry => ({ name: e.name, @@ -90,8 +90,8 @@ export namespace FSUtil { }) }) - const resolve = Effect.fn("FileSystem.resolve")(function* (path: string) { - const resolved = pathResolve(windowsPath(path)) + const resolve = Effect.fn("FileSystem.resolve")(function* (input: string) { + const resolved = path.resolve(windowsPath(input)) return yield* fs.realPath(resolved).pipe( Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(resolved)), Effect.orDie, @@ -219,7 +219,7 @@ export namespace FSUtil { export function normalizePath(p: string): string { if (process.platform !== "win32") return p - const resolved = pathResolve(windowsPath(p)) + const resolved = path.resolve(windowsPath(p)) try { return realpathSync.native(resolved) } catch { @@ -237,7 +237,7 @@ export namespace FSUtil { } export function resolve(p: string): string { - const resolved = pathResolve(windowsPath(p)) + const resolved = path.resolve(windowsPath(p)) try { return normalizePath(realpathSync(resolved)) } catch (e: any) { diff --git a/packages/core/src/id/id.ts b/packages/core/src/id/id.ts index be1efc446a..b4d6e496ea 100644 --- a/packages/core/src/id/id.ts +++ b/packages/core/src/id/id.ts @@ -1,4 +1,4 @@ -import { create as createIdentifier } from "@opencode-ai/schema/identifier" +import { create } from "@opencode-ai/schema/identifier" const prefixes = { job: "job", @@ -23,7 +23,7 @@ export function descending(prefix: keyof typeof prefixes, given?: string) { function generateID(prefix: keyof typeof prefixes, direction: "descending" | "ascending", given?: string): string { if (!given) { - return create(prefixes[prefix], direction) + return createID(prefixes[prefix], direction) } if (!given.startsWith(prefixes[prefix])) { @@ -32,10 +32,12 @@ function generateID(prefix: keyof typeof prefixes, direction: "descending" | "as return given } -export function create(prefix: string, direction: "descending" | "ascending", timestamp?: number): string { - return prefix + "_" + createIdentifier(direction === "descending", timestamp) +function createID(prefix: string, direction: "descending" | "ascending", timestamp?: number): string { + return prefix + "_" + create(direction === "descending", timestamp) } +export { createID as create } + /** Extract timestamp from an ascending ID. Does not work with descending IDs. */ export function timestamp(id: string): number { const prefix = id.split("_")[0] diff --git a/packages/core/src/integration.ts b/packages/core/src/integration.ts index 9acbbe93eb..12dad07dd3 100644 --- a/packages/core/src/integration.ts +++ b/packages/core/src/integration.ts @@ -406,7 +406,7 @@ const layer = Layer.effect( .get() .integrations.get(input.integrationID) ?.methods.some((method) => method.type === "key") - if (!method) return yield* Effect.die(`Key method not found: ${input.integrationID}`) + if (!method) return yield* Effect.die(new Error(`Key method not found: ${input.integrationID}`)) yield* credentials.create({ integrationID: input.integrationID, label: input.label, @@ -418,7 +418,7 @@ const layer = Layer.effect( oauth: Effect.fn("Integration.connection.oauth")(function* (input) { const method = state.get().integrations.get(input.integrationID)?.implementations.get(input.methodID) if (!method) { - return yield* Effect.die(`OAuth method not found: ${input.integrationID}/${input.methodID}`) + return yield* Effect.die(new Error(`OAuth method not found: ${input.integrationID}/${input.methodID}`)) } const attemptScope = yield* Scope.fork(scope) const authorization = yield* authorize(method.authorize(input.inputs)).pipe( @@ -475,7 +475,7 @@ const layer = Layer.effect( attempt: { status: Effect.fn("Integration.attempt.status")(function* (attemptID) { const attempt = (yield* SynchronizedRef.get(attempts)).get(attemptID) - if (!attempt) return yield* Effect.die(`OAuth attempt not found: ${attemptID}`) + if (!attempt) return yield* Effect.die(new Error(`OAuth attempt not found: ${attemptID}`)) if (attempt.status === "failed") { return { status: attempt.status, message: attempt.message ?? "Authorization failed", time: attempt.time } } @@ -488,12 +488,13 @@ const layer = Layer.effect( if (match.authorization.mode === "code" && input.code === undefined) return [match, current] return [match, new Map(current).set(input.attemptID, { ...match, completing: true })] }) - if (!attempt) return yield* Effect.die(`OAuth attempt not found: ${input.attemptID}`) + if (!attempt) return yield* Effect.die(new Error(`OAuth attempt not found: ${input.attemptID}`)) if (attempt.status !== "pending") return if (attempt.authorization.mode === "code" && input.code === undefined) { return yield* new CodeRequiredError({ attemptID: input.attemptID }) } - if (attempt.completing) return yield* Effect.die(`OAuth attempt already completing: ${input.attemptID}`) + if (attempt.completing) + return yield* Effect.die(new Error(`OAuth attempt already completing: ${input.attemptID}`)) const callback = attempt.authorization.mode === "auto" ? attempt.authorization.callback diff --git a/packages/core/src/location-services.ts b/packages/core/src/location-services.ts index 1af35e61a1..ffb7db2cf1 100644 --- a/packages/core/src/location-services.ts +++ b/packages/core/src/location-services.ts @@ -29,7 +29,7 @@ import { QuestionV2 } from "./question" import { Shell } from "./shell" import { Reference } from "./reference" import { ReferenceGuidance } from "./reference/guidance" -import * as SessionRunnerLLM from "./session/runner/llm" +import { SessionRunnerLLM } from "./session/runner/llm" import { SessionRunnerModel } from "./session/runner/model" import { SessionCompaction } from "./session/compaction" import { SessionTitle } from "./session/title" diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index 791d0a9bcd..3a8dc12b25 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -1,7 +1,7 @@ export * as PermissionV2 from "./permission" import { makeLocationNode } from "./effect/app-node" -import { Context, Deferred, Effect as EffectRuntime, Layer, Schema } from "effect" +import { Context, Deferred, Effect, Layer, Schema } from "effect" import { Permission } from "@opencode-ai/schema/permission" import { EventV2 } from "./event" import { Location } from "./location" @@ -11,7 +11,9 @@ import { SessionStore } from "./session/store" import { Wildcard } from "./util/wildcard" import { PermissionSaved } from "./permission/saved" -export { Effect, Rule, Ruleset } from "@opencode-ai/schema/permission" +const PermissionEffect = Permission.Effect +export { PermissionEffect as Effect } +export { Rule, Ruleset } from "@opencode-ai/schema/permission" const missingAgentPermissions: Permission.Ruleset = [{ action: "*", resource: "*", effect: "deny" }] export const ID = Permission.ID @@ -90,12 +92,12 @@ export function merge(...rulesets: Permission.Ruleset[]): Permission.Ruleset { } export interface Interface { - readonly ask: (input: AssertInput) => EffectRuntime.Effect - readonly assert: (input: AssertInput) => EffectRuntime.Effect - readonly reply: (input: ReplyInput) => EffectRuntime.Effect - readonly get: (id: ID) => EffectRuntime.Effect - readonly forSession: (sessionID: SessionV2.ID) => EffectRuntime.Effect> - readonly list: () => EffectRuntime.Effect> + readonly ask: (input: AssertInput) => Effect.Effect + readonly assert: (input: AssertInput) => Effect.Effect + readonly reply: (input: ReplyInput) => Effect.Effect + readonly get: (id: ID) => Effect.Effect + readonly forSession: (sessionID: SessionV2.ID) => Effect.Effect> + readonly list: () => Effect.Effect> } export class Service extends Context.Service()("@opencode/v2/Permission") {} @@ -108,7 +110,7 @@ interface Pending { const layer = Layer.effect( Service, - EffectRuntime.gen(function* () { + Effect.gen(function* () { const events = yield* EventV2.Service const location = yield* Location.Service const agents = yield* AgentV2.Service @@ -116,28 +118,25 @@ const layer = Layer.effect( const saved = yield* PermissionSaved.Service const pending = new Map() - yield* EffectRuntime.addFinalizer(() => - EffectRuntime.forEach(pending.values(), (item) => Deferred.fail(item.deferred, new RejectedError()), { + yield* Effect.addFinalizer(() => + Effect.forEach(pending.values(), (item) => Deferred.fail(item.deferred, new RejectedError()), { discard: true, }).pipe( - EffectRuntime.ensuring( - EffectRuntime.sync(() => { + Effect.ensuring( + Effect.sync(() => { pending.clear() }), ), ), ) - const savedRules = EffectRuntime.fnUntraced(function* () { + const savedRules = Effect.fnUntraced(function* () { return (yield* saved.list({ projectID: location.project.id })).map( (item): Permission.Rule => ({ action: item.action, resource: item.resource, effect: "allow" }), ) }) - const configured = EffectRuntime.fn("PermissionV2.configured")(function* ( - sessionID: SessionV2.ID, - agentID?: AgentV2.ID, - ) { + const configured = Effect.fn("PermissionV2.configured")(function* (sessionID: SessionV2.ID, agentID?: AgentV2.ID) { const session = yield* sessions.get(sessionID) if (!session) return yield* new SessionV2.NotFoundError({ sessionID }) const agent = yield* agents.resolve(agentID ?? session.agent) @@ -152,7 +151,7 @@ const layer = Layer.effect( return rules.filter((rule) => Wildcard.match(input.action, rule.action)) } - const evaluateInput = EffectRuntime.fnUntraced(function* (input: AssertInput) { + const evaluateInput = Effect.fnUntraced(function* (input: AssertInput) { const rules = yield* configured(input.sessionID, input.agent) if (denied(input, rules)) return { effect: "deny" as const, rules } const all = [...rules, ...(yield* savedRules())] @@ -174,29 +173,30 @@ const layer = Layer.effect( } const create = (request: Request, agent?: AgentV2.ID) => - EffectRuntime.uninterruptible( - EffectRuntime.gen(function* () { + Effect.uninterruptible( + Effect.gen(function* () { const deferred = yield* Deferred.make() const item = { request, agent, deferred } - if (pending.has(request.id)) return yield* EffectRuntime.die(`Duplicate pending permission ID: ${request.id}`) + if (pending.has(request.id)) + return yield* Effect.die(new Error(`Duplicate pending permission ID: ${request.id}`)) pending.set(request.id, item) yield* events .publish(Event.Asked, request) - .pipe(EffectRuntime.onError(() => EffectRuntime.sync(() => pending.delete(request.id)))) + .pipe(Effect.onError(() => Effect.sync(() => pending.delete(request.id)))) return item }), ) - const ask = EffectRuntime.fn("PermissionV2.ask")(function* (input: AssertInput) { + const ask = Effect.fn("PermissionV2.ask")(function* (input: AssertInput) { const result = yield* evaluateInput(input) const value = request(input) if (result.effect === "ask") yield* create(value, input.agent) return { id: value.id, effect: result.effect } }) - const assert = EffectRuntime.fn("PermissionV2.assert")((input: AssertInput) => - EffectRuntime.uninterruptibleMask((restore) => - EffectRuntime.gen(function* () { + const assert = Effect.fn("PermissionV2.assert")((input: AssertInput) => + Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { const result = yield* evaluateInput(input) if (result.effect === "deny") { return yield* new DeniedError({ @@ -206,8 +206,8 @@ const layer = Layer.effect( if (result.effect === "allow") return const item = yield* create(request(input), input.agent) return yield* restore(Deferred.await(item.deferred)).pipe( - EffectRuntime.ensuring( - EffectRuntime.sync(() => { + Effect.ensuring( + Effect.sync(() => { pending.delete(item.request.id) }), ), @@ -216,9 +216,9 @@ const layer = Layer.effect( ), ) - const reply = EffectRuntime.fn("PermissionV2.reply")((input: ReplyInput) => - EffectRuntime.uninterruptible( - EffectRuntime.gen(function* () { + const reply = Effect.fn("PermissionV2.reply")((input: ReplyInput) => + Effect.uninterruptible( + Effect.gen(function* () { const existing = pending.get(input.requestID) if (!existing) return yield* new NotFoundError({ requestID: input.requestID }) yield* events.publish(Event.Replied, { @@ -261,7 +261,7 @@ const layer = Layer.effect( for (const [id, item] of pending) { const input = { ...item.request } const rules = yield* configured(item.request.sessionID, item.agent).pipe( - EffectRuntime.catchTag("Session.NotFoundError", () => EffectRuntime.succeed(undefined)), + Effect.catchTag("Session.NotFoundError", () => Effect.succeed(undefined)), ) if (!rules) continue if (denied(input, rules)) continue @@ -284,15 +284,15 @@ const layer = Layer.effect( ), ) - const list = EffectRuntime.fn("PermissionV2.list")(function* () { + const list = Effect.fn("PermissionV2.list")(function* () { return Array.from(pending.values(), (item) => item.request) }) - const get = EffectRuntime.fn("PermissionV2.get")(function* (id: ID) { + const get = Effect.fn("PermissionV2.get")(function* (id: ID) { return pending.get(id)?.request }) - const forSession = EffectRuntime.fn("PermissionV2.forSession")(function* (sessionID: SessionV2.ID) { + const forSession = Effect.fn("PermissionV2.forSession")(function* (sessionID: SessionV2.ID) { return Array.from(pending.values(), (item) => item.request).filter((request) => request.sessionID === sessionID) }) diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index dd80647a73..a6ff337c62 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -48,7 +48,7 @@ const layer = Layer.effect( let host: Parameters[0] const add = Effect.fn("Plugin.add")(function* (id: ID, effect: PluginDefinition["effect"]) { - if (loading.has(id)) return yield* Effect.die(`Plugin load cycle detected for ${id}`) + if (loading.has(id)) return yield* Effect.die(new Error(`Plugin load cycle detected for ${id}`)) yield* locks.withLock(id)( Effect.sync(() => { @@ -90,7 +90,7 @@ const layer = Layer.effect( }) const remove = Effect.fn("Plugin.remove")(function* (id: ID) { - if (loading.has(id)) return yield* Effect.die(`Cannot remove plugin ${id} while it is loading`) + if (loading.has(id)) return yield* Effect.die(new Error(`Cannot remove plugin ${id} while it is loading`)) yield* locks.withLock(id)( State.batch( diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index 00ff7c82af..d07ba6f0fd 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -1,6 +1,6 @@ export * as PluginHost from "./host" -import type { PluginContext as Interface } from "@opencode-ai/plugin/v2/effect" +import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { Effect, Schema } from "effect" import { AgentV2 } from "../agent" import { AISDK } from "../aisdk" @@ -40,7 +40,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Int workspaceID: location.workspaceID, project: location.project, }) - const locationRef = (input?: Parameters[0]) => + const locationRef = (input?: Parameters[0]) => input?.location === undefined ? undefined : Location.Ref.make({ @@ -305,5 +305,5 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Int command: runtime.session.command, interrupt: (input) => runtime.session.interrupt(input.sessionID), }, - } satisfies Interface + } satisfies PluginContext }) diff --git a/packages/core/src/plugin/runtime.ts b/packages/core/src/plugin/runtime.ts index cb5b40fd17..e79b498bd4 100644 --- a/packages/core/src/plugin/runtime.ts +++ b/packages/core/src/plugin/runtime.ts @@ -31,7 +31,7 @@ export interface Cell { export const makeCell = (): Cell => ({}) -const unavailable = () => Effect.die("Plugin runtime is unavailable") as Effect.Effect +const unavailable = () => Effect.die(new Error("Plugin runtime is unavailable")) as Effect.Effect const require = (cell: Cell, f: (runtime: Interface) => Effect.Effect) => Effect.suspend(() => { const runtime = cell.runtime diff --git a/packages/core/src/policy.ts b/packages/core/src/policy.ts index 782f182b0e..d1dbb3e37c 100644 --- a/packages/core/src/policy.ts +++ b/packages/core/src/policy.ts @@ -1,22 +1,23 @@ export * as Policy from "./policy" import { makeLocationNode } from "./effect/app-node" -import { Context, Effect as EffectRuntime, Layer, Schema } from "effect" +import { Context, Effect, Layer, Schema } from "effect" import { Wildcard } from "./util/wildcard" import { Location } from "./location" -export const Effect = Schema.Literals(["allow", "deny"]).annotate({ identifier: "Policy.Effect" }) -export type Effect = typeof Effect.Type +const PolicyEffect = Schema.Literals(["allow", "deny"]).annotate({ identifier: "Policy.Effect" }) +export { PolicyEffect as Effect } +export type Effect = typeof PolicyEffect.Type export class Info extends Schema.Class("Policy.Info")({ action: Schema.String, - effect: Effect, + effect: PolicyEffect, resource: Schema.String, }) {} export interface Interface { - readonly load: (statements: Info[]) => EffectRuntime.Effect - readonly evaluate: (action: string, resource: string, fallback: Effect) => EffectRuntime.Effect + readonly load: (statements: Info[]) => Effect.Effect + readonly evaluate: (action: string, resource: string, fallback: Effect) => Effect.Effect readonly hasStatements: () => boolean } @@ -24,16 +25,16 @@ export class Service extends Context.Service()("@opencode/v2 const layer = Layer.effect( Service, - EffectRuntime.gen(function* () { + Effect.gen(function* () { let statements: Info[] = [] yield* Location.Service return Service.of({ - load: EffectRuntime.fn("Policy.load")(function* (input) { + load: Effect.fn("Policy.load")(function* (input) { statements = input }), hasStatements: () => statements.length > 0, - evaluate: EffectRuntime.fn("Policy.evaluate")(function* (action, resource, fallback) { + evaluate: Effect.fn("Policy.evaluate")(function* (action, resource, fallback) { return ( statements.findLast( (statement) => Wildcard.match(action, statement.action) && Wildcard.match(resource, statement.resource), diff --git a/packages/core/src/project/sql.ts b/packages/core/src/project/sql.ts index ab05fdac4a..6a7e5a9d54 100644 --- a/packages/core/src/project/sql.ts +++ b/packages/core/src/project/sql.ts @@ -1,11 +1,11 @@ import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core" -import * as DatabasePath from "../database/path" +import { absoluteArrayColumn, absoluteColumn } from "../database/path" import { Timestamps } from "../database/schema.sql" import { ProjectSchema } from "./schema" export const ProjectTable = sqliteTable("project", { id: text().$type().primaryKey(), - worktree: DatabasePath.absoluteColumn().notNull(), + worktree: absoluteColumn().notNull(), vcs: text(), name: text(), icon_url: text(), @@ -13,7 +13,7 @@ export const ProjectTable = sqliteTable("project", { icon_color: text(), ...Timestamps, time_initialized: integer(), - sandboxes: DatabasePath.absoluteArrayColumn().notNull(), + sandboxes: absoluteArrayColumn().notNull(), commands: text({ mode: "json" }).$type<{ start?: string }>(), }) @@ -24,7 +24,7 @@ export const ProjectDirectoryTable = sqliteTable( .$type() .notNull() .references(() => ProjectTable.id, { onDelete: "cascade" }), - directory: DatabasePath.absoluteColumn().notNull(), + directory: absoluteColumn().notNull(), type: text().$type<"main" | "root" | "git_worktree">(), strategy: text(), time_created: integer() diff --git a/packages/core/src/pty/pty.bun.ts b/packages/core/src/pty/pty.bun.ts index 1f8ce8e454..b92ba4409b 100644 --- a/packages/core/src/pty/pty.bun.ts +++ b/packages/core/src/pty/pty.bun.ts @@ -1,10 +1,10 @@ -import { spawn as create } from "bun-pty" +import { spawn } from "bun-pty" import type { Opts, Proc } from "./pty" export type { Disp, Exit, Opts, Proc } from "./pty" -export function spawn(file: string, args: string[], opts: Opts): Proc { - const pty = create(file, args, opts) +function spawnPty(file: string, args: string[], opts: Opts): Proc { + const pty = spawn(file, args, opts) return { pid: pty.pid, onData(listener) { @@ -24,3 +24,5 @@ export function spawn(file: string, args: string[], opts: Opts): Proc { }, } } + +export { spawnPty as spawn } diff --git a/packages/core/src/pty/pty.node.ts b/packages/core/src/pty/pty.node.ts index 76f415f4cd..cc775c8fda 100644 --- a/packages/core/src/pty/pty.node.ts +++ b/packages/core/src/pty/pty.node.ts @@ -1,3 +1,4 @@ +// ast-grep-ignore: no-star-import import * as pty from "@lydell/node-pty" import type { Opts, Proc } from "./pty" diff --git a/packages/core/src/pty/ticket.ts b/packages/core/src/pty/ticket.ts index 07838b1415..2f227aa142 100644 --- a/packages/core/src/pty/ticket.ts +++ b/packages/core/src/pty/ticket.ts @@ -32,7 +32,7 @@ function matches(record: Scope, input: Scope) { // Tickets are inserted via Cache.set and removed atomically via invalidateWhen. The lookup is // never invoked; it dies if it ever is, which would signal a misuse of the Service interface. -const noLookup = () => Effect.die("PtyTicket cache must be used via set/invalidateWhen, never get") +const noLookup = () => Effect.die(new Error("PtyTicket cache must be used via set/invalidateWhen, never get")) // Visible for tests so the TTL can be shortened. Production uses `layer` with the default TTL. export const make = (ttl: Duration.Input = DEFAULT_TTL) => diff --git a/packages/core/src/session/compaction.ts b/packages/core/src/session/compaction.ts index 9ff953be82..fdb81c5045 100644 --- a/packages/core/src/session/compaction.ts +++ b/packages/core/src/session/compaction.ts @@ -2,10 +2,8 @@ export * as SessionCompaction from "./compaction" import { LLM, LLMClient, LLMError, LLMEvent, Message, type LLMRequest, type Model } from "@opencode-ai/llm" import { Context, DateTime, Effect, Layer, Stream } from "effect" -import type { Config } from "../config" -import { Config as ConfigV2 } from "../config" -import type { EventV2 } from "../event" -import { EventV2 as EventV2Service } from "../event" +import { Config } from "../config" +import { EventV2 } from "../event" import { makeLocationNode } from "../effect/app-node" import { llmClient } from "../effect/app-node-platform" import { SessionEvent } from "./event" @@ -311,9 +309,9 @@ const make = (dependencies: Dependencies) => { export const layer = Layer.effect( Service, Effect.gen(function* () { - const events = yield* EventV2Service.Service + const events = yield* EventV2.Service const llm = yield* LLMClient.Service - const config = yield* ConfigV2.Service + const config = yield* Config.Service const models = yield* SessionRunnerModel.Service const compaction = make({ events, llm, config: yield* config.entries() }) @@ -336,5 +334,5 @@ export const layer = Layer.effect( export const node = makeLocationNode({ service: Service, layer, - deps: [EventV2Service.node, llmClient, ConfigV2.node, SessionRunnerModel.node], + deps: [EventV2.node, llmClient, Config.node, SessionRunnerModel.node], }) diff --git a/packages/core/src/session/context-checkpoint.ts b/packages/core/src/session/context-checkpoint.ts index c2036e726a..8ea1f46513 100644 --- a/packages/core/src/session/context-checkpoint.ts +++ b/packages/core/src/session/context-checkpoint.ts @@ -112,7 +112,7 @@ const rewrite = Effect.fnUntraced(function* ( .returning({ sessionID: SessionContextCheckpointTable.session_id }) .get() .pipe(Effect.orDie) - if (!updated) return yield* Effect.die("Context checkpoint not found") + if (!updated) return yield* Effect.die(new Error("Context checkpoint not found")) }) const advance = Effect.fnUntraced(function* ( @@ -127,5 +127,5 @@ const advance = Effect.fnUntraced(function* ( .returning({ sessionID: SessionContextCheckpointTable.session_id }) .get() .pipe(Effect.orDie) - if (!updated) return yield* Effect.die("Context checkpoint not found") + if (!updated) return yield* Effect.die(new Error("Context checkpoint not found")) }) diff --git a/packages/core/src/session/execution/local.ts b/packages/core/src/session/execution/local.ts index 8609162c82..60e32b7c2c 100644 --- a/packages/core/src/session/execution/local.ts +++ b/packages/core/src/session/execution/local.ts @@ -19,7 +19,7 @@ const layer = Layer.effect( const coordinator = yield* SessionRunCoordinator.make({ drain: Effect.fnUntraced(function* (sessionID: SessionSchema.ID, force) { const session = yield* store.get(sessionID) - if (!session) return yield* Effect.die(`Session not found: ${sessionID}`) + if (!session) return yield* Effect.die(new Error(`Session not found: ${sessionID}`)) return yield* SessionRunner.Service.use((runner) => runner.run({ sessionID, force })).pipe( Effect.provide(locations.get(session.location)), Effect.tapCause((cause) => diff --git a/packages/core/src/session/input.ts b/packages/core/src/session/input.ts index 2c6aeda460..8d89563543 100644 --- a/packages/core/src/session/input.ts +++ b/packages/core/src/session/input.ts @@ -62,7 +62,7 @@ export const admit = Effect.fn("SessionInput.admit")(function* ( .pipe( Effect.flatMap((event) => event.durable === undefined - ? Effect.die("Prompt admission event is missing aggregate sequence") + ? Effect.die(new Error("Prompt admission event is missing aggregate sequence")) : Effect.succeed( Admitted.make({ admittedSeq: event.durable.seq, diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index 5e2d112229..7b08733684 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -157,7 +157,7 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( .where(eq(SessionTable.id, event.data.parentID)) .get() .pipe(Effect.orDie) - if (!parent) return yield* Effect.die(`Fork parent session not found: ${event.data.parentID}`) + if (!parent) return yield* Effect.die(new Error(`Fork parent session not found: ${event.data.parentID}`)) const boundary = event.data.messageID ? yield* db .select({ seq: SessionMessageTable.seq }) @@ -172,7 +172,7 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( .pipe(Effect.orDie) : undefined if (event.data.messageID && !boundary) - return yield* Effect.die(`Fork boundary message not found: ${event.data.messageID}`) + return yield* Effect.die(new Error(`Fork boundary message not found: ${event.data.messageID}`)) const copied = yield* db .select({ seq: SessionMessageTable.seq }) .from(SessionMessageTable) @@ -341,7 +341,8 @@ function run(db: DatabaseService, event: MessageEvent) { const decodeRow = (row: typeof SessionMessageTable.$inferSelect) => decodeMessage({ ...row.data, id: row.id, type: row.type }) const updateMessage = (message: SessionMessage.Message) => { - if (event.durable === undefined) return Effect.die("Durable Session event is missing aggregate sequence") + if (event.durable === undefined) + return Effect.die(new Error("Durable Session event is missing aggregate sequence")) const encoded = encodeMessage(message) const { id, type, ...data } = encoded return db @@ -418,7 +419,7 @@ function run(db: DatabaseService, event: MessageEvent) { } function insertMessage(db: DatabaseService, event: SessionEvent.DurableEvent, message: SessionMessage.Message) { - if (event.durable === undefined) return Effect.die("Durable Session event is missing aggregate sequence") + if (event.durable === undefined) return Effect.die(new Error("Durable Session event is missing aggregate sequence")) const encoded = encodeMessage(message) const { id, type, ...data } = encoded return db @@ -585,7 +586,8 @@ const layer = Layer.effectDiscard( yield* events.project(SessionEvent.Forked, (event) => projectFork(db, event)) yield* events.project(SessionEvent.Prompted, (event) => Effect.gen(function* () { - if (event.durable === undefined) return yield* Effect.die("Durable Session event is missing aggregate sequence") + if (event.durable === undefined) + return yield* Effect.die(new Error("Durable Session event is missing aggregate sequence")) yield* SessionInput.projectPrompted(db, { id: event.data.messageID, sessionID: event.data.sessionID, @@ -599,7 +601,8 @@ const layer = Layer.effectDiscard( ) yield* events.project(SessionEvent.PromptAdmitted, (event) => Effect.gen(function* () { - if (event.durable === undefined) return yield* Effect.die("Durable Session event is missing aggregate sequence") + if (event.durable === undefined) + return yield* Effect.die(new Error("Durable Session event is missing aggregate sequence")) yield* SessionInput.projectAdmitted(db, { admittedSeq: event.durable.seq, id: event.data.messageID, @@ -670,7 +673,7 @@ const layer = Layer.effectDiscard( ) .get() .pipe(Effect.orDie) - if (!boundary) return yield* Effect.die(`Revert boundary message not found: ${event.data.messageID}`) + if (!boundary) return yield* Effect.die(new Error(`Revert boundary message not found: ${event.data.messageID}`)) yield* db .delete(SessionMessageTable) .where( diff --git a/packages/core/src/session/runner/llm.ts b/packages/core/src/session/runner/llm.ts index 42e9674904..f76ee10a3f 100644 --- a/packages/core/src/session/runner/llm.ts +++ b/packages/core/src/session/runner/llm.ts @@ -1,3 +1,5 @@ +export * as SessionRunnerLLM from "./llm" + import { LLM, LLMClient, @@ -119,7 +121,7 @@ const layer = Layer.effect( const forkTitle = yield* FiberSet.makeRuntime() const getSession = Effect.fn("SessionRunner.getSession")(function* (sessionID: SessionSchema.ID) { const session = yield* store.get(sessionID) - if (!session) return yield* Effect.die(`Session not found: ${sessionID}`) + if (!session) return yield* Effect.die(new Error(`Session not found: ${sessionID}`)) return session }) diff --git a/packages/core/src/session/runner/model.ts b/packages/core/src/session/runner/model.ts index b21492d18d..2b81e609ea 100644 --- a/packages/core/src/session/runner/model.ts +++ b/packages/core/src/session/runner/model.ts @@ -2,8 +2,11 @@ export * as SessionRunnerModel from "./model" import { makeLocationNode } from "../../effect/app-node" import { type Model } from "@opencode-ai/llm" +// ast-grep-ignore: no-star-import import * as AnthropicMessages from "@opencode-ai/llm/protocols/anthropic-messages" +// ast-grep-ignore: no-star-import import * as OpenAICompatibleChat from "@opencode-ai/llm/protocols/openai-compatible-chat" +// ast-grep-ignore: no-star-import import * as OpenAIResponses from "@opencode-ai/llm/protocols/openai-responses" import { Auth, type AnyRoute } from "@opencode-ai/llm/route" import { Context, Effect, Layer, Schema } from "effect" diff --git a/packages/core/src/session/runner/publish-llm-event.ts b/packages/core/src/session/runner/publish-llm-event.ts index 33652a618c..04c6437ef4 100644 --- a/packages/core/src/session/runner/publish-llm-event.ts +++ b/packages/core/src/session/runner/publish-llm-event.ts @@ -85,7 +85,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) }) const currentAssistantMessageID = () => assistantMessageID === undefined - ? Effect.die("Tool event before assistant step start") + ? Effect.die(new Error("Tool event before assistant step start")) : Effect.succeed(assistantMessageID) const fragments = ( @@ -95,20 +95,20 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) const chunks = new Map() const start = (id: string) => Effect.suspend(() => { - if (chunks.has(id)) return Effect.die(`Duplicate ${name} start: ${id}`) + if (chunks.has(id)) return Effect.die(new Error(`Duplicate ${name} start: ${id}`)) chunks.set(id, []) return Effect.void }) const append = (id: string, value: string) => Effect.suspend(() => { const current = chunks.get(id) - if (!current) return Effect.die(`${name} delta before start: ${id}`) + if (!current) return Effect.die(new Error(`${name} delta before start: ${id}`)) current.push(value) return Effect.void }) const end = Effect.fnUntraced(function* (id: string, providerMetadata?: ProviderMetadata) { const current = chunks.get(id) - if (!current) return yield* Effect.die(`${name} end before start: ${id}`) + if (!current) return yield* Effect.die(new Error(`${name} end before start: ${id}`)) yield* ended(id, current.join(""), providerMetadata) chunks.delete(id) }) @@ -144,7 +144,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) const toolInput = fragments("tool input", (callID, value) => Effect.gen(function* () { const tool = tools.get(callID) - if (!tool) return yield* Effect.die(`Tool input end before start: ${callID}`) + if (!tool) return yield* Effect.die(new Error(`Tool input end before start: ${callID}`)) yield* events.publish(SessionEvent.Tool.Input.Ended, { sessionID: input.sessionID, timestamp: yield* timestamp, @@ -163,7 +163,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) }) const startToolInput = Effect.fnUntraced(function* (event: { readonly id: string; readonly name: string }) { - if (tools.has(event.id)) return yield* Effect.die(`Duplicate tool input start: ${event.id}`) + if (tools.has(event.id)) return yield* Effect.die(new Error(`Duplicate tool input start: ${event.id}`)) const assistantMessageID = yield* startAssistant() tools.set(event.id, { assistantMessageID, @@ -185,10 +185,10 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) const endToolInput = Effect.fnUntraced(function* (event: { readonly id: string; readonly name: string }) { const tool = tools.get(event.id) - if (!tool) return yield* Effect.die(`Tool input end before start: ${event.id}`) + if (!tool) return yield* Effect.die(new Error(`Tool input end before start: ${event.id}`)) if (tool.name !== event.name) - return yield* Effect.die(`Tool input name changed for ${event.id}: ${tool.name} -> ${event.name}`) - if (tool.inputEnded) return yield* Effect.die(`Duplicate tool input end: ${event.id}`) + return yield* Effect.die(new Error(`Tool input name changed for ${event.id}: ${tool.name} -> ${event.name}`)) + if (tool.inputEnded) return yield* Effect.die(new Error(`Duplicate tool input end: ${event.id}`)) yield* toolInput.end(event.id) }) @@ -233,7 +233,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) const assistantMessageIDForTool = (callID: string) => { const tool = tools.get(callID) - return tool ? Effect.succeed(tool.assistantMessageID) : Effect.die(`Unknown tool call: ${callID}`) + return tool ? Effect.succeed(tool.assistantMessageID) : Effect.die(new Error(`Unknown tool call: ${callID}`)) } const publish = Effect.fn("SessionRunner.publishLLMEvent")(function* ( @@ -293,10 +293,10 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) return case "tool-input-delta": { const tool = tools.get(event.id) - if (!tool) return yield* Effect.die(`Tool input delta before start: ${event.id}`) + if (!tool) return yield* Effect.die(new Error(`Tool input delta before start: ${event.id}`)) if (tool.name !== event.name) - return yield* Effect.die(`Tool input name changed for ${event.id}: ${tool.name} -> ${event.name}`) - if (tool.inputEnded) return yield* Effect.die(`Tool input delta after end: ${event.id}`) + return yield* Effect.die(new Error(`Tool input name changed for ${event.id}: ${tool.name} -> ${event.name}`)) + if (tool.inputEnded) return yield* Effect.die(new Error(`Tool input delta after end: ${event.id}`)) yield* toolInput.append(event.id, event.text) yield* events.publish(SessionEvent.Tool.Input.Delta, { sessionID: input.sessionID, @@ -315,8 +315,8 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) const tool = tools.get(event.id)! if (!tool.inputEnded) yield* endToolInput(event) if (tool.name !== event.name) - return yield* Effect.die(`Tool call name changed for ${event.id}: ${tool.name} -> ${event.name}`) - if (tool.called) return yield* Effect.die(`Duplicate tool call: ${event.id}`) + return yield* Effect.die(new Error(`Tool call name changed for ${event.id}: ${tool.name} -> ${event.name}`)) + if (tool.called) return yield* Effect.die(new Error(`Duplicate tool call: ${event.id}`)) tool.called = true tool.providerExecuted = event.providerExecuted === true tool.providerMetadata = event.providerMetadata @@ -336,12 +336,12 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) } case "tool-result": { const tool = tools.get(event.id) - if (!tool?.called) return yield* Effect.die(`Tool result before call: ${event.id}`) + if (!tool?.called) return yield* Effect.die(new Error(`Tool result before call: ${event.id}`)) if (tool.name !== event.name) - return yield* Effect.die(`Tool result name changed for ${event.id}: ${tool.name} -> ${event.name}`) + return yield* Effect.die(new Error(`Tool result name changed for ${event.id}: ${tool.name} -> ${event.name}`)) if (tool.settled) { if (event.result.type === "error") return - return yield* Effect.die(`Duplicate tool result: ${event.id}`) + return yield* Effect.die(new Error(`Duplicate tool result: ${event.id}`)) } tool.settled = true const result = settledOutput(event.output, event.result) @@ -375,10 +375,10 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) } case "tool-error": { const tool = tools.get(event.id) - if (!tool?.called) return yield* Effect.die(`Tool error before call: ${event.id}`) + if (!tool?.called) return yield* Effect.die(new Error(`Tool error before call: ${event.id}`)) if (tool.name !== event.name) - return yield* Effect.die(`Tool error name changed for ${event.id}: ${tool.name} -> ${event.name}`) - if (tool.settled) return yield* Effect.die(`Duplicate tool error: ${event.id}`) + return yield* Effect.die(new Error(`Tool error name changed for ${event.id}: ${tool.name} -> ${event.name}`)) + if (tool.settled) return yield* Effect.die(new Error(`Duplicate tool error: ${event.id}`)) tool.settled = true yield* events.publish(SessionEvent.Tool.Failed, { sessionID: input.sessionID, @@ -396,7 +396,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) case "step-finish": yield* flush() assistantActive = false - if (stepSettlement) return yield* Effect.die("Duplicate step finish") + if (stepSettlement) return yield* Effect.die(new Error("Duplicate step finish")) stepSettlement = { finish: event.reason, tokens: tokens(event.usage) } return case "finish": diff --git a/packages/core/src/session/sql.ts b/packages/core/src/session/sql.ts index d1e923b40f..739d3f1888 100644 --- a/packages/core/src/session/sql.ts +++ b/packages/core/src/session/sql.ts @@ -1,5 +1,5 @@ import { sqliteTable, text, integer, index, primaryKey, real, uniqueIndex } from "drizzle-orm/sqlite-core" -import * as DatabasePath from "../database/path" +import { directoryColumn, pathColumn } from "../database/path" import { ProjectTable } from "../project/sql" import type { SessionMessage } from "./message" import type { Prompt } from "./prompt" @@ -31,8 +31,8 @@ export const SessionTable = sqliteTable( workspace_id: text().$type(), parent_id: text().$type(), slug: text().notNull(), - directory: DatabasePath.directoryColumn().notNull(), - path: DatabasePath.pathColumn(), + directory: directoryColumn().notNull(), + path: pathColumn(), title: text().notNull(), version: text().notNull(), share_url: text(), diff --git a/packages/core/src/shell/select.ts b/packages/core/src/shell/select.ts index 110697421d..311fb7c9a1 100644 --- a/packages/core/src/shell/select.ts +++ b/packages/core/src/shell/select.ts @@ -4,7 +4,7 @@ import path from "path" import { spawn, type ChildProcess } from "child_process" import { readFile } from "fs/promises" import { statSync } from "fs" -import { setTimeout as sleep } from "node:timers/promises" +import { setTimeout } from "node:timers/promises" import { Flag } from "../flag/flag" import { FSUtil } from "../fs-util" import { which } from "../util/which" @@ -46,13 +46,13 @@ export async function killTree(proc: ChildProcess, opts?: { exited?: () => boole try { process.kill(-pid, "SIGTERM") - await sleep(SIGKILL_TIMEOUT_MS) + await setTimeout(SIGKILL_TIMEOUT_MS) if (!opts?.exited?.()) { process.kill(-pid, "SIGKILL") } } catch { proc.kill("SIGTERM") - await sleep(SIGKILL_TIMEOUT_MS) + await setTimeout(SIGKILL_TIMEOUT_MS) if (!opts?.exited?.()) { proc.kill("SIGKILL") } diff --git a/packages/core/test/session-runner.test.ts b/packages/core/test/session-runner.test.ts index 45699e7112..4c9446394c 100644 --- a/packages/core/test/session-runner.test.ts +++ b/packages/core/test/session-runner.test.ts @@ -3424,9 +3424,10 @@ describe("SessionRunnerLLM", () => { streamStarted = undefined response = [LLMEvent.textStart({ id: "text-1" }), LLMEvent.textStart({ id: "text-1" })] - expect(yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))).toBe( - "Duplicate text start: text-1", - ) + const defect = yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed)) + expect(defect).toBeInstanceOf(Error) + if (!(defect instanceof Error)) return + expect(defect.message).toBe("Duplicate text start: text-1") }), ) @@ -3468,9 +3469,10 @@ describe("SessionRunnerLLM", () => { streamStarted = undefined response = [LLMEvent.toolInputDelta({ id: "call-1", name: "read", text: "{}" })] - expect(yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))).toBe( - "Tool input delta before start: call-1", - ) + const defect = yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed)) + expect(defect).toBeInstanceOf(Error) + if (!(defect instanceof Error)) return + expect(defect.message).toBe("Tool input delta before start: call-1") }), ) }) diff --git a/packages/server/src/auth.ts b/packages/server/src/auth.ts index c71536518d..239eb0d237 100644 --- a/packages/server/src/auth.ts +++ b/packages/server/src/auth.ts @@ -1,6 +1,7 @@ export * as ServerAuth from "./auth" -import { Config as EffectConfig, Context, Effect, Layer, Option, Redacted } from "effect" +import { Context, Effect, Layer, Option, Redacted } from "effect" +import { all, option, string, withDefault } from "effect/Config" export type Credentials = { password?: string @@ -27,9 +28,9 @@ export class Config extends Context.Service()("@opencode/ServerAut this, Effect.gen(function* () { return Config.of( - yield* EffectConfig.all({ - password: EffectConfig.string("OPENCODE_SERVER_PASSWORD").pipe(EffectConfig.option), - username: EffectConfig.string("OPENCODE_SERVER_USERNAME").pipe(EffectConfig.withDefault("opencode")), + yield* all({ + password: string("OPENCODE_SERVER_PASSWORD").pipe(option), + username: string("OPENCODE_SERVER_USERNAME").pipe(withDefault("opencode")), }), ) }), diff --git a/packages/server/src/handlers/event.ts b/packages/server/src/handlers/event.ts index f412137aba..ca9c02620d 100644 --- a/packages/server/src/handlers/event.ts +++ b/packages/server/src/handlers/event.ts @@ -1,9 +1,9 @@ import { EventV2 } from "@opencode-ai/core/event" import { OpenCodeEvent } from "@opencode-ai/protocol/groups/event" import { Effect, Schema, Stream } from "effect" +import { Sse } from "effect/unstable/encoding" import { HttpServerResponse } from "effect/unstable/http" import { HttpApiBuilder } from "effect/unstable/httpapi" -import * as Sse from "effect/unstable/encoding/Sse" import { Api } from "../api" const subscriberCapacity = 256 diff --git a/packages/server/src/handlers/pty.ts b/packages/server/src/handlers/pty.ts index e2c5fcc568..7f8a9ea64e 100644 --- a/packages/server/src/handlers/pty.ts +++ b/packages/server/src/handlers/pty.ts @@ -5,7 +5,7 @@ import { Location } from "@opencode-ai/core/location" import { Effect, Queue } from "effect" import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http" import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi" -import * as Socket from "effect/unstable/socket/Socket" +import { Socket } from "effect/unstable/socket" import { Api } from "../api" import { CorsConfig, isAllowedRequestOrigin } from "../cors" import { ForbiddenError, PtyNotFoundError } from "@opencode-ai/protocol/errors" diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index 30c3d961b7..db69ba6c7f 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -23,7 +23,7 @@ import { handlers } from "./handlers" import { authorizationLayer } from "./middleware/authorization" import { schemaErrorLayer } from "./middleware/schema-error" import { PtyEnvironment } from "./pty-environment" -import { layer as locationLayer } from "./location" +import { layer } from "./location" import { formLocationLayer } from "./middleware/form-location" import { sessionLocationLayer } from "./middleware/session-location" @@ -82,7 +82,7 @@ function makeRoutes( Layer.provide(handlers), Layer.provide(formLocationLayer), Layer.provide(sessionLocationLayer), - Layer.provide(locationLayer), + Layer.provide(layer), Layer.provide(authorizationLayer), Layer.provide(schemaErrorLayer), Layer.provide(auth), diff --git a/script/ast-grep/rule-tests/__snapshots__/no-drizzle-column-name-snapshot.yml b/script/ast-grep/rule-tests/__snapshots__/no-drizzle-column-name-snapshot.yml new file mode 100644 index 0000000000..aae0c580ee --- /dev/null +++ b/script/ast-grep/rule-tests/__snapshots__/no-drizzle-column-name-snapshot.yml @@ -0,0 +1,12 @@ +id: no-drizzle-column-name +snapshots: + ? | + const table = sqliteTable("session", { + projectID: text("project_id").notNull(), + createdAt: integer("time_created").notNull(), + }) + : labels: + - source: text("project_id") + style: primary + start: 52 + end: 70 diff --git a/script/ast-grep/rule-tests/__snapshots__/no-effect-die-string-snapshot.yml b/script/ast-grep/rule-tests/__snapshots__/no-effect-die-string-snapshot.yml new file mode 100644 index 0000000000..a1bb464164 --- /dev/null +++ b/script/ast-grep/rule-tests/__snapshots__/no-effect-die-string-snapshot.yml @@ -0,0 +1,30 @@ +id: no-effect-die-string +snapshots: + Effect.die("boom"): + labels: + - source: Effect.die("boom") + style: primary + start: 0 + end: 18 + - source: '"boom"' + style: secondary + start: 11 + end: 17 + - source: ("boom") + style: secondary + start: 10 + end: 18 + Effect.die(`boom ${value}`): + labels: + - source: Effect.die(`boom ${value}`) + style: primary + start: 0 + end: 27 + - source: '`boom ${value}`' + style: secondary + start: 11 + end: 26 + - source: (`boom ${value}`) + style: secondary + start: 10 + end: 27 diff --git a/script/ast-grep/rule-tests/__snapshots__/no-import-alias-snapshot.yml b/script/ast-grep/rule-tests/__snapshots__/no-import-alias-snapshot.yml new file mode 100644 index 0000000000..6336c0bd01 --- /dev/null +++ b/script/ast-grep/rule-tests/__snapshots__/no-import-alias-snapshot.yml @@ -0,0 +1,42 @@ +id: no-import-alias +snapshots: + import { baz, foo as bar } from "./foo": + labels: + - source: foo as bar + style: primary + start: 14 + end: 24 + - source: bar + style: secondary + start: 21 + end: 24 + import { foo as bar } from "./foo": + labels: + - source: foo as bar + style: primary + start: 9 + end: 19 + - source: bar + style: secondary + start: 16 + end: 19 + import { foo as bar, baz } from "./foo": + labels: + - source: foo as bar + style: primary + start: 9 + end: 19 + - source: bar + style: secondary + start: 16 + end: 19 + import { type Foo as Bar, baz } from "./foo": + labels: + - source: type Foo as Bar + style: primary + start: 9 + end: 24 + - source: Bar + style: secondary + start: 21 + end: 24 diff --git a/script/ast-grep/rule-tests/__snapshots__/no-json-parse-cast-snapshot.yml b/script/ast-grep/rule-tests/__snapshots__/no-json-parse-cast-snapshot.yml new file mode 100644 index 0000000000..0aa2a274ea --- /dev/null +++ b/script/ast-grep/rule-tests/__snapshots__/no-json-parse-cast-snapshot.yml @@ -0,0 +1,8 @@ +id: no-json-parse-cast +snapshots: + const value = JSON.parse(input) as Record: + labels: + - source: JSON.parse(input) as Record + style: primary + start: 14 + end: 58 diff --git a/script/ast-grep/rule-tests/__snapshots__/no-nested-effect-service-yield-snapshot.yml b/script/ast-grep/rule-tests/__snapshots__/no-nested-effect-service-yield-snapshot.yml new file mode 100644 index 0000000000..30619694f8 --- /dev/null +++ b/script/ast-grep/rule-tests/__snapshots__/no-nested-effect-service-yield-snapshot.yml @@ -0,0 +1,20 @@ +id: no-nested-effect-service-yield +snapshots: + ? | + Effect.gen(function* () { + yield* (yield* Foo.Service).client.run() + }) + : labels: + - source: (yield* Foo.Service).client.run() + style: primary + start: 35 + end: 68 + ? | + Effect.gen(function* () { + yield* (yield* Foo.Service).run() + }) + : labels: + - source: (yield* Foo.Service).run() + style: primary + start: 35 + end: 61 diff --git a/script/ast-grep/rule-tests/__snapshots__/no-star-import-snapshot.yml b/script/ast-grep/rule-tests/__snapshots__/no-star-import-snapshot.yml new file mode 100644 index 0000000000..dab38e82f6 --- /dev/null +++ b/script/ast-grep/rule-tests/__snapshots__/no-star-import-snapshot.yml @@ -0,0 +1,22 @@ +id: no-star-import +snapshots: + import * as Foo from "./foo": + labels: + - source: '* as Foo' + style: primary + start: 7 + end: 15 + - source: import * as Foo from "./foo" + style: secondary + start: 0 + end: 28 + import type * as Foo from "./foo": + labels: + - source: '* as Foo' + style: primary + start: 12 + end: 20 + - source: import type * as Foo from "./foo" + style: secondary + start: 0 + end: 33 diff --git a/script/ast-grep/rule-tests/no-drizzle-column-name-test.yml b/script/ast-grep/rule-tests/no-drizzle-column-name-test.yml new file mode 100644 index 0000000000..00e1a7bb28 --- /dev/null +++ b/script/ast-grep/rule-tests/no-drizzle-column-name-test.yml @@ -0,0 +1,14 @@ +id: no-drizzle-column-name +valid: + - | + const table = sqliteTable("session", { + project_id: text().notNull(), + time_created: integer().notNull(), + payload: text({ mode: "json" }), + }) +invalid: + - | + const table = sqliteTable("session", { + projectID: text("project_id").notNull(), + createdAt: integer("time_created").notNull(), + }) diff --git a/script/ast-grep/rule-tests/no-effect-die-string-test.yml b/script/ast-grep/rule-tests/no-effect-die-string-test.yml new file mode 100644 index 0000000000..4ca9e737c0 --- /dev/null +++ b/script/ast-grep/rule-tests/no-effect-die-string-test.yml @@ -0,0 +1,7 @@ +id: no-effect-die-string +valid: + - Effect.die(new Error("boom")) + - Effect.fail("boom") +invalid: + - Effect.die("boom") + - Effect.die(`boom ${value}`) diff --git a/script/ast-grep/rule-tests/no-import-alias-test.yml b/script/ast-grep/rule-tests/no-import-alias-test.yml new file mode 100644 index 0000000000..7c3ab9235b --- /dev/null +++ b/script/ast-grep/rule-tests/no-import-alias-test.yml @@ -0,0 +1,13 @@ +id: no-import-alias +valid: + - import { foo } from "./foo" + - import type { Foo } from "./foo" + - import foo from "./foo" + - export { foo as bar } from "./foo" + - import type { Plugin as EffectPlugin } from "./foo" + - import type { Foo as Bar, Baz } from "./foo" +invalid: + - import { foo as bar } from "./foo" + - import { baz, foo as bar } from "./foo" + - import { foo as bar, baz } from "./foo" + - import { type Foo as Bar, baz } from "./foo" diff --git a/script/ast-grep/rule-tests/no-json-parse-cast-test.yml b/script/ast-grep/rule-tests/no-json-parse-cast-test.yml new file mode 100644 index 0000000000..ee44819ce8 --- /dev/null +++ b/script/ast-grep/rule-tests/no-json-parse-cast-test.yml @@ -0,0 +1,6 @@ +id: no-json-parse-cast +valid: + - const value = JSON.parse(input) + - const value = Schema.decodeUnknownOption(Schema.UnknownFromJsonString)(input) +invalid: + - const value = JSON.parse(input) as Record diff --git a/script/ast-grep/rule-tests/no-nested-effect-service-yield-test.yml b/script/ast-grep/rule-tests/no-nested-effect-service-yield-test.yml new file mode 100644 index 0000000000..e126f2d68a --- /dev/null +++ b/script/ast-grep/rule-tests/no-nested-effect-service-yield-test.yml @@ -0,0 +1,21 @@ +id: no-nested-effect-service-yield +valid: + - | + Effect.gen(function* () { + const service = yield* Foo.Service + yield* service.run() + }) + - | + Effect.gen(function* () { + const db = (yield* Database.Service).db + yield* db.run() + }) +invalid: + - | + Effect.gen(function* () { + yield* (yield* Foo.Service).run() + }) + - | + Effect.gen(function* () { + yield* (yield* Foo.Service).client.run() + }) diff --git a/script/ast-grep/rule-tests/no-star-import-test.yml b/script/ast-grep/rule-tests/no-star-import-test.yml new file mode 100644 index 0000000000..6006f02140 --- /dev/null +++ b/script/ast-grep/rule-tests/no-star-import-test.yml @@ -0,0 +1,8 @@ +id: no-star-import +valid: + - import { Foo } from "./foo" + - import Foo from "./foo" + - export * as Foo from "./foo" +invalid: + - import * as Foo from "./foo" + - import type * as Foo from "./foo" diff --git a/script/ast-grep/rules/no-drizzle-column-name.yml b/script/ast-grep/rules/no-drizzle-column-name.yml new file mode 100644 index 0000000000..5b798b81ab --- /dev/null +++ b/script/ast-grep/rules/no-drizzle-column-name.yml @@ -0,0 +1,22 @@ +id: no-drizzle-column-name +language: TypeScript +message: Use snake_case object keys instead of explicit drizzle column names. +severity: error +files: + - packages/core/src/**/sql.ts + - packages/core/src/**/*.sql.ts +rule: + any: + - pattern: text($NAME) + - pattern: text($NAME, $$$ARGS) + - pattern: integer($NAME) + - pattern: integer($NAME, $$$ARGS) + - pattern: blob($NAME) + - pattern: blob($NAME, $$$ARGS) + - pattern: real($NAME) + - pattern: real($NAME, $$$ARGS) + - pattern: numeric($NAME) + - pattern: numeric($NAME, $$$ARGS) +constraints: + NAME: + kind: string diff --git a/script/ast-grep/rules/no-effect-die-string.yml b/script/ast-grep/rules/no-effect-die-string.yml new file mode 100644 index 0000000000..77265afb29 --- /dev/null +++ b/script/ast-grep/rules/no-effect-die-string.yml @@ -0,0 +1,22 @@ +id: no-effect-die-string +language: TypeScript +message: die with `new Error(...)`. +severity: error +rule: + any: + - all: + - pattern: Effect.die($MESSAGE) + - has: + field: arguments + all: + - kind: arguments + - has: + kind: string + - all: + - pattern: Effect.die($MESSAGE) + - has: + field: arguments + all: + - kind: arguments + - has: + kind: template_string diff --git a/script/ast-grep/rules/no-import-alias.yml b/script/ast-grep/rules/no-import-alias.yml new file mode 100644 index 0000000000..1c6c4c5298 --- /dev/null +++ b/script/ast-grep/rules/no-import-alias.yml @@ -0,0 +1,14 @@ +id: no-import-alias +language: TypeScript +message: Do not alias value imports. For type name collisions, alias inside a dedicated `import type` statement. +severity: error +rule: + all: + - kind: import_specifier + - has: + field: alias + kind: identifier + - not: + inside: + pattern: import type { $$$SPECS } from "$MOD" + stopBy: end diff --git a/script/ast-grep/no-json-parse-cast.yml b/script/ast-grep/rules/no-json-parse-cast.yml similarity index 100% rename from script/ast-grep/no-json-parse-cast.yml rename to script/ast-grep/rules/no-json-parse-cast.yml diff --git a/script/ast-grep/no-nested-effect-service-yield.yml b/script/ast-grep/rules/no-nested-effect-service-yield.yml similarity index 100% rename from script/ast-grep/no-nested-effect-service-yield.yml rename to script/ast-grep/rules/no-nested-effect-service-yield.yml diff --git a/script/ast-grep/rules/no-star-import.yml b/script/ast-grep/rules/no-star-import.yml new file mode 100644 index 0000000000..e804223108 --- /dev/null +++ b/script/ast-grep/rules/no-star-import.yml @@ -0,0 +1,10 @@ +id: no-star-import +language: TypeScript +message: Do not use star imports. +severity: error +rule: + all: + - kind: namespace_import + - inside: + kind: import_statement + stopBy: end diff --git a/script/ast-grep/sgconfig.yml b/script/ast-grep/sgconfig.yml new file mode 100644 index 0000000000..098ecb2af4 --- /dev/null +++ b/script/ast-grep/sgconfig.yml @@ -0,0 +1,4 @@ +ruleDirs: + - rules +testConfigs: + - testDir: rule-tests From 2ff19171dcc733e31f8aa312b7743251cba7fd6b Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 14:01:00 -0400 Subject: [PATCH 18/82] feat(tui): reload command restarts the service --- packages/cli/src/commands/handlers/default.ts | 20 +++++++++++++++- packages/cli/src/tui.ts | 8 ++++++- packages/tui/src/app.tsx | 23 ++++++++++++++++++- packages/tui/src/context/sdk.tsx | 3 +++ 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/commands/handlers/default.ts b/packages/cli/src/commands/handlers/default.ts index 1f8ebe89c4..d7ba88a824 100644 --- a/packages/cli/src/commands/handlers/default.ts +++ b/packages/cli/src/commands/handlers/default.ts @@ -63,6 +63,24 @@ export default Runtime.handler(Commands, (input) => }).pipe(Effect.provide(NodeFileSystem.layer)), ) : () => Promise.resolve(transport) - yield* runTui(transport, { continue: input.continue, sessionID: Option.getOrUndefined(input.session) }, discover) + // Restart the managed service in place; start() resolves once the + // replacement is healthy and the reconnect loop reattaches on its own. + // Only meaningful in service mode: --server is not ours to restart and a + // standalone child cannot be respawned. + const reload = serviceOptions + ? () => + Effect.runPromise( + Effect.gen(function* () { + yield* Service.stop(serviceOptions) + yield* Service.start(serviceOptions) + }).pipe(Effect.provide(NodeFileSystem.layer)), + ) + : undefined + yield* runTui( + transport, + { continue: input.continue, sessionID: Option.getOrUndefined(input.session) }, + discover, + reload, + ) }), ) diff --git a/packages/cli/src/tui.ts b/packages/cli/src/tui.ts index a535309d42..96d92c50b2 100644 --- a/packages/cli/src/tui.ts +++ b/packages/cli/src/tui.ts @@ -9,7 +9,12 @@ import type { Service } from "@opencode-ai/client/effect" import { createOpencodeClient } from "@opencode-ai/sdk/v2/client" import type { Args } from "@opencode-ai/tui/context/args" -export function runTui(transport: Service.Transport, args: Args, discover?: () => Promise) { +export function runTui( + transport: Service.Transport, + args: Args, + discover?: () => Promise, + reload?: () => Promise, +) { const config = TuiConfig.resolve({}, { terminalSuspend: false }) let disposeSlots: (() => void) | undefined return Effect.gen(function* () { @@ -33,6 +38,7 @@ export function runTui(transport: Service.Transport, args: Args, discover?: () = } } : undefined, + reload, args, config, pluginHost: { diff --git a/packages/tui/src/app.tsx b/packages/tui/src/app.tsx index ccde2fa5e6..876faff9de 100644 --- a/packages/tui/src/app.tsx +++ b/packages/tui/src/app.tsx @@ -139,6 +139,7 @@ export type TuiInput = { client: OpencodeClient api: OpenCodeClient discover?: () => Promise<{ client: OpencodeClient; api: OpenCodeClient }> + reload?: () => Promise args: Args config: TuiConfig.Resolved onSnapshot?: () => Promise @@ -301,7 +302,7 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) { > - + @@ -800,6 +801,26 @@ function App(props: { onSnapshot?: () => Promise; pluginHost: TuiPlugi }, category: "System", }, + ...(sdk.reload + ? [ + { + name: "server.reload", + title: "Reload server", + slashName: "reload", + run: async () => { + dialog.clear() + toast.show({ variant: "info", message: "Reloading server...", duration: 30000 }) + // reload resolves once the replacement service is healthy; the + // event stream reattaches through the reconnect loop. + await sdk + .reload!() + .then(() => toast.show({ variant: "success", message: "Server reloaded" })) + .catch(toast.error) + }, + category: "System", + }, + ] + : []), { name: "theme.switch", title: "Switch theme", diff --git a/packages/tui/src/context/sdk.tsx b/packages/tui/src/context/sdk.tsx index 7686ed6e94..0ad516ceac 100644 --- a/packages/tui/src/context/sdk.tsx +++ b/packages/tui/src/context/sdk.tsx @@ -16,6 +16,8 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({ client: OpencodeClient api: OpenCodeClient discover?: () => Promise<{ client: OpencodeClient; api: OpenCodeClient }> + // Stops and starts the managed service; present only in service mode. + reload?: () => Promise }) => { const abort = new AbortController() let client = props.client @@ -138,6 +140,7 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({ return connection.connectedOnce }, }, + reload: props.reload, } }, }) From 4790a2772c0300ff610834c5628c62b4668c6bf1 Mon Sep 17 00:00:00 2001 From: James Long Date: Fri, 3 Jul 2026 14:19:25 -0400 Subject: [PATCH 19/82] feat(simulation): add driver controlled backend LLM (#35186) --- bun.lock | 19 + packages/core/src/effect/layer-node.ts | 2 +- packages/core/src/fs-util.ts | 4 +- packages/llm/src/protocols/openai-chat.ts | 4 +- .../specs/simulation/simulated-network-llm.md | 150 +++++++ .../specs/simulation/simulation-phases.md | 22 + packages/server/package.json | 1 + packages/server/src/routes.ts | 2 +- packages/server/src/simulation/index.ts | 14 - packages/simulation/package.json | 28 ++ packages/simulation/src/backend/control.ts | 145 +++++++ packages/simulation/src/backend/filesystem.ts | 390 ++++++++++++++++++ packages/simulation/src/backend/fs-util.ts | 89 ++++ packages/simulation/src/backend/index.ts | 41 ++ .../simulation/src/backend/llm-exchange.ts | 105 +++++ packages/simulation/src/backend/network.ts | 94 +++++ packages/simulation/src/backend/openai.ts | 89 ++++ .../src/frontend}/actions.ts | 0 .../src/frontend}/renderer.ts | 0 .../src/frontend}/server.ts | 0 .../src/frontend}/simulation.ts | 0 .../src/frontend}/trace.ts | 0 packages/simulation/tsconfig.json | 8 + packages/tui/package.json | 1 + packages/tui/src/app.tsx | 4 +- 25 files changed, 1191 insertions(+), 21 deletions(-) create mode 100644 packages/opencode/specs/simulation/simulated-network-llm.md delete mode 100644 packages/server/src/simulation/index.ts create mode 100644 packages/simulation/package.json create mode 100644 packages/simulation/src/backend/control.ts create mode 100644 packages/simulation/src/backend/filesystem.ts create mode 100644 packages/simulation/src/backend/fs-util.ts create mode 100644 packages/simulation/src/backend/index.ts create mode 100644 packages/simulation/src/backend/llm-exchange.ts create mode 100644 packages/simulation/src/backend/network.ts create mode 100644 packages/simulation/src/backend/openai.ts rename packages/{tui/src/simulation => simulation/src/frontend}/actions.ts (100%) rename packages/{tui/src/simulation => simulation/src/frontend}/renderer.ts (100%) rename packages/{tui/src/simulation => simulation/src/frontend}/server.ts (100%) rename packages/{tui/src/simulation => simulation/src/frontend}/simulation.ts (100%) rename packages/{tui/src/simulation => simulation/src/frontend}/trace.ts (100%) create mode 100644 packages/simulation/tsconfig.json diff --git a/bun.lock b/bun.lock index 9c5bbb1591..6522800a13 100644 --- a/bun.lock +++ b/bun.lock @@ -796,6 +796,7 @@ "dependencies": { "@opencode-ai/core": "workspace:*", "@opencode-ai/protocol": "workspace:*", + "@opencode-ai/simulation": "workspace:*", "drizzle-orm": "catalog:", "effect": "catalog:", }, @@ -849,6 +850,21 @@ "vite": "catalog:", }, }, + "packages/simulation": { + "name": "@opencode-ai/simulation", + "version": "1.17.13", + "dependencies": { + "@opencode-ai/core": "workspace:*", + "@opencode-ai/llm": "workspace:*", + "@opentui/core": "catalog:", + "effect": "catalog:", + }, + "devDependencies": { + "@tsconfig/bun": "catalog:", + "@types/bun": "catalog:", + "@typescript/native-preview": "catalog:", + }, + }, "packages/slack": { "name": "@opencode-ai/slack", "version": "1.17.13", @@ -963,6 +979,7 @@ "@opencode-ai/core": "workspace:*", "@opencode-ai/plugin": "workspace:*", "@opencode-ai/sdk": "workspace:*", + "@opencode-ai/simulation": "workspace:*", "@opencode-ai/ui": "workspace:*", "@opentui/core": "catalog:", "@opentui/keymap": "catalog:", @@ -2019,6 +2036,8 @@ "@opencode-ai/session-ui": ["@opencode-ai/session-ui@workspace:packages/session-ui"], + "@opencode-ai/simulation": ["@opencode-ai/simulation@workspace:packages/simulation"], + "@opencode-ai/slack": ["@opencode-ai/slack@workspace:packages/slack"], "@opencode-ai/stats-app": ["@opencode-ai/stats-app@workspace:packages/stats/app"], diff --git a/packages/core/src/effect/layer-node.ts b/packages/core/src/effect/layer-node.ts index 9dbc3d5160..dc7aa972f0 100644 --- a/packages/core/src/effect/layer-node.ts +++ b/packages/core/src/effect/layer-node.ts @@ -227,7 +227,7 @@ export function hoist +export type OpenAIChatEvent = Schema.Schema.Type type OpenAIChatRequestMessage = LLMRequest["messages"][number] interface ParserState { diff --git a/packages/opencode/specs/simulation/simulated-network-llm.md b/packages/opencode/specs/simulation/simulated-network-llm.md new file mode 100644 index 0000000000..c7631cf4cb --- /dev/null +++ b/packages/opencode/specs/simulation/simulated-network-llm.md @@ -0,0 +1,150 @@ +# Simulated Network And Driver-Scripted LLM + +Status: design for the Phase 2 network and LLM items in `simulation-phases.md`. + +## Summary + +Simulation replaces the `HttpClient.HttpClient` platform node with a simulated network. The LLM is not a separate fake: it is one registered route in that network (`api.openai.com`), answered by the **external driver** over the existing control WebSocket. When the app issues a provider request, the backend forwards it to the driver and the driver streams response chunks back. There is no enqueueing and no scripted-response store; the driver is the model. + +Everything above the HTTP boundary runs real: catalog and auth resolution, `LLMClient`, request body construction, SSE framing, the OpenAI protocol event schema, the `step` state machine, `Lifecycle` grammar, tool-argument accumulation, the session runner, tools, and permissions. + +## Why the network seam + +`LLMClient.stream` sits on a stack that ends in one platform node: + +``` +LLMClient.stream(request) + route.body.from LLMRequest -> OpenAI JSON body (real) + transport.prepare body + endpoint + auth -> HttpRequest (real) + RequestExecutor.execute status/error taxonomy (real) + HttpClient.HttpClient <- replaced by the simulated network + Framing.sse bytes -> frames (real) + protocol.stream.event frame -> OpenAIChatEvent, validated (real) + protocol.stream.step state machine -> LLMEvents (real) +``` + +Replacing `httpClient` (already a `LayerNode` in `app-node-platform.ts`, already used by `simulationReplacements` mechanics) keeps the entire pipeline under test and gives wire-fidelity observation of what would have been sent to the provider. Failure injection (429s, malformed SSE, truncated streams) exercises real error paths that a typed `LLMClient` fake cannot reach. + +## Components + +### 1. Simulated network (`packages/simulation/src/backend/network.ts`) + +Replaces `httpClient` in `simulationReplacements`. An in-memory route table: + +- `register(matcher, responder)` where matcher is method + URL pattern and responder is `(HttpClientRequest) => Effect`. +- Unknown requests fail loudly with a typed simulation error (spec: deny unknown external network by default). +- Optional loopback allowance for the app's own server is not required server-side (the server does not call itself over HTTP); revisit if a consumer needs it. +- Every request/response summary is traced. + +### 2. OpenAI endpoint route (`packages/simulation/src/backend/openai.ts`) + +Registered in the network at startup for `POST {DEFAULT_BASE_URL}{PATH}` from `protocols/openai-chat.ts` (`https://api.openai.com/v1/chat/completions`). + +On request: + +1. Allocate an exchange id. Parse the real OpenAI request body (available to the driver for assertions). +2. Publish a `request` record to the LLM exchange service (below) and create a chunk `Queue`. +3. Return `HttpClientResponse` with `content-type: text/event-stream` whose body stream reads from the queue, encoding each item as an SSE `data:` frame, terminated by `[DONE]`. + +Chunks are constructed through the `OpenAIChatEvent` schema so drift in the protocol schema breaks the build, not the runtime. + +The response stream is interruptible like a real HTTP response: if the runner cancels (user interrupt), the exchange closes and the driver is notified. + +### 3. LLM exchange service (`packages/simulation/src/backend/llm-exchange.ts`) + +Process-global simulation service owning pending exchanges: + +``` +Exchange = { id, body, queue: Queue, deferred lifecycle } +``` + +- `requests()` — stream of newly opened exchanges (consumed by the control route). +- `push(id, item)` — append one response item to an open exchange. +- `finish(id, reason)` / `fail(id, failure)` — terminate the exchange. +- Exchanges that receive no driver within a configurable timeout fail the provider request with a simulation error (surfaces in the real provider-error path). + +### 4. Backend control WebSocket (simulation-gated) + +Started when the simulation module loads (lazy import, `OPENCODE_SIMULATION` only): a loopback JSON-RPC 2.0 WebSocket on `127.0.0.1:40950+`, hosted by the backend process. Drivers connect to it directly — the standalone topology has exactly one backend per TUI, so there is no proxying through the frontend. This socket is also the headless-simulation interface: it works with no TUI at all. + +Server -> driver notification (after `llm.attach`; pending exchanges are replayed on attach so late-attaching drivers miss nothing): + +``` +{ "jsonrpc": "2.0", "method": "llm.request", + "params": { "id": "ex_1", "url": "...", "body": { ...openai request body... } } } +``` + +Driver -> server methods: + +``` +llm.attach subscribe to llm.request notifications +llm.chunk { id, items: Item[] } append response items +llm.finish { id, reason?: "stop" | ... } finish the exchange +llm.pending list open exchanges +network.log simulated network request log +``` + +`Item` is the response vocabulary the driver speaks: + +``` +{ type: "textDelta", text } +{ type: "reasoningDelta", text } +{ type: "toolCall", id, name, input } +{ type: "raw", chunk } // escape hatch: raw OpenAIChatEvent JSON +``` + +The backend compiles items to OpenAI chunks (`delta.content`, `delta.tool_calls[].function.arguments`, `finish_reason`); `raw` passes through unmodified. Streaming granularity is the driver's choice: many small `llm.chunk` calls stream word by word; one call with many items plus `llm.finish` responds at once. + +Failure injection (`llm.fail`: HTTP status instead of SSE) is specced but not yet implemented. + +### 5. Driver topology + +A driver manages two loopback WebSocket connections: + +- TUI control server (`127.0.0.1:40900+`) — UI state, actions, render, trace. +- Backend control server (`127.0.0.1:40950+`) — LLM exchanges, network log. + +Both speak the same JSON-RPC shape. Headless drivers use only the backend socket plus the normal HTTP API. Multiple drivers are out of scope; last attach wins. + +### 6. Pacing and the clock + +No server-side pacing by default: the driver controls timing by when it sends chunks, which is the point of driver-in-the-loop. A convenience `llm.chunk` option `{ delayMs }` may sleep via `Effect.sleep` between items server-side; because that uses the fiber `Clock`, scoping a controllable clock to the exchange stream (`Stream.provideService(Clock.Clock, simClock)`) remains available for deterministic replay without touching app time. Defer until replay work needs it. + +### 7. Catalog and auth seeding + +The driver-facing model must be selectable in the TUI. Simulation seeds config (via the snapshot filesystem) defining a provider on the openai-chat route with `baseURL` left at the OpenAI default and a dummy `apiKey` (satisfies `Catalog.available()`). No catalog code changes. + +## End-to-end flow + +``` +driver TUI sim server (40900+) backend + control WS (40950+) + | | | + |-- ui.action (submit) ----->| | + | |-- (normal app HTTP) ---->| session runner starts + | | | llm.stream -> HttpClient + | | | simulated network matches openai route + |<================== llm.request {ex_1} ===============| exchange ex_1 opened + |-- llm.chunk {ex_1,[...]} ============================>| SSE frames flow into the real + |-- llm.chunk {ex_1,[...]} ============================>| decode -> step -> LLMEvents -> + |-- llm.finish {ex_1} =================================>| runner publishes, TUI renders + | | | + | (if toolCall was sent: runner executes the real tool against the + | fake filesystem, then issues the next provider turn -> new exchange + | ex_2 -> driver decides the next response) +``` + +The driver observes the TUI through `ui.state` while chunks stream, so mid-stream UI assertions need no clock control at all: the driver simply has not sent the rest yet. + +## Implementation order + +1. `network.ts`: simulated `HttpClient` + route table + deny-unknown + trace. Replace `httpClient` in `simulationReplacements`. +2. `llm-exchange.ts` + `openai.ts`: exchange service and the OpenAI SSE route (schema-constructed chunks, `[DONE]`, interruption). +3. `control.ts`: backend-hosted control WebSocket (`llm.attach|chunk|finish|pending`, `network.log`), started when the simulation module loads. +4. Config seeding for the sim provider; end-to-end verification via `packages/server/script/e2e-sim.ts` (headless) and `packages/tui/script/sim-llm-driver.ts` (TUI + backend sockets). +5. Trace records for network and LLM exchange activity. + +## Consequences + +- No enqueue/script store to keep consistent; the driver is the single source of model behavior. +- Deterministic tests write drivers (respond to `llm.request` programmatically) instead of pre-baked scripts; replay (Phase 4) records exchanges and replays them as an automatic driver. +- Provider-coupling is confined to `openai.ts` (one wire encoder against a schema that lives in the repo); a second simulated provider (e.g. Anthropic) is another route file if ever needed. diff --git a/packages/opencode/specs/simulation/simulation-phases.md b/packages/opencode/specs/simulation/simulation-phases.md index ef7aa41e3f..ebc4bd3743 100644 --- a/packages/opencode/specs/simulation/simulation-phases.md +++ b/packages/opencode/specs/simulation/simulation-phases.md @@ -51,6 +51,28 @@ Out of scope: Goal: make the app safe and controlled by swapping the lowest layers, not app logic. +Implementation checklist: + +- [x] Add `packages/simulation/src/backend` as the home for backend simulation layer replacements, exported from `backend/index.ts` as `simulationReplacements`; `@opencode-ai/simulation` is private/non-published and depends on logic/framework packages (`core`, `llm`, `effect`, OpenTUI), while `server` and `tui` consume it. +- [x] Wire simulation replacements through the server's `makeRoutes` via `Layer.unwrap` + dynamic `import("@opencode-ai/simulation/backend")` gated on `OPENCODE_SIMULATION`, so the simulation module is never loaded eagerly and `makeRoutes` stays synchronous. +- [x] Implement in-memory `FileSystem.FileSystem` (`simulation/filesystem.ts`) replacing the `NodeFileSystem` platform node. Backed by a flat path map; implements the operations the app uses (stat, access, chmod, realPath, read/write file, make/read directory, remove, rename, copy, copyFile, temp dirs, read-only open handles); unused operations die with a clear defect; `watch` fails as unsupported. +- [x] Root the fake filesystem at `OPENCODE_SIMULATION_ROOT` (falling back to `process.cwd()` at layer-build time). The anchor is a real, empty host directory the runner creates and cds into. +- [x] Deny host filesystem escapes loudly: content/mutation operations outside the root fail with `PermissionDenied` simulation errors. Probe operations (`stat`/`access`/`exists`) report `NotFound` outside the root so walk-up loops (project discovery, `findUp`, `globUp`) terminate naturally. +- [x] Add `SimulationFSUtil` replacement (`simulation/fs-util.ts`): wraps the real `FSUtil` layer and reroutes `readDirectoryEntries`, `glob`, and `globUp` — which bypass the injected `FileSystem` via node `fs/promises` and the `glob` package — through the simulated filesystem. +- [x] Fix `LayerNode.hoist` conflict detection to compare node implementations instead of object identity; replacement rewriting produces dependency-rewritten copies of the same node, which previously false-positived as "conflicting implementations". +- [x] Add snapshot seeding from `OPENCODE_SIMULATION_STATE`: `project/` contents of the snapshot directory are read from the host once at layer-build time and seeded into the in-memory tree joined onto the anchor root. +- [x] Verify end to end: `opencode serve` boots with `OPENCODE_SIMULATION=1` + `OPENCODE_SIMULATION_ROOT` + path/DB env seams (`OPENCODE_CONFIG_DIR`, `OPENCODE_TEST_HOME`, `OPENCODE_DB=:memory:`); `fs.list`/`fs.read` observe only seeded in-memory files; the anchor directory on the host remains empty after the run. +- [ ] Create the anchor directory + `chdir` + env seam setup automatically in CLI startup when simulation mode is enabled (currently set manually by the runner; a full run needs `OPENCODE_SIMULATION_ROOT/STATE`, `OPENCODE_CONFIG_DIR`, `OPENCODE_TEST_HOME`, `OPENCODE_DB=:memory:`, and `XDG_*_HOME` pointed into the anchor, plus Bun's `--preload=@opentui/solid/preload` when launched outside `packages/cli`). +- [ ] Assert the anchor directory is still empty at the end of the run (KV/log/flock still write through real XDG paths; they are contained in the anchor by the env seams but not yet in-memory). +- [x] Add simulated network registry (`packages/simulation/src/backend/network.ts`): replaces the `httpClient` platform node, resolves all outbound HTTP against an in-memory route table, denies unknown destinations loudly, and keeps a bounded request log (design: `simulated-network-llm.md`). +- [x] Add driver-answered LLM as an OpenAI route in the simulated network (`openai.ts` + `llm-exchange.ts`): provider requests open exchanges; the driver streams chunks back which are encoded as real OpenAI Chat SSE (schema-checked against `OpenAIChatEvent`) and consumed by the real protocol pipeline. No enqueue store — the driver is the model. +- [x] Add backend-hosted simulation control WebSocket (`control.ts`): JSON-RPC on `127.0.0.1:40950+`, started when the simulation module loads. Drivers connect directly (standalone topology — no frontend proxy): `llm.attach` (replays pending exchanges), `llm.chunk`, `llm.finish`, `llm.pending`, `network.log`; `llm.request` notifications push opened exchanges. This is also the headless-simulation interface. Drivers manage two sockets: TUI control (40900+) for UI, backend control (40950+) for LLM/network. +- [x] Answer `https://models.dev/api.json` with an empty catalog in the simulated network; providers come from seeded config (`opencode.json` in the snapshot defines an openai-compatible provider with a dummy `apiKey`, which passes the catalog availability gate and resolves onto the real openai-chat route). +- [x] Fix `buildLocationServiceMap` to apply replacements when compiling hoisted global nodes; platform-node replacements (filesystem, httpClient) were silently ignored inside hoisted globals. +- [x] Verify end to end headless (real route stack in-process + backend control WS: prompt -> `llm.request` -> driver chunks -> assistant message contains driver text; script: `packages/server/script/e2e-sim.ts`) and through the TUI (fake renderer, both sockets: type + submit via TUI WS, answer `llm.request` via backend WS, assistant reply rendered on screen; script: `packages/tui/script/sim-llm-driver.ts`). +- [ ] Add simulated process registry (shell via `just-bash`, minimal fake `git`, deny unsupported spawns). +- [ ] Trace filesystem, process, and LLM exchange activity (network requests are traced in the backend network log ring buffer; LLM exchange trace records moved out with the frontend proxy and need re-adding on the backend control server). + Scope: - Wire simulation replacements through `AppNodeBuilder.build(...)` and `AppNodeBuilderV1.build(...)`. diff --git a/packages/server/package.json b/packages/server/package.json index 86e5683dcf..6c5b3cb1b5 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -14,6 +14,7 @@ "dependencies": { "@opencode-ai/core": "workspace:*", "@opencode-ai/protocol": "workspace:*", + "@opencode-ai/simulation": "workspace:*", "drizzle-orm": "catalog:", "effect": "catalog:" }, diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index db69ba6c7f..2157dd0b04 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -72,7 +72,7 @@ function makeRoutes( const serviceLayer = simulationEnabled() ? Layer.unwrap( Effect.gen(function* () { - const { simulationReplacements } = yield* Effect.promise(() => import("./simulation")) + const { simulationReplacements } = yield* Effect.promise(() => import("@opencode-ai/simulation/backend")) return AppNodeBuilder.build(applicationServices, [...replacements, ...simulationReplacements]) }), ) diff --git a/packages/server/src/simulation/index.ts b/packages/server/src/simulation/index.ts deleted file mode 100644 index 3f499a5bf8..0000000000 --- a/packages/server/src/simulation/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { LayerNode } from "@opencode-ai/core/effect/layer-node" - -/** - * Layer replacements applied when the server is built in simulation mode. - * - * Empty for now; simulation-mode implementations will populate this with - * replacement nodes/layers that swap real services for simulated ones (e.g. - * a fake filesystem). The server merges these into the app node build when - * `OPENCODE_SIMULATION` is enabled, via a dynamic import so this module is - * never loaded eagerly. - */ -export const simulationReplacements: LayerNode.Replacements = [] - -export * as Simulation from "./index" diff --git a/packages/simulation/package.json b/packages/simulation/package.json new file mode 100644 index 0000000000..93bab0540e --- /dev/null +++ b/packages/simulation/package.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://json.schemastore.org/package.json", + "name": "@opencode-ai/simulation", + "version": "1.17.13", + "private": true, + "type": "module", + "license": "MIT", + "exports": { + "./backend": "./src/backend/index.ts", + "./backend/*": "./src/backend/*.ts", + "./frontend": "./src/frontend/simulation.ts", + "./frontend/*": "./src/frontend/*.ts" + }, + "scripts": { + "typecheck": "tsgo --noEmit" + }, + "dependencies": { + "@opencode-ai/core": "workspace:*", + "@opencode-ai/llm": "workspace:*", + "@opentui/core": "catalog:", + "effect": "catalog:" + }, + "devDependencies": { + "@tsconfig/bun": "catalog:", + "@types/bun": "catalog:", + "@typescript/native-preview": "catalog:" + } +} diff --git a/packages/simulation/src/backend/control.ts b/packages/simulation/src/backend/control.ts new file mode 100644 index 0000000000..f3fc67116c --- /dev/null +++ b/packages/simulation/src/backend/control.ts @@ -0,0 +1,145 @@ +import { Effect, Schema } from "effect" +import { SimulationLLMExchange } from "./llm-exchange" +import { SimulationNetwork } from "./network" + +/** + * Backend-hosted simulation control WebSocket. + * + * JSON-RPC 2.0 over a loopback WebSocket, mirroring the protocol of the TUI + * simulation server. Drivers connect directly (standalone topology; no + * frontend proxy) to answer LLM exchanges and inspect the simulated network. + * This is also the headless-simulation interface: it works with no TUI at + * all. + * + * Methods: + * - `llm.attach` -> subscribe; pending and future exchanges arrive + * as `llm.request` notifications + * - `llm.chunk` { id, items } append response items to an exchange + * - `llm.finish` { id, reason? } finish an exchange + * - `llm.pending` list open exchanges + * - `network.log` simulated network request log + */ + +const DefaultPort = 40950 +const MaxPortAttempts = 100 + +const ChunkItem = Schema.Union([ + Schema.Struct({ type: Schema.Literal("textDelta"), text: Schema.String }), + Schema.Struct({ type: Schema.Literal("reasoningDelta"), text: Schema.String }), + Schema.Struct({ type: Schema.Literal("toolCall"), id: Schema.String, name: Schema.String, input: Schema.Unknown }), + Schema.Struct({ type: Schema.Literal("raw"), chunk: Schema.Unknown }), +]) + +const ChunkParams = Schema.Struct({ id: Schema.String, items: Schema.Array(ChunkItem) }) + +const FinishParams = Schema.Struct({ + id: Schema.String, + reason: Schema.Literals(["stop", "tool-calls", "length", "content-filter"]).pipe( + Schema.withDecodingDefault(Effect.succeed("stop" as const)), + ), +}) + +const decodeChunkParams = Schema.decodeUnknownPromise(ChunkParams) +const decodeFinishParams = Schema.decodeUnknownPromise(FinishParams) + +type JsonRpcRequest = { + readonly jsonrpc: "2.0" + readonly id?: string | number | null + readonly method: string + readonly params?: unknown +} + +type ControlSocket = Bun.ServerWebSocket<{ unsubscribe?: () => void }> + +function parseRequest(input: string | Buffer): JsonRpcRequest { + const value = JSON.parse(typeof input === "string" ? input : input.toString()) as unknown + if (typeof value !== "object" || value === null) throw new Error("Invalid JSON-RPC request") + if (!("jsonrpc" in value) || value.jsonrpc !== "2.0") throw new Error("Invalid JSON-RPC version") + if (!("method" in value) || typeof value.method !== "string") throw new Error("Invalid JSON-RPC method") + return value as JsonRpcRequest +} + +async function handle(socket: ControlSocket, request: JsonRpcRequest): Promise { + switch (request.method) { + case "llm.attach": { + socket.data.unsubscribe?.() + socket.data.unsubscribe = SimulationLLMExchange.subscribe((exchange) => { + socket.send(JSON.stringify({ jsonrpc: "2.0", method: "llm.request", params: exchange })) + }) + return { attached: true } + } + case "llm.chunk": { + const params = await decodeChunkParams(request.params) + await Effect.runPromise( + SimulationLLMExchange.push( + params.id, + params.items.map((item) => ({ type: "item", item }) as const), + ), + ) + return { ok: true } + } + case "llm.finish": { + const params = await decodeFinishParams(request.params) + await Effect.runPromise(SimulationLLMExchange.push(params.id, [{ type: "finish", reason: params.reason }])) + return { ok: true } + } + case "llm.pending": + return { exchanges: SimulationLLMExchange.pending() } + case "network.log": + return { entries: SimulationNetwork.log() } + } + throw new Error(`Unknown simulation control method: ${request.method}`) +} + +function serve(port = DefaultPort, attempts = MaxPortAttempts): Bun.Server<{ unsubscribe?: () => void }> { + try { + return Bun.serve<{ unsubscribe?: () => void }>({ + hostname: "127.0.0.1", + port, + fetch(request, server) { + if (server.upgrade(request, { data: {} })) return undefined + return new Response("opencode simulation control websocket", { status: 426 }) + }, + websocket: { + close(socket) { + socket.data.unsubscribe?.() + }, + async message(socket, message) { + let request: JsonRpcRequest | undefined + try { + request = parseRequest(message) + const result = await handle(socket, request) + if (request.id !== undefined) socket.send(JSON.stringify({ jsonrpc: "2.0", id: request.id, result })) + } catch (error) { + socket.send( + JSON.stringify({ + jsonrpc: "2.0", + id: request?.id ?? null, + error: { code: -32000, message: error instanceof Error ? error.message : String(error) }, + }), + ) + } + }, + }, + }) + } catch (error) { + const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase() + const unavailable = message.includes("eaddrinuse") || message.includes("in use") + if (!unavailable || attempts <= 1 || port >= 65535) throw error + return serve(port + 1, attempts - 1) + } +} + +export function start() { + const server = serve() + const url = `ws://${server.hostname}:${server.port}` + process.stderr.write(`opencode simulation backend control websocket: ${url}\n`) + return { + url, + stop: () => { + server.stop(true) + }, + } +} + +export * as SimulationControl from "./control" diff --git a/packages/simulation/src/backend/filesystem.ts b/packages/simulation/src/backend/filesystem.ts new file mode 100644 index 0000000000..01a7b00329 --- /dev/null +++ b/packages/simulation/src/backend/filesystem.ts @@ -0,0 +1,390 @@ +import { Effect, FileSystem, Layer, Option, Stream } from "effect" +import { systemError, type PlatformError, type SystemErrorTag } from "effect/PlatformError" +import nodeFs from "fs" +import path from "path" + +/** + * In-memory simulated `FileSystem.FileSystem`. + * + * Replaces the `NodeFileSystem` platform node when the server runs in + * simulation mode. Backed by a flat map of absolute paths to entries and + * rooted at a single directory (the simulation anchor): paths that resolve + * outside the root fail with `PermissionDenied` so host filesystem escapes + * are loud. Only the operations the app actually uses are implemented; + * everything else dies with a clear defect. + * + * Inspired by the V1 prototype on `jlongster/simulation-rebase`, rewritten + * for the V2 platform node shape without the `just-bash` dependency. + */ + +export interface Options { + readonly root: string + readonly files?: Record +} + +interface FileEntry { + readonly type: "File" + content: Uint8Array + mode: number + mtime: Date +} + +interface DirectoryEntry { + readonly type: "Directory" + mode: number + mtime: Date +} + +type Entry = FileEntry | DirectoryEntry + +export function make(options: Options): FileSystem.FileSystem { + const root = path.resolve(options.root) + const store = new Map() + const temp = { value: 0 } + const encoder = new TextEncoder() + store.set(root, makeDirectoryEntry()) + + const within = (resolved: string) => resolved === root || resolved.startsWith(withSep(root)) + + const childrenOf = (resolved: string) => [...store.keys()].filter((key) => key.startsWith(withSep(resolved))) + + const fail = ( + tag: SystemErrorTag, + method: string, + file: string, + description?: string, + ): Effect.Effect => + Effect.fail( + systemError({ _tag: tag, module: "SimulationFileSystem", method, description, pathOrDescriptor: file }), + ) + + const locate = (method: string, file: string): Effect.Effect => { + const resolved = path.resolve(root, file) + if (within(resolved)) return Effect.succeed(resolved) + return fail("PermissionDenied", method, file, "path escapes the simulated filesystem root") + } + + const requireEntry = (method: string, file: string): Effect.Effect => + locate(method, file).pipe( + Effect.flatMap((resolved) => { + const entry = store.get(resolved) + if (!entry) return fail("NotFound", method, file) + return Effect.succeed([resolved, entry] as const) + }), + ) + + const requireParentDirectory = ( + method: string, + resolved: string, + file: string, + ): Effect.Effect => { + const parent = store.get(path.dirname(resolved)) + if (parent?.type === "Directory") return Effect.void + return fail("NotFound", method, file, "parent directory does not exist") + } + + // Creates every missing directory between root and resolved (inclusive). + const ensureDirectories = (method: string, file: string, resolved: string): Effect.Effect => + Effect.suspend(() => { + const segments = path.relative(root, resolved).split(path.sep).filter(Boolean) + const conflict = segments.reduce>((current, segment) => { + if (typeof current !== "string") return current + const next = path.join(current, segment) + const entry = store.get(next) + if (entry && entry.type !== "Directory") + return fail("AlreadyExists", method, file, "path component is not a directory") + if (!entry) store.set(next, makeDirectoryEntry()) + return next + }, root) + return typeof conflict === "string" ? Effect.void : conflict + }) + + // Seed initial files, creating parents as needed. Entries outside the root are ignored. + for (const [file, content] of Object.entries(options.files ?? {})) { + const resolved = path.resolve(root, file) + if (!within(resolved)) continue + Effect.runSync(ensureDirectories("seed", file, path.dirname(resolved))) + store.set(resolved, { + type: "File", + content: typeof content === "string" ? encoder.encode(content) : content.slice(), + mode: 0o644, + mtime: new Date(), + }) + } + + // Probe operations report NotFound outside the root instead of + // PermissionDenied: walk-up loops (project discovery, findUp, globUp) + // legitimately probe ancestor directories of the anchor and must observe + // "nothing there". Content access and mutation outside the root stay loud. + const probe = (method: string, file: string): Effect.Effect => + Effect.suspend(() => { + const resolved = path.resolve(root, file) + const entry = within(resolved) ? store.get(resolved) : undefined + if (!entry) return fail("NotFound", method, file) + return Effect.succeed(entry) + }) + + const stat: FileSystem.FileSystem["stat"] = (file) => probe("stat", file).pipe(Effect.map(toInfo)) + + const access: FileSystem.FileSystem["access"] = (file) => probe("access", file).pipe(Effect.asVoid) + + const chmod: FileSystem.FileSystem["chmod"] = (file, mode) => + requireEntry("chmod", file).pipe( + Effect.map(([, entry]) => { + entry.mode = mode + }), + ) + + const realPath: FileSystem.FileSystem["realPath"] = (file) => + requireEntry("realPath", file).pipe(Effect.map(([resolved]) => resolved)) + + const readFile: FileSystem.FileSystem["readFile"] = (file) => + requireEntry("readFile", file).pipe( + Effect.flatMap(([, entry]) => { + if (entry.type !== "File") return fail("BadResource", "readFile", file, "path is a directory") + return Effect.succeed(entry.content.slice()) + }), + ) + + const writeFile: FileSystem.FileSystem["writeFile"] = (file, data, writeOptions) => + locate("writeFile", file).pipe( + Effect.flatMap((resolved) => { + const existing = store.get(resolved) + if (existing?.type === "Directory") return fail("BadResource", "writeFile", file, "path is a directory") + return requireParentDirectory("writeFile", resolved, file).pipe( + Effect.map(() => { + store.set(resolved, { + type: "File", + content: data.slice(), + mode: writeOptions?.mode ?? existing?.mode ?? 0o644, + mtime: new Date(), + }) + }), + ) + }), + ) + + const makeDirectory: FileSystem.FileSystem["makeDirectory"] = (file, dirOptions) => + locate("makeDirectory", file).pipe( + Effect.flatMap((resolved) => { + if (dirOptions?.recursive) return ensureDirectories("makeDirectory", file, resolved) + if (store.has(resolved)) return fail("AlreadyExists", "makeDirectory", file) + return requireParentDirectory("makeDirectory", resolved, file).pipe( + Effect.map(() => { + store.set(resolved, { type: "Directory", mode: dirOptions?.mode ?? 0o755, mtime: new Date() }) + }), + ) + }), + ) + + const readDirectory: FileSystem.FileSystem["readDirectory"] = (file, readOptions) => + requireEntry("readDirectory", file).pipe( + Effect.flatMap(([resolved, entry]) => { + if (entry.type !== "Directory") return fail("BadResource", "readDirectory", file, "path is not a directory") + const children = childrenOf(resolved) + const names = readOptions?.recursive + ? children.map((key) => path.relative(resolved, key)) + : children.filter((key) => path.dirname(key) === resolved).map((key) => path.basename(key)) + return Effect.succeed(names.sort((a, b) => a.localeCompare(b))) + }), + ) + + const remove: FileSystem.FileSystem["remove"] = (file, removeOptions) => + locate("remove", file).pipe( + Effect.flatMap((resolved) => { + const entry = store.get(resolved) + if (!entry) return removeOptions?.force ? Effect.void : fail("NotFound", "remove", file) + const children = childrenOf(resolved) + if (entry.type === "Directory" && children.length > 0 && !removeOptions?.recursive) + return fail("Unknown", "remove", file, "directory is not empty") + for (const key of children) store.delete(key) + store.delete(resolved) + // The root itself must always exist. + if (resolved === root) store.set(root, makeDirectoryEntry()) + return Effect.void + }), + ) + + const rename: FileSystem.FileSystem["rename"] = (oldPath, newPath) => + Effect.all([locate("rename", oldPath), locate("rename", newPath)]).pipe( + Effect.flatMap(([from, to]) => { + const entry = store.get(from) + if (!entry) return fail("NotFound", "rename", oldPath) + return requireParentDirectory("rename", to, newPath).pipe( + Effect.map(() => { + const moved = [from, ...childrenOf(from)].map((key) => [key, store.get(key)!] as const) + for (const [key] of moved) store.delete(key) + for (const key of [to, ...childrenOf(to)]) store.delete(key) + for (const [key, value] of moved) store.set(key === from ? to : to + key.slice(from.length), value) + }), + ) + }), + ) + + const copy: FileSystem.FileSystem["copy"] = (fromPath, toPath) => + Effect.all([locate("copy", fromPath), locate("copy", toPath)]).pipe( + Effect.flatMap(([from, to]) => { + const entry = store.get(from) + if (!entry) return fail("NotFound", "copy", fromPath) + return requireParentDirectory("copy", to, toPath).pipe( + Effect.map(() => { + for (const key of [from, ...childrenOf(from)]) { + const source = store.get(key)! + const target = key === from ? to : to + key.slice(from.length) + store.set( + target, + source.type === "File" + ? { ...source, content: source.content.slice(), mtime: new Date() } + : { ...source, mtime: new Date() }, + ) + } + }), + ) + }), + ) + + const copyFile: FileSystem.FileSystem["copyFile"] = (fromPath, toPath) => + readFile(fromPath).pipe(Effect.flatMap((content) => writeFile(toPath, content))) + + const makeTempDirectory: FileSystem.FileSystem["makeTempDirectory"] = (tempOptions) => + Effect.suspend(() => { + const directory = tempOptions?.directory ?? path.join(root, ".simulation-tmp") + const file = path.join(directory, `${tempOptions?.prefix ?? "tmp-"}${++temp.value}`) + return makeDirectory(file, { recursive: true }).pipe(Effect.map(() => file)) + }) + + const makeTempDirectoryScoped: FileSystem.FileSystem["makeTempDirectoryScoped"] = (tempOptions) => + Effect.acquireRelease(makeTempDirectory(tempOptions), (directory) => + remove(directory, { recursive: true, force: true }).pipe(Effect.ignore), + ) + + // Read-only file handle: enough for the read tool's stat/seek/readAlloc use. + const open: FileSystem.FileSystem["open"] = (file) => + requireEntry("open", file).pipe( + Effect.map(([resolved]) => { + const position = { value: 0 } + const contentOf = () => { + const current = store.get(resolved) + return current?.type === "File" ? current.content : new Uint8Array() + } + return { + [FileSystem.FileTypeId]: FileSystem.FileTypeId, + fd: FileSystem.FileDescriptor(0), + stat: Effect.suspend(() => stat(resolved)), + seek: (offset, from) => + Effect.sync(() => { + position.value = from === "start" ? Number(offset) : position.value + Number(offset) + }), + sync: Effect.void, + read: (buffer) => + Effect.sync(() => { + const chunk = contentOf().subarray(position.value, position.value + buffer.length) + buffer.set(chunk) + position.value += chunk.length + return FileSystem.Size(chunk.length) + }), + readAlloc: (size) => + Effect.sync(() => { + const chunk = contentOf().slice(position.value, position.value + Number(size)) + position.value += chunk.length + return chunk.length === 0 ? Option.none() : Option.some(chunk) + }), + truncate: () => unimplemented("File.truncate"), + write: () => unimplemented("File.write"), + writeAll: () => unimplemented("File.writeAll"), + } satisfies FileSystem.File + }), + ) + + return FileSystem.make({ + access, + chmod, + chown: () => unimplemented("chown"), + copy, + copyFile, + link: () => unimplemented("link"), + makeDirectory, + makeTempDirectory, + makeTempDirectoryScoped, + makeTempFile: () => unimplemented("makeTempFile"), + makeTempFileScoped: () => unimplemented("makeTempFileScoped"), + open, + readDirectory, + readFile, + readLink: () => unimplemented("readLink"), + realPath, + remove, + rename, + stat, + symlink: () => unimplemented("symlink"), + truncate: () => unimplemented("truncate"), + utimes: () => unimplemented("utimes"), + watch: () => Stream.die(new Error("SimulationFileSystem.watch is not implemented in simulation")), + writeFile, + }) +} + +/** + * Lazily constructed layer so the root defaults to `process.cwd()` at + * layer-build time (the simulation anchor directory), not at import time. + * + * When `OPENCODE_SIMULATION_STATE` points at a snapshot directory, its + * `project/` contents are read from the host once at build time and seeded + * into the in-memory tree, joined onto the anchor root. + */ +export const layer = (options?: Partial) => + Layer.sync(FileSystem.FileSystem)(() => + make({ + root: options?.root ?? process.cwd(), + files: { ...loadSnapshotFiles(process.env.OPENCODE_SIMULATION_STATE), ...options?.files }, + }), + ) + +function loadSnapshotFiles(stateDirectory: string | undefined) { + if (!stateDirectory) return {} + const project = path.join(stateDirectory, "project") + if (!nodeFs.existsSync(project)) return {} + const files: Record = {} + const walk = (dir: string) => { + for (const entry of nodeFs.readdirSync(dir, { withFileTypes: true })) { + const file = path.join(dir, entry.name) + if (entry.isDirectory()) walk(file) + if (entry.isFile()) files[path.relative(project, file)] = new Uint8Array(nodeFs.readFileSync(file)) + } + } + walk(project) + return files +} + +function makeDirectoryEntry(): Entry { + return { type: "Directory", mode: 0o755, mtime: new Date() } +} + +function withSep(dir: string) { + return dir.endsWith(path.sep) ? dir : dir + path.sep +} + +function toInfo(entry: Entry): FileSystem.File.Info { + return { + type: entry.type, + mtime: Option.some(entry.mtime), + atime: Option.some(entry.mtime), + birthtime: Option.some(entry.mtime), + dev: 0, + ino: Option.none(), + mode: entry.mode, + nlink: Option.none(), + uid: Option.none(), + gid: Option.none(), + rdev: Option.none(), + size: FileSystem.Size(entry.type === "File" ? entry.content.length : 0), + blksize: Option.none(), + blocks: Option.none(), + } +} + +function unimplemented(method: string) { + return Effect.die(new Error(`SimulationFileSystem.${method} is not implemented in simulation`)) +} + +export * as SimulationFileSystem from "./filesystem" diff --git a/packages/simulation/src/backend/fs-util.ts b/packages/simulation/src/backend/fs-util.ts new file mode 100644 index 0000000000..e24d0c9c4b --- /dev/null +++ b/packages/simulation/src/backend/fs-util.ts @@ -0,0 +1,89 @@ +import { Effect, FileSystem, Layer } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Glob } from "@opencode-ai/core/util/glob" +import { makeGlobalNode } from "@opencode-ai/core/effect/app-node" +import { filesystem } from "@opencode-ai/core/effect/app-node-platform" +import path from "path" + +/** + * Simulation replacement for `FSUtil`. + * + * The real `FSUtil` layer builds most helpers on the injected + * `FileSystem.FileSystem`, but `readDirectoryEntries`, `glob`, and `globUp` + * reach for node `fs/promises` and the `glob` package directly, and `resolve` + * canonicalizes through the host filesystem. This wraps the real layer and + * reroutes those through the injected `FileSystem`/lexical path resolution so + * every read observes the in-memory tree. + */ + +const layer = Layer.effect( + FSUtil.Service, + Effect.gen(function* () { + const base = yield* FSUtil.Service + const fs = yield* FileSystem.FileSystem + + const resolve = Effect.fn("SimulationFSUtil.resolve")(function* (input: string) { + return input + }) + + const readDirectoryEntries = Effect.fn("SimulationFSUtil.readDirectoryEntries")(function* (dirPath: string) { + const names = yield* fs.readDirectory(dirPath) + return yield* Effect.forEach(names, (name) => + fs.stat(path.join(dirPath, name)).pipe( + Effect.map( + (info): FSUtil.DirEntry => ({ + name, + type: + info.type === "Directory" + ? "directory" + : info.type === "File" + ? "file" + : info.type === "SymbolicLink" + ? "symlink" + : "other", + }), + ), + Effect.orElseSucceed((): FSUtil.DirEntry => ({ name, type: "other" })), + ), + ) + }) + + const glob = Effect.fn("SimulationFSUtil.glob")(function* (pattern: string, options?: Glob.Options) { + const cwd = path.resolve(options?.cwd ?? process.cwd()) + const entries = yield* fs + .readDirectory(cwd, { recursive: true }) + .pipe(Effect.orElseSucceed(() => [] as string[])) + const matches = yield* Effect.forEach(entries, (entry) => + fs.stat(path.join(cwd, entry)).pipe( + Effect.map((info) => ({ entry, type: info.type })), + Effect.orElseSucceed(() => undefined), + ), + ) + return matches + .filter((item) => item !== undefined) + .filter((item) => options?.include === "all" || item.type === "File") + .filter((item) => Glob.match(pattern, item.entry)) + .map((item) => (options?.absolute ? path.join(cwd, item.entry) : item.entry)) + .sort((a, b) => a.localeCompare(b)) + }) + + const globUp = Effect.fn("SimulationFSUtil.globUp")(function* (pattern: string, start: string, stop?: string) { + const result: string[] = [] + let current = path.resolve(start) + while (true) { + result.push(...(yield* glob(pattern, { cwd: current, absolute: true, include: "file", dot: true }))) + if (stop === current) break + const parent = path.dirname(current) + if (parent === current) break + current = parent + } + return result + }) + + return FSUtil.Service.of({ ...base, readDirectoryEntries, resolve, glob, globUp }) + }), +).pipe(Layer.provide(FSUtil.layer)) + +export const node = makeGlobalNode({ service: FSUtil.Service, layer, deps: [filesystem] }) + +export * as SimulationFSUtil from "./fs-util" diff --git a/packages/simulation/src/backend/index.ts b/packages/simulation/src/backend/index.ts new file mode 100644 index 0000000000..dd735d40dd --- /dev/null +++ b/packages/simulation/src/backend/index.ts @@ -0,0 +1,41 @@ +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { filesystem, httpClient } from "@opencode-ai/core/effect/app-node-platform" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { SimulationControl } from "./control" +import { SimulationFileSystem } from "./filesystem" +import { SimulationFSUtil } from "./fs-util" +import { SimulationNetwork } from "./network" +import { SimulationOpenAI } from "./openai" + +/** + * Layer replacements applied when the server is built in simulation mode. + * + * The server merges these into the app node build when `OPENCODE_SIMULATION` + * is enabled, via a dynamic import so this module is never loaded eagerly. + * + * - Filesystem: in-memory tree rooted at `OPENCODE_SIMULATION_ROOT` (the real, + * empty anchor directory the runner created and chdir'd into). Everything + * under the root lives in memory; paths outside it fail loudly. + * - Network: all outbound HTTP resolves against the simulated route table; + * unknown destinations are denied. The driver-answered OpenAI endpoint is + * registered here as the first route. + * + * Loading this module also starts the backend simulation control WebSocket, + * which drivers connect to directly for LLM exchange control and network + * inspection (standalone topology; also the headless-simulation interface). + */ + +SimulationNetwork.register(SimulationOpenAI.route) +// ModelsDev dies when its catalog fetch fails, so simulation answers it with +// an empty catalog; providers come from seeded config instead. +SimulationNetwork.register(SimulationNetwork.json("GET", "https://models.dev/api.json", {})) + +SimulationControl.start() + +export const simulationReplacements: LayerNode.Replacements = [ + [filesystem, SimulationFileSystem.layer({ root: process.env.OPENCODE_SIMULATION_ROOT })], + [FSUtil.node, SimulationFSUtil.node], + [httpClient, SimulationNetwork.layer], +] + +export * as Simulation from "./index" diff --git a/packages/simulation/src/backend/llm-exchange.ts b/packages/simulation/src/backend/llm-exchange.ts new file mode 100644 index 0000000000..759f52866c --- /dev/null +++ b/packages/simulation/src/backend/llm-exchange.ts @@ -0,0 +1,105 @@ +import { Effect, Queue } from "effect" + +/** + * Pending driver-answered LLM exchanges. + * + * When the simulated network receives a provider request it opens an + * exchange: the parsed request body plus a queue of response chunks. The + * simulation control WebSocket notifies the external driver, and the driver + * pushes chunks back until it finishes the exchange. The driver is the + * model; nothing is scripted or enqueued server-side. + * + * Process-global by design (plain module state, like the network route + * table): the simulated network and the control server must observe the same + * exchanges regardless of which layer instance touched them. + */ + +/** One response item the driver sends back. Compiled to provider wire chunks by the endpoint. */ +export type Item = + | { readonly type: "textDelta"; readonly text: string } + | { readonly type: "reasoningDelta"; readonly text: string } + | { readonly type: "toolCall"; readonly id: string; readonly name: string; readonly input: unknown } + | { readonly type: "raw"; readonly chunk: unknown } + +export type FinishReason = "stop" | "tool-calls" | "length" | "content-filter" + +export type Chunk = + | { readonly type: "item"; readonly item: Item } + | { readonly type: "finish"; readonly reason: FinishReason } + +export interface Exchange { + readonly id: string + readonly url: string + readonly body: unknown + readonly queue: Queue.Queue +} + +export interface OpenedExchange { + readonly id: string + readonly url: string + readonly body: unknown +} + +const state = { + counter: 0, + exchanges: new Map(), + listeners: new Set<(exchange: OpenedExchange) => void>(), +} + +export class ExchangeNotFoundError extends Error { + constructor(id: string) { + super(`Simulation LLM exchange not found or already finished: ${id}`) + } +} + +/** Opens an exchange and notifies listeners. Called by the simulated provider endpoint. */ +export const open = (input: { readonly url: string; readonly body: unknown }) => + Effect.gen(function* () { + const id = `ex_${++state.counter}` + const queue = yield* Queue.unbounded() + const exchange: Exchange = { id, url: input.url, body: input.body, queue } + state.exchanges.set(id, exchange) + for (const listener of state.listeners) listener({ id, url: input.url, body: input.body }) + return exchange + }) + +/** Closes an exchange without consuming remaining chunks (response interrupted or finished). */ +export const close = (id: string) => + Effect.suspend(() => { + const exchange = state.exchanges.get(id) + state.exchanges.delete(id) + if (!exchange) return Effect.void + return Queue.shutdown(exchange.queue).pipe(Effect.asVoid) + }) + +/** Appends response chunks to an open exchange. Driver-facing. */ +export const push = (id: string, chunks: readonly Chunk[]) => + Effect.gen(function* () { + const exchange = state.exchanges.get(id) + if (!exchange) return yield* Effect.fail(new ExchangeNotFoundError(id)) + yield* Queue.offerAll(exchange.queue, chunks) + }) + +/** + * Registers a listener for newly opened exchanges and immediately replays + * currently-pending ones, so a late-attaching driver observes requests that + * arrived before it connected. Returns an unsubscribe function. + */ +export function subscribe(listener: (exchange: OpenedExchange) => void) { + state.listeners.add(listener) + for (const exchange of pending()) listener(exchange) + return () => { + state.listeners.delete(listener) + } +} + +/** Snapshot of currently open exchanges, for control-surface inspection. */ +export function pending(): OpenedExchange[] { + return [...state.exchanges.values()].map((exchange) => ({ + id: exchange.id, + url: exchange.url, + body: exchange.body, + })) +} + +export * as SimulationLLMExchange from "./llm-exchange" diff --git a/packages/simulation/src/backend/network.ts b/packages/simulation/src/backend/network.ts new file mode 100644 index 0000000000..7b002fcb4e --- /dev/null +++ b/packages/simulation/src/backend/network.ts @@ -0,0 +1,94 @@ +import { Effect, Layer } from "effect" +import { HttpClient, HttpClientResponse } from "effect/unstable/http" +import { HttpClientError, TransportError } from "effect/unstable/http/HttpClientError" +import type { HttpClientRequest } from "effect/unstable/http" + +/** + * Simulated network. + * + * Replaces the `HttpClient.HttpClient` platform node in simulation mode. All + * outbound HTTP resolves against an in-memory route table; unknown + * destinations fail loudly with a transport error so no simulation run can + * silently reach the real network. The scripted LLM is one registered route, + * not a separate mechanism. + * + * The route table is process-global module state so the control surface and + * the client layer observe the same registrations. + */ + +export interface Route { + /** Return a response effect to claim the request, undefined to pass. */ + readonly match: ( + request: HttpClientRequest.HttpClientRequest, + url: URL, + ) => Effect.Effect | undefined +} + +interface LogEntry { + readonly time: number + readonly method: string + readonly url: string + readonly matched: boolean +} + +const state = { + routes: [] as Route[], + log: [] as LogEntry[], +} + +const LOG_LIMIT = 1000 + +export function register(route: Route) { + state.routes.push(route) + return () => { + const index = state.routes.indexOf(route) + if (index >= 0) state.routes.splice(index, 1) + } +} + +/** Static JSON route: exact method + origin/path match answered with a fixed body. */ +export function json(method: string, url: string, body: unknown): Route { + return { + match: (request, requestUrl) => { + if (request.method !== method) return undefined + if (requestUrl.origin + requestUrl.pathname !== url) return undefined + return Effect.sync(() => + HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }), + ), + ) + }, + } +} + +export function log(): readonly LogEntry[] { + return state.log +} + +function record(entry: LogEntry) { + state.log.push(entry) + if (state.log.length > LOG_LIMIT) state.log.splice(0, state.log.length - LOG_LIMIT) +} + +export const layer = Layer.sync(HttpClient.HttpClient)(() => + HttpClient.make((request, url) => + Effect.suspend(() => { + const matched = state.routes + .map((route) => route.match(request, url)) + .find((response) => response !== undefined) + record({ time: Date.now(), method: request.method, url: url.toString(), matched: matched !== undefined }) + if (matched) return matched + return Effect.fail( + new HttpClientError({ + reason: new TransportError({ + request, + description: `Simulation denied unregistered network destination: ${request.method} ${url}`, + }), + }), + ) + }), + ), +) + +export * as SimulationNetwork from "./network" diff --git a/packages/simulation/src/backend/openai.ts b/packages/simulation/src/backend/openai.ts new file mode 100644 index 0000000000..c13e7772ef --- /dev/null +++ b/packages/simulation/src/backend/openai.ts @@ -0,0 +1,89 @@ +import { Effect, Schema, Stream } from "effect" +import { HttpClientResponse } from "effect/unstable/http" +import { OpenAIChatEvent, DEFAULT_BASE_URL, PATH } from "@opencode-ai/llm/protocols/openai-chat" +import { SimulationLLMExchange } from "./llm-exchange" +import { SimulationNetwork } from "./network" + +/** + * Driver-answered OpenAI endpoint for the simulated network. + * + * Claims `POST {DEFAULT_BASE_URL}{PATH}` (the real openai-chat route + * endpoint), opens an LLM exchange, and streams the driver's chunks back as + * an OpenAI Chat SSE response terminated by `[DONE]`. Everything downstream + * of the response bytes is the real pipeline: SSE framing, the OpenAIChat + * event schema, the protocol state machine, and Lifecycle grammar. + */ + +const encodeChunk = Schema.encodeUnknownSync(OpenAIChatEvent) + +const encoder = new TextEncoder() + +// The simulated model id is echoed back only in non-schema fields; the +// protocol event schema ignores unknown fields, so id/object/model are +// decorative wire realism. +function chunkOf(item: SimulationLLMExchange.Item): OpenAIChatEvent | unknown { + if (item.type === "textDelta") return { choices: [{ delta: { content: item.text } }] } + if (item.type === "reasoningDelta") return { choices: [{ delta: { reasoning_content: item.text } }] } + if (item.type === "toolCall") + return { + choices: [ + { + delta: { + tool_calls: [ + { index: 0, id: item.id, function: { name: item.name, arguments: JSON.stringify(item.input) } }, + ], + }, + }, + ], + } + return item.chunk +} + +const finishReasonWire: Record = { + stop: "stop", + "tool-calls": "tool_calls", + length: "length", + "content-filter": "content_filter", +} + +function frame(payload: unknown): Uint8Array { + return encoder.encode(`data: ${JSON.stringify(payload)}\n\n`) +} + +function sseBody(exchange: SimulationLLMExchange.Exchange): Stream.Stream { + const chunks = Stream.fromQueue(exchange.queue).pipe( + Stream.takeUntil((chunk) => chunk.type === "finish"), + Stream.map((chunk) => { + if (chunk.type === "finish") + return frame(encodeChunk({ choices: [{ delta: {}, finish_reason: finishReasonWire[chunk.reason] }] })) + if (chunk.item.type === "raw") return frame(chunk.item.chunk) + return frame(encodeChunk(chunkOf(chunk.item))) + }), + ) + return chunks.pipe( + Stream.concat(Stream.make(encoder.encode("data: [DONE]\n\n"))), + // Close the exchange when the response body ends or is interrupted, so + // late driver pushes fail with ExchangeNotFoundError instead of leaking. + Stream.ensuring(SimulationLLMExchange.close(exchange.id)), + ) +} + +export const route: SimulationNetwork.Route = { + match: (request, url) => { + if (request.method !== "POST") return undefined + if (url.origin + url.pathname !== DEFAULT_BASE_URL + PATH) return undefined + return Effect.gen(function* () { + const body = request.body._tag === "Uint8Array" ? JSON.parse(new TextDecoder().decode(request.body.body)) : {} + const exchange = yield* SimulationLLMExchange.open({ url: url.toString(), body }) + return HttpClientResponse.fromWeb( + request, + new Response(Stream.toReadableStream(sseBody(exchange)), { + status: 200, + headers: { "content-type": "text/event-stream" }, + }), + ) + }) + }, +} + +export * as SimulationOpenAI from "./openai" diff --git a/packages/tui/src/simulation/actions.ts b/packages/simulation/src/frontend/actions.ts similarity index 100% rename from packages/tui/src/simulation/actions.ts rename to packages/simulation/src/frontend/actions.ts diff --git a/packages/tui/src/simulation/renderer.ts b/packages/simulation/src/frontend/renderer.ts similarity index 100% rename from packages/tui/src/simulation/renderer.ts rename to packages/simulation/src/frontend/renderer.ts diff --git a/packages/tui/src/simulation/server.ts b/packages/simulation/src/frontend/server.ts similarity index 100% rename from packages/tui/src/simulation/server.ts rename to packages/simulation/src/frontend/server.ts diff --git a/packages/tui/src/simulation/simulation.ts b/packages/simulation/src/frontend/simulation.ts similarity index 100% rename from packages/tui/src/simulation/simulation.ts rename to packages/simulation/src/frontend/simulation.ts diff --git a/packages/tui/src/simulation/trace.ts b/packages/simulation/src/frontend/trace.ts similarity index 100% rename from packages/tui/src/simulation/trace.ts rename to packages/simulation/src/frontend/trace.ts diff --git a/packages/simulation/tsconfig.json b/packages/simulation/tsconfig.json new file mode 100644 index 0000000000..00ef125468 --- /dev/null +++ b/packages/simulation/tsconfig.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@tsconfig/bun/tsconfig.json", + "compilerOptions": { + "lib": ["ESNext", "DOM", "DOM.Iterable"], + "noUncheckedIndexedAccess": false + } +} diff --git a/packages/tui/package.json b/packages/tui/package.json index 8bf349c2da..4dade71898 100644 --- a/packages/tui/package.json +++ b/packages/tui/package.json @@ -51,6 +51,7 @@ "@opencode-ai/core": "workspace:*", "@opencode-ai/plugin": "workspace:*", "@opencode-ai/sdk": "workspace:*", + "@opencode-ai/simulation": "workspace:*", "@opencode-ai/ui": "workspace:*", "@opentui/core": "catalog:", "@opentui/keymap": "catalog:", diff --git a/packages/tui/src/app.tsx b/packages/tui/src/app.tsx index 876faff9de..d5cf93c2c7 100644 --- a/packages/tui/src/app.tsx +++ b/packages/tui/src/app.tsx @@ -200,8 +200,8 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) { }, } satisfies CliRendererConfig - if (process.env.OPENCODE_SIMULATION === "1" || process.env.OPENCODE_SIMULATION === "true") { - const { Simulation } = await import("./simulation/simulation") + if (!!process.env.OPENCODE_SIMULATION) { + const { Simulation } = await import("@opencode-ai/simulation/frontend") return Simulation.createSimulation(options) } From 394e0b9045d08e334463aeeb4f80fd231d74c848 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 14:25:59 -0400 Subject: [PATCH 20/82] refactor(schema): rename V2 session events and normalize payloads (#35217) --- .../client/src/promise/generated/types.ts | 509 +++-- packages/client/test/effect.test.ts | 29 +- packages/client/test/promise.test.ts | 11 +- packages/core/schema.json | 14 +- .../core/src/control-plane/move-session.ts | 3 +- packages/core/src/database/migration.gen.ts | 2 + ...60703090000_reset_v2_event_rename_sweep.ts | 17 + .../20260703181610_event_created_column.ts | 11 + packages/core/src/database/schema.gen.ts | 1 + packages/core/src/event.ts | 9 +- packages/core/src/event/sql.ts | 1 + packages/core/src/session.ts | 20 +- packages/core/src/session/compaction.ts | 7 +- .../core/src/session/context-checkpoint.ts | 5 +- packages/core/src/session/execution/local.ts | 1 - packages/core/src/session/input.ts | 27 +- packages/core/src/session/instructions.ts | 8 +- packages/core/src/session/message-updater.ts | 138 +- packages/core/src/session/projector.ts | 61 +- packages/core/src/session/revert.ts | 3 - packages/core/src/session/runner/llm.ts | 2 - .../src/session/runner/publish-llm-event.ts | 16 - packages/core/src/session/title.ts | 8 +- packages/core/test/database-migration.test.ts | 2 +- packages/core/test/event.test.ts | 32 +- packages/core/test/session-compact.test.ts | 10 +- packages/core/test/session-create.test.ts | 17 +- .../core/test/session-instructions.test.ts | 2 - packages/core/test/session-log.test.ts | 4 +- packages/core/test/session-projector.test.ts | 70 +- packages/core/test/session-prompt.test.ts | 32 +- .../core/test/session-runner-message.test.ts | 4 +- .../core/test/session-runner-recorded.test.ts | 12 +- .../test/session-runner-tool-events.test.ts | 11 +- packages/core/test/session-runner.test.ts | 58 +- packages/core/test/session-title.test.ts | 10 +- .../core/test/session-tool-progress.test.ts | 7 - packages/core/test/shared-schema.test.ts | 4 +- packages/core/test/tool-shell.test.ts | 4 - packages/core/test/tool-subagent.test.ts | 4 - .../src/cli/cmd/run/noninteractive.ts | 42 +- .../opencode/src/cli/cmd/run/session-data.ts | 4 +- .../src/cli/cmd/run/stream-v2.subagent.ts | 60 +- .../src/cli/cmd/run/stream-v2.transport.ts | 73 +- .../test/cli/run/noninteractive.test.ts | 18 +- .../test/cli/run/session-data.test.ts | 12 +- .../test/cli/run/stream-v2.transport.test.ts | 167 +- .../test/v2/session-message-updater.test.ts | 64 +- packages/schema/src/event.ts | 5 +- packages/schema/src/session-event.ts | 119 +- packages/schema/src/session-message.ts | 24 +- packages/schema/test/event-manifest.test.ts | 68 +- packages/sdk-next/test/embedded.test.ts | 12 +- packages/sdk/js/script/build.ts | 14 +- packages/sdk/js/src/v2/gen/types.gen.ts | 1732 ++++++++--------- packages/tui/src/context/data.tsx | 160 +- .../feature-plugins/system/notifications.ts | 16 +- packages/tui/src/routes/session/rows.ts | 44 +- .../test/cli/cmd/tui/notifications.test.ts | 34 +- packages/tui/test/cli/tui/data.test.tsx | 103 +- packages/tui/test/cli/tui/use-event.test.tsx | 2 + specs/v2/schema-changelog.md | 14 + specs/v2/session.md | 6 +- 63 files changed, 1939 insertions(+), 2040 deletions(-) create mode 100644 packages/core/src/database/migration/20260703090000_reset_v2_event_rename_sweep.ts create mode 100644 packages/core/src/database/migration/20260703181610_event_created_column.ts diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 798155e88e..13dab421d5 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -1107,74 +1107,75 @@ export type SessionLogOutput = | ( | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.agent.switched" + readonly type: "agent.selected" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly agent: string - } + readonly data: { readonly sessionID: string; readonly agent: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.model.switched" + readonly type: "model.selected" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string - readonly messageID: string readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.moved" + readonly type: "session.moved" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly location: { readonly directory: string; readonly workspaceID?: string } - readonly subdirectory?: string + readonly subpath?: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.renamed" + readonly type: "renamed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly timestamp: number; readonly sessionID: string; readonly title: string } + readonly data: { readonly sessionID: string; readonly title: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.forked" + readonly type: "forked" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly parentID: string - readonly messageID?: string - } + readonly data: { readonly sessionID: string; readonly parentID: string; readonly from?: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.prompted" + readonly type: "prompt.promoted" + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly location?: { readonly directory: string; readonly workspaceID?: string } + readonly data: { readonly sessionID: string; readonly inputID: string } + } + | { + readonly id: string + readonly created: number + readonly metadata?: { readonly [x: string]: unknown } + readonly type: "prompt.admitted" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string - readonly messageID: string + readonly inputID: string readonly prompt: { readonly text: string readonly files?: ReadonlyArray<{ @@ -1194,54 +1195,22 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.prompt.admitted" + readonly type: "session.context.updated" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly prompt: { - readonly text: string - readonly files?: ReadonlyArray<{ - readonly uri: string - readonly mime: string - readonly name?: string - readonly description?: string - readonly source?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly source?: { readonly start: number; readonly end: number; readonly text: string } - }> - } - readonly delivery: "steer" | "queue" - } + readonly data: { readonly sessionID: string; readonly text: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.context.updated" + readonly type: "synthetic" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string - readonly messageID: string - readonly text: string - } - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.synthetic" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string readonly text: string readonly description?: string readonly metadata?: { readonly [x: string]: unknown } @@ -1249,53 +1218,39 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.skill.activated" + readonly type: "skill.activated" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly name: string - readonly text: string - } + readonly data: { readonly sessionID: string; readonly name: string; readonly text: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.shell.started" + readonly type: "shell.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly callID: string - readonly command: string - } + readonly data: { readonly sessionID: string; readonly callID: string; readonly command: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.shell.ended" + readonly type: "shell.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly callID: string - readonly output: string - } + readonly data: { readonly sessionID: string; readonly callID: string; readonly output: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.step.started" + readonly type: "step.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly agent: string @@ -1305,12 +1260,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.step.ended" + readonly type: "step.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly finish: string @@ -1327,12 +1282,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.step.failed" + readonly type: "step.failed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly error: { readonly type: "unknown"; readonly message: string } @@ -1340,25 +1295,21 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.text.started" + readonly type: "text.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly assistantMessageID: string - readonly textID: string - } + readonly data: { readonly sessionID: string; readonly assistantMessageID: string; readonly textID: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.text.ended" + readonly type: "text.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly textID: string @@ -1367,12 +1318,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.reasoning.started" + readonly type: "reasoning.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly reasoningID: string @@ -1381,12 +1332,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.reasoning.ended" + readonly type: "reasoning.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly reasoningID: string @@ -1396,12 +1347,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.input.started" + readonly type: "tool.input.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -1410,12 +1361,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.input.ended" + readonly type: "tool.input.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -1424,12 +1375,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.called" + readonly type: "tool.called" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -1443,12 +1394,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.progress" + readonly type: "tool.progress" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -1461,12 +1412,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.success" + readonly type: "tool.success" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -1485,12 +1436,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.failed" + readonly type: "tool.failed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -1504,12 +1455,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.retried" + readonly type: "retried" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly attempt: number readonly error: { @@ -1524,27 +1475,22 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.compaction.started" + readonly type: "compaction.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly reason: "auto" | "manual" - } + readonly data: { readonly sessionID: string; readonly reason: "auto" | "manual" } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.compaction.ended" + readonly type: "compaction.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string - readonly messageID: string readonly reason: "auto" | "manual" readonly text: string readonly recent: string @@ -1552,12 +1498,12 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.revert.staged" + readonly type: "revert.staged" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly revert: { readonly messageID: string @@ -1576,19 +1522,21 @@ export type SessionLogOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.revert.cleared" + readonly type: "revert.cleared" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly timestamp: number; readonly sessionID: string } + readonly data: { readonly sessionID: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.revert.committed" + readonly type: "revert.committed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly timestamp: number; readonly sessionID: string; readonly messageID: string } + readonly data: { readonly sessionID: string; readonly messageID: string } } ) | { readonly type: "log.synced"; readonly aggregateID: string; readonly seq?: number } @@ -3771,6 +3719,7 @@ export type SkillListOutput = { export type EventSubscribeOutput = | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "models-dev.refreshed" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -3778,6 +3727,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "integration.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -3785,6 +3735,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "integration.connection.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -3792,6 +3743,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "catalog.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -3799,6 +3751,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "agent.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -3806,6 +3759,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.created" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } @@ -3867,6 +3821,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.updated" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } @@ -3928,6 +3883,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.deleted" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } @@ -3989,6 +3945,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "message.updated" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } @@ -4093,6 +4050,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "message.removed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } @@ -4101,6 +4059,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "message.part.updated" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } @@ -4339,6 +4298,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "message.part.removed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } @@ -4347,74 +4307,75 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.agent.switched" + readonly type: "agent.selected" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly agent: string - } + readonly data: { readonly sessionID: string; readonly agent: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.model.switched" + readonly type: "model.selected" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string - readonly messageID: string readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.moved" + readonly type: "session.moved" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly location: { readonly directory: string; readonly workspaceID?: string } - readonly subdirectory?: string + readonly subpath?: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.renamed" + readonly type: "renamed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly timestamp: number; readonly sessionID: string; readonly title: string } + readonly data: { readonly sessionID: string; readonly title: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.forked" + readonly type: "forked" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly parentID: string - readonly messageID?: string - } + readonly data: { readonly sessionID: string; readonly parentID: string; readonly from?: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.prompted" + readonly type: "prompt.promoted" + readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly location?: { readonly directory: string; readonly workspaceID?: string } + readonly data: { readonly sessionID: string; readonly inputID: string } + } + | { + readonly id: string + readonly created: number + readonly metadata?: { readonly [x: string]: unknown } + readonly type: "prompt.admitted" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string - readonly messageID: string + readonly inputID: string readonly prompt: { readonly text: string readonly files?: ReadonlyArray<{ @@ -4434,38 +4395,11 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.prompt.admitted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } + readonly type: "execution.settled" readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly prompt: { - readonly text: string - readonly files?: ReadonlyArray<{ - readonly uri: string - readonly mime: string - readonly name?: string - readonly description?: string - readonly source?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly source?: { readonly start: number; readonly end: number; readonly text: string } - }> - } - readonly delivery: "steer" | "queue" - } - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.execution.settled" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number readonly sessionID: string readonly outcome: "success" | "failure" | "interrupted" readonly error?: { readonly type: "unknown"; readonly message: string } @@ -4473,27 +4407,22 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.context.updated" + readonly type: "session.context.updated" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly text: string - } + readonly data: { readonly sessionID: string; readonly text: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.synthetic" + readonly type: "synthetic" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string - readonly messageID: string readonly text: string readonly description?: string readonly metadata?: { readonly [x: string]: unknown } @@ -4501,53 +4430,39 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.skill.activated" + readonly type: "skill.activated" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly name: string - readonly text: string - } + readonly data: { readonly sessionID: string; readonly name: string; readonly text: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.shell.started" + readonly type: "shell.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly callID: string - readonly command: string - } + readonly data: { readonly sessionID: string; readonly callID: string; readonly command: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.shell.ended" + readonly type: "shell.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly callID: string - readonly output: string - } + readonly data: { readonly sessionID: string; readonly callID: string; readonly output: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.step.started" + readonly type: "step.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly agent: string @@ -4557,12 +4472,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.step.ended" + readonly type: "step.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly finish: string @@ -4579,12 +4494,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.step.failed" + readonly type: "step.failed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly error: { readonly type: "unknown"; readonly message: string } @@ -4592,24 +4507,20 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.text.started" + readonly type: "text.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly assistantMessageID: string - readonly textID: string - } + readonly data: { readonly sessionID: string; readonly assistantMessageID: string; readonly textID: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.text.delta" + readonly type: "text.delta" readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly textID: string @@ -4618,12 +4529,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.text.ended" + readonly type: "text.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly textID: string @@ -4632,12 +4543,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.reasoning.started" + readonly type: "reasoning.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly reasoningID: string @@ -4646,11 +4557,11 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.reasoning.delta" + readonly type: "reasoning.delta" readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly reasoningID: string @@ -4659,12 +4570,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.reasoning.ended" + readonly type: "reasoning.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly reasoningID: string @@ -4674,12 +4585,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.input.started" + readonly type: "tool.input.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -4688,11 +4599,11 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.input.delta" + readonly type: "tool.input.delta" readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -4701,12 +4612,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.input.ended" + readonly type: "tool.input.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -4715,12 +4626,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.called" + readonly type: "tool.called" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -4734,12 +4645,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.progress" + readonly type: "tool.progress" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -4752,12 +4663,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.success" + readonly type: "tool.success" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -4776,12 +4687,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.tool.failed" + readonly type: "tool.failed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly assistantMessageID: string readonly callID: string @@ -4795,12 +4706,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.retried" + readonly type: "retried" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly attempt: number readonly error: { @@ -4815,39 +4726,30 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.compaction.started" + readonly type: "compaction.started" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly reason: "auto" | "manual" - } + readonly data: { readonly sessionID: string; readonly reason: "auto" | "manual" } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.compaction.delta" + readonly type: "compaction.delta" readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly timestamp: number - readonly sessionID: string - readonly messageID: string - readonly text: string - } + readonly data: { readonly sessionID: string; readonly text: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.compaction.ended" + readonly type: "compaction.ended" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string - readonly messageID: string readonly reason: "auto" | "manual" readonly text: string readonly recent: string @@ -4855,12 +4757,12 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.revert.staged" + readonly type: "revert.staged" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { - readonly timestamp: number readonly sessionID: string readonly revert: { readonly messageID: string @@ -4879,22 +4781,25 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.revert.cleared" + readonly type: "revert.cleared" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly timestamp: number; readonly sessionID: string } + readonly data: { readonly sessionID: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.next.revert.committed" + readonly type: "revert.committed" readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: number } readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly timestamp: number; readonly sessionID: string; readonly messageID: string } + readonly data: { readonly sessionID: string; readonly messageID: string } } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "file.edited" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4902,6 +4807,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "reference.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4909,6 +4815,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "permission.v2.asked" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4924,6 +4831,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "permission.v2.replied" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4935,6 +4843,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "plugin.added" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4942,6 +4851,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "project.directories.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4949,6 +4859,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "command.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4956,6 +4867,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "skill.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4963,6 +4875,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "file.watcher.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4970,6 +4883,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "pty.created" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -4988,6 +4902,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "pty.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5006,6 +4921,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "pty.exited" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5013,6 +4929,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "pty.deleted" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5020,6 +4937,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "shell.created" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5040,6 +4958,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "shell.exited" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5051,6 +4970,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "shell.deleted" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5058,6 +4978,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.v2.asked" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5076,6 +4997,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.v2.replied" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5087,6 +5009,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.v2.rejected" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5094,6 +5017,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "form.created" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5208,6 +5132,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "form.replied" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5219,6 +5144,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "form.cancelled" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5226,6 +5152,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "todo.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5236,6 +5163,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.status" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5262,6 +5190,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.idle" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5269,6 +5198,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "tui.prompt.append" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5276,6 +5206,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "tui.command.execute" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5303,6 +5234,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "tui.toast.show" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5315,6 +5247,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "tui.session.select" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5322,6 +5255,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "installation.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5329,6 +5263,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "installation.update-available" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5336,6 +5271,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "vcs.branch.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5343,6 +5279,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "mcp.status.changed" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5350,6 +5287,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "permission.asked" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5365,6 +5303,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "permission.replied" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5376,6 +5315,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.asked" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5394,6 +5334,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.replied" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5405,6 +5346,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "question.rejected" readonly location?: { readonly directory: string; readonly workspaceID?: string } @@ -5412,6 +5354,7 @@ export type EventSubscribeOutput = } | { readonly id: string + readonly created: number readonly metadata?: { readonly [x: string]: unknown } readonly type: "session.error" readonly location?: { readonly directory: string; readonly workspaceID?: string } diff --git a/packages/client/test/effect.test.ts b/packages/client/test/effect.test.ts index 445a9cf3de..5a7ec9b7cc 100644 --- a/packages/client/test/effect.test.ts +++ b/packages/client/test/effect.test.ts @@ -1,7 +1,17 @@ import { expect, test } from "bun:test" import { DateTime, Effect, Stream } from "effect" import { HttpClient, HttpClientResponse } from "effect/unstable/http" -import { AbsolutePath, Agent, Event, Location, Model, OpenCode, Prompt, Session, SessionMessage } from "../src/effect/index" +import { + AbsolutePath, + Agent, + Event, + Location, + Model, + OpenCode, + Prompt, + Session, + SessionMessage, +} from "../src/effect/index" const synced = { type: "log.synced" as const, aggregateID: "ses_test", seq: Event.Seq.make(1) } @@ -23,7 +33,7 @@ test("event.subscribe exposes and decodes the native Effect event stream", async HttpClientResponse.fromWeb( request, new Response( - `data: ${JSON.stringify({ id: "evt_connected", type: "server.connected", data: {} })}\n\n` + + `data: ${JSON.stringify({ id: "evt_connected", created: 0, type: "server.connected", data: {} })}\n\n` + `data: ${JSON.stringify(modelSwitchedEvent)}\n\n`, { headers: { "content-type": "text/event-stream" } }, ), @@ -35,10 +45,10 @@ test("event.subscribe exposes and decodes the native Effect event stream", async return yield* client.event.subscribe().pipe(Stream.runCollect) }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.runPromise) - expect(Array.from(events).map((event) => event.type)).toEqual(["server.connected", "session.next.model.switched"]) + expect(Array.from(events).map((event) => event.type)).toEqual(["server.connected", "model.selected"]) const durable = events[1] - if (durable?.type !== "session.next.model.switched") throw new Error("Expected model event") - expect(DateTime.toEpochMillis(durable.data.timestamp)).toBe(1_717_171_717_000) + if (durable?.type !== "model.selected") throw new Error("Expected model event") + expect(DateTime.toEpochMillis(durable.created)).toBe(1_717_171_717_000) expect(durable.durable).toEqual({ aggregateID: "ses_test", seq: 1, version: 1 }) }) @@ -149,8 +159,8 @@ test("session methods retain decoded Effect inputs and outputs", async () => { expect(result.context).toEqual([]) expect(logQueries[0]).toEqual({ after: "0" }) const logged = Array.from(result.log) - expect(logged.map((item) => item.type)).toEqual(["session.next.model.switched", "log.synced"]) - expect(logged[0]?.type === "session.next.model.switched" && DateTime.toEpochMillis(logged[0].data.timestamp)).toBe( + expect(logged.map((item) => item.type)).toEqual(["model.selected", "log.synced"]) + expect(logged[0]?.type === "model.selected" && DateTime.toEpochMillis(logged[0].created)).toBe( 1_717_171_717_000, ) expect(logged.at(-1)).toEqual(synced) @@ -217,12 +227,11 @@ const modelSwitchedMessage = { const modelSwitchedEvent = { id: "evt_model", - type: "session.next.model.switched", + created: 1_717_171_717_000, + type: "model.selected", durable: { aggregateID: "ses_test", seq: 1, version: 1 }, data: { - timestamp: 1_717_171_717_000, sessionID: "ses_test", - messageID: "msg_model", model: { id: "claude", providerID: "anthropic" }, }, } diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index 030b761fa6..9e8ea7acfe 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -151,7 +151,7 @@ test("event.subscribe exposes the Promise event stream wire projection", async ( baseUrl: "http://localhost:3000", fetch: async () => new Response( - `: heartbeat\n\ndata: ${JSON.stringify({ id: "evt_connected", type: "server.connected", data: {} })}\n\n` + + `: heartbeat\n\ndata: ${JSON.stringify({ id: "evt_connected", created: 0, type: "server.connected", data: {} })}\n\n` + `data: ${JSON.stringify(modelSwitchedEvent)}\n\n`, { headers: { "content-type": "text/event-stream" } }, ), @@ -159,8 +159,8 @@ test("event.subscribe exposes the Promise event stream wire projection", async ( const events = [] for await (const event of client.event.subscribe()) events.push(event) - expect(events).toEqual([{ id: "evt_connected", type: "server.connected", data: {} }, modelSwitchedEvent]) - expect(events[1]?.type === "session.next.model.switched" && events[1].data.timestamp).toBe(1_717_171_717_000) + expect(events).toEqual([{ id: "evt_connected", created: 0, type: "server.connected", data: {} }, modelSwitchedEvent]) + expect(events[1]?.type === "model.selected" && events[1].created).toBe(1_717_171_717_000) }) test("event.subscribe terminates on malformed Promise SSE data", async () => { @@ -328,12 +328,11 @@ const synced = { type: "log.synced", aggregateID: "ses_test", seq: 1 } const modelSwitchedEvent = { id: "evt_model", - type: "session.next.model.switched", + created: 1_717_171_717_000, + type: "model.selected", durable: { aggregateID: "ses_test", seq: 1, version: 1 }, data: { - timestamp: 1_717_171_717_000, sessionID: "ses_test", - messageID: "msg_model", model: { id: "claude", providerID: "anthropic" }, }, } diff --git a/packages/core/schema.json b/packages/core/schema.json index e8a2502a34..d9e0b20b22 100644 --- a/packages/core/schema.json +++ b/packages/core/schema.json @@ -1,9 +1,9 @@ { "version": "7", "dialect": "sqlite", - "id": "22e57fed-b9b8-4e94-a3b4-f94bece680a8", + "id": "96e9fe64-d810-4102-8f79-3317a88bb6d2", "prevIds": [ - "f14a9b18-8207-487e-a3d3-227e629ba9ad" + "22e57fed-b9b8-4e94-a3b4-f94bece680a8" ], "ddl": [ { @@ -526,6 +526,16 @@ "entityType": "columns", "table": "event" }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "created", + "entityType": "columns", + "table": "event" + }, { "type": "text", "notNull": true, diff --git a/packages/core/src/control-plane/move-session.ts b/packages/core/src/control-plane/move-session.ts index e227f88df5..6f0c6e3081 100644 --- a/packages/core/src/control-plane/move-session.ts +++ b/packages/core/src/control-plane/move-session.ts @@ -106,8 +106,7 @@ const layer = Layer.effect( yield* events.publish(SessionEvent.Moved, { sessionID: input.sessionID, location: Location.Ref.make({ directory }), - subdirectory: RelativePath.make(path.relative(destination.directory, directory).replaceAll("\\", "/")), - timestamp: yield* DateTime.now, + subpath: RelativePath.make(path.relative(destination.directory, directory).replaceAll("\\", "/")), }) if (patch) { diff --git a/packages/core/src/database/migration.gen.ts b/packages/core/src/database/migration.gen.ts index 55c1b212cd..7956b64f4d 100644 --- a/packages/core/src/database/migration.gen.ts +++ b/packages/core/src/database/migration.gen.ts @@ -41,5 +41,7 @@ export const migrations = ( import("./migration/20260622170816_reset_v2_session_state"), import("./migration/20260622202450_simplify_session_input"), import("./migration/20260702134641_add_session_context_entry"), + import("./migration/20260703090000_reset_v2_event_rename_sweep"), + import("./migration/20260703181610_event_created_column"), ]) ).map((module) => module.default) satisfies DatabaseMigration.Migration[] diff --git a/packages/core/src/database/migration/20260703090000_reset_v2_event_rename_sweep.ts b/packages/core/src/database/migration/20260703090000_reset_v2_event_rename_sweep.ts new file mode 100644 index 0000000000..20672f0734 --- /dev/null +++ b/packages/core/src/database/migration/20260703090000_reset_v2_event_rename_sweep.ts @@ -0,0 +1,17 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260703090000_reset_v2_event_rename_sweep", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`DELETE FROM \`session_input\`;`) + yield* tx.run(`DELETE FROM \`session_message\`;`) + yield* tx.run(`DELETE FROM \`event\`;`) + yield* tx.run(`DELETE FROM \`event_sequence\`;`) + // `created` column is added by the generated 20260703181610_event_created_column + // migration, which runs after this wipe (NOT NULL without default is safe on the + // emptied table). + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260703181610_event_created_column.ts b/packages/core/src/database/migration/20260703181610_event_created_column.ts new file mode 100644 index 0000000000..29d2cf9c12 --- /dev/null +++ b/packages/core/src/database/migration/20260703181610_event_created_column.ts @@ -0,0 +1,11 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260703181610_event_created_column", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`event\` ADD \`created\` integer NOT NULL;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/schema.gen.ts b/packages/core/src/database/schema.gen.ts index d8f0f1c665..17a7d12aed 100644 --- a/packages/core/src/database/schema.gen.ts +++ b/packages/core/src/database/schema.gen.ts @@ -81,6 +81,7 @@ export default { \`id\` text PRIMARY KEY, \`aggregate_id\` text NOT NULL, \`seq\` integer NOT NULL, + \`created\` integer NOT NULL, \`type\` text NOT NULL, \`data\` text NOT NULL, CONSTRAINT \`fk_event_aggregate_id_event_sequence_aggregate_id_fk\` FOREIGN KEY (\`aggregate_id\`) REFERENCES \`event_sequence\`(\`aggregate_id\`) ON DELETE CASCADE diff --git a/packages/core/src/event.ts b/packages/core/src/event.ts index dd0aa43181..587688d814 100644 --- a/packages/core/src/event.ts +++ b/packages/core/src/event.ts @@ -1,6 +1,6 @@ export * as EventV2 from "./event" -import { Cause, Context, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect" +import { Cause, Context, DateTime, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect" import { Event } from "@opencode-ai/schema/event" import type { Data, Definition, Payload } from "@opencode-ai/schema/event" import type { EventLog } from "@opencode-ai/schema/event-log" @@ -55,6 +55,7 @@ export const reserveSequence = Effect.fn("EventV2.reserveSequence")(function* ( export type SerializedEvent = { readonly id: ID readonly type: string + readonly created?: DateTime.Utc readonly seq: number readonly aggregateID: string readonly data: Record @@ -81,6 +82,7 @@ const decodeSerializedEvent = (event: SerializedEvent): Payload => { } return { id: event.id, + created: event.created ?? DateTime.makeUnsafe(0), type: definition.type, durable: envelope(event.aggregateID, event.seq, definition.durable.version), data: Schema.decodeUnknownSync(definition.data)(event.data), @@ -295,6 +297,7 @@ export const layerWith = (options?: LayerOptions) => if ( stored?.id === event.id && stored.type === versionedType(definition.type, durable.version) && + stored.created === DateTime.toEpochMillis(event.created ?? DateTime.makeUnsafe(0)) && isDeepStrictEqual(stored.data, encoded) ) { if (input.ownerID && row?.ownerID == null) { @@ -366,6 +369,7 @@ export const layerWith = (options?: LayerOptions) => id: event.id, aggregate_id: aggregateID, seq, + created: DateTime.toEpochMillis(event.created ?? DateTime.makeUnsafe(0)), type: versionedType(definition.type, durable.version), data: encoded, }, @@ -471,6 +475,7 @@ export const layerWith = (options?: LayerOptions) => definition, { id: options?.id ?? ID.create(), + created: yield* DateTime.now, ...(options?.metadata ? { metadata: options.metadata } : {}), type: definition.type, ...(location ? { location } : {}), @@ -494,6 +499,7 @@ export const layerWith = (options?: LayerOptions) => } else { const payload = { id: event.id, + created: event.created ?? DateTime.makeUnsafe(0), type: definition.type, data: Schema.decodeUnknownSync(definition.data)(event.data), } as Payload @@ -610,6 +616,7 @@ export const layerWith = (options?: LayerOptions) => return [ decodeSerializedEvent({ id: event.id, + created: DateTime.makeUnsafe(event.created), aggregateID: event.aggregate_id, seq: event.seq, type: event.type, diff --git a/packages/core/src/event/sql.ts b/packages/core/src/event/sql.ts index 38fe34f1e3..17c88cefd3 100644 --- a/packages/core/src/event/sql.ts +++ b/packages/core/src/event/sql.ts @@ -15,6 +15,7 @@ export const EventTable = sqliteTable( .notNull() .references(() => EventSequenceTable.aggregate_id, { onDelete: "cascade" }), seq: integer().notNull(), + created: integer().notNull(), type: text().notNull(), data: text({ mode: "json" }).$type>().notNull(), }, diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index acae2691c8..108d36707a 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -363,8 +363,7 @@ const layer = Layer.effect( yield* events.publish(SessionEvent.Forked, { sessionID, parentID: parent.id, - messageID: input.messageID, - timestamp: yield* DateTime.now, + from: input.messageID, }) return yield* result.get(sessionID).pipe(Effect.orDie) }), @@ -551,16 +550,13 @@ const layer = Layer.effect( Effect.gen(function* () { activeShells.add(input.sessionID) if ((yield* execution.active).has(input.sessionID)) yield* execution.awaitIdle(input.sessionID) - const messageID = SessionMessage.ID.create() const callID = Identifier.ascending() yield* events.publish( SessionEvent.Shell.Started, { sessionID: input.sessionID, - messageID, callID, command: input.command, - timestamp: yield* DateTime.now, }, { id: input.id }, ) @@ -571,7 +567,6 @@ const layer = Layer.effect( sessionID: input.sessionID, callID, output, - timestamp: yield* DateTime.now, }) }).pipe( Effect.ensuring( @@ -590,8 +585,6 @@ const layer = Layer.effect( if (!skill) return yield* new SkillNotFoundError({ skill: input.skill }) yield* events.publish(SessionEvent.Skill.Activated, { sessionID: input.sessionID, - messageID: input.id ?? SessionMessage.ID.create(), - timestamp: yield* DateTime.now, name: skill.name, text: skill.content, }) @@ -602,10 +595,8 @@ const layer = Layer.effect( }), switchAgent: Effect.fn("V2Session.switchAgent")(function* (input) { yield* result.get(input.sessionID) - yield* events.publish(SessionEvent.AgentSwitched, { + yield* events.publish(SessionEvent.AgentSelected, { sessionID: input.sessionID, - messageID: SessionMessage.ID.create(), - timestamp: yield* DateTime.now, agent: input.agent, }) }), @@ -617,10 +608,8 @@ const layer = Layer.effect( (session.model.variant ?? "default") === (input.model.variant ?? "default") ) return - yield* events.publish(SessionEvent.ModelSwitched, { + yield* events.publish(SessionEvent.ModelSelected, { sessionID: input.sessionID, - messageID: SessionMessage.ID.create(), - timestamp: yield* DateTime.now, model: input.model, }) }), @@ -628,7 +617,6 @@ const layer = Layer.effect( yield* result.get(input.sessionID) yield* events.publish(SessionEvent.Renamed, { sessionID: input.sessionID, - timestamp: yield* DateTime.now, title: input.title, }) }), @@ -676,8 +664,6 @@ const layer = Layer.effect( yield* result.get(input.sessionID) yield* events.publish(SessionEvent.Synthetic, { sessionID: input.sessionID, - messageID: SessionMessage.ID.create(), - timestamp: yield* DateTime.now, text: input.text, description: input.description, metadata: input.metadata, diff --git a/packages/core/src/session/compaction.ts b/packages/core/src/session/compaction.ts index fdb81c5045..1174b65f40 100644 --- a/packages/core/src/session/compaction.ts +++ b/packages/core/src/session/compaction.ts @@ -7,7 +7,7 @@ import { EventV2 } from "../event" import { makeLocationNode } from "../effect/app-node" import { llmClient } from "../effect/app-node-platform" import { SessionEvent } from "./event" -import { SessionMessage } from "./message" +import type { SessionMessage } from "./message" import { SessionRunnerModel } from "./runner/model" import { SessionSchema } from "./schema" import { Token } from "../util/token" @@ -206,11 +206,8 @@ const make = (dependencies: Dependencies) => { const summaryPrompt = buildPrompt({ previousSummary: input.previousSummary, context: input.context }) const summaryOutput = Math.min(output || SUMMARY_OUTPUT_TOKENS, SUMMARY_OUTPUT_TOKENS) if (Token.estimate(summaryPrompt) > context - summaryOutput) return false - const messageID = SessionMessage.ID.create() yield* dependencies.events.publish(SessionEvent.Compaction.Started, { sessionID: input.sessionID, - messageID, - timestamp: yield* DateTime.now, reason: input.reason, }) @@ -238,8 +235,6 @@ const make = (dependencies: Dependencies) => { if (!summarized || failed || !summary.trim()) return false yield* dependencies.events.publish(SessionEvent.Compaction.Ended, { sessionID: input.sessionID, - messageID, - timestamp: yield* DateTime.now, reason: input.reason, text: summary, recent: input.recent, diff --git a/packages/core/src/session/context-checkpoint.ts b/packages/core/src/session/context-checkpoint.ts index 8ea1f46513..fa3b24aedb 100644 --- a/packages/core/src/session/context-checkpoint.ts +++ b/packages/core/src/session/context-checkpoint.ts @@ -1,13 +1,12 @@ export * as SessionContextCheckpoint from "./context-checkpoint" import { eq } from "drizzle-orm" -import { DateTime, Effect, Option, Schema } from "effect" +import { Effect, Option, Schema } from "effect" import type { Database } from "../database/database" import { EventV2 } from "../event" import { SystemContext } from "../system-context/index" import { SessionEvent } from "./event" import { SessionHistory } from "./history" -import { SessionMessage } from "./message" import { SessionSchema } from "./schema" import { SessionContextCheckpointTable } from "./sql" @@ -50,7 +49,7 @@ export const prepare = Effect.fn("SessionContextCheckpoint.prepare")(function* ( yield* events.publish( SessionEvent.ContextUpdated, - { sessionID, messageID: SessionMessage.ID.create(), timestamp: yield* DateTime.now, text: result.text }, + { sessionID, text: result.text }, { commit: () => advance(db, sessionID, result.applied).pipe(Effect.orDie) }, ) return { baseline: stored.baseline, baselineSeq: stored.baseline_seq } diff --git a/packages/core/src/session/execution/local.ts b/packages/core/src/session/execution/local.ts index 60e32b7c2c..1a45537490 100644 --- a/packages/core/src/session/execution/local.ts +++ b/packages/core/src/session/execution/local.ts @@ -36,7 +36,6 @@ const layer = Layer.effect( Exit.isFailure(exit) && !Cause.hasInterrupts(exit.cause) ? Cause.squash(exit.cause) : undefined yield* events.publish(SessionEvent.ExecutionSettled, { sessionID, - timestamp: yield* DateTime.now, outcome: Exit.isSuccess(exit) ? "success" : Cause.hasInterrupts(exit.cause) ? "interrupted" : "failure", error: failure !== undefined diff --git a/packages/core/src/session/input.ts b/packages/core/src/session/input.ts index 8d89563543..1d0dfc71c3 100644 --- a/packages/core/src/session/input.ts +++ b/packages/core/src/session/input.ts @@ -50,12 +50,10 @@ export const admit = Effect.fn("SessionInput.admit")(function* ( ) { const existing = yield* find(db, input.id) if (existing !== undefined) return existing - const timestamp = yield* DateTime.now return yield* events .publish(SessionEvent.PromptAdmitted, { - messageID: input.id, + inputID: input.id, sessionID: input.sessionID, - timestamp, prompt: input.prompt, delivery: input.delivery, }) @@ -70,7 +68,7 @@ export const admit = Effect.fn("SessionInput.admit")(function* ( sessionID: input.sessionID, prompt: input.prompt, delivery: input.delivery, - timeCreated: timestamp, + timeCreated: event.created, }), ), ), @@ -115,14 +113,11 @@ export const projectAdmitted = Effect.fn("SessionInput.projectAdmitted")(functio if (!stored) return yield* Effect.die(new LifecycleConflict({ id: input.id })) }) -export const projectPrompted = Effect.fn("SessionInput.projectPrompted")(function* ( +export const projectPromptPromoted = Effect.fn("SessionInput.projectPromptPromoted")(function* ( db: DatabaseService, input: { readonly id: SessionMessage.ID readonly sessionID: SessionSchema.ID - readonly prompt: Prompt - readonly delivery: Delivery - readonly timeCreated: DateTime.Utc readonly promotedSeq: number }, ) { @@ -141,15 +136,16 @@ export const projectPrompted = Effect.fn("SessionInput.projectPrompted")(functio .pipe(Effect.orDie) if (updated) { const stored = fromRow(updated) - if (!matchesProjection(stored, input)) return yield* Effect.die(new LifecycleConflict({ id: input.id })) - return + if (stored.sessionID !== input.sessionID) return yield* Effect.die(new LifecycleConflict({ id: input.id })) + return stored } - // Every Prompted event is published from an admitted inbox row, so a missing or + // Every PromptPromoted event is published from an admitted inbox row, so a missing or // divergent row on replay is an invariant violation. const stored = yield* find(db, input.id) - if (!stored || !matchesProjection(stored, input) || stored.promotedSeq !== input.promotedSeq) + if (!stored || stored.sessionID !== input.sessionID || stored.promotedSeq !== input.promotedSeq) return yield* Effect.die(new LifecycleConflict({ id: input.id })) + return stored }) export const hasPending = Effect.fn("SessionInput.hasPending")(function* ( @@ -206,12 +202,9 @@ const publish = Effect.fn("SessionInput.publish")(function* ( for (const row of rows) { const id = SessionMessage.ID.make(row.id) yield* events - .publish(SessionEvent.Prompted, { + .publish(SessionEvent.PromptPromoted, { sessionID, - timestamp: DateTime.makeUnsafe(row.time_created), - messageID: id, - prompt: decodePrompt(row.prompt), - delivery: row.delivery, + inputID: id, }) .pipe( Effect.catchDefect((defect) => diff --git a/packages/core/src/session/instructions.ts b/packages/core/src/session/instructions.ts index 913f5c7334..a75074ae04 100644 --- a/packages/core/src/session/instructions.ts +++ b/packages/core/src/session/instructions.ts @@ -60,9 +60,9 @@ const layer = Layer.effect( const files = yield* Effect.forEach( toInject, (path) => - fs.readFileStringSafe(path).pipe( - Effect.map((content) => (content === undefined ? undefined : { path, content })), - ), + fs + .readFileStringSafe(path) + .pipe(Effect.map((content) => (content === undefined ? undefined : { path, content }))), { concurrency: "unbounded" }, ) const readable = files.filter((file): file is { path: string; content: string } => file !== undefined) @@ -74,8 +74,6 @@ const layer = Layer.effect( // metadata so it survives across Location layer restarts. yield* events.publish(SessionEvent.Synthetic, { sessionID: input.sessionID, - messageID: SessionMessage.ID.create(), - timestamp: yield* DateTime.now, text: readable.map((file) => `Instructions from: ${file.path}\n${file.content}`).join("\n\n"), description: `Loaded ${readable.map((file) => describePath(root, file.path)).join(", ")}`, metadata: { instruction: { paths: readable.map((file) => file.path) } }, diff --git a/packages/core/src/session/message-updater.ts b/packages/core/src/session/message-updater.ts index 9ee8f5f739..b07d0d1234 100644 --- a/packages/core/src/session/message-updater.ts +++ b/packages/core/src/session/message-updater.ts @@ -100,112 +100,100 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { return Effect.gen(function* () { yield* SessionEvent.All.match(event, { - "session.next.agent.switched": (event) => { + "agent.selected": (event) => { return adapter.appendMessage( - SessionMessage.AgentSwitched.make({ - id: event.data.messageID, + SessionMessage.AgentSelected.make({ + id: SessionMessage.ID.fromEvent(event.id), type: "agent-switched", metadata: event.metadata, agent: event.data.agent, - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ) }, - "session.next.model.switched": (event) => { + "model.selected": (event) => { return adapter.appendMessage( - SessionMessage.ModelSwitched.make({ - id: event.data.messageID, + SessionMessage.ModelSelected.make({ + id: SessionMessage.ID.fromEvent(event.id), type: "model-switched", metadata: event.metadata, model: event.data.model, - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ) }, - "session.next.moved": () => Effect.void, - "session.next.renamed": () => Effect.void, - "session.next.forked": () => Effect.void, - "session.next.prompted": (event) => { - return adapter.appendMessage( - SessionMessage.User.make({ - id: event.data.messageID, - type: "user", - metadata: event.metadata, - text: event.data.prompt.text, - files: event.data.prompt.files, - agents: event.data.prompt.agents, - time: { created: event.data.timestamp }, - }), - ) - }, - "session.next.prompt.admitted": () => Effect.void, - "session.next.execution.settled": () => Effect.void, - "session.next.context.updated": (event) => + "session.moved": () => Effect.void, + renamed: () => Effect.void, + forked: () => Effect.void, + "prompt.promoted": () => Effect.void, + "prompt.admitted": () => Effect.void, + "execution.settled": () => Effect.void, + "session.context.updated": (event) => adapter.appendMessage( SessionMessage.System.make({ - id: event.data.messageID, + id: SessionMessage.ID.fromEvent(event.id), type: "system", text: event.data.text, - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ), - "session.next.synthetic": (event) => { + synthetic: (event) => { return adapter.appendMessage( SessionMessage.Synthetic.make({ sessionID: event.data.sessionID, text: event.data.text, description: event.data.description, metadata: event.data.metadata, - id: event.data.messageID, + id: SessionMessage.ID.fromEvent(event.id), type: "synthetic", - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ) }, - "session.next.skill.activated": (event) => { + "skill.activated": (event) => { return adapter.appendMessage( SessionMessage.Skill.make({ - id: event.data.messageID, + id: SessionMessage.ID.fromEvent(event.id), type: "skill", name: event.data.name, text: event.data.text, - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ) }, - "session.next.shell.started": (event) => { + "shell.started": (event) => { return adapter.appendMessage( SessionMessage.Shell.make({ - id: event.data.messageID, + id: SessionMessage.ID.fromEvent(event.id), type: "shell", metadata: event.metadata, callID: event.data.callID, command: event.data.command, output: "", - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ) }, - "session.next.shell.ended": (event) => { + "shell.ended": (event) => { return Effect.gen(function* () { const currentShell = yield* adapter.getCurrentShell(event.data.callID) if (currentShell) { yield* adapter.updateShell( produce(currentShell, (draft) => { draft.output = event.data.output - draft.time.completed = event.data.timestamp + draft.time.completed = event.created }), ) } }) }, - "session.next.step.started": (event) => { + "step.started": (event) => { return Effect.gen(function* () { const currentAssistant = yield* adapter.getCurrentAssistant() if (currentAssistant) { yield* adapter.updateAssistant( produce(currentAssistant, (draft) => { - draft.time.completed = event.data.timestamp + draft.time.completed = event.created }), ) } @@ -215,16 +203,16 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { type: "assistant", agent: event.data.agent, model: event.data.model, - time: { created: event.data.timestamp }, + time: { created: event.created }, content: [], snapshot: event.data.snapshot ? { start: event.data.snapshot } : undefined, }), ) }) }, - "session.next.step.ended": (event) => { + "step.ended": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { - draft.time.completed = event.data.timestamp + draft.time.completed = event.created draft.finish = event.data.finish draft.cost = event.data.cost draft.tokens = event.data.tokens @@ -236,33 +224,33 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "session.next.step.failed": (event) => { + "step.failed": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { - draft.time.completed = event.data.timestamp + draft.time.completed = event.created draft.finish = "error" draft.error = event.data.error }) }, - "session.next.text.started": (event) => { + "text.started": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { draft.content.push( castDraft(SessionMessage.AssistantText.make({ type: "text", id: event.data.textID, text: "" })), ) }) }, - "session.next.text.delta": (event) => { + "text.delta": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestText(draft, event.data.textID) if (match) match.text += event.data.delta }) }, - "session.next.text.ended": (event) => { + "text.ended": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestText(draft, event.data.textID) if (match) match.text = event.data.text }) }, - "session.next.tool.input.started": (event) => { + "tool.input.started": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { draft.content.push( castDraft( @@ -270,26 +258,26 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { type: "tool", id: event.data.callID, name: event.data.name, - time: { created: event.data.timestamp }, + time: { created: event.created }, state: SessionMessage.ToolStatePending.make({ status: "pending", input: "" }), }), ), ) }) }, - "session.next.tool.input.delta": () => Effect.void, - "session.next.tool.input.ended": (event) => { + "tool.input.delta": () => Effect.void, + "tool.input.ended": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match && match.state.status === "pending") match.state.input = event.data.text }) }, - "session.next.tool.called": (event) => { + "tool.called": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match) { match.provider = event.data.provider - match.time.ran = event.data.timestamp + match.time.ran = event.created match.state = castDraft( SessionMessage.ToolStateRunning.make({ status: "running", @@ -301,7 +289,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "session.next.tool.progress": (event) => { + "tool.progress": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match && match.state.status === "running") { @@ -310,7 +298,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "session.next.tool.success": (event) => { + "tool.success": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match && match.state.status === "running") { @@ -319,7 +307,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { metadata: match.provider?.metadata, resultMetadata: event.data.provider.metadata, } - match.time.completed = event.data.timestamp + match.time.completed = event.created match.state = castDraft( SessionMessage.ToolStateCompleted.make({ status: "completed", @@ -333,7 +321,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "session.next.tool.failed": (event) => { + "tool.failed": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match && (match.state.status === "pending" || match.state.status === "running")) { @@ -342,7 +330,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { metadata: match.provider?.metadata, resultMetadata: event.data.provider.metadata, } - match.time.completed = event.data.timestamp + match.time.completed = event.created match.state = castDraft( SessionMessage.ToolStateError.make({ status: "error", @@ -356,7 +344,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "session.next.reasoning.started": (event) => { + "reasoning.started": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { draft.content.push( castDraft( @@ -365,47 +353,47 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { id: event.data.reasoningID, text: "", providerMetadata: event.data.providerMetadata, - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ), ) }) }, - "session.next.reasoning.delta": (event) => { + "reasoning.delta": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestReasoning(draft, event.data.reasoningID) if (match) match.text += event.data.delta }) }, - "session.next.reasoning.ended": (event) => { + "reasoning.ended": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestReasoning(draft, event.data.reasoningID) if (match) { match.text = event.data.text - match.time = { created: match.time?.created ?? event.data.timestamp, completed: event.data.timestamp } + match.time = { created: match.time?.created ?? event.created, completed: event.created } if (event.data.providerMetadata !== undefined) match.providerMetadata = event.data.providerMetadata } }) }, - "session.next.retried": () => Effect.void, - "session.next.compaction.started": () => Effect.void, - "session.next.compaction.delta": () => Effect.void, - "session.next.compaction.ended": (event) => { + retried: () => Effect.void, + "compaction.started": () => Effect.void, + "compaction.delta": () => Effect.void, + "compaction.ended": (event) => { return adapter.appendMessage( SessionMessage.Compaction.make({ - id: event.data.messageID, + id: SessionMessage.ID.fromEvent(event.id), type: "compaction", metadata: event.metadata, reason: event.data.reason, summary: event.data.text, recent: event.data.recent, - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ) }, - "session.next.revert.staged": () => Effect.void, - "session.next.revert.cleared": () => Effect.void, - "session.next.revert.committed": () => Effect.void, + "revert.staged": () => Effect.void, + "revert.cleared": () => Effect.void, + "revert.committed": () => Effect.void, }) }) } diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index 7b08733684..62ad7ec2ce 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -158,21 +158,17 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( .get() .pipe(Effect.orDie) if (!parent) return yield* Effect.die(new Error(`Fork parent session not found: ${event.data.parentID}`)) - const boundary = event.data.messageID + const boundary = event.data.from ? yield* db .select({ seq: SessionMessageTable.seq }) .from(SessionMessageTable) .where( - and( - eq(SessionMessageTable.session_id, event.data.parentID), - eq(SessionMessageTable.id, event.data.messageID), - ), + and(eq(SessionMessageTable.session_id, event.data.parentID), eq(SessionMessageTable.id, event.data.from)), ) .get() .pipe(Effect.orDie) : undefined - if (event.data.messageID && !boundary) - return yield* Effect.die(new Error(`Fork boundary message not found: ${event.data.messageID}`)) + if (event.data.from && !boundary) return yield* Effect.die(new Error(`Fork boundary message not found: ${event.data.from}`)) const copied = yield* db .select({ seq: SessionMessageTable.seq }) .from(SessionMessageTable) @@ -208,8 +204,8 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( tokens_reasoning: 0, tokens_cache_read: 0, tokens_cache_write: 0, - time_created: DateTime.toEpochMillis(event.data.timestamp), - time_updated: DateTime.toEpochMillis(event.data.timestamp), + time_created: DateTime.toEpochMillis(event.created), + time_updated: DateTime.toEpochMillis(event.created), }) .onConflictDoNothing() .returning({ sessionID: SessionTable.id }) @@ -474,9 +470,9 @@ const layer = Layer.effectDiscard( .update(SessionTable) .set({ directory: event.data.location.directory, - path: event.data.subdirectory, + path: event.data.subpath, workspace_id: event.data.location.workspaceID ? WorkspaceV2.ID.make(event.data.location.workspaceID) : null, - time_updated: DateTime.toEpochMillis(event.data.timestamp), + time_updated: DateTime.toEpochMillis(event.created), }) .where(eq(SessionTable.id, event.data.sessionID)) .run() @@ -556,19 +552,19 @@ const layer = Layer.effectDiscard( if (next) yield* applyUsage(db, sessionID, next) }), ) - yield* events.project(SessionEvent.AgentSwitched, (event) => + yield* events.project(SessionEvent.AgentSelected, (event) => db .update(SessionTable) - .set({ agent: event.data.agent, time_updated: DateTime.toEpochMillis(event.data.timestamp) }) + .set({ agent: event.data.agent, time_updated: DateTime.toEpochMillis(event.created) }) .where(eq(SessionTable.id, event.data.sessionID)) .run() .pipe(Effect.orDie, Effect.andThen(run(db, event))), ) - yield* events.project(SessionEvent.ModelSwitched, (event) => + yield* events.project(SessionEvent.ModelSelected, (event) => Effect.gen(function* () { yield* db .update(SessionTable) - .set({ model: event.data.model, time_updated: DateTime.toEpochMillis(event.data.timestamp) }) + .set({ model: event.data.model, time_updated: DateTime.toEpochMillis(event.created) }) .where(eq(SessionTable.id, event.data.sessionID)) .run() .pipe(Effect.orDie) @@ -578,25 +574,30 @@ const layer = Layer.effectDiscard( yield* events.project(SessionEvent.Renamed, (event) => db .update(SessionTable) - .set({ title: event.data.title, time_updated: DateTime.toEpochMillis(event.data.timestamp) }) + .set({ title: event.data.title, time_updated: DateTime.toEpochMillis(event.created) }) .where(eq(SessionTable.id, event.data.sessionID)) .run() .pipe(Effect.orDie), ) yield* events.project(SessionEvent.Forked, (event) => projectFork(db, event)) - yield* events.project(SessionEvent.Prompted, (event) => + yield* events.project(SessionEvent.PromptPromoted, (event) => Effect.gen(function* () { if (event.durable === undefined) return yield* Effect.die(new Error("Durable Session event is missing aggregate sequence")) - yield* SessionInput.projectPrompted(db, { - id: event.data.messageID, + const input = yield* SessionInput.projectPromptPromoted(db, { + id: event.data.inputID, sessionID: event.data.sessionID, - prompt: event.data.prompt, - delivery: event.data.delivery, - timeCreated: event.data.timestamp, promotedSeq: event.durable.seq, }) - yield* run(db, event) + yield* insertMessage(db, event, { + id: input.id, + type: "user", + metadata: event.metadata, + text: input.prompt.text, + files: input.prompt.files, + agents: input.prompt.agents, + time: { created: event.created }, + }) }), ) yield* events.project(SessionEvent.PromptAdmitted, (event) => @@ -605,11 +606,11 @@ const layer = Layer.effectDiscard( return yield* Effect.die(new Error("Durable Session event is missing aggregate sequence")) yield* SessionInput.projectAdmitted(db, { admittedSeq: event.durable.seq, - id: event.data.messageID, + id: event.data.inputID, sessionID: event.data.sessionID, prompt: event.data.prompt, delivery: event.data.delivery, - timeCreated: event.data.timestamp, + timeCreated: event.created, }) }), ) @@ -617,11 +618,11 @@ const layer = Layer.effectDiscard( yield* events.project(SessionEvent.Synthetic, (event) => run(db, event)) yield* events.project(SessionEvent.Skill.Activated, (event) => insertMessage(db, event, { - id: event.data.messageID, + id: SessionMessage.ID.fromEvent(event.id), type: "skill", name: event.data.name, text: event.data.text, - time: { created: event.data.timestamp }, + time: { created: event.created }, }), ) yield* events.project(SessionEvent.Shell.Started, (event) => run(db, event)) @@ -646,7 +647,7 @@ const layer = Layer.effectDiscard( .update(SessionTable) .set({ revert: { ...event.data.revert, files: event.data.revert.files ? [...event.data.revert.files] : undefined }, - time_updated: DateTime.toEpochMillis(event.data.timestamp), + time_updated: DateTime.toEpochMillis(event.created), }) .where(eq(SessionTable.id, event.data.sessionID)) .run() @@ -655,7 +656,7 @@ const layer = Layer.effectDiscard( yield* events.project(SessionEvent.RevertEvent.Cleared, (event) => db .update(SessionTable) - .set({ revert: null, time_updated: DateTime.toEpochMillis(event.data.timestamp) }) + .set({ revert: null, time_updated: DateTime.toEpochMillis(event.created) }) .where(eq(SessionTable.id, event.data.sessionID)) .run() .pipe(Effect.orDie, Effect.asVoid), @@ -693,7 +694,7 @@ const layer = Layer.effectDiscard( .pipe(Effect.orDie) yield* db .update(SessionTable) - .set({ revert: null, time_updated: DateTime.toEpochMillis(event.data.timestamp) }) + .set({ revert: null, time_updated: DateTime.toEpochMillis(event.created) }) .where(eq(SessionTable.id, event.data.sessionID)) .run() .pipe(Effect.orDie) diff --git a/packages/core/src/session/revert.ts b/packages/core/src/session/revert.ts index 9999d5da5a..8c0b8bbf7b 100644 --- a/packages/core/src/session/revert.ts +++ b/packages/core/src/session/revert.ts @@ -89,7 +89,6 @@ export const stage = Effect.fn("SessionRevert.stage")(function* (input: { } satisfies SessionSchema.Info["revert"] yield* events.publish(SessionEvent.RevertEvent.Staged, { sessionID: input.session.id, - timestamp: yield* DateTime.now, revert, }) return revert @@ -106,7 +105,6 @@ export const clear = Effect.fn("SessionRevert.clear")(function* (session: Sessio const events = yield* EventV2.Service yield* events.publish(SessionEvent.RevertEvent.Cleared, { sessionID: session.id, - timestamp: yield* DateTime.now, }) }) @@ -116,6 +114,5 @@ export const commit = Effect.fn("SessionRevert.commit")(function* (session: Sess yield* events.publish(SessionEvent.RevertEvent.Committed, { sessionID: session.id, messageID: session.revert.messageID, - timestamp: yield* DateTime.now, }) }) diff --git a/packages/core/src/session/runner/llm.ts b/packages/core/src/session/runner/llm.ts index f76ee10a3f..ba575b8146 100644 --- a/packages/core/src/session/runner/llm.ts +++ b/packages/core/src/session/runner/llm.ts @@ -134,7 +134,6 @@ const layer = Layer.effect( if (tool.type !== "tool" || (tool.state.status !== "pending" && tool.state.status !== "running")) continue yield* events.publish(SessionEvent.Tool.Failed, { sessionID, - timestamp: yield* DateTime.now, assistantMessageID: message.id, callID: tool.id, error: { type: "unknown", message: "Tool execution interrupted" }, @@ -297,7 +296,6 @@ const layer = Layer.effect( yield* serialized( events.publish(SessionEvent.Step.Ended, { sessionID: session.id, - timestamp: yield* DateTime.now, assistantMessageID: yield* publisher.startAssistant(), finish: settlement.finish, cost: 0, diff --git a/packages/core/src/session/runner/publish-llm-event.ts b/packages/core/src/session/runner/publish-llm-event.ts index 04c6437ef4..4b7b6fb92c 100644 --- a/packages/core/src/session/runner/publish-llm-event.ts +++ b/packages/core/src/session/runner/publish-llm-event.ts @@ -78,7 +78,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* events.publish(SessionEvent.Step.Started, { ...input, assistantMessageID, - timestamp: yield* timestamp, snapshot: input.snapshot, }) return assistantMessageID @@ -123,7 +122,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* events.publish(SessionEvent.Text.Ended, { sessionID: input.sessionID, assistantMessageID: yield* currentAssistantMessageID(), - timestamp: yield* timestamp, textID, text: value, }) @@ -134,7 +132,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* events.publish(SessionEvent.Reasoning.Ended, { sessionID: input.sessionID, assistantMessageID: yield* currentAssistantMessageID(), - timestamp: yield* timestamp, reasoningID, text: value, providerMetadata, @@ -147,7 +144,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) if (!tool) return yield* Effect.die(new Error(`Tool input end before start: ${callID}`)) yield* events.publish(SessionEvent.Tool.Input.Ended, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID: tool.assistantMessageID, callID, text: value, @@ -176,7 +172,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* toolInput.start(event.id) yield* events.publish(SessionEvent.Tool.Input.Started, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID, callID: event.id, name: event.name, @@ -204,7 +199,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) assistantFailed = true yield* events.publish(SessionEvent.Step.Failed, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID, error: { type: "unknown", message }, }) @@ -219,7 +213,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) tool.settled = true yield* events.publish(SessionEvent.Tool.Failed, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID: tool.assistantMessageID, callID, error: { type: "unknown", message }, @@ -248,7 +241,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* events.publish(SessionEvent.Text.Started, { sessionID: input.sessionID, assistantMessageID: yield* startAssistant(), - timestamp: yield* timestamp, textID: event.id, }) return @@ -257,7 +249,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* events.publish(SessionEvent.Text.Delta, { sessionID: input.sessionID, assistantMessageID: yield* currentAssistantMessageID(), - timestamp: yield* timestamp, textID: event.id, delta: event.text, }) @@ -270,7 +261,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* events.publish(SessionEvent.Reasoning.Started, { sessionID: input.sessionID, assistantMessageID: yield* startAssistant(), - timestamp: yield* timestamp, reasoningID: event.id, providerMetadata: event.providerMetadata, }) @@ -280,7 +270,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* events.publish(SessionEvent.Reasoning.Delta, { sessionID: input.sessionID, assistantMessageID: yield* currentAssistantMessageID(), - timestamp: yield* timestamp, reasoningID: event.id, delta: event.text, }) @@ -300,7 +289,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) yield* toolInput.append(event.id, event.text) yield* events.publish(SessionEvent.Tool.Input.Delta, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID: tool.assistantMessageID, callID: event.id, delta: event.text, @@ -322,7 +310,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) tool.providerMetadata = event.providerMetadata yield* events.publish(SessionEvent.Tool.Called, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID: tool.assistantMessageID, callID: event.id, tool: event.name, @@ -352,7 +339,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) if ("error" in result) { yield* events.publish(SessionEvent.Tool.Failed, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID: tool.assistantMessageID, callID: event.id, error: result.error, @@ -363,7 +349,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) } yield* events.publish(SessionEvent.Tool.Success, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID: tool.assistantMessageID, callID: event.id, ...result, @@ -382,7 +367,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) tool.settled = true yield* events.publish(SessionEvent.Tool.Failed, { sessionID: input.sessionID, - timestamp: yield* timestamp, assistantMessageID: tool.assistantMessageID, callID: event.id, error: { type: "unknown", message: event.message }, diff --git a/packages/core/src/session/title.ts b/packages/core/src/session/title.ts index abed5ce33c..8e7b5857b7 100644 --- a/packages/core/src/session/title.ts +++ b/packages/core/src/session/title.ts @@ -42,9 +42,10 @@ const make = (dependencies: Dependencies) => { if (!firstUser) return const agent = yield* dependencies.agents.get(AgentV2.ID.make("title")) if (!agent) return - const resolved = yield* (agent.model - ? dependencies.models.resolve({ ...session, model: agent.model }) - : dependencies.models.resolve(session) + const resolved = yield* ( + agent.model + ? dependencies.models.resolve({ ...session, model: agent.model }) + : dependencies.models.resolve(session) ).pipe(Effect.catch(() => Effect.succeed(undefined))) if (!resolved) return const chunks: string[] = [] @@ -76,7 +77,6 @@ const make = (dependencies: Dependencies) => { if (!title) return yield* dependencies.events.publish(SessionEvent.Renamed, { sessionID: session.id, - timestamp: yield* DateTime.now, title: truncate(title), }) }) diff --git a/packages/core/test/database-migration.test.ts b/packages/core/test/database-migration.test.ts index b381cc7418..b36de1abac 100644 --- a/packages/core/test/database-migration.test.ts +++ b/packages/core/test/database-migration.test.ts @@ -255,7 +255,7 @@ describe("DatabaseMigration", () => { ) yield* db.run(sql`INSERT INTO event_sequence (aggregate_id, seq) VALUES ('session', 9)`) yield* db.run( - sql`INSERT INTO event (id, aggregate_id, seq, type, data) VALUES ('event', 'session', 9, 'session.updated.1', '{}')`, + sql`INSERT INTO event (id, aggregate_id, seq, type, data, created) VALUES ('event', 'session', 9, 'session.updated.1', '{}', 1)`, ) yield* db.run( sql`INSERT INTO session_input (id, session_id, prompt, delivery, admitted_seq, time_created) VALUES ('input', 'session', '{}', 'steer', 9, 1)`, diff --git a/packages/core/test/event.test.ts b/packages/core/test/event.test.ts index a9220df422..65c370f1eb 100644 --- a/packages/core/test/event.test.ts +++ b/packages/core/test/event.test.ts @@ -554,6 +554,7 @@ describe("EventV2", () => { yield* events.replay({ id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -573,6 +574,7 @@ describe("EventV2", () => { yield* events.replay({ id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -609,6 +611,7 @@ describe("EventV2", () => { const exit = yield* events .replay({ id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 1, aggregateID: envelopeAggregateID, @@ -642,6 +645,7 @@ describe("EventV2", () => { yield* events.replay({ id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -650,6 +654,7 @@ describe("EventV2", () => { const exit = yield* events .replay({ id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 5, aggregateID, @@ -674,13 +679,14 @@ describe("EventV2", () => { yield* events.replay({ id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(SessionEvent.ContextUpdated.type, 1), seq: 0, aggregateID, - data: { sessionID: aggregateID, messageID: "msg_context", timestamp: 0, text: "context" }, + data: { sessionID: aggregateID, text: "context" }, }) - expect(received[0]?.data.timestamp).toEqual(DateTime.makeUnsafe(0)) + expect(received[0]?.created).toEqual(DateTime.makeUnsafe(0)) }), ) @@ -690,6 +696,7 @@ describe("EventV2", () => { const exit = yield* events .replay({ id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: "unknown.event.1", seq: 0, aggregateID: EventV2.ID.create(), @@ -708,6 +715,7 @@ describe("EventV2", () => { const source = yield* events.replayAll([ { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -715,6 +723,7 @@ describe("EventV2", () => { }, { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 1, aggregateID, @@ -735,6 +744,7 @@ describe("EventV2", () => { const one = yield* events.replayAll([ { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -742,6 +752,7 @@ describe("EventV2", () => { }, { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 1, aggregateID, @@ -751,6 +762,7 @@ describe("EventV2", () => { const two = yield* events.replayAll([ { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 2, aggregateID, @@ -758,6 +770,7 @@ describe("EventV2", () => { }, { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 3, aggregateID, @@ -793,6 +806,7 @@ describe("EventV2", () => { yield* events.replay( { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 1, aggregateID, @@ -812,6 +826,7 @@ describe("EventV2", () => { const id = EventV2.ID.create() const replayed = { id, + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -833,6 +848,7 @@ describe("EventV2", () => { const published = yield* events.publish(DurableMessage, durableData(aggregateID, "owned")) const replayed = { id: published.id, + created: published.created, type: EventV2.versionedType(DurableMessage.type, 1), seq: published.durable!.seq, aggregateID, @@ -867,6 +883,7 @@ describe("EventV2", () => { yield* events.replay( { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -895,6 +912,7 @@ describe("EventV2", () => { yield* events.replay( { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 1, aggregateID, @@ -905,6 +923,7 @@ describe("EventV2", () => { yield* events.replay( { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 2, aggregateID, @@ -937,6 +956,7 @@ describe("EventV2", () => { yield* events.replay( { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -949,6 +969,7 @@ describe("EventV2", () => { .replay( { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 1, aggregateID, @@ -970,6 +991,7 @@ describe("EventV2", () => { yield* events.listen((event) => Effect.sync(() => received.push(event))) const replayed = { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -990,6 +1012,7 @@ describe("EventV2", () => { const aggregateID = Session.ID.create() const replayed = { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -1014,6 +1037,7 @@ describe("EventV2", () => { const id = EventV2.ID.create() yield* events.replay({ id, + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -1023,6 +1047,7 @@ describe("EventV2", () => { const exit = yield* events .replay({ id, + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 1, aggregateID, @@ -1045,6 +1070,7 @@ describe("EventV2", () => { yield* events.replay( { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, @@ -1055,6 +1081,7 @@ describe("EventV2", () => { yield* events.replay( { id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 1, aggregateID, @@ -1116,6 +1143,7 @@ describe("EventV2", () => { yield* events.replay({ id: EventV2.ID.create(), + created: DateTime.makeUnsafe(0), type: EventV2.versionedType(DurableMessage.type, 1), seq: 0, aggregateID, diff --git a/packages/core/test/session-compact.test.ts b/packages/core/test/session-compact.test.ts index cee32ade04..4a9a520d59 100644 --- a/packages/core/test/session-compact.test.ts +++ b/packages/core/test/session-compact.test.ts @@ -85,17 +85,13 @@ describe("SessionV2.compact", () => { const prompt = Prompt.make({ text: "Please compact this session history." }) yield* events.publish(SessionEvent.PromptAdmitted, { sessionID: created.id, - messageID, - timestamp: DateTime.makeUnsafe(0), + inputID: messageID, prompt, delivery: "steer", }) - yield* events.publish(SessionEvent.Prompted, { + yield* events.publish(SessionEvent.PromptPromoted, { sessionID: created.id, - messageID, - timestamp: DateTime.makeUnsafe(0), - prompt, - delivery: "steer", + inputID: messageID, }) yield* session.compact({ sessionID: created.id }) diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index b22c65ec97..0100ca4ae9 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -197,8 +197,6 @@ describe("SessionV2.create", () => { yield* SessionInput.promoteSteers(db, events, parent.id) yield* events.publish(SessionEvent.Synthetic, { sessionID: parent.id, - messageID: SessionMessage.ID.create(), - timestamp: yield* DateTime.now, text: "parent note", }) @@ -215,7 +213,7 @@ describe("SessionV2.create", () => { expect(forkContext.map((message) => message.id)).not.toEqual(parentContext.map((message) => message.id)) expect(history).toHaveLength(1) expect(history[0]).toMatchObject({ - type: "session.next.forked", + type: "forked", durable: { seq: 0 }, data: { sessionID: forked.id, parentID: parent.id }, }) @@ -267,7 +265,7 @@ describe("SessionV2.create", () => { const history = Array.from(yield* Stream.runCollect(logEvents(session, forked.id))) expect(context).toMatchObject([{ text: "First" }]) expect(context[0]?.id).not.toBe(first.id) - expect(history[0]).toMatchObject({ data: { messageID: second.id } }) + expect(history[0]).toMatchObject({ data: { from: second.id } }) }), ) @@ -380,8 +378,8 @@ describe("SessionV2.create", () => { expect( Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(2), Stream.runCollect)), ).toMatchObject([ - { durable: { seq: 1 }, type: "session.next.prompt.admitted", data: { prompt: { text: "Hello" } } }, - { durable: { seq: 2 }, type: "session.next.prompted" }, + { durable: { seq: 1 }, type: "prompt.admitted", data: { prompt: { text: "Hello" } } }, + { durable: { seq: 2 }, type: "prompt.promoted" }, ]) }), ) @@ -406,6 +404,7 @@ describe("SessionV2.create", () => { .all() .pipe(Effect.orDie)).map((event) => ({ id: event.id, + created: DateTime.makeUnsafe(event.created), aggregateID: event.aggregate_id, seq: event.seq, type: event.type, @@ -466,7 +465,7 @@ describe("SessionV2.create", () => { ).toEqual([ [0, EventV2.versionedType(SessionV1.Event.Created.type, 1)], [1, EventV2.versionedType(SessionEvent.PromptAdmitted.type, 1)], - [2, EventV2.versionedType(SessionEvent.Prompted.type, 1)], + [2, EventV2.versionedType(SessionEvent.PromptPromoted.type, 1)], ]) }).pipe(Effect.provide(Layer.fresh(targetLayer))) }), @@ -530,7 +529,7 @@ describe("SessionV2.create", () => { expect(yield* session.get(created.id)).toMatchObject({ agent: "plan" }) expect( Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)), - ).toMatchObject([{ type: "session.next.agent.switched", data: { agent: "plan" } }]) + ).toMatchObject([{ type: "agent.selected", data: { agent: "plan" } }]) }), ) @@ -563,7 +562,7 @@ describe("SessionV2.create", () => { expect(yield* session.get(created.id)).toMatchObject({ model }) expect( Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)), - ).toMatchObject([{ type: "session.next.model.switched", data: { model } }]) + ).toMatchObject([{ type: "model.selected", data: { model } }]) }), ) diff --git a/packages/core/test/session-instructions.test.ts b/packages/core/test/session-instructions.test.ts index e87fce7234..daf0308b6f 100644 --- a/packages/core/test/session-instructions.test.ts +++ b/packages/core/test/session-instructions.test.ts @@ -133,8 +133,6 @@ const seedSynthetic = (sessionID: SessionV2.ID, paths: string[]) => const events = yield* EventV2.Service yield* events.publish(SessionEvent.Synthetic, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: yield* DateTime.now, text: `Instructions from: ${paths[0]}\nprior`, description: `Loaded ${paths[0]}`, metadata: { instruction: { paths } }, diff --git a/packages/core/test/session-log.test.ts b/packages/core/test/session-log.test.ts index 3b9229589c..8c49b94582 100644 --- a/packages/core/test/session-log.test.ts +++ b/packages/core/test/session-log.test.ts @@ -47,7 +47,7 @@ describe("SessionV2.log", () => { // Session creation commits a non-public durable event, so the marker's // seq covers more of the aggregate than the public events emitted. - expect(items.map((item) => item.type)).toEqual(["session.next.renamed", "log.synced"]) + expect(items.map((item) => item.type)).toEqual(["renamed", "log.synced"]) expect(items.at(-1)).toEqual({ type: "log.synced", aggregateID: created.id, seq: watermark }) }), ) @@ -64,7 +64,7 @@ describe("SessionV2.log", () => { yield* session.rename({ sessionID: created.id, title: "renamed live" }) const items = Array.from(yield* Fiber.join(fiber)) - expect(items.map((item) => item.type)).toEqual(["log.synced", "session.next.renamed"]) + expect(items.map((item) => item.type)).toEqual(["log.synced", "renamed"]) }), ) diff --git a/packages/core/test/session-projector.test.ts b/packages/core/test/session-projector.test.ts index 4191a58715..c0d172088e 100644 --- a/packages/core/test/session-projector.test.ts +++ b/packages/core/test/session-projector.test.ts @@ -79,7 +79,6 @@ describe("SessionProjector", () => { const events = yield* EventV2.Service yield* events.publish(SessionEvent.RevertEvent.Staged, { sessionID, - timestamp: DateTime.makeUnsafe(1), revert: { messageID: boundary, snapshot: Snapshot.ID.make("tree"), diff: "patch", files: [] }, }) expect((yield* db.select({ revert: SessionTable.revert }).from(SessionTable).get())?.revert).toMatchObject({ @@ -87,17 +86,15 @@ describe("SessionProjector", () => { snapshot: "tree", files: [], }) - yield* events.publish(SessionEvent.RevertEvent.Cleared, { sessionID, timestamp: DateTime.makeUnsafe(2) }) + yield* events.publish(SessionEvent.RevertEvent.Cleared, { sessionID }) expect((yield* db.select({ revert: SessionTable.revert }).from(SessionTable).get())?.revert).toBeNull() yield* events.publish(SessionEvent.RevertEvent.Staged, { sessionID, - timestamp: DateTime.makeUnsafe(3), revert: { messageID: boundary, files: [] }, }) yield* events.publish(SessionEvent.RevertEvent.Committed, { sessionID, messageID: boundary, - timestamp: DateTime.makeUnsafe(4), }) expect( (yield* db.select({ id: SessionMessageTable.id }).from(SessionMessageTable).all()).map((row) => row.id), @@ -131,37 +128,29 @@ describe("SessionProjector", () => { yield* events.publish(SessionEvent.PromptAdmitted, { sessionID, - messageID: SessionMessage.ID.make("msg_first"), - timestamp: created, + inputID: SessionMessage.ID.make("msg_first"), prompt: Prompt.make({ text: "first" }), delivery: "steer", }) yield* events.publish( - SessionEvent.Prompted, + SessionEvent.PromptPromoted, { sessionID, - messageID: SessionMessage.ID.make("msg_first"), - timestamp: created, - prompt: Prompt.make({ text: "first" }), - delivery: "steer", + inputID: SessionMessage.ID.make("msg_first"), }, { id: EventV2.ID.make("evt_z") }, ) yield* events.publish(SessionEvent.PromptAdmitted, { sessionID, - messageID: SessionMessage.ID.make("msg_second"), - timestamp: created, + inputID: SessionMessage.ID.make("msg_second"), prompt: Prompt.make({ text: "second" }), delivery: "steer", }) yield* events.publish( - SessionEvent.Prompted, + SessionEvent.PromptPromoted, { sessionID, - messageID: SessionMessage.ID.make("msg_second"), - timestamp: created, - prompt: Prompt.make({ text: "second" }), - delivery: "steer", + inputID: SessionMessage.ID.make("msg_second"), }, { id: EventV2.ID.make("evt_a") }, ) @@ -190,7 +179,7 @@ describe("SessionProjector", () => { }).pipe(Effect.provide(sessionsLayer)), ) - it.effect("marks an inbox row promoted with the Prompted event sequence", () => + it.effect("marks an inbox row promoted with the PromptPromoted event sequence", () => Effect.gen(function* () { const { db } = yield* Database.Service yield* db @@ -220,12 +209,9 @@ describe("SessionProjector", () => { }) if (!admitted) return yield* Effect.die("Prompt admission failed") - const event = yield* events.publish(SessionEvent.Prompted, { + const event = yield* events.publish(SessionEvent.PromptPromoted, { sessionID, - timestamp: admitted.timeCreated, - messageID: id, - prompt: Prompt.make({ text: "promote me" }), - delivery: "steer", + inputID: id, }) expect( @@ -256,49 +242,36 @@ describe("SessionProjector", () => { .pipe(Effect.orDie) const events = yield* EventV2.Service - yield* events.publish(SessionEvent.AgentSwitched, { + yield* events.publish(SessionEvent.AgentSelected, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: created, agent: "build", }) - yield* events.publish(SessionEvent.ModelSwitched, { + yield* events.publish(SessionEvent.ModelSelected, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: created, model, }) yield* events.publish(SessionEvent.Synthetic, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: created, text: "synthetic context", metadata: { source: "projector-test" }, }) yield* events.publish(SessionEvent.Shell.Started, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: created, callID: "shell-1", command: "pwd", }) yield* events.publish(SessionEvent.Shell.Ended, { sessionID, - timestamp: DateTime.makeUnsafe(1), callID: "shell-1", output: "/project", }) const compactionID = SessionMessage.ID.create() yield* events.publish(SessionEvent.Compaction.Started, { sessionID, - messageID: compactionID, - timestamp: created, reason: "manual", }) yield* events.publish(SessionEvent.Compaction.Delta, { sessionID, - messageID: compactionID, - timestamp: created, text: "partial", }) expect( @@ -319,8 +292,6 @@ describe("SessionProjector", () => { ).toEqual([]) yield* events.publish(SessionEvent.Compaction.Ended, { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(1), reason: "manual", text: "summary", recent: "recent context", @@ -350,7 +321,7 @@ describe("SessionProjector", () => { }) expect(messages.find((message) => message.type === "shell")).toMatchObject({ output: "/project", - time: { completed: DateTime.makeUnsafe(1) }, + time: { completed: DateTime.makeUnsafe(0) }, }) expect(messages.find((message) => message.type === "compaction")).toMatchObject({ summary: "summary", @@ -388,13 +359,20 @@ describe("SessionProjector", () => { .pipe(Effect.orDie) const events = yield* EventV2.Service const id = SessionMessage.ID.make("msg_creator_collision") + const { + id: _, + type, + ...data + } = encodeMessage({ id, sessionID, type: "synthetic", text: "existing", time: { created } }) + yield* db + .insert(SessionMessageTable) + .values({ id, session_id: sessionID, type, seq: 0, time_created: 0, data }) + .run() - yield* events.publish(SessionEvent.Synthetic, { sessionID, messageID: id, timestamp: created, text: "keep me" }) const exit = yield* events .publish(SessionEvent.Step.Started, { sessionID, assistantMessageID: id, - timestamp: created, agent: "build", model, }) @@ -464,7 +442,6 @@ describe("SessionProjector", () => { const service = yield* EventV2.Service yield* service.publish(SessionEvent.Step.Ended, { sessionID, - timestamp: DateTime.makeUnsafe(1), assistantMessageID: SessionMessage.ID.make("msg_assistant_2"), finish: "stop", cost: 0, @@ -485,7 +462,7 @@ describe("SessionProjector", () => { expect(messages[1]).toMatchObject({ type: "assistant", finish: "stop", - time: { completed: DateTime.makeUnsafe(1) }, + time: { completed: DateTime.makeUnsafe(0) }, }) }), ) @@ -526,7 +503,6 @@ describe("SessionProjector", () => { yield* service.publish(SessionEvent.Text.Started, { sessionID, assistantMessageID: SessionMessage.ID.make("msg_assistant_completed"), - timestamp: DateTime.makeUnsafe(3), textID: "text-stale", }) diff --git a/packages/core/test/session-prompt.test.ts b/packages/core/test/session-prompt.test.ts index 58e26b7b5c..58a613a324 100644 --- a/packages/core/test/session-prompt.test.ts +++ b/packages/core/test/session-prompt.test.ts @@ -201,7 +201,6 @@ describe("SessionV2.prompt", () => { yield* db.insert(SessionMessageTable).values(assistantRow(stale, 100)).run().pipe(Effect.orDie) yield* events.publish(SessionEvent.RevertEvent.Staged, { sessionID, - timestamp: yield* DateTime.now, revert: { messageID: boundary.id, files: [] }, }) expect((yield* session.get(sessionID)).revert?.messageID).toBe(boundary.id) @@ -257,16 +256,16 @@ describe("SessionV2.prompt", () => { const streamed = Array.from(yield* Fiber.join(fiber)) expect(streamed.map((event): [number | undefined, string] => [event.durable?.seq, event.type])).toEqual([ - [0, "session.next.prompt.admitted"], - [1, "session.next.prompt.admitted"], - [2, "session.next.prompted"], - [3, "session.next.prompted"], + [0, "prompt.admitted"], + [1, "prompt.admitted"], + [2, "prompt.promoted"], + [3, "prompt.promoted"], ]) expect( Array.from( yield* publicEvents({ sessionID, after: streamed[0].durable?.seq }).pipe(Stream.take(1), Stream.runCollect), ).map((event): [number | undefined, string] => [event.durable?.seq, event.type]), - ).toEqual([[1, "session.next.prompt.admitted"]]) + ).toEqual([[1, "prompt.admitted"]]) }), ) @@ -429,7 +428,7 @@ describe("SessionV2.prompt", () => { { concurrency: "unbounded" }, ) - expect(yield* eventCount(EventV2.versionedType(SessionEvent.Prompted.type, 1))).toBe(1) + expect(yield* eventCount(EventV2.versionedType(SessionEvent.PromptPromoted.type, 1))).toBe(1) expect(yield* admitted(messageID)).toMatchObject({ promotedSeq: 1 }) expect(yield* session.messages({ sessionID })).toMatchObject([ { id: messageID, type: "user", text: "Promote once" }, @@ -467,6 +466,7 @@ describe("SessionV2.prompt", () => { yield* events.replayAll( recorded.map((event) => ({ id: event.id, + created: DateTime.makeUnsafe(event.created), aggregateID: event.aggregate_id, seq: event.seq, type: event.type, @@ -514,13 +514,23 @@ describe("SessionV2.prompt", () => { Effect.gen(function* () { yield* setup const session = yield* SessionV2.Service - const events = yield* EventV2.Service - yield* events.publish(SessionEvent.Synthetic, { + const { db } = yield* Database.Service + const { + id: _, + type, + ...data + } = encodeMessage({ + id: messageID, sessionID, - messageID, - timestamp: yield* DateTime.now, + type: "synthetic", text: "Existing history", + time: { created: DateTime.makeUnsafe(0) }, }) + yield* db + .insert(SessionMessageTable) + .values({ id: messageID, session_id: sessionID, type, seq: 0, time_created: 0, data }) + .run() + .pipe(Effect.orDie) const failure = yield* session .prompt({ id: messageID, sessionID, prompt: Prompt.make({ text: "Conflicting prompt" }), resume: false }) diff --git a/packages/core/test/session-runner-message.test.ts b/packages/core/test/session-runner-message.test.ts index 5798b665a8..840a4e424c 100644 --- a/packages/core/test/session-runner-message.test.ts +++ b/packages/core/test/session-runner-message.test.ts @@ -51,13 +51,13 @@ describe("toLLMMessages", () => { const file = FileAttachment.make({ uri: "data:image/png;base64,aGVsbG8=", mime: "image/png", name: "hello.png" }) const messages = toLLMMessages( [ - SessionMessage.AgentSwitched.make({ + SessionMessage.AgentSelected.make({ id: id("agent"), type: "agent-switched", agent: "build", time: { created }, }), - SessionMessage.ModelSwitched.make({ + SessionMessage.ModelSelected.make({ id: id("model"), type: "model-switched", model: { id: ModelV2.ID.make("model"), providerID: ProviderV2.ID.make("provider") }, diff --git a/packages/core/test/session-runner-recorded.test.ts b/packages/core/test/session-runner-recorded.test.ts index 0ebe7a6f9e..2768be820a 100644 --- a/packages/core/test/session-runner-recorded.test.ts +++ b/packages/core/test/session-runner-recorded.test.ts @@ -193,12 +193,12 @@ describe("SessionRunnerLLM recorded", () => { .orderBy(EventTable.seq) .all()).map((event) => event.type), ).toEqual([ - "session.next.prompt.admitted.1", - "session.next.prompted.1", - "session.next.step.started.1", - "session.next.text.started.1", - "session.next.text.ended.1", - "session.next.step.ended.2", + "prompt.admitted.1", + "prompt.promoted.1", + "step.started.1", + "text.started.1", + "text.ended.1", + "step.ended.1", ]) }), ) diff --git a/packages/core/test/session-runner-tool-events.test.ts b/packages/core/test/session-runner-tool-events.test.ts index 048766e439..5c8d7e07f4 100644 --- a/packages/core/test/session-runner-tool-events.test.ts +++ b/packages/core/test/session-runner-tool-events.test.ts @@ -76,7 +76,7 @@ test("local tool success serializes media base64 once and reconstructs from stru await Effect.runPromise(publisher.publish(call)) await Effect.runPromise(publisher.publish(result)) - const success = published.find((event) => event.type === "session.next.tool.success.1") + const success = published.find((event) => event.type === "tool.success.1") expect(success).toBeDefined() const serialized = JSON.stringify(success) expect(serialized.split(base64)).toHaveLength(2) @@ -94,7 +94,7 @@ test("provider-executed success retains its compatibility result", async () => { const { published, publisher } = capture() await Effect.runPromise(publisher.publish(LLMEvent.toolCall({ ...call, providerExecuted: true }))) await Effect.runPromise(publisher.publish(LLMEvent.toolResult({ ...result, providerExecuted: true }))) - const success = published.find((event) => event.type === "session.next.tool.success.1") + const success = published.find((event) => event.type === "tool.success.1") expect(success?.data).toHaveProperty("result") }) @@ -110,14 +110,13 @@ test("binary failure emits no success event", async () => { }), ), ) - expect(published.some((event) => event.type === "session.next.tool.success.1")).toBe(false) - expect(published.some((event) => event.type === "session.next.tool.failed.1")).toBe(true) + expect(published.some((event) => event.type === "tool.success.1")).toBe(false) + expect(published.some((event) => event.type === "tool.failed.1")).toBe(true) }) test("old success event data containing result still decodes", () => { const decoded = Schema.decodeUnknownSync(SessionEvent.Tool.Success.data)({ sessionID, - timestamp: Date.now(), assistantMessageID: SessionMessage.ID.create(), callID: "call-old", structured: { type: "media", mime: "image/png" }, @@ -133,6 +132,6 @@ test("step finish records settlement without publishing step ended", async () => await Effect.runPromise(publisher.publish(LLMEvent.stepStart({ index: 0 }))) await Effect.runPromise(publisher.publish(LLMEvent.stepFinish({ index: 0, reason: "stop" }))) - expect(published.some((event) => event.type === "session.next.step.ended.2")).toBe(false) + expect(published.some((event) => event.type === "step.ended.2")).toBe(false) expect(publisher.stepSettlement()).toMatchObject({ finish: "stop" }) }) diff --git a/packages/core/test/session-runner.test.ts b/packages/core/test/session-runner.test.ts index 4c9446394c..ca8ec42775 100644 --- a/packages/core/test/session-runner.test.ts +++ b/packages/core/test/session-runner.test.ts @@ -423,6 +423,7 @@ const replaySessionProjection = (id: SessionV2.ID) => yield* events.replayAll( recorded.map((event) => ({ id: event.id, + created: DateTime.makeUnsafe(event.created), aggregateID: event.aggregate_id, seq: event.seq, type: event.type, @@ -740,7 +741,6 @@ describe("SessionRunnerLLM", () => { yield* events.publish(SessionEvent.Moved, { sessionID, - timestamp: DateTime.makeUnsafe(1), location: Location.Ref.make({ directory: AbsolutePath.make("/moved") }), }) expect( @@ -848,7 +848,7 @@ describe("SessionRunnerLLM", () => { yield* db .select({ id: EventTable.id }) .from(EventTable) - .where(eq(EventTable.type, "session.next.context.updated.1")) + .where(eq(EventTable.type, "session.context.updated.1")) .all() .pipe(Effect.orDie), ).toHaveLength(1) @@ -1010,10 +1010,8 @@ describe("SessionRunnerLLM", () => { response = [] yield* session.resume(sessionID) skillBaselines.set(AgentV2.ID.make("reviewer"), "Reviewer skills") - yield* events.publish(SessionEvent.AgentSwitched, { + yield* events.publish(SessionEvent.AgentSelected, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: DateTime.makeUnsafe(1), agent: "reviewer", }) yield* session.prompt({ sessionID, prompt: Prompt.make({ text: "Second" }), resume: false }) @@ -1039,10 +1037,8 @@ describe("SessionRunnerLLM", () => { if (switched) return Effect.void switched = true return events - .publish(SessionEvent.AgentSwitched, { + .publish(SessionEvent.AgentSelected, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: DateTime.makeUnsafe(1), agent: "reviewer", }) .pipe(Effect.asVoid) @@ -1069,10 +1065,8 @@ describe("SessionRunnerLLM", () => { if (switched) return Effect.void switched = true return events - .publish(SessionEvent.ModelSwitched, { + .publish(SessionEvent.ModelSelected, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: DateTime.makeUnsafe(1), model: { id: ModelV2.ID.make("replacement"), providerID: ProviderV2.ID.make("fake") }, }) .pipe(Effect.asVoid) @@ -1175,10 +1169,8 @@ describe("SessionRunnerLLM", () => { systemBaseline = "Changed context" yield* session.prompt({ sessionID, prompt: Prompt.make({ text: "Second" }), resume: false }) yield* session.resume(sessionID) - yield* events.publish(SessionEvent.ModelSwitched, { + yield* events.publish(SessionEvent.ModelSelected, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: DateTime.makeUnsafe(1), model: { id: ModelV2.ID.make("replacement"), providerID: ProviderV2.ID.make("fake") }, }) systemBaseline = "Replacement context" @@ -1217,10 +1209,8 @@ describe("SessionRunnerLLM", () => { requests.length = 0 response = [] yield* session.resume(sessionID) - yield* events.publish(SessionEvent.ModelSwitched, { + yield* events.publish(SessionEvent.ModelSelected, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: DateTime.makeUnsafe(1), model: { id: ModelV2.ID.make("replacement"), providerID: ProviderV2.ID.make("fake") }, }) systemUnavailable = true @@ -1252,14 +1242,10 @@ describe("SessionRunnerLLM", () => { const compactionID = SessionMessage.ID.create() yield* events.publish(SessionEvent.Compaction.Started, { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(1), reason: "manual", }) yield* events.publish(SessionEvent.Compaction.Ended, { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(2), reason: "manual", text: "summary", recent: "", @@ -1482,14 +1468,10 @@ describe("SessionRunnerLLM", () => { const compactionID = SessionMessage.ID.create() yield* events.publish(SessionEvent.Compaction.Started, { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(1), reason: "manual", }) yield* events.publish(SessionEvent.Compaction.Ended, { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(2), reason: "manual", text: "summary", recent: "", @@ -1686,10 +1668,8 @@ describe("SessionRunnerLLM", () => { toolExecutionsReady = 1 const run = yield* Effect.forkChild(session.resume(sessionID)) yield* Deferred.await(toolExecutionsStarted) - yield* events.publish(SessionEvent.ModelSwitched, { + yield* events.publish(SessionEvent.ModelSelected, { sessionID, - messageID: SessionMessage.ID.create(), - timestamp: DateTime.makeUnsafe(1), model: { id: ModelV2.ID.make("replacement"), providerID: ProviderV2.ID.make("fake") }, }) systemBaseline = "Replacement context" @@ -2403,27 +2383,23 @@ describe("SessionRunnerLLM", () => { yield* events.publish(SessionEvent.Step.Started, { sessionID, assistantMessageID, - timestamp: yield* DateTime.now, agent: "build", model: { id: ModelV2.ID.make("fake-model"), providerID: ProviderV2.ID.make("fake") }, }) yield* events.publish(SessionEvent.Tool.Input.Started, { sessionID, - timestamp: yield* DateTime.now, assistantMessageID, callID: "call-interrupted", name: "echo", }) yield* events.publish(SessionEvent.Tool.Input.Ended, { sessionID, - timestamp: yield* DateTime.now, assistantMessageID, callID: "call-interrupted", text: '{"text":"stale"}', }) yield* events.publish(SessionEvent.Tool.Called, { sessionID, - timestamp: yield* DateTime.now, assistantMessageID, callID: "call-interrupted", tool: "echo", @@ -2467,27 +2443,23 @@ describe("SessionRunnerLLM", () => { yield* events.publish(SessionEvent.Step.Started, { sessionID, assistantMessageID, - timestamp: yield* DateTime.now, agent: "build", model: { id: ModelV2.ID.make("fake-model"), providerID: ProviderV2.ID.make("fake") }, }) yield* events.publish(SessionEvent.Tool.Input.Started, { sessionID, - timestamp: yield* DateTime.now, assistantMessageID, callID: "call-hosted-interrupted", name: "web_search", }) yield* events.publish(SessionEvent.Tool.Input.Ended, { sessionID, - timestamp: yield* DateTime.now, assistantMessageID, callID: "call-hosted-interrupted", text: '{"query":"stale"}', }) yield* events.publish(SessionEvent.Tool.Called, { sessionID, - timestamp: yield* DateTime.now, assistantMessageID, callID: "call-hosted-interrupted", tool: "web_search", @@ -2527,13 +2499,11 @@ describe("SessionRunnerLLM", () => { yield* events.publish(SessionEvent.Step.Started, { sessionID, assistantMessageID, - timestamp: yield* DateTime.now, agent: "build", model: { id: ModelV2.ID.make("fake-model"), providerID: ProviderV2.ID.make("fake") }, }) yield* events.publish(SessionEvent.Tool.Input.Started, { sessionID, - timestamp: yield* DateTime.now, assistantMessageID, callID: "call-pending-interrupted", name: "echo", @@ -2578,7 +2548,7 @@ describe("SessionRunnerLLM", () => { const events = yield* EventV2.Service const defect = new Error("fail after prompt promotion") let fail = true - yield* events.project(SessionEvent.Prompted, () => (fail ? Effect.die(defect) : Effect.void)) + yield* events.project(SessionEvent.PromptPromoted, () => (fail ? Effect.die(defect) : Effect.void)) yield* session.prompt({ sessionID, prompt: Prompt.make({ text: "Recover promoted input" }), resume: false }) expect(yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))).toBe(defect) @@ -2603,7 +2573,9 @@ describe("SessionRunnerLLM", () => { const session = yield* SessionV2.Service const events = yield* EventV2.Service yield* events.listen((event) => - event.type === SessionEvent.Prompted.type ? Effect.die("fail after prompt promotion commits") : Effect.void, + event.type === SessionEvent.PromptPromoted.type + ? Effect.die("fail after prompt promotion commits") + : Effect.void, ) yield* session.prompt({ sessionID, @@ -3013,7 +2985,7 @@ describe("SessionRunnerLLM", () => { { type: "user", text: "Interrupt provider" }, { type: "assistant", finish: "error", error: { type: "unknown", message: "Provider turn interrupted" } }, ]) - expect(yield* recordedEventTypes(sessionID)).toContain("session.next.step.failed.2") + expect(yield* recordedEventTypes(sessionID)).toContain("step.failed.1") yield* session.interrupt(sessionID) }), ) @@ -3057,8 +3029,8 @@ describe("SessionRunnerLLM", () => { }, ]) const eventTypes = yield* recordedEventTypes(sessionID) - expect(eventTypes).toContain("session.next.step.failed.2") - expect(eventTypes).not.toContain("session.next.step.ended.2") + expect(eventTypes).toContain("step.failed.1") + expect(eventTypes).not.toContain("step.ended.1") }), ) diff --git a/packages/core/test/session-title.test.ts b/packages/core/test/session-title.test.ts index 1e9bcfbeb8..59abb8fabc 100644 --- a/packages/core/test/session-title.test.ts +++ b/packages/core/test/session-title.test.ts @@ -86,17 +86,13 @@ const prompt = (sessionID: SessionV2.ID, text: string) => const messageID = SessionMessage.ID.create() yield* events.publish(SessionEvent.PromptAdmitted, { sessionID, - messageID, - timestamp: DateTime.makeUnsafe(0), + inputID: messageID, prompt: Prompt.make({ text }), delivery: "steer", }) - yield* events.publish(SessionEvent.Prompted, { + yield* events.publish(SessionEvent.PromptPromoted, { sessionID, - messageID, - timestamp: DateTime.makeUnsafe(0), - prompt: Prompt.make({ text }), - delivery: "steer", + inputID: messageID, }) }) diff --git a/packages/core/test/session-tool-progress.test.ts b/packages/core/test/session-tool-progress.test.ts index 6d07b14657..e730b3556b 100644 --- a/packages/core/test/session-tool-progress.test.ts +++ b/packages/core/test/session-tool-progress.test.ts @@ -51,7 +51,6 @@ describe("Tool.Progress", () => { yield* service.publish(SessionEvent.Step.Started, { sessionID, assistantMessageID, - timestamp, agent: "build", model, }) @@ -69,14 +68,12 @@ describe("Tool.Progress", () => { Effect.gen(function* () { yield* service.publish(SessionEvent.Tool.Input.Started, { sessionID, - timestamp, assistantMessageID, callID, name: "bash", }) yield* service.publish(SessionEvent.Tool.Called, { sessionID, - timestamp, assistantMessageID, callID, tool: "bash", @@ -92,7 +89,6 @@ describe("Tool.Progress", () => { yield* service.publish(SessionEvent.Tool.Progress, { sessionID, - timestamp, assistantMessageID, callID: "call-success", structured: { phase: "checkpoint" }, @@ -104,7 +100,6 @@ describe("Tool.Progress", () => { const success = yield* service.publish(SessionEvent.Tool.Success, { sessionID, - timestamp, assistantMessageID, callID: "call-success", structured: { phase: "done" }, @@ -118,7 +113,6 @@ describe("Tool.Progress", () => { yield* start("call-failed") yield* service.publish(SessionEvent.Tool.Progress, { sessionID, - timestamp, assistantMessageID, callID: "call-failed", structured: { phase: "checkpoint" }, @@ -126,7 +120,6 @@ describe("Tool.Progress", () => { }) const failed = yield* service.publish(SessionEvent.Tool.Failed, { sessionID, - timestamp, assistantMessageID, callID: "call-failed", error: { type: "unknown", message: "boom" }, diff --git a/packages/core/test/shared-schema.test.ts b/packages/core/test/shared-schema.test.ts index e7556a8b7c..ecdd555fa8 100644 --- a/packages/core/test/shared-schema.test.ts +++ b/packages/core/test/shared-schema.test.ts @@ -148,8 +148,8 @@ test("Core reuses the canonical shared schemas", async () => { [coreSessionInput.Admitted, SessionInput.Admitted], [coreSessionMessage.ID, SessionMessage.ID], [coreSessionMessage.UnknownError, SessionMessage.UnknownError], - [coreSessionMessage.AgentSwitched, SessionMessage.AgentSwitched], - [coreSessionMessage.ModelSwitched, SessionMessage.ModelSwitched], + [coreSessionMessage.AgentSelected, SessionMessage.AgentSelected], + [coreSessionMessage.ModelSelected, SessionMessage.ModelSelected], [coreSessionMessage.User, SessionMessage.User], [coreSessionMessage.Synthetic, SessionMessage.Synthetic], [coreSessionMessage.System, SessionMessage.System], diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 15bd741a2e..6fd43ee2a2 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -79,27 +79,23 @@ const executionNode = makeGlobalNode({ yield* events.publish(SessionEvent.Step.Started, { sessionID: id, assistantMessageID, - timestamp: yield* DateTime.now, agent: session.agent ?? AgentV2.ID.make("code"), model: sessionModel, }) yield* events.publish(SessionEvent.Text.Started, { sessionID: id, assistantMessageID, - timestamp: yield* DateTime.now, textID, }) yield* events.publish(SessionEvent.Text.Ended, { sessionID: id, assistantMessageID, - timestamp: yield* DateTime.now, textID, text: "ok", }) yield* events.publish(SessionEvent.Step.Ended, { sessionID: id, assistantMessageID, - timestamp: yield* DateTime.now, finish: "stop", cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index 6274e329aa..4dd46da691 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -53,27 +53,23 @@ const executionNode = makeGlobalNode({ yield* events.publish(SessionEvent.Step.Started, { sessionID, assistantMessageID, - timestamp: yield* DateTime.now, agent: AgentV2.ID.make("reviewer"), model: childModel, }) yield* events.publish(SessionEvent.Text.Started, { sessionID, assistantMessageID, - timestamp: yield* DateTime.now, textID, }) yield* events.publish(SessionEvent.Text.Ended, { sessionID, assistantMessageID, - timestamp: yield* DateTime.now, textID, text: childText, }) yield* events.publish(SessionEvent.Step.Ended, { sessionID, assistantMessageID, - timestamp: yield* DateTime.now, finish: "stop", cost: 0, tokens, diff --git a/packages/opencode/src/cli/cmd/run/noninteractive.ts b/packages/opencode/src/cli/cmd/run/noninteractive.ts index fe6b95267c..60ded4ebd9 100644 --- a/packages/opencode/src/cli/cmd/run/noninteractive.ts +++ b/packages/opencode/src/cli/cmd/run/noninteractive.ts @@ -156,17 +156,16 @@ export async function runNonInteractivePrompt(input: Input) { continue } if (!("sessionID" in event.data) || event.data.sessionID !== input.sessionID) continue - const time = "timestamp" in event.data ? toMillis(event.data.timestamp) : Date.now() + const time = toMillis(event.created) - if (event.type === "session.next.prompted") { - if (event.data.messageID === messageID) { + if (event.type === "prompt.promoted") { + if (event.data.inputID === messageID) { promoted = true continue } - if (promoted && event.data.delivery === "queue") return } if ( - event.type === "session.next.execution.settled" && + event.type === "execution.settled" && event.data.outcome === "interrupted" && (interrupted || permissionRejected || questionRejected || formCancelled) ) { @@ -174,7 +173,7 @@ export async function runNonInteractivePrompt(input: Input) { } if (!promoted) continue - if (event.type === "session.next.step.started") { + if (event.type === "step.started") { const part: StepStartPart = { id: partID(event.id), sessionID: input.sessionID, @@ -190,11 +189,11 @@ export async function runNonInteractivePrompt(input: Input) { continue } - if (event.type === "session.next.text.started") { + if (event.type === "text.started") { starts.set(event.data.textID, { id: partID(event.id), timestamp: time }) continue } - if (event.type === "session.next.text.ended") { + if (event.type === "text.ended") { const started = starts.get(event.data.textID) const part: TextPart = { id: started?.id ?? partID(event.id), @@ -208,11 +207,11 @@ export async function runNonInteractivePrompt(input: Input) { continue } - if (event.type === "session.next.reasoning.started") { + if (event.type === "reasoning.started") { starts.set(event.data.reasoningID, { id: partID(event.id), timestamp: time }) continue } - if (event.type === "session.next.reasoning.ended" && input.thinking) { + if (event.type === "reasoning.ended" && input.thinking) { const started = starts.get(event.data.reasoningID) const part: ReasoningPart = { id: started?.id ?? partID(event.id), @@ -237,7 +236,7 @@ export async function runNonInteractivePrompt(input: Input) { continue } - if (event.type === "session.next.tool.input.started") { + if (event.type === "tool.input.started") { tools.set(event.data.callID, { id: partID(event.id), timestamp: time, @@ -247,12 +246,12 @@ export async function runNonInteractivePrompt(input: Input) { }) continue } - if (event.type === "session.next.tool.input.ended") { + if (event.type === "tool.input.ended") { const current = tools.get(event.data.callID) if (current) current.raw = event.data.text continue } - if (event.type === "session.next.tool.called") { + if (event.type === "tool.called") { const current = tools.get(event.data.callID) tools.set(event.data.callID, { id: current?.id ?? partID(event.id), @@ -265,7 +264,7 @@ export async function runNonInteractivePrompt(input: Input) { }) continue } - if (event.type === "session.next.tool.success") { + if (event.type === "tool.success") { const current = tools.get(event.data.callID) ?? fallbackTool(event) const part: ToolPart = { id: current.id, @@ -298,7 +297,7 @@ export async function runNonInteractivePrompt(input: Input) { if (!emit("tool_use", time, { part })) await input.renderTool(part) continue } - if (event.type === "session.next.tool.failed") { + if (event.type === "tool.failed") { const current = tools.get(event.data.callID) ?? fallbackTool(event) const error = event.data.error.message const part: ToolPart = { @@ -329,7 +328,7 @@ export async function runNonInteractivePrompt(input: Input) { continue } - if (event.type === "session.next.step.ended") { + if (event.type === "step.ended") { const part: StepFinishPart = { id: partID(event.id), sessionID: input.sessionID, @@ -343,19 +342,19 @@ export async function runNonInteractivePrompt(input: Input) { emit("step_finish", time, { part }) continue } - if (event.type === "session.next.step.failed") { + if (event.type === "step.failed") { if (interrupted || permissionRejected || questionRejected || formCancelled) continue emittedError = true process.exitCode = 1 if (!emit("error", time, { error: event.data.error })) UI.error(event.data.error.message) continue } - if (event.type === "session.next.execution.settled") { + if (event.type === "execution.settled") { if (event.data.outcome === "failure" && !emittedError && !questionRejected && !formCancelled) { emittedError = true process.exitCode = 1 const error = event.data.error ?? { type: "unknown", message: "Session execution failed" } - if (!emit("error", toMillis(event.data.timestamp), { error })) UI.error(error.message) + if (!emit("error", time, { error })) UI.error(error.message) } if (event.data.outcome === "interrupted" && interrupted) process.exitCode = 130 return @@ -458,11 +457,12 @@ function partID(eventID: string) { function fallbackTool(event: { id: string - data: { timestamp: number; assistantMessageID: string; callID: string } + created: number + data: { assistantMessageID: string; callID: string } }): ToolState { return { id: partID(event.id), - timestamp: toMillis(event.data.timestamp), + timestamp: toMillis(event.created), assistantMessageID: event.data.assistantMessageID, tool: "tool", input: {}, diff --git a/packages/opencode/src/cli/cmd/run/session-data.ts b/packages/opencode/src/cli/cmd/run/session-data.ts index 05daa8b423..9450f6cf78 100644 --- a/packages/opencode/src/cli/cmd/run/session-data.ts +++ b/packages/opencode/src/cli/cmd/run/session-data.ts @@ -728,7 +728,7 @@ export function reduceSessionData(input: SessionDataInput): SessionDataOutput { const data = input.data const event = input.event - if (event.type === "session.next.shell.started") { + if (event.type === "shell.started") { if (event.properties.sessionID !== input.sessionID) { return out(data, commits) } @@ -748,7 +748,7 @@ export function reduceSessionData(input: SessionDataInput): SessionDataOutput { return out(data, commits, patch({ status: "running shell" })) } - if (event.type === "session.next.shell.ended") { + if (event.type === "shell.ended") { if (event.properties.sessionID !== input.sessionID) { return out(data, commits) } diff --git a/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts b/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts index eac116b0b8..ac652423a1 100644 --- a/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts +++ b/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts @@ -424,21 +424,21 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac } const reduce = (child: ChildState, event: V2Event) => { - if (event.type === "session.next.prompted") { - if (userFrame(child, event.data.messageID, event.data.prompt.text)) { - touch(child, event.data.timestamp) + if (event.type === "prompt.promoted") { + if (userFrame(child, event.data.inputID, "")) { + touch(child, event.created) notifyDetail(child) } return } - if (event.type === "session.next.step.started") { - touch(child, event.data.timestamp) + if (event.type === "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.next.text.delta") { + if (event.type === "text.delta") { const projected = child.projectedText.get(event.data.textID) const covered = projected?.indexOf(event.data.delta) ?? -1 if (projected && covered >= 0) { @@ -455,11 +455,11 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac messageID: event.data.assistantMessageID, partID: event.data.textID, }) - touch(child, event.data.timestamp) + touch(child, event.created) notifyDetail(child) return } - if (event.type === "session.next.text.ended") { + if (event.type === "text.ended") { child.text.set(event.data.textID, event.data.text) child.projectedText.delete(event.data.textID) setFrame(child, `text:${event.data.textID}`, { @@ -470,11 +470,11 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac messageID: event.data.assistantMessageID, partID: event.data.textID, }) - touch(child, event.data.timestamp) + touch(child, event.created) notifyDetail(child) return } - if (event.type === "session.next.reasoning.delta") { + if (event.type === "reasoning.delta") { const projected = child.projectedReasoning.get(event.data.reasoningID) const covered = projected?.indexOf(event.data.delta) ?? -1 if (projected && covered >= 0) { @@ -495,7 +495,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "session.next.reasoning.ended") { + if (event.type === "reasoning.ended") { child.reasoning.set(event.data.reasoningID, event.data.text) child.projectedReasoning.delete(event.data.reasoningID) if (!input.thinking) return @@ -510,16 +510,16 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "session.next.tool.input.started") { - child.tools.set(event.data.callID, { name: event.data.name, input: {}, started: event.data.timestamp }) + if (event.type === "tool.input.started") { + child.tools.set(event.data.callID, { name: event.data.name, input: {}, started: event.created }) return } - if (event.type === "session.next.tool.called") { + if (event.type === "tool.called") { const current = child.tools.get(event.data.callID) child.tools.set(event.data.callID, { name: event.data.tool, input: event.data.input, - started: current?.started ?? event.data.timestamp, + started: current?.started ?? event.created, }) childTool( child, @@ -529,18 +529,18 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac name: event.data.tool, provider: event.data.provider, state: { status: "running", input: event.data.input, structured: {}, content: [] }, - time: { created: current?.started ?? event.data.timestamp, ran: event.data.timestamp }, + time: { created: current?.started ?? event.created, ran: event.created }, }, event.data.assistantMessageID, ) - touch(child, event.data.timestamp) + touch(child, event.created) notifyDetail(child) return } - if (event.type === "session.next.tool.success" || event.type === "session.next.tool.failed") { + if (event.type === "tool.success" || event.type === "tool.failed") { if (child.finishedTools.has(event.data.callID)) return const current = child.tools.get(event.data.callID) - const failed = event.type === "session.next.tool.failed" + const failed = event.type === "tool.failed" childTool( child, { @@ -566,18 +566,18 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac result: event.data.result, }, time: { - created: current?.started ?? event.data.timestamp, + created: current?.started ?? event.created, ran: current?.started, - completed: event.data.timestamp, + completed: event.created, }, }, event.data.assistantMessageID, ) - touch(child, event.data.timestamp) + touch(child, event.created) notifyDetail(child) return } - if (event.type === "session.next.step.failed") { + if (event.type === "step.failed") { setFrame(child, `error:step:${event.data.assistantMessageID}`, { kind: "error", source: "system", @@ -585,14 +585,14 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac phase: "start", messageID: event.data.assistantMessageID, }) - touch(child, event.data.timestamp) + touch(child, event.created) notifyDetail(child) return } - if (event.type === "session.next.execution.settled") { + if (event.type === "execution.settled") { child.status = event.data.outcome === "success" ? "completed" : event.data.outcome === "interrupted" ? "cancelled" : "error" - touch(child, event.data.timestamp) + touch(child, event.created) input.emit() } } @@ -613,15 +613,15 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac return { main(event) { - if (event.type === "session.next.tool.called") { + if (event.type === "tool.called") { if (event.data.tool === "subagent") pendingCalls.set(event.data.callID, event.data.input) return } - if (event.type === "session.next.tool.failed") { + if (event.type === "tool.failed") { pendingCalls.delete(event.data.callID) return } - if (event.type !== "session.next.tool.success") return + if (event.type !== "tool.success") return const pending = pendingCalls.get(event.data.callID) pendingCalls.delete(event.data.callID) const found = childSessionID(record(event.data.structured)) @@ -633,7 +633,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac child.status = "running" } if (!found.running && child.status === "running") child.status = "completed" - touch(child, event.data.timestamp) + touch(child, event.created) input.emit() if (!child.hydrated) void hydrateChild(child) }, diff --git a/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts b/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts index 7700ddd024..614a960634 100644 --- a/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts +++ b/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts @@ -294,7 +294,14 @@ export async function createSessionTransport(input: StreamInput): Promise { @@ -395,17 +402,17 @@ export async function createSessionTransport(input: StreamInput): Promise previous.length) @@ -445,7 +452,7 @@ export async function createSessionTransport(input: StreamInput): Promise previous.length) @@ -486,17 +493,17 @@ export async function createSessionTransport(input: StreamInput): Promise 0 ? total.toLocaleString() : "" - write([], { phase: event.data.finish === "tool-calls" ? "running" : "idle", usage: event.data.cost ? `${usage} · ${money.format(event.data.cost)}` : usage }) + write([], { + phase: event.data.finish === "tool-calls" ? "running" : "idle", + usage: event.data.cost ? `${usage} · ${money.format(event.data.cost)}` : usage, + }) return } - if (event.type === "session.next.step.failed") { + if (event.type === "step.failed") { state.errors.add(event.data.assistantMessageID) if (state.wait) state.wait.failureRendered = true write([{ kind: "error", source: "system", text: errorMessage(event.data.error), phase: "start" }]) return } - if (event.type === "session.next.execution.settled") { + if (event.type === "execution.settled") { write([], { phase: "idle", status: "" }) const current = state.wait if (!current || (!current.promoted && !current.interrupted)) return @@ -611,7 +628,7 @@ export async function createSessionTransport(input: StreamInput): Promise + const stream = response.stream[Symbol.asyncIterator]() as AsyncGenerator try { const first = await stream.next() if (first.done || first.value.type !== "server.connected") throw new Error("Event stream disconnected") @@ -689,10 +706,7 @@ export async function createSessionTransport(input: StreamInput): Promise (file.attachment ? [file.attachment] : [])), - ...promptFiles, - ] + const attachments = [...prepared.flatMap((file) => (file.attachment ? [file.attachment] : [])), ...promptFiles] const agents = next.prompt.parts.flatMap((part) => part.type === "agent" ? [ @@ -735,10 +749,7 @@ export async function createSessionTransport(input: StreamInput): Promise (file.text ? [file.text] : [])), - ].join("\n\n"), + text: [next.prompt.text, ...prepared.flatMap((file) => (file.text ? [file.text] : []))].join("\n\n"), files: attachments.length ? attachments : undefined, agents: agents.length ? agents : undefined, }, diff --git a/packages/opencode/test/cli/run/noninteractive.test.ts b/packages/opencode/test/cli/run/noninteractive.test.ts index d8bff61a73..839b99656b 100644 --- a/packages/opencode/test/cli/run/noninteractive.test.ts +++ b/packages/opencode/test/cli/run/noninteractive.test.ts @@ -18,31 +18,33 @@ function form(id: string, sessionID: string): FormInfo { } function formCreated(info: FormInfo): V2Event { - return { id: `evt_${info.id}`, type: "form.created", data: { form: info } } + return { id: `evt_${info.id}`, created: 0, type: "form.created", data: { form: info } } } -function prompted(messageID: string): V2Event { +function prompted(inputID: string): V2Event { return { id: "evt_prompted", - type: "session.next.prompted", + created: 0, + type: "prompt.promoted", durable: { aggregateID: "ses_1", seq: 0, version: 1 }, - data: { timestamp: 1, sessionID: "ses_1", messageID, prompt: { text: "hello" }, delivery: "steer" }, + data: { sessionID: "ses_1", inputID }, } } function settled(outcome: "success" | "interrupted" = "success"): V2Event { return { id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 2, sessionID: "ses_1", outcome }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome }, } } // Runs one non-interactive prompt against a mocked SDK. `turn` produces the // live events the prompt admission triggers, keyed by the generated message ID. -async function run(input: { turn: (messageID: string) => V2Event[]; pendingForms?: FormInfo[]; attached?: boolean }) { +async function run(input: { turn: (inputID: string) => V2Event[]; pendingForms?: FormInfo[]; attached?: boolean }) { const sdk = new OpencodeClient() - const values: V2Event[] = [{ id: "evt_connected", type: "server.connected", data: {} }] + const values: V2Event[] = [{ id: "evt_connected", created: 0, type: "server.connected", data: {} }] let wake: (() => void) | undefined const stream = (async function* (): AsyncGenerator { while (true) { diff --git a/packages/opencode/test/cli/run/session-data.test.ts b/packages/opencode/test/cli/run/session-data.test.ts index ec21cd007e..89a6751d1b 100644 --- a/packages/opencode/test/cli/run/session-data.test.ts +++ b/packages/opencode/test/cli/run/session-data.test.ts @@ -329,7 +329,7 @@ describe("run session data", () => { test("renders direct shell mode from first-class shell events", () => { let data = createSessionData() const started = reduce(data, { - type: "session.next.shell.started", + type: "shell.started", properties: { sessionID: "session-1", timestamp: 1, @@ -353,7 +353,7 @@ describe("run session data", () => { data = started.data const ended = reduce(data, { - type: "session.next.shell.ended", + type: "shell.ended", properties: { sessionID: "session-1", timestamp: 2, @@ -380,7 +380,7 @@ describe("run session data", () => { test("suppresses legacy bash part updates once shell events claim the call", () => { let data = reduce(createSessionData(), { - type: "session.next.shell.started", + type: "shell.started", properties: { sessionID: "session-1", timestamp: 1, @@ -409,7 +409,7 @@ describe("run session data", () => { ).toEqual([]) data = reduce(data, { - type: "session.next.shell.ended", + type: "shell.ended", properties: { sessionID: "session-1", timestamp: 2, @@ -463,7 +463,7 @@ describe("run session data", () => { expect( reduce(data, { - type: "session.next.shell.started", + type: "shell.started", properties: { sessionID: "session-1", timestamp: 1, @@ -497,7 +497,7 @@ describe("run session data", () => { expect( reduce(data, { - type: "session.next.shell.ended", + type: "shell.ended", properties: { sessionID: "session-1", timestamp: 2, diff --git a/packages/opencode/test/cli/run/stream-v2.transport.test.ts b/packages/opencode/test/cli/run/stream-v2.transport.test.ts index 2f78d106cf..8bf429e500 100644 --- a/packages/opencode/test/cli/run/stream-v2.transport.test.ts +++ b/packages/opencode/test/cli/run/stream-v2.transport.test.ts @@ -50,7 +50,7 @@ function ok(data: T) { } function connected(id = "evt_connected") { - return { id, type: "server.connected", data: {} } satisfies RunV2Event + return { id, created: 0, type: "server.connected", data: {} } satisfies RunV2Event } function durable(sessionID: string, seq = 0, version = 1) { @@ -125,22 +125,20 @@ function sdk(input: { spyOn(client.v2.session, "switchModel").mockImplementation(() => ok(undefined)) // The generated methods have conditional return types for throwOnError; the // minimal shapes below are enough for family discovery and model fallback. - spyOn(client.v2.session, "list").mockImplementation( - (request) => { - const parentID = request?.parentID - return ok({ - location: { directory: "/tmp", project: { id: "proj_1", directory: "/tmp" } }, - data: - input.sessions?.filter((session) => - parentID === undefined - ? true - : parentID === null - ? session.parentID === undefined - : session.parentID === parentID, - ) ?? [], - }) as never - }, - ) + spyOn(client.v2.session, "list").mockImplementation((request) => { + const parentID = request?.parentID + return ok({ + location: { directory: "/tmp", project: { id: "proj_1", directory: "/tmp" } }, + data: + input.sessions?.filter((session) => + parentID === undefined + ? true + : parentID === null + ? session.parentID === undefined + : session.parentID === parentID, + ) ?? [], + }) as never + }) spyOn(client.v2.model, "default").mockImplementation( () => ok({ @@ -201,21 +199,19 @@ describe("V2 mini transport", () => { while (!admitted) await Bun.sleep(0) events.push({ id: "evt_prompted", - type: "session.next.prompted", + created: 0, + type: "prompt.promoted", durable: durable("ses_1"), data: { - timestamp: 2, sessionID: "ses_1", - messageID: "msg_prompt", - prompt: { text: "hello" }, - delivery: "steer", + inputID: "msg_prompt", }, }) events.push({ id: "evt_text", - type: "session.next.text.delta", + created: 0, + type: "text.delta", data: { - timestamp: 3, sessionID: "ses_1", assistantMessageID: "msg_assistant", textID: "txt_1", @@ -224,8 +220,9 @@ describe("V2 mini transport", () => { }) events.push({ id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 4, sessionID: "ses_1", outcome: "success" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -261,20 +258,19 @@ describe("V2 mini transport", () => { queueMicrotask(() => { events.push({ id: "evt_prompted", - type: "session.next.prompted", + created: 0, + type: "prompt.promoted", durable: durable("ses_1"), data: { - timestamp: 2, sessionID: "ses_1", - messageID: "msg_prompt", - prompt: { text: input.prompt?.text ?? "" }, - delivery: "steer", + inputID: "msg_prompt", }, }) events.push({ id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 3, sessionID: "ses_1", outcome: "success" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, }) }) return ok({ @@ -356,20 +352,19 @@ describe("V2 mini transport", () => { queueMicrotask(() => { events.push({ id: "evt_prompted", - type: "session.next.prompted", + created: 0, + type: "prompt.promoted", durable: durable("ses_1"), data: { - timestamp: 2, sessionID: "ses_1", - messageID: "msg_prompt", - prompt: { text: input.prompt?.text ?? "" }, - delivery: "steer", + inputID: "msg_prompt", }, }) events.push({ id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 3, sessionID: "ses_1", outcome: "success" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, }) }) return ok({ @@ -454,20 +449,19 @@ describe("V2 mini transport", () => { queueMicrotask(() => { events.push({ id: "evt_prompted", - type: "session.next.prompted", + created: 0, + type: "prompt.promoted", durable: durable("ses_1"), data: { - timestamp: 2, sessionID: "ses_1", - messageID: "msg_prompt", - prompt: { text: input.prompt?.text ?? "" }, - delivery: "steer", + inputID: "msg_prompt", }, }) events.push({ id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 3, sessionID: "ses_1", outcome: "success" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, }) }) return ok({ @@ -528,6 +522,7 @@ describe("V2 mini transport", () => { }) events.push({ id: "evt_permission", + created: 0, type: "permission.v2.asked", data: { id: "per_1", sessionID: "ses_1", action: "read", resources: ["/tmp/file"] }, }) @@ -728,9 +723,9 @@ describe("V2 mini transport", () => { const replay = transport.replayOnResize({ localRows: () => [], reset: () => resetting }) events.push({ id: "evt_text", - type: "session.next.text.delta", + created: 0, + type: "text.delta", data: { - timestamp: 3, sessionID: "ses_1", assistantMessageID: "msg_assistant", textID: "txt_1", @@ -813,10 +808,10 @@ describe("V2 mini transport", () => { }) events.push({ id: "evt_reasoning", - type: "session.next.reasoning.ended", + created: 0, + type: "reasoning.ended", durable: durable("ses_1"), data: { - timestamp: 3, sessionID: "ses_1", assistantMessageID: "msg_assistant", reasoningID: "reasoning_1", @@ -869,8 +864,9 @@ describe("V2 mini transport", () => { await transport.interruptActiveTurn() events.push({ id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 3, sessionID: "ses_1", outcome: "interrupted" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -924,20 +920,19 @@ describe("V2 mini transport", () => { while (!admitted) await Bun.sleep(0) events.push({ id: "evt_prompted", - type: "session.next.prompted", + created: 0, + type: "prompt.promoted", durable: durable("ses_1"), data: { - timestamp: 2, sessionID: "ses_1", - messageID: "msg_prompt", - prompt: { text: "hello" }, - delivery: "steer", + inputID: "msg_prompt", }, }) events.push({ id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 3, sessionID: "ses_1", outcome: "success" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -985,22 +980,21 @@ describe("V2 mini transport", () => { while (!admitted) await Bun.sleep(0) events.push({ id: "evt_prompted", - type: "session.next.prompted", + created: 0, + type: "prompt.promoted", durable: durable("ses_1"), data: { - timestamp: 2, sessionID: "ses_1", - messageID: "msg_prompt", - prompt: { text: "hello" }, - delivery: "steer", + inputID: "msg_prompt", }, }) await Bun.sleep(0) controller.abort() events.push({ id: "evt_settled", - type: "session.next.execution.settled", - data: { timestamp: 3, sessionID: "ses_1", outcome: "interrupted" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -1054,10 +1048,10 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_step", - type: "session.next.step.started", + created: 0, + type: "step.started", durable: durable("ses_child"), data: { - timestamp: 2, sessionID: "ses_child", assistantMessageID: "msg_child_a", agent: "explore", @@ -1072,9 +1066,9 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_text", - type: "session.next.text.delta", + created: 0, + type: "text.delta", data: { - timestamp: 3, sessionID: "ses_child", assistantMessageID: "msg_child_a", textID: "txt_child", @@ -1086,8 +1080,9 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_settled", - type: "session.next.execution.settled", - data: { timestamp: 4, sessionID: "ses_child", outcome: "success" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_child", outcome: "success" }, }) while (!states().some((state) => state.tabs.some((tab) => tab.status === "completed"))) await Bun.sleep(0) await transport.close() @@ -1130,10 +1125,10 @@ describe("V2 mini transport", () => { // Both events arrive while session.get is still in flight. events.push({ id: "evt_child_step", - type: "session.next.step.started", + created: 0, + type: "step.started", durable: durable("ses_child"), data: { - timestamp: 2, sessionID: "ses_child", assistantMessageID: "msg_child_a", agent: "explore", @@ -1142,8 +1137,9 @@ describe("V2 mini transport", () => { }) events.push({ id: "evt_child_settled", - type: "session.next.execution.settled", - data: { timestamp: 3, sessionID: "ses_child", outcome: "interrupted" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_child", outcome: "interrupted" }, }) await Bun.sleep(0) resolveGet?.() @@ -1188,10 +1184,10 @@ describe("V2 mini transport", () => { // Child event arrives first and gets buffered behind the gated session.get. events.push({ id: "evt_child_step", - type: "session.next.step.started", + created: 0, + type: "step.started", durable: durable("ses_child"), data: { - timestamp: 2, sessionID: "ses_child", assistantMessageID: "msg_child_a", agent: "explore", @@ -1201,10 +1197,10 @@ describe("V2 mini transport", () => { // Parent's background subagent tool.success adopts the child mid-discovery. events.push({ id: "evt_parent_call", - type: "session.next.tool.called", + created: 0, + type: "tool.called", durable: durable("ses_1"), data: { - timestamp: 3, sessionID: "ses_1", assistantMessageID: "msg_parent_a", callID: "call_sub", @@ -1215,10 +1211,10 @@ describe("V2 mini transport", () => { }) events.push({ id: "evt_parent_success", - type: "session.next.tool.success", + created: 0, + type: "tool.success", durable: durable("ses_1", 1), data: { - timestamp: 4, sessionID: "ses_1", assistantMessageID: "msg_parent_a", callID: "call_sub", @@ -1230,8 +1226,9 @@ describe("V2 mini transport", () => { // The settled event arrives after adoption, so it applies directly. events.push({ id: "evt_child_settled", - type: "session.next.execution.settled", - data: { timestamp: 5, sessionID: "ses_child", outcome: "interrupted" }, + created: 0, + type: "execution.settled", + data: { sessionID: "ses_child", outcome: "interrupted" }, }) while (!states().some((state) => state.tabs.some((tab) => tab.status === "cancelled"))) await Bun.sleep(0) diff --git a/packages/opencode/test/v2/session-message-updater.test.ts b/packages/opencode/test/v2/session-message-updater.test.ts index e85afaeeff..4da4dc9d13 100644 --- a/packages/opencode/test/v2/session-message-updater.test.ts +++ b/packages/opencode/test/v2/session-message-updater.test.ts @@ -21,12 +21,12 @@ test.skip("step snapshots carry over to assistant messages", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.step.started", + created: DateTime.makeUnsafe(0), + type: "step.started", durable: durable(sessionID), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(1), agent: "build", model: { id: ModelV2.ID.make("model"), @@ -43,12 +43,12 @@ test.skip("step snapshots carry over to assistant messages", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.step.ended", + created: DateTime.makeUnsafe(0), + type: "step.ended", durable: durable(sessionID, 1, 2), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(2), finish: "stop", cost: 0, tokens: { @@ -76,12 +76,12 @@ test.skip("text ended populates assistant text content", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.step.started", + created: DateTime.makeUnsafe(0), + type: "step.started", durable: durable(sessionID), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(1), agent: "build", model: { id: ModelV2.ID.make("model"), @@ -95,12 +95,12 @@ test.skip("text ended populates assistant text content", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.text.started", + created: DateTime.makeUnsafe(0), + type: "text.started", durable: durable(sessionID, 1), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(2), textID: "text-1", }, } satisfies SessionEvent.Event), @@ -109,12 +109,12 @@ test.skip("text ended populates assistant text content", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.text.ended", + created: DateTime.makeUnsafe(0), + type: "text.ended", durable: durable(sessionID, 2), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(3), textID: "text-1", text: "hello assistant", }, @@ -135,12 +135,12 @@ test.skip("tool completion stores completed timestamp", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.step.started", + created: DateTime.makeUnsafe(0), + type: "step.started", durable: durable(sessionID), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(1), agent: "build", model: { id: ModelV2.ID.make("model"), @@ -154,12 +154,12 @@ test.skip("tool completion stores completed timestamp", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.tool.input.started", + created: DateTime.makeUnsafe(0), + type: "tool.input.started", durable: durable(sessionID, 1), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(2), callID, name: "bash", }, @@ -169,12 +169,12 @@ test.skip("tool completion stores completed timestamp", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.tool.called", + created: DateTime.makeUnsafe(0), + type: "tool.called", durable: durable(sessionID, 2), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(3), callID, tool: "bash", input: { command: "pwd" }, @@ -186,12 +186,12 @@ test.skip("tool completion stores completed timestamp", () => { Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.tool.success", + created: DateTime.makeUnsafe(0), + type: "tool.success", durable: durable(sessionID, 3), data: { sessionID, assistantMessageID, - timestamp: DateTime.makeUnsafe(4), callID, structured: {}, content: [{ type: "text", text: "/tmp" }], @@ -212,17 +212,16 @@ test("compaction events reduce to compaction message only when completed", () => const state: SessionMessageUpdater.MemoryState = { messages: [] } const sessionID = SessionID.make("session") const id = EventV2.ID.create() - const compactionID = SessionMessage.ID.create() + const endedID = EventV2.ID.create() Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id, - type: "session.next.compaction.started", + created: DateTime.makeUnsafe(0), + type: "compaction.started", durable: durable(sessionID), data: { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(1), reason: "auto", }, } satisfies SessionEvent.Event), @@ -233,11 +232,10 @@ test("compaction events reduce to compaction message only when completed", () => Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.compaction.delta", + created: DateTime.makeUnsafe(0), + type: "compaction.delta", data: { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(2), text: "hello ", }, } satisfies SessionEvent.Event), @@ -246,11 +244,10 @@ test("compaction events reduce to compaction message only when completed", () => Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), - type: "session.next.compaction.delta", + created: DateTime.makeUnsafe(0), + type: "compaction.delta", data: { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(3), text: "summary", }, } satisfies SessionEvent.Event), @@ -258,13 +255,12 @@ test("compaction events reduce to compaction message only when completed", () => Effect.runSync( SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.compaction.ended", + id: endedID, + created: DateTime.makeUnsafe(0), + type: "compaction.ended", durable: durable(sessionID, 1), data: { sessionID, - messageID: compactionID, - timestamp: DateTime.makeUnsafe(4), reason: "auto", text: "final summary", recent: "recent context", @@ -274,11 +270,11 @@ test("compaction events reduce to compaction message only when completed", () => expect(state.messages).toHaveLength(1) expect(state.messages[0]).toMatchObject({ - id: compactionID, + id: SessionMessage.ID.fromEvent(endedID), type: "compaction", reason: "auto", summary: "final summary", recent: "recent context", - time: { created: DateTime.makeUnsafe(4) }, + time: { created: DateTime.makeUnsafe(0) }, }) }) diff --git a/packages/schema/src/event.ts b/packages/schema/src/event.ts index aac2f0315e..9f7c347b03 100644 --- a/packages/schema/src/event.ts +++ b/packages/schema/src/event.ts @@ -4,7 +4,7 @@ import { Schema } from "effect" import { optional } from "./schema.js" import { ascending } from "./identifier.js" import { Location } from "./location.js" -import { statics } from "./schema.js" +import { DateTimeUtcFromMillis, statics } from "./schema.js" export const ID = Schema.String.check(Schema.isStartsWith("evt_")).pipe( Schema.brand("Event.ID"), @@ -60,6 +60,7 @@ export type Data = Schema.Schema.Type type PayloadBase = { readonly id: ID readonly type: D["type"] + readonly created: typeof DateTimeUtcFromMillis.Type readonly data: Data readonly location?: Location.Ref readonly metadata?: Record @@ -85,6 +86,7 @@ export function durable< const data = Schema.Struct(input.schema) return Schema.Struct({ id: ID, + created: DateTimeUtcFromMillis, metadata: optional(Schema.Record(Schema.String, Schema.Unknown)), type: Schema.Literal(input.type), durable: DurableEnvelope, @@ -109,6 +111,7 @@ export function ephemeral< const data = Schema.Struct(input.schema) return Schema.Struct({ id: ID, + created: DateTimeUtcFromMillis, metadata: optional(Schema.Record(Schema.String, Schema.Unknown)), type: Schema.Literal(input.type), location: optional(Location.Ref), diff --git a/packages/schema/src/session-event.ts b/packages/schema/src/session-event.ts index fe1a698555..fce091545a 100644 --- a/packages/schema/src/session-event.ts +++ b/packages/schema/src/session-event.ts @@ -6,7 +6,7 @@ import { Event } from "./event.js" import { ProviderMetadata, ToolContent } from "./llm.js" import { Delivery } from "./session-delivery.js" import { Model } from "./model.js" -import { DateTimeUtcFromMillis, NonNegativeInt, RelativePath } from "./schema.js" +import { NonNegativeInt, RelativePath } from "./schema.js" import { FileAttachment, Prompt } from "./prompt.js" import { SessionID } from "./session-id.js" import { Location } from "./location.js" @@ -20,17 +20,16 @@ export const Source = Schema.Struct({ end: NonNegativeInt, text: Schema.String, }).annotate({ - identifier: "session.next.event.source", + identifier: "session.event.source", }) export interface Source extends Schema.Schema.Type {} const Base = { - timestamp: DateTimeUtcFromMillis, sessionID: SessionID, } const PromptFields = { ...Base, - messageID: SessionMessage.ID, + inputID: SessionMessage.ID, prompt: Prompt, delivery: Delivery, } @@ -44,48 +43,46 @@ const options = { const stepSettlementOptions = { durable: { aggregate: "sessionID", - version: 2, + version: 1, }, } as const export const UnknownError = SessionMessage.UnknownError export type UnknownError = SessionMessage.UnknownError -export const AgentSwitched = Event.durable({ - type: "session.next.agent.switched", +export const AgentSelected = Event.durable({ + type: "agent.selected", ...options, schema: { ...Base, - messageID: SessionMessage.ID, agent: Schema.String, }, }) -export type AgentSwitched = typeof AgentSwitched.Type +export type AgentSelected = typeof AgentSelected.Type -export const ModelSwitched = Event.durable({ - type: "session.next.model.switched", +export const ModelSelected = Event.durable({ + type: "model.selected", ...options, schema: { ...Base, - messageID: SessionMessage.ID, model: Model.Ref, }, }) -export type ModelSwitched = typeof ModelSwitched.Type +export type ModelSelected = typeof ModelSelected.Type export const Moved = Event.durable({ - type: "session.next.moved", + type: "session.moved", ...options, schema: { ...Base, location: Location.Ref, - subdirectory: RelativePath.pipe(optional), + subpath: RelativePath.pipe(optional), }, }) export type Moved = typeof Moved.Type export const Renamed = Event.durable({ - type: "session.next.renamed", + type: "renamed", ...options, schema: { ...Base, @@ -95,32 +92,35 @@ export const Renamed = Event.durable({ export type Renamed = typeof Renamed.Type export const Forked = Event.durable({ - type: "session.next.forked", + type: "forked", ...options, schema: { ...Base, parentID: SessionID, - messageID: SessionMessage.ID.pipe(optional), + from: SessionMessage.ID.pipe(optional), }, }) export type Forked = typeof Forked.Type -export const Prompted = Event.durable({ - type: "session.next.prompted", +export const PromptPromoted = Event.durable({ + type: "prompt.promoted", ...options, - schema: PromptFields, + schema: { + sessionID: SessionID, + inputID: SessionMessage.ID, + }, }) -export type Prompted = typeof Prompted.Type +export type PromptPromoted = typeof PromptPromoted.Type export const PromptAdmitted = Event.durable({ - type: "session.next.prompt.admitted", + type: "prompt.admitted", ...options, schema: PromptFields, }) export type PromptAdmitted = typeof PromptAdmitted.Type export const ExecutionSettled = Event.ephemeral({ - type: "session.next.execution.settled", + type: "execution.settled", schema: { ...Base, outcome: Schema.Literals(["success", "failure", "interrupted"]), @@ -130,22 +130,20 @@ export const ExecutionSettled = Event.ephemeral({ export type ExecutionSettled = typeof ExecutionSettled.Type export const ContextUpdated = Event.durable({ - type: "session.next.context.updated", + type: "session.context.updated", ...options, schema: { ...Base, - messageID: SessionMessage.ID, text: Schema.String, }, }) export type ContextUpdated = typeof ContextUpdated.Type export const Synthetic = Event.durable({ - type: "session.next.synthetic", + type: "synthetic", ...options, schema: { ...Base, - messageID: SessionMessage.ID, text: Schema.String, description: Schema.String.pipe(optional), metadata: Schema.Record(Schema.String, Schema.Unknown).pipe(optional), @@ -155,11 +153,10 @@ export type Synthetic = typeof Synthetic.Type export namespace Skill { export const Activated = Event.durable({ - type: "session.next.skill.activated", + type: "skill.activated", ...options, schema: { ...Base, - messageID: SessionMessage.ID, name: Schema.String, text: Schema.String, }, @@ -169,11 +166,10 @@ export namespace Skill { export namespace Shell { export const Started = Event.durable({ - type: "session.next.shell.started", + type: "shell.started", ...options, schema: { ...Base, - messageID: SessionMessage.ID, callID: Schema.String, command: Schema.String, }, @@ -181,7 +177,7 @@ export namespace Shell { export type Started = typeof Started.Type export const Ended = Event.durable({ - type: "session.next.shell.ended", + type: "shell.ended", ...options, schema: { ...Base, @@ -194,7 +190,7 @@ export namespace Shell { export namespace Step { export const Started = Event.durable({ - type: "session.next.step.started", + type: "step.started", ...options, schema: { ...Base, @@ -207,7 +203,7 @@ export namespace Step { export type Started = typeof Started.Type export const Ended = Event.durable({ - type: "session.next.step.ended", + type: "step.ended", ...stepSettlementOptions, schema: { ...Base, @@ -230,7 +226,7 @@ export namespace Step { export type Ended = typeof Ended.Type export const Failed = Event.durable({ - type: "session.next.step.failed", + type: "step.failed", ...stepSettlementOptions, schema: { ...Base, @@ -243,7 +239,7 @@ export namespace Step { export namespace Text { export const Started = Event.durable({ - type: "session.next.text.started", + type: "text.started", ...options, schema: { ...Base, @@ -255,7 +251,7 @@ export namespace Text { // Stream fragments are live-only; Text.Ended is the replayable full-value boundary. export const Delta = Event.ephemeral({ - type: "session.next.text.delta", + type: "text.delta", schema: { ...Base, assistantMessageID: SessionMessage.ID, @@ -266,7 +262,7 @@ export namespace Text { export type Delta = typeof Delta.Type export const Ended = Event.durable({ - type: "session.next.text.ended", + type: "text.ended", ...options, schema: { ...Base, @@ -280,7 +276,7 @@ export namespace Text { export namespace Reasoning { export const Started = Event.durable({ - type: "session.next.reasoning.started", + type: "reasoning.started", ...options, schema: { ...Base, @@ -293,7 +289,7 @@ export namespace Reasoning { // Stream fragments are live-only; Reasoning.Ended is the replayable full-value boundary. export const Delta = Event.ephemeral({ - type: "session.next.reasoning.delta", + type: "reasoning.delta", schema: { ...Base, assistantMessageID: SessionMessage.ID, @@ -304,7 +300,7 @@ export namespace Reasoning { export type Delta = typeof Delta.Type export const Ended = Event.durable({ - type: "session.next.reasoning.ended", + type: "reasoning.ended", ...options, schema: { ...Base, @@ -326,7 +322,7 @@ export namespace Tool { export namespace Input { export const Started = Event.durable({ - type: "session.next.tool.input.started", + type: "tool.input.started", ...options, schema: { ...ToolBase, @@ -337,7 +333,7 @@ export namespace Tool { // Stream fragments are live-only; Input.Ended is the replayable raw-input boundary. export const Delta = Event.ephemeral({ - type: "session.next.tool.input.delta", + type: "tool.input.delta", schema: { ...ToolBase, delta: Schema.String, @@ -346,7 +342,7 @@ export namespace Tool { export type Delta = typeof Delta.Type export const Ended = Event.durable({ - type: "session.next.tool.input.ended", + type: "tool.input.ended", ...options, schema: { ...ToolBase, @@ -357,7 +353,7 @@ export namespace Tool { } export const Called = Event.durable({ - type: "session.next.tool.called", + type: "tool.called", ...options, schema: { ...ToolBase, @@ -376,7 +372,7 @@ export namespace Tool { * transitions or at a bounded cadence, not persist every stdout/stderr chunk. */ export const Progress = Event.durable({ - type: "session.next.tool.progress", + type: "tool.progress", ...options, schema: { ...ToolBase, @@ -387,7 +383,7 @@ export namespace Tool { export type Progress = typeof Progress.Type export const Success = Event.durable({ - type: "session.next.tool.success", + type: "tool.success", ...options, schema: { ...ToolBase, @@ -404,7 +400,7 @@ export namespace Tool { export type Success = typeof Success.Type export const Failed = Event.durable({ - type: "session.next.tool.failed", + type: "tool.failed", ...options, schema: { ...ToolBase, @@ -427,12 +423,12 @@ export const RetryError = Schema.Struct({ responseBody: Schema.String.pipe(optional), metadata: Schema.Record(Schema.String, Schema.String).pipe(optional), }).annotate({ - identifier: "session.next.retry_error", + identifier: "session.retry.error", }) export interface RetryError extends Schema.Schema.Type {} export const Retried = Event.durable({ - type: "session.next.retried", + type: "retried", ...options, schema: { ...Base, @@ -444,32 +440,29 @@ export type Retried = typeof Retried.Type export namespace Compaction { export const Started = Event.durable({ - type: "session.next.compaction.started", + type: "compaction.started", ...options, schema: { ...Base, - messageID: SessionMessage.ID, reason: Schema.Union([Schema.Literal("auto"), Schema.Literal("manual")]), }, }) export type Started = typeof Started.Type export const Delta = Event.ephemeral({ - type: "session.next.compaction.delta", + type: "compaction.delta", schema: { ...Base, - messageID: SessionMessage.ID, text: Schema.String, }, }) export type Delta = typeof Delta.Type export const Ended = Event.durable({ - type: "session.next.compaction.ended", + type: "compaction.ended", ...options, schema: { ...Base, - messageID: SessionMessage.ID, reason: Started.data.fields.reason, text: Schema.String, recent: Schema.String, @@ -480,25 +473,25 @@ export namespace Compaction { export namespace RevertEvent { export const Staged = Event.durable({ - type: "session.next.revert.staged", + type: "revert.staged", ...options, schema: { ...Base, revert: Revert.State }, }) - export const Cleared = Event.durable({ type: "session.next.revert.cleared", ...options, schema: Base }) + export const Cleared = Event.durable({ type: "revert.cleared", ...options, schema: Base }) export const Committed = Event.durable({ - type: "session.next.revert.committed", + type: "revert.committed", ...options, schema: { ...Base, messageID: SessionMessage.ID }, }) } export const Definitions = Event.inventory( - AgentSwitched, - ModelSwitched, + AgentSelected, + ModelSelected, Moved, Renamed, Forked, - Prompted, + PromptPromoted, PromptAdmitted, ExecutionSettled, ContextUpdated, diff --git a/packages/schema/src/session-message.ts b/packages/schema/src/session-message.ts index 457cf87206..349d04d06e 100644 --- a/packages/schema/src/session-message.ts +++ b/packages/schema/src/session-message.ts @@ -8,10 +8,14 @@ import { FileAttachment, Prompt } from "./prompt.js" import { DateTimeUtcFromMillis, RelativePath, statics } from "./schema.js" import { SessionID } from "./session-id.js" import { ascending } from "./identifier.js" +import { Event } from "./event.js" export const ID = Schema.String.check(Schema.isStartsWith("msg_")).pipe( Schema.brand("Session.Message.ID"), - statics((schema) => ({ create: () => schema.make("msg_" + ascending()) })), + statics((schema) => ({ + create: () => schema.make("msg_" + ascending()), + fromEvent: (eventID: Event.ID) => schema.make(eventID.replace(/^evt_/, "msg_")), + })), ) export type ID = typeof ID.Type @@ -27,19 +31,19 @@ const Base = { time: Schema.Struct({ created: DateTimeUtcFromMillis }), } -export interface AgentSwitched extends Schema.Schema.Type {} -export const AgentSwitched = Schema.Struct({ +export interface AgentSelected extends Schema.Schema.Type {} +export const AgentSelected = Schema.Struct({ ...Base, type: Schema.Literal("agent-switched"), agent: Schema.String, -}).annotate({ identifier: "Session.Message.AgentSwitched" }) +}).annotate({ identifier: "Session.Message.AgentSelected" }) -export interface ModelSwitched extends Schema.Schema.Type {} -export const ModelSwitched = Schema.Struct({ +export interface ModelSelected extends Schema.Schema.Type {} +export const ModelSelected = Schema.Struct({ ...Base, type: Schema.Literal("model-switched"), model: Model.Ref, -}).annotate({ identifier: "Session.Message.ModelSwitched" }) +}).annotate({ identifier: "Session.Message.ModelSelected" }) export interface User extends Schema.Schema.Type {} export const User = Schema.Struct({ @@ -207,8 +211,8 @@ export const Compaction = Schema.Struct({ }).annotate({ identifier: "Session.Message.Compaction" }) export const Message = Schema.Union([ - AgentSwitched, - ModelSwitched, + AgentSelected, + ModelSelected, User, Synthetic, System, @@ -219,5 +223,5 @@ export const Message = Schema.Union([ ]) .pipe(Schema.toTaggedUnion("type")) .annotate({ identifier: "Session.Message" }) -export type Message = AgentSwitched | ModelSwitched | User | Synthetic | System | Skill | Shell | Assistant | Compaction +export type Message = AgentSelected | ModelSelected | User | Synthetic | System | Skill | Shell | Assistant | Compaction export type Type = Message["type"] diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 4e0c6eaa18..9cdf3a787a 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -52,7 +52,7 @@ describe("public event manifest", () => { expect(Session.Event.Definitions).toBe(SessionEvent.Definitions) expect(Workspace.Event).toBe(WorkspaceEvent) expect(Workspace.Event.Definitions).toBe(WorkspaceEvent.Definitions) - expect(EventManifest.Latest.get("session.next.step.ended")).toBe(SessionEvent.Step.Ended) + expect(EventManifest.Latest.get("step.ended")).toBe(SessionEvent.Step.Ended) expect(EventManifest.Latest.get("todo.updated")).toBe(SessionTodo.Event.Updated) expect(EventManifest.Latest.get("agent.updated")).toBe(Agent.Event.Updated) expect(EventManifest.Latest.get("project.updated")).toBe(Project.Event.Updated) @@ -71,8 +71,8 @@ describe("public event manifest", () => { SessionV1.Event.Diff, SessionV1.Event.Error, ]) - expect(EventManifest.Durable.has("session.next.step.ended.1")).toBe(false) - expect(EventManifest.Durable.get("session.next.step.ended.2")).toBe(SessionEvent.Step.Ended) + expect(EventManifest.Durable.get("step.ended.1")).toBe(SessionEvent.Step.Ended) + expect(EventManifest.Durable.has("step.ended.2")).toBe(false) }) test("derives durable definitions from explicit definition durability", () => { @@ -85,37 +85,37 @@ describe("public event manifest", () => { "message.removed.1", "message.part.updated.1", "message.part.removed.1", - "session.next.agent.switched.1", - "session.next.model.switched.1", - "session.next.moved.1", - "session.next.renamed.1", - "session.next.forked.1", - "session.next.prompted.1", - "session.next.prompt.admitted.1", - "session.next.context.updated.1", - "session.next.synthetic.1", - "session.next.skill.activated.1", - "session.next.shell.started.1", - "session.next.shell.ended.1", - "session.next.step.started.1", - "session.next.step.ended.2", - "session.next.step.failed.2", - "session.next.text.started.1", - "session.next.text.ended.1", - "session.next.tool.input.started.1", - "session.next.tool.input.ended.1", - "session.next.tool.called.1", - "session.next.tool.progress.1", - "session.next.tool.success.1", - "session.next.tool.failed.1", - "session.next.reasoning.started.1", - "session.next.reasoning.ended.1", - "session.next.retried.1", - "session.next.compaction.started.1", - "session.next.compaction.ended.1", - "session.next.revert.staged.1", - "session.next.revert.cleared.1", - "session.next.revert.committed.1", + "agent.selected.1", + "model.selected.1", + "session.moved.1", + "renamed.1", + "forked.1", + "prompt.promoted.1", + "prompt.admitted.1", + "session.context.updated.1", + "synthetic.1", + "skill.activated.1", + "shell.started.1", + "shell.ended.1", + "step.started.1", + "step.ended.1", + "step.failed.1", + "text.started.1", + "text.ended.1", + "tool.input.started.1", + "tool.input.ended.1", + "tool.called.1", + "tool.progress.1", + "tool.success.1", + "tool.failed.1", + "reasoning.started.1", + "reasoning.ended.1", + "retried.1", + "compaction.started.1", + "compaction.ended.1", + "revert.staged.1", + "revert.cleared.1", + "revert.committed.1", ].toSorted(), ) expect(SessionEvent.DurableDefinitions).toEqual( diff --git a/packages/sdk-next/test/embedded.test.ts b/packages/sdk-next/test/embedded.test.ts index 81f3d480ad..5419b7e838 100644 --- a/packages/sdk-next/test/embedded.test.ts +++ b/packages/sdk-next/test/embedded.test.ts @@ -78,7 +78,7 @@ it.live( prompt: fixture.sdk.Prompt.make({ text: "Promote this input" }), }) const prompted = yield* opencode.sessions.log({ sessionID: id, follow: true }).pipe( - Stream.filter((event) => event.type === "session.next.prompted" && event.data.messageID === wake.id), + Stream.filter((event) => event.type === "prompt.promoted" && event.data.inputID === wake.id), Stream.runHead, Effect.timeout("10 seconds"), Effect.map(Option.getOrThrow), @@ -119,7 +119,7 @@ it.live( expect(page.data.some((session) => session.id === id)).toBe(true) expect(active).toEqual({ data: {}, watermarks: {} }) expect(admitted.sessionID).toBe(id) - expect(prompted.type).toBe("session.next.prompted") + expect(prompted.type).toBe("prompt.promoted") expect(wakeContext).toContainEqual(expect.objectContaining({ id: wake.id, type: "user" })) expect(contextEntries).toEqual([ { key: "deploy-target", value: "production" }, @@ -127,7 +127,7 @@ it.live( ]) expect(remainingContextEntries).toEqual([{ key: "deploy-target", value: "production" }]) expect(context.some((message) => message.type === "model-switched")).toBe(true) - expect(event).toMatchObject({ type: "session.next.model.switched", durable: { seq: 1 } }) + expect(event).toMatchObject({ type: "model.selected", durable: { seq: 1 } }) expect(message).toEqual(modelMessage) expect(missing.map((error) => error._tag)).toEqual([ "SessionNotFoundError", @@ -149,13 +149,13 @@ it.live( const opencode = yield* fixture.sdk.OpenCode.create() const id = sessionID(fixture) const connected = yield* Latch.make(false) - const prompted = yield* Deferred.make>() + const prompted = yield* Deferred.make>() yield* opencode.events.subscribe().pipe( Stream.runForEach((event) => event.type === "server.connected" ? connected.open - : event.type === "session.next.prompted" && event.data.sessionID === id + : event.type === "prompt.promoted" && event.data.sessionID === id ? Deferred.succeed(prompted, event).pipe(Effect.asVoid) : Effect.void, ), @@ -191,7 +191,7 @@ it.live( Stream.runForEach((notification: OpenCodeEvent) => notification.type === "server.connected" ? ready.open - : notification.type === "session.next.agent.switched" && notification.data.sessionID === id + : notification.type === "agent.selected" && notification.data.sessionID === id ? event.open : Effect.void, ) diff --git a/packages/sdk/js/script/build.ts b/packages/sdk/js/script/build.ts index 8fc0f363e7..d87f8bf98a 100755 --- a/packages/sdk/js/script/build.ts +++ b/packages/sdk/js/script/build.ts @@ -59,7 +59,13 @@ if (schemas) { } visit({ ...document, components: { ...document.components, schemas: undefined } }) for (const name of Object.keys(schemas)) { - if (/^SessionNext\w+1$/.test(name) && !reachable.has(name)) delete schemas[name] + if ( + /^(AgentSelected|ModelSelected|SessionMoved|Renamed|Forked|PromptPromoted|PromptAdmitted|ExecutionSettled|ContextUpdated|Synthetic|SkillActivated|ShellStarted|ShellEnded|StepStarted|StepEnded|StepFailed|TextStarted|TextDelta|TextEnded|ReasoningStarted|ReasoningDelta|ReasoningEnded|ToolInputStarted|ToolInputDelta|ToolInputEnded|ToolCalled|ToolProgress|ToolSuccess|ToolFailed|Retried|CompactionStarted|CompactionDelta|CompactionEnded|RevertStaged|RevertCleared|RevertCommitted)1$/.test( + name, + ) && + !reachable.has(name) + ) + delete schemas[name] } await Bun.write("./openapi.json", JSON.stringify(document)) } @@ -93,7 +99,11 @@ await createClient({ const generatedTypesPath = "./src/v2/gen/types.gen.ts" const generatedTypes = await Bun.file(generatedTypesPath).text() -if (/export type SessionNext\w+1 =/.test(generatedTypes)) { +if ( + /export type (AgentSelected|ModelSelected|SessionMoved|Renamed|Forked|PromptPromoted|PromptAdmitted|ExecutionSettled|ContextUpdated|Synthetic|SkillActivated|ShellStarted|ShellEnded|StepStarted|StepEnded|StepFailed|TextStarted|TextDelta|TextEnded|ReasoningStarted|ReasoningDelta|ReasoningEnded|ToolInputStarted|ToolInputDelta|ToolInputEnded|ToolCalled|ToolProgress|ToolSuccess|ToolFailed|Retried|CompactionStarted|CompactionDelta|CompactionEnded|RevertStaged|RevertCleared|RevertCommitted)1 =/.test( + generatedTypes, + ) +) { throw new Error("Session history generated duplicate Session event variants") } const logTypesPatched = generatedTypes.replace( diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index a1ba35e5ae..d97eb59298 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -17,42 +17,42 @@ export type Event = | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved - | EventSessionNextAgentSwitched - | EventSessionNextModelSwitched - | EventSessionNextMoved - | EventSessionNextRenamed - | EventSessionNextForked - | EventSessionNextPrompted - | EventSessionNextPromptAdmitted - | EventSessionNextExecutionSettled - | EventSessionNextContextUpdated - | EventSessionNextSynthetic - | EventSessionNextSkillActivated - | EventSessionNextShellStarted - | EventSessionNextShellEnded - | EventSessionNextStepStarted - | EventSessionNextStepEnded - | EventSessionNextStepFailed - | EventSessionNextTextStarted - | EventSessionNextTextDelta - | EventSessionNextTextEnded - | EventSessionNextReasoningStarted - | EventSessionNextReasoningDelta - | EventSessionNextReasoningEnded - | EventSessionNextToolInputStarted - | EventSessionNextToolInputDelta - | EventSessionNextToolInputEnded - | EventSessionNextToolCalled - | EventSessionNextToolProgress - | EventSessionNextToolSuccess - | EventSessionNextToolFailed - | EventSessionNextRetried - | EventSessionNextCompactionStarted - | EventSessionNextCompactionDelta - | EventSessionNextCompactionEnded - | EventSessionNextRevertStaged - | EventSessionNextRevertCleared - | EventSessionNextRevertCommitted + | EventAgentSelected + | EventModelSelected + | EventSessionMoved + | EventRenamed + | EventForked + | EventPromptPromoted + | EventPromptAdmitted + | EventExecutionSettled + | EventSessionContextUpdated + | EventSynthetic + | EventSkillActivated + | EventShellStarted + | EventShellEnded + | EventStepStarted + | EventStepEnded + | EventStepFailed + | EventTextStarted + | EventTextDelta + | EventTextEnded + | EventReasoningStarted + | EventReasoningDelta + | EventReasoningEnded + | EventToolInputStarted + | EventToolInputDelta + | EventToolInputEnded + | EventToolCalled + | EventToolProgress + | EventToolSuccess + | EventToolFailed + | EventRetried + | EventCompactionStarted + | EventCompactionDelta + | EventCompactionEnded + | EventRevertStaged + | EventRevertCleared + | EventRevertCommitted | EventMessagePartDelta | EventSessionDiff | EventSessionError @@ -859,80 +859,68 @@ export type GlobalEvent = { } | { id: string - type: "session.next.agent.switched" + type: "agent.selected" properties: { - timestamp: number sessionID: string - messageID: string agent: string } } | { id: string - type: "session.next.model.switched" + type: "model.selected" properties: { - timestamp: number sessionID: string - messageID: string model: ModelRef } } | { id: string - type: "session.next.moved" + type: "session.moved" properties: { - timestamp: number sessionID: string location: LocationRef - subdirectory?: string + subpath?: string } } | { id: string - type: "session.next.renamed" + type: "renamed" properties: { - timestamp: number sessionID: string title: string } } | { id: string - type: "session.next.forked" + type: "forked" properties: { - timestamp: number sessionID: string parentID: string - messageID?: string + from?: string } } | { id: string - type: "session.next.prompted" + type: "prompt.promoted" properties: { - timestamp: number sessionID: string - messageID: string + inputID: string + } + } + | { + id: string + type: "prompt.admitted" + properties: { + sessionID: string + inputID: string prompt: Prompt delivery: "steer" | "queue" } } | { id: string - type: "session.next.prompt.admitted" + type: "execution.settled" properties: { - timestamp: number - sessionID: string - messageID: string - prompt: Prompt - delivery: "steer" | "queue" - } - } - | { - id: string - type: "session.next.execution.settled" - properties: { - timestamp: number sessionID: string outcome: "success" | "failure" | "interrupted" error?: SessionErrorUnknown @@ -940,21 +928,17 @@ export type GlobalEvent = { } | { id: string - type: "session.next.context.updated" + type: "session.context.updated" properties: { - timestamp: number sessionID: string - messageID: string text: string } } | { id: string - type: "session.next.synthetic" + type: "synthetic" properties: { - timestamp: number sessionID: string - messageID: string text: string description?: string metadata?: { @@ -964,31 +948,26 @@ export type GlobalEvent = { } | { id: string - type: "session.next.skill.activated" + type: "skill.activated" properties: { - timestamp: number sessionID: string - messageID: string name: string text: string } } | { id: string - type: "session.next.shell.started" + type: "shell.started" properties: { - timestamp: number sessionID: string - messageID: string callID: string command: string } } | { id: string - type: "session.next.shell.ended" + type: "shell.ended" properties: { - timestamp: number sessionID: string callID: string output: string @@ -996,9 +975,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.step.started" + type: "step.started" properties: { - timestamp: number sessionID: string assistantMessageID: string agent: string @@ -1008,9 +986,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.step.ended" + type: "step.ended" properties: { - timestamp: number sessionID: string assistantMessageID: string finish: string @@ -1030,9 +1007,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.step.failed" + type: "step.failed" properties: { - timestamp: number sessionID: string assistantMessageID: string error: SessionErrorUnknown @@ -1040,9 +1016,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.text.started" + type: "text.started" properties: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -1050,9 +1025,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.text.delta" + type: "text.delta" properties: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -1061,9 +1035,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.text.ended" + type: "text.ended" properties: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -1072,9 +1045,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.reasoning.started" + type: "reasoning.started" properties: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -1083,9 +1055,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.reasoning.delta" + type: "reasoning.delta" properties: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -1094,9 +1065,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.reasoning.ended" + type: "reasoning.ended" properties: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -1106,9 +1076,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.tool.input.started" + type: "tool.input.started" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -1117,9 +1086,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.tool.input.delta" + type: "tool.input.delta" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -1128,9 +1096,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.tool.input.ended" + type: "tool.input.ended" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -1139,9 +1106,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.tool.called" + type: "tool.called" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -1157,9 +1123,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.tool.progress" + type: "tool.progress" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -1171,9 +1136,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.tool.success" + type: "tool.success" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -1191,9 +1155,8 @@ export type GlobalEvent = { } | { id: string - type: "session.next.tool.failed" + type: "tool.failed" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -1207,41 +1170,34 @@ export type GlobalEvent = { } | { id: string - type: "session.next.retried" + type: "retried" properties: { - timestamp: number sessionID: string attempt: number - error: SessionNextRetryError + error: SessionRetryError } } | { id: string - type: "session.next.compaction.started" + type: "compaction.started" properties: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" } } | { id: string - type: "session.next.compaction.delta" + type: "compaction.delta" properties: { - timestamp: number sessionID: string - messageID: string text: string } } | { id: string - type: "session.next.compaction.ended" + type: "compaction.ended" properties: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" text: string recent: string @@ -1249,26 +1205,23 @@ export type GlobalEvent = { } | { id: string - type: "session.next.revert.staged" + type: "revert.staged" properties: { - timestamp: number sessionID: string revert: RevertState } } | { id: string - type: "session.next.revert.cleared" + type: "revert.cleared" properties: { - timestamp: number sessionID: string } } | { id: string - type: "session.next.revert.committed" + type: "revert.committed" properties: { - timestamp: number sessionID: string messageID: string } @@ -1760,37 +1713,37 @@ export type GlobalEvent = { | SyncEventMessageRemoved | SyncEventMessagePartUpdated | SyncEventMessagePartRemoved - | SyncEventSessionNextAgentSwitched - | SyncEventSessionNextModelSwitched - | SyncEventSessionNextMoved - | SyncEventSessionNextRenamed - | SyncEventSessionNextForked - | SyncEventSessionNextPrompted - | SyncEventSessionNextPromptAdmitted - | SyncEventSessionNextContextUpdated - | SyncEventSessionNextSynthetic - | SyncEventSessionNextSkillActivated - | SyncEventSessionNextShellStarted - | SyncEventSessionNextShellEnded - | SyncEventSessionNextStepStarted - | SyncEventSessionNextStepEnded - | SyncEventSessionNextStepFailed - | SyncEventSessionNextTextStarted - | SyncEventSessionNextTextEnded - | SyncEventSessionNextReasoningStarted - | SyncEventSessionNextReasoningEnded - | SyncEventSessionNextToolInputStarted - | SyncEventSessionNextToolInputEnded - | SyncEventSessionNextToolCalled - | SyncEventSessionNextToolProgress - | SyncEventSessionNextToolSuccess - | SyncEventSessionNextToolFailed - | SyncEventSessionNextRetried - | SyncEventSessionNextCompactionStarted - | SyncEventSessionNextCompactionEnded - | SyncEventSessionNextRevertStaged - | SyncEventSessionNextRevertCleared - | SyncEventSessionNextRevertCommitted + | SyncEventAgentSelected + | SyncEventModelSelected + | SyncEventSessionMoved + | SyncEventRenamed + | SyncEventForked + | SyncEventPromptPromoted + | SyncEventPromptAdmitted + | SyncEventSessionContextUpdated + | SyncEventSynthetic + | SyncEventSkillActivated + | SyncEventShellStarted + | SyncEventShellEnded + | SyncEventStepStarted + | SyncEventStepEnded + | SyncEventStepFailed + | SyncEventTextStarted + | SyncEventTextEnded + | SyncEventReasoningStarted + | SyncEventReasoningEnded + | SyncEventToolInputStarted + | SyncEventToolInputEnded + | SyncEventToolCalled + | SyncEventToolProgress + | SyncEventToolSuccess + | SyncEventToolFailed + | SyncEventRetried + | SyncEventCompactionStarted + | SyncEventCompactionEnded + | SyncEventRevertStaged + | SyncEventRevertCleared + | SyncEventRevertCommitted } /** @@ -2910,38 +2863,120 @@ export type UnknownError1 = { ref?: string } +export type Renamed = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "renamed" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + sessionID: string + title: string + } +} + +export type Forked = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "forked" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + sessionID: string + parentID: string + from?: string + } +} + +export type Synthetic = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "synthetic" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + sessionID: string + text: string + description?: string + metadata?: { + [key: string]: unknown + } + } +} + +export type Retried = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "retried" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + sessionID: string + attempt: number + error: SessionRetryError + } +} + export type SessionDurableEvent = - | SessionNextAgentSwitched - | SessionNextModelSwitched - | SessionNextMoved - | SessionNextRenamed - | SessionNextForked - | SessionNextPrompted - | SessionNextPromptAdmitted - | SessionNextContextUpdated - | SessionNextSynthetic - | SessionNextSkillActivated - | SessionNextShellStarted - | SessionNextShellEnded - | SessionNextStepStarted - | SessionNextStepEnded - | SessionNextStepFailed - | SessionNextTextStarted - | SessionNextTextEnded - | SessionNextReasoningStarted - | SessionNextReasoningEnded - | SessionNextToolInputStarted - | SessionNextToolInputEnded - | SessionNextToolCalled - | SessionNextToolProgress - | SessionNextToolSuccess - | SessionNextToolFailed - | SessionNextRetried - | SessionNextCompactionStarted - | SessionNextCompactionEnded - | SessionNextRevertStaged - | SessionNextRevertCleared - | SessionNextRevertCommitted + | AgentSelected + | ModelSelected + | SessionMoved + | Renamed + | Forked + | PromptPromoted + | PromptAdmitted + | SessionContextUpdated + | Synthetic + | SkillActivated + | ShellStarted + | ShellEnded + | StepStarted + | StepEnded + | StepFailed + | TextStarted + | TextEnded + | ReasoningStarted + | ReasoningEnded + | ToolInputStarted + | ToolInputEnded + | ToolCalled + | ToolProgress + | ToolSuccess + | ToolFailed + | Retried + | CompactionStarted + | CompactionEnded + | RevertStaged + | RevertCleared + | RevertCommitted export type SessionLogItem = SessionDurableEvent | EventLogSynced @@ -3016,6 +3051,7 @@ export type Shell1 = { export type SessionStatus2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -3029,6 +3065,7 @@ export type SessionStatus2 = { export type QuestionReplied2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -3043,6 +3080,7 @@ export type QuestionReplied2 = { export type QuestionRejected2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -3067,42 +3105,42 @@ export type V2Event = | MessageRemoved | MessagePartUpdated | MessagePartRemoved - | SessionNextAgentSwitched - | SessionNextModelSwitched - | SessionNextMoved - | SessionNextRenamed - | SessionNextForked - | SessionNextPrompted - | SessionNextPromptAdmitted - | SessionNextExecutionSettled - | SessionNextContextUpdated - | SessionNextSynthetic - | SessionNextSkillActivated - | SessionNextShellStarted - | SessionNextShellEnded - | SessionNextStepStarted - | SessionNextStepEnded - | SessionNextStepFailed - | SessionNextTextStarted - | SessionNextTextDelta - | SessionNextTextEnded - | SessionNextReasoningStarted - | SessionNextReasoningDelta - | SessionNextReasoningEnded - | SessionNextToolInputStarted - | SessionNextToolInputDelta - | SessionNextToolInputEnded - | SessionNextToolCalled - | SessionNextToolProgress - | SessionNextToolSuccess - | SessionNextToolFailed - | SessionNextRetried - | SessionNextCompactionStarted - | SessionNextCompactionDelta - | SessionNextCompactionEnded - | SessionNextRevertStaged - | SessionNextRevertCleared - | SessionNextRevertCommitted + | AgentSelected + | ModelSelected + | SessionMoved + | Renamed + | Forked + | PromptPromoted + | PromptAdmitted + | ExecutionSettled + | SessionContextUpdated + | Synthetic + | SkillActivated + | ShellStarted + | ShellEnded + | StepStarted + | StepEnded + | StepFailed + | TextStarted + | TextDelta + | TextEnded + | ReasoningStarted + | ReasoningDelta + | ReasoningEnded + | ToolInputStarted + | ToolInputDelta + | ToolInputEnded + | ToolCalled + | ToolProgress + | ToolSuccess + | ToolFailed + | Retried + | CompactionStarted + | CompactionDelta + | CompactionEnded + | RevertStaged + | RevertCleared + | RevertCommitted | MessagePartDelta | SessionDiff | SessionError @@ -3338,7 +3376,7 @@ export type ToolFileContent = { export type LlmToolContent = ToolTextContent | ToolFileContent -export type SessionNextRetryError = { +export type SessionRetryError = { message: string statusCode?: number isRetryable: boolean @@ -3661,155 +3699,140 @@ export type SyncEventMessagePartRemoved = { } } -export type SyncEventSessionNextAgentSwitched = { +export type SyncEventAgentSelected = { type: "sync" id: string syncEvent: { - type: "session.next.agent.switched.1" + type: "agent.selected.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string agent: string } } } -export type SyncEventSessionNextModelSwitched = { +export type SyncEventModelSelected = { type: "sync" id: string syncEvent: { - type: "session.next.model.switched.1" + type: "model.selected.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string model: ModelRef } } } -export type SyncEventSessionNextMoved = { +export type SyncEventSessionMoved = { type: "sync" id: string syncEvent: { - type: "session.next.moved.1" + type: "session.moved.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string location: LocationRef - subdirectory?: string + subpath?: string } } } -export type SyncEventSessionNextRenamed = { +export type SyncEventRenamed = { type: "sync" id: string syncEvent: { - type: "session.next.renamed.1" + type: "renamed.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string title: string } } } -export type SyncEventSessionNextForked = { +export type SyncEventForked = { type: "sync" id: string syncEvent: { - type: "session.next.forked.1" + type: "forked.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string parentID: string - messageID?: string + from?: string } } } -export type SyncEventSessionNextPrompted = { +export type SyncEventPromptPromoted = { type: "sync" id: string syncEvent: { - type: "session.next.prompted.1" + type: "prompt.promoted.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string + inputID: string + } + } +} + +export type SyncEventPromptAdmitted = { + type: "sync" + id: string + syncEvent: { + type: "prompt.admitted.1" + id: string + seq: number + aggregateID: string + data: { + sessionID: string + inputID: string prompt: Prompt delivery: "steer" | "queue" } } } -export type SyncEventSessionNextPromptAdmitted = { +export type SyncEventSessionContextUpdated = { type: "sync" id: string syncEvent: { - type: "session.next.prompt.admitted.1" + type: "session.context.updated.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string - prompt: Prompt - delivery: "steer" | "queue" - } - } -} - -export type SyncEventSessionNextContextUpdated = { - type: "sync" - id: string - syncEvent: { - type: "session.next.context.updated.1" - id: string - seq: number - aggregateID: string - data: { - timestamp: number - sessionID: string - messageID: string text: string } } } -export type SyncEventSessionNextSynthetic = { +export type SyncEventSynthetic = { type: "sync" id: string syncEvent: { - type: "session.next.synthetic.1" + type: "synthetic.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string text: string description?: string metadata?: { @@ -3819,52 +3842,47 @@ export type SyncEventSessionNextSynthetic = { } } -export type SyncEventSessionNextSkillActivated = { +export type SyncEventSkillActivated = { type: "sync" id: string syncEvent: { - type: "session.next.skill.activated.1" + type: "skill.activated.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string name: string text: string } } } -export type SyncEventSessionNextShellStarted = { +export type SyncEventShellStarted = { type: "sync" id: string syncEvent: { - type: "session.next.shell.started.1" + type: "shell.started.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string callID: string command: string } } } -export type SyncEventSessionNextShellEnded = { +export type SyncEventShellEnded = { type: "sync" id: string syncEvent: { - type: "session.next.shell.ended.1" + type: "shell.ended.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string callID: string output: string @@ -3872,16 +3890,15 @@ export type SyncEventSessionNextShellEnded = { } } -export type SyncEventSessionNextStepStarted = { +export type SyncEventStepStarted = { type: "sync" id: string syncEvent: { - type: "session.next.step.started.1" + type: "step.started.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string agent: string @@ -3891,16 +3908,15 @@ export type SyncEventSessionNextStepStarted = { } } -export type SyncEventSessionNextStepEnded = { +export type SyncEventStepEnded = { type: "sync" id: string syncEvent: { - type: "session.next.step.ended.2" + type: "step.ended.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string finish: string @@ -3920,16 +3936,15 @@ export type SyncEventSessionNextStepEnded = { } } -export type SyncEventSessionNextStepFailed = { +export type SyncEventStepFailed = { type: "sync" id: string syncEvent: { - type: "session.next.step.failed.2" + type: "step.failed.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string error: SessionErrorUnknown @@ -3937,16 +3952,15 @@ export type SyncEventSessionNextStepFailed = { } } -export type SyncEventSessionNextTextStarted = { +export type SyncEventTextStarted = { type: "sync" id: string syncEvent: { - type: "session.next.text.started.1" + type: "text.started.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -3954,16 +3968,15 @@ export type SyncEventSessionNextTextStarted = { } } -export type SyncEventSessionNextTextEnded = { +export type SyncEventTextEnded = { type: "sync" id: string syncEvent: { - type: "session.next.text.ended.1" + type: "text.ended.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -3972,16 +3985,15 @@ export type SyncEventSessionNextTextEnded = { } } -export type SyncEventSessionNextReasoningStarted = { +export type SyncEventReasoningStarted = { type: "sync" id: string syncEvent: { - type: "session.next.reasoning.started.1" + type: "reasoning.started.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -3990,16 +4002,15 @@ export type SyncEventSessionNextReasoningStarted = { } } -export type SyncEventSessionNextReasoningEnded = { +export type SyncEventReasoningEnded = { type: "sync" id: string syncEvent: { - type: "session.next.reasoning.ended.1" + type: "reasoning.ended.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -4009,16 +4020,15 @@ export type SyncEventSessionNextReasoningEnded = { } } -export type SyncEventSessionNextToolInputStarted = { +export type SyncEventToolInputStarted = { type: "sync" id: string syncEvent: { - type: "session.next.tool.input.started.1" + type: "tool.input.started.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -4027,16 +4037,15 @@ export type SyncEventSessionNextToolInputStarted = { } } -export type SyncEventSessionNextToolInputEnded = { +export type SyncEventToolInputEnded = { type: "sync" id: string syncEvent: { - type: "session.next.tool.input.ended.1" + type: "tool.input.ended.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -4045,16 +4054,15 @@ export type SyncEventSessionNextToolInputEnded = { } } -export type SyncEventSessionNextToolCalled = { +export type SyncEventToolCalled = { type: "sync" id: string syncEvent: { - type: "session.next.tool.called.1" + type: "tool.called.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -4070,16 +4078,15 @@ export type SyncEventSessionNextToolCalled = { } } -export type SyncEventSessionNextToolProgress = { +export type SyncEventToolProgress = { type: "sync" id: string syncEvent: { - type: "session.next.tool.progress.1" + type: "tool.progress.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -4091,16 +4098,15 @@ export type SyncEventSessionNextToolProgress = { } } -export type SyncEventSessionNextToolSuccess = { +export type SyncEventToolSuccess = { type: "sync" id: string syncEvent: { - type: "session.next.tool.success.1" + type: "tool.success.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -4118,16 +4124,15 @@ export type SyncEventSessionNextToolSuccess = { } } -export type SyncEventSessionNextToolFailed = { +export type SyncEventToolFailed = { type: "sync" id: string syncEvent: { - type: "session.next.tool.failed.1" + type: "tool.failed.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -4141,52 +4146,47 @@ export type SyncEventSessionNextToolFailed = { } } -export type SyncEventSessionNextRetried = { +export type SyncEventRetried = { type: "sync" id: string syncEvent: { - type: "session.next.retried.1" + type: "retried.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string attempt: number - error: SessionNextRetryError + error: SessionRetryError } } } -export type SyncEventSessionNextCompactionStarted = { +export type SyncEventCompactionStarted = { type: "sync" id: string syncEvent: { - type: "session.next.compaction.started.1" + type: "compaction.started.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" } } } -export type SyncEventSessionNextCompactionEnded = { +export type SyncEventCompactionEnded = { type: "sync" id: string syncEvent: { - type: "session.next.compaction.ended.1" + type: "compaction.ended.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" text: string recent: string @@ -4194,47 +4194,44 @@ export type SyncEventSessionNextCompactionEnded = { } } -export type SyncEventSessionNextRevertStaged = { +export type SyncEventRevertStaged = { type: "sync" id: string syncEvent: { - type: "session.next.revert.staged.1" + type: "revert.staged.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string revert: RevertState } } } -export type SyncEventSessionNextRevertCleared = { +export type SyncEventRevertCleared = { type: "sync" id: string syncEvent: { - type: "session.next.revert.cleared.1" + type: "revert.cleared.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string } } } -export type SyncEventSessionNextRevertCommitted = { +export type SyncEventRevertCommitted = { type: "sync" id: string syncEvent: { - type: "session.next.revert.committed.1" + type: "revert.committed.1" id: string seq: number aggregateID: string data: { - timestamp: number sessionID: string messageID: string } @@ -4375,7 +4372,7 @@ export type SessionInputAdmitted = { promotedSeq?: number } -export type SessionMessageAgentSwitched = { +export type SessionMessageAgentSelected = { id: string metadata?: { [key: string]: unknown @@ -4387,7 +4384,7 @@ export type SessionMessageAgentSwitched = { agent: string } -export type SessionMessageModelSwitched = { +export type SessionMessageModelSelected = { id: string metadata?: { [key: string]: unknown @@ -4596,8 +4593,8 @@ export type SessionMessageCompaction = { } export type SessionMessage = - | SessionMessageAgentSwitched - | SessionMessageModelSwitched + | SessionMessageAgentSelected + | SessionMessageModelSelected | SessionMessageUser | SessionMessageSynthetic | SessionMessageSystem @@ -4613,12 +4610,13 @@ export type SessionContextEntryInfo = { value: unknown } -export type SessionNextAgentSwitched = { +export type AgentSelected = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.agent.switched" + type: "agent.selected" durable: { aggregateID: string seq: number @@ -4626,19 +4624,18 @@ export type SessionNextAgentSwitched = { } location?: LocationRef data: { - timestamp: number sessionID: string - messageID: string agent: string } } -export type SessionNextModelSwitched = { +export type ModelSelected = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.model.switched" + type: "model.selected" durable: { aggregateID: string seq: number @@ -4646,19 +4643,18 @@ export type SessionNextModelSwitched = { } location?: LocationRef data: { - timestamp: number sessionID: string - messageID: string model: ModelRef } } -export type SessionNextMoved = { +export type SessionMoved = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.moved" + type: "session.moved" durable: { aggregateID: string seq: number @@ -4666,19 +4662,19 @@ export type SessionNextMoved = { } location?: LocationRef data: { - timestamp: number sessionID: string location: LocationRef - subdirectory?: string + subpath?: string } } -export type SessionNextRenamed = { +export type PromptPromoted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.renamed" + type: "prompt.promoted" durable: { aggregateID: string seq: number @@ -4686,18 +4682,18 @@ export type SessionNextRenamed = { } location?: LocationRef data: { - timestamp: number sessionID: string - title: string + inputID: string } } -export type SessionNextForked = { +export type PromptAdmitted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.forked" + type: "prompt.admitted" durable: { aggregateID: string seq: number @@ -4705,40 +4701,20 @@ export type SessionNextForked = { } location?: LocationRef data: { - timestamp: number sessionID: string - parentID: string - messageID?: string - } -} - -export type SessionNextPrompted = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.prompted" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - timestamp: number - sessionID: string - messageID: string + inputID: string prompt: Prompt delivery: "steer" | "queue" } } -export type SessionNextPromptAdmitted = { +export type SessionContextUpdated = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.prompt.admitted" + type: "session.context.updated" durable: { aggregateID: string seq: number @@ -4746,40 +4722,18 @@ export type SessionNextPromptAdmitted = { } location?: LocationRef data: { - timestamp: number sessionID: string - messageID: string - prompt: Prompt - delivery: "steer" | "queue" - } -} - -export type SessionNextContextUpdated = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.context.updated" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - timestamp: number - sessionID: string - messageID: string text: string } } -export type SessionNextSynthetic = { +export type SkillActivated = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.synthetic" + type: "skill.activated" durable: { aggregateID: string seq: number @@ -4787,44 +4741,19 @@ export type SessionNextSynthetic = { } location?: LocationRef data: { - timestamp: number sessionID: string - messageID: string - text: string - description?: string - metadata?: { - [key: string]: unknown - } - } -} - -export type SessionNextSkillActivated = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.skill.activated" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - timestamp: number - sessionID: string - messageID: string name: string text: string } } -export type SessionNextShellStarted = { +export type ShellStarted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.shell.started" + type: "shell.started" durable: { aggregateID: string seq: number @@ -4832,20 +4761,19 @@ export type SessionNextShellStarted = { } location?: LocationRef data: { - timestamp: number sessionID: string - messageID: string callID: string command: string } } -export type SessionNextShellEnded = { +export type ShellEnded = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.shell.ended" + type: "shell.ended" durable: { aggregateID: string seq: number @@ -4853,19 +4781,19 @@ export type SessionNextShellEnded = { } location?: LocationRef data: { - timestamp: number sessionID: string callID: string output: string } } -export type SessionNextStepStarted = { +export type StepStarted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.step.started" + type: "step.started" durable: { aggregateID: string seq: number @@ -4873,7 +4801,6 @@ export type SessionNextStepStarted = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string agent: string @@ -4882,12 +4809,13 @@ export type SessionNextStepStarted = { } } -export type SessionNextStepEnded = { +export type StepEnded = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.step.ended" + type: "step.ended" durable: { aggregateID: string seq: number @@ -4895,7 +4823,6 @@ export type SessionNextStepEnded = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string finish: string @@ -4914,12 +4841,13 @@ export type SessionNextStepEnded = { } } -export type SessionNextStepFailed = { +export type StepFailed = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.step.failed" + type: "step.failed" durable: { aggregateID: string seq: number @@ -4927,19 +4855,19 @@ export type SessionNextStepFailed = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string error: SessionErrorUnknown } } -export type SessionNextTextStarted = { +export type TextStarted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.text.started" + type: "text.started" durable: { aggregateID: string seq: number @@ -4947,19 +4875,19 @@ export type SessionNextTextStarted = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string textID: string } } -export type SessionNextTextEnded = { +export type TextEnded = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.text.ended" + type: "text.ended" durable: { aggregateID: string seq: number @@ -4967,7 +4895,6 @@ export type SessionNextTextEnded = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -4975,12 +4902,13 @@ export type SessionNextTextEnded = { } } -export type SessionNextReasoningStarted = { +export type ReasoningStarted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.reasoning.started" + type: "reasoning.started" durable: { aggregateID: string seq: number @@ -4988,7 +4916,6 @@ export type SessionNextReasoningStarted = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -4996,12 +4923,13 @@ export type SessionNextReasoningStarted = { } } -export type SessionNextReasoningEnded = { +export type ReasoningEnded = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.reasoning.ended" + type: "reasoning.ended" durable: { aggregateID: string seq: number @@ -5009,7 +4937,6 @@ export type SessionNextReasoningEnded = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -5018,12 +4945,13 @@ export type SessionNextReasoningEnded = { } } -export type SessionNextToolInputStarted = { +export type ToolInputStarted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.input.started" + type: "tool.input.started" durable: { aggregateID: string seq: number @@ -5031,7 +4959,6 @@ export type SessionNextToolInputStarted = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -5039,12 +4966,13 @@ export type SessionNextToolInputStarted = { } } -export type SessionNextToolInputEnded = { +export type ToolInputEnded = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.input.ended" + type: "tool.input.ended" durable: { aggregateID: string seq: number @@ -5052,7 +4980,6 @@ export type SessionNextToolInputEnded = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -5060,12 +4987,13 @@ export type SessionNextToolInputEnded = { } } -export type SessionNextToolCalled = { +export type ToolCalled = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.called" + type: "tool.called" durable: { aggregateID: string seq: number @@ -5073,7 +5001,6 @@ export type SessionNextToolCalled = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -5088,12 +5015,13 @@ export type SessionNextToolCalled = { } } -export type SessionNextToolProgress = { +export type ToolProgress = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.progress" + type: "tool.progress" durable: { aggregateID: string seq: number @@ -5101,7 +5029,6 @@ export type SessionNextToolProgress = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -5112,12 +5039,13 @@ export type SessionNextToolProgress = { } } -export type SessionNextToolSuccess = { +export type ToolSuccess = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.success" + type: "tool.success" durable: { aggregateID: string seq: number @@ -5125,7 +5053,6 @@ export type SessionNextToolSuccess = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -5142,12 +5069,13 @@ export type SessionNextToolSuccess = { } } -export type SessionNextToolFailed = { +export type ToolFailed = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.failed" + type: "tool.failed" durable: { aggregateID: string seq: number @@ -5155,7 +5083,6 @@ export type SessionNextToolFailed = { } location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -5168,12 +5095,13 @@ export type SessionNextToolFailed = { } } -export type SessionNextRetried = { +export type CompactionStarted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.retried" + type: "compaction.started" durable: { aggregateID: string seq: number @@ -5181,39 +5109,18 @@ export type SessionNextRetried = { } location?: LocationRef data: { - timestamp: number sessionID: string - attempt: number - error: SessionNextRetryError - } -} - -export type SessionNextCompactionStarted = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.compaction.started" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - timestamp: number - sessionID: string - messageID: string reason: "auto" | "manual" } } -export type SessionNextCompactionEnded = { +export type CompactionEnded = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.compaction.ended" + type: "compaction.ended" durable: { aggregateID: string seq: number @@ -5221,21 +5128,20 @@ export type SessionNextCompactionEnded = { } location?: LocationRef data: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" text: string recent: string } } -export type SessionNextRevertStaged = { +export type RevertStaged = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.revert.staged" + type: "revert.staged" durable: { aggregateID: string seq: number @@ -5243,18 +5149,18 @@ export type SessionNextRevertStaged = { } location?: LocationRef data: { - timestamp: number sessionID: string revert: RevertState } } -export type SessionNextRevertCleared = { +export type RevertCleared = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.revert.cleared" + type: "revert.cleared" durable: { aggregateID: string seq: number @@ -5262,17 +5168,17 @@ export type SessionNextRevertCleared = { } location?: LocationRef data: { - timestamp: number sessionID: string } } -export type SessionNextRevertCommitted = { +export type RevertCommitted = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.revert.committed" + type: "revert.committed" durable: { aggregateID: string seq: number @@ -5280,7 +5186,6 @@ export type SessionNextRevertCommitted = { } location?: LocationRef data: { - timestamp: number sessionID: string messageID: string } @@ -5615,6 +5520,7 @@ export type SkillV2Info = { export type ModelsDevRefreshed = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5627,6 +5533,7 @@ export type ModelsDevRefreshed = { export type IntegrationUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5639,6 +5546,7 @@ export type IntegrationUpdated = { export type IntegrationConnectionUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5651,6 +5559,7 @@ export type IntegrationConnectionUpdated = { export type CatalogUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5663,6 +5572,7 @@ export type CatalogUpdated = { export type AgentUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5675,6 +5585,7 @@ export type AgentUpdated = { export type SessionCreated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5693,6 +5604,7 @@ export type SessionCreated = { export type SessionUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5711,6 +5623,7 @@ export type SessionUpdated = { export type SessionDeleted = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5729,6 +5642,7 @@ export type SessionDeleted = { export type MessageUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5747,6 +5661,7 @@ export type MessageUpdated = { export type MessageRemoved = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5765,6 +5680,7 @@ export type MessageRemoved = { export type MessagePartUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5784,6 +5700,7 @@ export type MessagePartUpdated = { export type MessagePartRemoved = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5801,30 +5718,30 @@ export type MessagePartRemoved = { } } -export type SessionNextExecutionSettled = { +export type ExecutionSettled = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.execution.settled" + type: "execution.settled" location?: LocationRef data: { - timestamp: number sessionID: string outcome: "success" | "failure" | "interrupted" error?: SessionErrorUnknown } } -export type SessionNextTextDelta = { +export type TextDelta = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.text.delta" + type: "text.delta" location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -5832,15 +5749,15 @@ export type SessionNextTextDelta = { } } -export type SessionNextReasoningDelta = { +export type ReasoningDelta = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.reasoning.delta" + type: "reasoning.delta" location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -5848,15 +5765,15 @@ export type SessionNextReasoningDelta = { } } -export type SessionNextToolInputDelta = { +export type ToolInputDelta = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.input.delta" + type: "tool.input.delta" location?: LocationRef data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -5864,23 +5781,23 @@ export type SessionNextToolInputDelta = { } } -export type SessionNextCompactionDelta = { +export type CompactionDelta = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.compaction.delta" + type: "compaction.delta" location?: LocationRef data: { - timestamp: number sessionID: string - messageID: string text: string } } export type MessagePartDelta = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5897,6 +5814,7 @@ export type MessagePartDelta = { export type SessionDiff = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5910,6 +5828,7 @@ export type SessionDiff = { export type SessionError = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5931,6 +5850,7 @@ export type SessionError = { export type InstallationUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5943,6 +5863,7 @@ export type InstallationUpdated = { export type InstallationUpdateAvailable = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5955,6 +5876,7 @@ export type InstallationUpdateAvailable = { export type FileEdited = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5967,6 +5889,7 @@ export type FileEdited = { export type ReferenceUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5979,6 +5902,7 @@ export type ReferenceUpdated = { export type PermissionV2Asked = { id: string + created: number metadata?: { [key: string]: unknown } @@ -5999,6 +5923,7 @@ export type PermissionV2Asked = { export type PermissionV2Replied = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6013,6 +5938,7 @@ export type PermissionV2Replied = { export type PluginAdded = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6025,6 +5951,7 @@ export type PluginAdded = { export type ProjectDirectoriesUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6037,6 +5964,7 @@ export type ProjectDirectoriesUpdated = { export type CommandUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6049,6 +5977,7 @@ export type CommandUpdated = { export type SkillUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6061,6 +5990,7 @@ export type SkillUpdated = { export type FileWatcherUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6074,6 +6004,7 @@ export type FileWatcherUpdated = { export type PtyCreated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6086,6 +6017,7 @@ export type PtyCreated = { export type PtyUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6098,6 +6030,7 @@ export type PtyUpdated = { export type PtyExited = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6111,6 +6044,7 @@ export type PtyExited = { export type PtyDeleted = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6123,6 +6057,7 @@ export type PtyDeleted = { export type ShellCreated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6135,6 +6070,7 @@ export type ShellCreated = { export type ShellExited = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6149,6 +6085,7 @@ export type ShellExited = { export type ShellDeleted = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6161,6 +6098,7 @@ export type ShellDeleted = { export type QuestionV2Asked = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6179,6 +6117,7 @@ export type QuestionV2Asked = { export type QuestionV2Replied = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6193,6 +6132,7 @@ export type QuestionV2Replied = { export type QuestionV2Rejected = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6236,6 +6176,7 @@ export type FormIntegerField1 = { export type FormCreated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6250,6 +6191,7 @@ export type FormValue1 = string | number | "NaN" | "Infinity" | "-Infinity" | bo export type FormReplied = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6264,6 +6206,7 @@ export type FormReplied = { export type FormCancelled = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6277,6 +6220,7 @@ export type FormCancelled = { export type TodoUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6290,6 +6234,7 @@ export type TodoUpdated = { export type LspUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6302,6 +6247,7 @@ export type LspUpdated = { export type PermissionAsked = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6325,6 +6271,7 @@ export type PermissionAsked = { export type PermissionReplied = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6339,6 +6286,7 @@ export type PermissionReplied = { export type TuiPromptAppend = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6351,6 +6299,7 @@ export type TuiPromptAppend = { export type TuiCommandExecute = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6381,6 +6330,7 @@ export type TuiCommandExecute = { export type TuiToastShow = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6396,6 +6346,7 @@ export type TuiToastShow = { export type TuiSessionSelect = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6411,6 +6362,7 @@ export type TuiSessionSelect = { export type McpToolsChanged = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6423,6 +6375,7 @@ export type McpToolsChanged = { export type McpBrowserOpenFailed = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6436,6 +6389,7 @@ export type McpBrowserOpenFailed = { export type McpStatusChanged = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6448,6 +6402,7 @@ export type McpStatusChanged = { export type CommandExecuted = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6463,6 +6418,7 @@ export type CommandExecuted = { export type ProjectUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6482,6 +6438,7 @@ export type ProjectUpdated = { export type SessionIdle = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6494,6 +6451,7 @@ export type SessionIdle = { export type QuestionAsked = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6512,6 +6470,7 @@ export type QuestionAsked = { export type SessionCompacted = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6524,6 +6483,7 @@ export type SessionCompacted = { export type VcsBranchUpdated = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6536,6 +6496,7 @@ export type VcsBranchUpdated = { export type WorkspaceReady = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6548,6 +6509,7 @@ export type WorkspaceReady = { export type WorkspaceFailed = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6560,6 +6522,7 @@ export type WorkspaceFailed = { export type WorkspaceStatus = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6573,6 +6536,7 @@ export type WorkspaceStatus = { export type WorktreeReady = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6586,6 +6550,7 @@ export type WorktreeReady = { export type WorktreeFailed = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6598,6 +6563,7 @@ export type WorktreeFailed = { export type ServerConnected = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6610,6 +6576,7 @@ export type ServerConnected = { export type GlobalDisposed = { id: string + created: number metadata?: { [key: string]: unknown } @@ -6787,113 +6754,97 @@ export type EventMessagePartRemoved = { } } -export type EventSessionNextAgentSwitched = { +export type EventAgentSelected = { id: string - type: "session.next.agent.switched" + type: "agent.selected" properties: { - timestamp: number sessionID: string - messageID: string agent: string } } -export type EventSessionNextModelSwitched = { +export type EventModelSelected = { id: string - type: "session.next.model.switched" + type: "model.selected" properties: { - timestamp: number sessionID: string - messageID: string model: ModelRef } } -export type EventSessionNextMoved = { +export type EventSessionMoved = { id: string - type: "session.next.moved" + type: "session.moved" properties: { - timestamp: number sessionID: string location: LocationRef - subdirectory?: string + subpath?: string } } -export type EventSessionNextRenamed = { +export type EventRenamed = { id: string - type: "session.next.renamed" + type: "renamed" properties: { - timestamp: number sessionID: string title: string } } -export type EventSessionNextForked = { +export type EventForked = { id: string - type: "session.next.forked" + type: "forked" properties: { - timestamp: number sessionID: string parentID: string - messageID?: string + from?: string } } -export type EventSessionNextPrompted = { +export type EventPromptPromoted = { id: string - type: "session.next.prompted" + type: "prompt.promoted" properties: { - timestamp: number sessionID: string - messageID: string + inputID: string + } +} + +export type EventPromptAdmitted = { + id: string + type: "prompt.admitted" + properties: { + sessionID: string + inputID: string prompt: Prompt delivery: "steer" | "queue" } } -export type EventSessionNextPromptAdmitted = { +export type EventExecutionSettled = { id: string - type: "session.next.prompt.admitted" + type: "execution.settled" properties: { - timestamp: number - sessionID: string - messageID: string - prompt: Prompt - delivery: "steer" | "queue" - } -} - -export type EventSessionNextExecutionSettled = { - id: string - type: "session.next.execution.settled" - properties: { - timestamp: number sessionID: string outcome: "success" | "failure" | "interrupted" error?: SessionErrorUnknown } } -export type EventSessionNextContextUpdated = { +export type EventSessionContextUpdated = { id: string - type: "session.next.context.updated" + type: "session.context.updated" properties: { - timestamp: number sessionID: string - messageID: string text: string } } -export type EventSessionNextSynthetic = { +export type EventSynthetic = { id: string - type: "session.next.synthetic" + type: "synthetic" properties: { - timestamp: number sessionID: string - messageID: string text: string description?: string metadata?: { @@ -6902,46 +6853,40 @@ export type EventSessionNextSynthetic = { } } -export type EventSessionNextSkillActivated = { +export type EventSkillActivated = { id: string - type: "session.next.skill.activated" + type: "skill.activated" properties: { - timestamp: number sessionID: string - messageID: string name: string text: string } } -export type EventSessionNextShellStarted = { +export type EventShellStarted = { id: string - type: "session.next.shell.started" + type: "shell.started" properties: { - timestamp: number sessionID: string - messageID: string callID: string command: string } } -export type EventSessionNextShellEnded = { +export type EventShellEnded = { id: string - type: "session.next.shell.ended" + type: "shell.ended" properties: { - timestamp: number sessionID: string callID: string output: string } } -export type EventSessionNextStepStarted = { +export type EventStepStarted = { id: string - type: "session.next.step.started" + type: "step.started" properties: { - timestamp: number sessionID: string assistantMessageID: string agent: string @@ -6950,11 +6895,10 @@ export type EventSessionNextStepStarted = { } } -export type EventSessionNextStepEnded = { +export type EventStepEnded = { id: string - type: "session.next.step.ended" + type: "step.ended" properties: { - timestamp: number sessionID: string assistantMessageID: string finish: string @@ -6973,33 +6917,30 @@ export type EventSessionNextStepEnded = { } } -export type EventSessionNextStepFailed = { +export type EventStepFailed = { id: string - type: "session.next.step.failed" + type: "step.failed" properties: { - timestamp: number sessionID: string assistantMessageID: string error: SessionErrorUnknown } } -export type EventSessionNextTextStarted = { +export type EventTextStarted = { id: string - type: "session.next.text.started" + type: "text.started" properties: { - timestamp: number sessionID: string assistantMessageID: string textID: string } } -export type EventSessionNextTextDelta = { +export type EventTextDelta = { id: string - type: "session.next.text.delta" + type: "text.delta" properties: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -7007,11 +6948,10 @@ export type EventSessionNextTextDelta = { } } -export type EventSessionNextTextEnded = { +export type EventTextEnded = { id: string - type: "session.next.text.ended" + type: "text.ended" properties: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -7019,11 +6959,10 @@ export type EventSessionNextTextEnded = { } } -export type EventSessionNextReasoningStarted = { +export type EventReasoningStarted = { id: string - type: "session.next.reasoning.started" + type: "reasoning.started" properties: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -7031,11 +6970,10 @@ export type EventSessionNextReasoningStarted = { } } -export type EventSessionNextReasoningDelta = { +export type EventReasoningDelta = { id: string - type: "session.next.reasoning.delta" + type: "reasoning.delta" properties: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -7043,11 +6981,10 @@ export type EventSessionNextReasoningDelta = { } } -export type EventSessionNextReasoningEnded = { +export type EventReasoningEnded = { id: string - type: "session.next.reasoning.ended" + type: "reasoning.ended" properties: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -7056,11 +6993,10 @@ export type EventSessionNextReasoningEnded = { } } -export type EventSessionNextToolInputStarted = { +export type EventToolInputStarted = { id: string - type: "session.next.tool.input.started" + type: "tool.input.started" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -7068,11 +7004,10 @@ export type EventSessionNextToolInputStarted = { } } -export type EventSessionNextToolInputDelta = { +export type EventToolInputDelta = { id: string - type: "session.next.tool.input.delta" + type: "tool.input.delta" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -7080,11 +7015,10 @@ export type EventSessionNextToolInputDelta = { } } -export type EventSessionNextToolInputEnded = { +export type EventToolInputEnded = { id: string - type: "session.next.tool.input.ended" + type: "tool.input.ended" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -7092,11 +7026,10 @@ export type EventSessionNextToolInputEnded = { } } -export type EventSessionNextToolCalled = { +export type EventToolCalled = { id: string - type: "session.next.tool.called" + type: "tool.called" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -7111,11 +7044,10 @@ export type EventSessionNextToolCalled = { } } -export type EventSessionNextToolProgress = { +export type EventToolProgress = { id: string - type: "session.next.tool.progress" + type: "tool.progress" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -7126,11 +7058,10 @@ export type EventSessionNextToolProgress = { } } -export type EventSessionNextToolSuccess = { +export type EventToolSuccess = { id: string - type: "session.next.tool.success" + type: "tool.success" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -7147,11 +7078,10 @@ export type EventSessionNextToolSuccess = { } } -export type EventSessionNextToolFailed = { +export type EventToolFailed = { id: string - type: "session.next.tool.failed" + type: "tool.failed" properties: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -7164,76 +7094,66 @@ export type EventSessionNextToolFailed = { } } -export type EventSessionNextRetried = { +export type EventRetried = { id: string - type: "session.next.retried" + type: "retried" properties: { - timestamp: number sessionID: string attempt: number - error: SessionNextRetryError + error: SessionRetryError } } -export type EventSessionNextCompactionStarted = { +export type EventCompactionStarted = { id: string - type: "session.next.compaction.started" + type: "compaction.started" properties: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" } } -export type EventSessionNextCompactionDelta = { +export type EventCompactionDelta = { id: string - type: "session.next.compaction.delta" + type: "compaction.delta" properties: { - timestamp: number sessionID: string - messageID: string text: string } } -export type EventSessionNextCompactionEnded = { +export type EventCompactionEnded = { id: string - type: "session.next.compaction.ended" + type: "compaction.ended" properties: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" text: string recent: string } } -export type EventSessionNextRevertStaged = { +export type EventRevertStaged = { id: string - type: "session.next.revert.staged" + type: "revert.staged" properties: { - timestamp: number sessionID: string revert: RevertState } } -export type EventSessionNextRevertCleared = { +export type EventRevertCleared = { id: string - type: "session.next.revert.cleared" + type: "revert.cleared" properties: { - timestamp: number sessionID: string } } -export type EventSessionNextRevertCommitted = { +export type EventRevertCommitted = { id: string - type: "session.next.revert.committed" + type: "revert.committed" properties: { - timestamp: number sessionID: string messageID: string } @@ -8035,7 +7955,7 @@ export type UnknownErrorV2 = { ref?: string | null } -export type SessionMessageAgentSwitched2 = { +export type SessionMessageAgentSelected2 = { id: string metadata?: { [key: string]: unknown @@ -8047,7 +7967,7 @@ export type SessionMessageAgentSwitched2 = { agent: string } -export type SessionMessageModelSwitched2 = { +export type SessionMessageModelSelected2 = { id: string metadata?: { [key: string]: unknown @@ -8281,8 +8201,8 @@ export type SessionMessageCompaction2 = { } export type SessionMessage2 = - | SessionMessageAgentSwitched2 - | SessionMessageModelSwitched2 + | SessionMessageAgentSelected2 + | SessionMessageModelSelected2 | SessionMessageUser2 | SessionMessageSynthetic2 | SessionMessageSystem2 @@ -8301,12 +8221,13 @@ export type SessionContextEntryInfo2 = { value: unknown } -export type SessionNextAgentSwitched2 = { +export type AgentSelected2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.agent.switched" + type: "agent.selected" durable: { aggregateID: string seq: number @@ -8314,19 +8235,18 @@ export type SessionNextAgentSwitched2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string agent: string } } -export type SessionNextModelSwitched2 = { +export type ModelSelected2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.model.switched" + type: "model.selected" durable: { aggregateID: string seq: number @@ -8334,19 +8254,18 @@ export type SessionNextModelSwitched2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string model: ModelRef2 } } -export type SessionNextMoved2 = { +export type SessionMoved2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.moved" + type: "session.moved" durable: { aggregateID: string seq: number @@ -8354,19 +8273,19 @@ export type SessionNextMoved2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string location: LocationRef2 - subdirectory?: string + subpath?: string } } -export type SessionNextRenamed2 = { +export type RenamedV2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.renamed" + type: "renamed" durable: { aggregateID: string seq: number @@ -8374,18 +8293,18 @@ export type SessionNextRenamed2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string title: string } } -export type SessionNextForked2 = { +export type ForkedV2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.forked" + type: "forked" durable: { aggregateID: string seq: number @@ -8393,19 +8312,19 @@ export type SessionNextForked2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string parentID: string - messageID?: string + from?: string } } -export type SessionNextPrompted2 = { +export type PromptPromoted2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.prompted" + type: "prompt.promoted" durable: { aggregateID: string seq: number @@ -8413,20 +8332,39 @@ export type SessionNextPrompted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string + inputID: string + } +} + +export type PromptAdmitted2 = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "prompt.admitted" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef2 + data: { + sessionID: string + inputID: string prompt: PromptV2 delivery: "steer" | "queue" } } -export type SessionNextPromptAdmitted2 = { +export type SessionContextUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.prompt.admitted" + type: "session.context.updated" durable: { aggregateID: string seq: number @@ -8434,40 +8372,18 @@ export type SessionNextPromptAdmitted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string - prompt: PromptV2 - delivery: "steer" | "queue" - } -} - -export type SessionNextContextUpdated2 = { - id: string - metadata?: { - [key: string]: unknown - } - type: "session.next.context.updated" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef2 - data: { - timestamp: number - sessionID: string - messageID: string text: string } } -export type SessionNextSynthetic2 = { +export type SyntheticV2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.synthetic" + type: "synthetic" durable: { aggregateID: string seq: number @@ -8475,9 +8391,7 @@ export type SessionNextSynthetic2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string text: string description?: string metadata?: { @@ -8486,12 +8400,13 @@ export type SessionNextSynthetic2 = { } } -export type SessionNextSkillActivated2 = { +export type SkillActivated2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.skill.activated" + type: "skill.activated" durable: { aggregateID: string seq: number @@ -8499,20 +8414,19 @@ export type SessionNextSkillActivated2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string name: string text: string } } -export type SessionNextShellStarted2 = { +export type ShellStarted2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.shell.started" + type: "shell.started" durable: { aggregateID: string seq: number @@ -8520,20 +8434,19 @@ export type SessionNextShellStarted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string callID: string command: string } } -export type SessionNextShellEnded2 = { +export type ShellEnded2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.shell.ended" + type: "shell.ended" durable: { aggregateID: string seq: number @@ -8541,19 +8454,19 @@ export type SessionNextShellEnded2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string callID: string output: string } } -export type SessionNextStepStarted2 = { +export type StepStarted2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.step.started" + type: "step.started" durable: { aggregateID: string seq: number @@ -8561,7 +8474,6 @@ export type SessionNextStepStarted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string agent: string @@ -8570,12 +8482,13 @@ export type SessionNextStepStarted2 = { } } -export type SessionNextStepEnded2 = { +export type StepEnded2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.step.ended" + type: "step.ended" durable: { aggregateID: string seq: number @@ -8583,7 +8496,6 @@ export type SessionNextStepEnded2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string finish: string @@ -8602,12 +8514,13 @@ export type SessionNextStepEnded2 = { } } -export type SessionNextStepFailed2 = { +export type StepFailed2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.step.failed" + type: "step.failed" durable: { aggregateID: string seq: number @@ -8615,19 +8528,19 @@ export type SessionNextStepFailed2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string error: SessionErrorUnknown2 } } -export type SessionNextTextStarted2 = { +export type TextStarted2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.text.started" + type: "text.started" durable: { aggregateID: string seq: number @@ -8635,19 +8548,19 @@ export type SessionNextTextStarted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string textID: string } } -export type SessionNextTextEnded2 = { +export type TextEnded2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.text.ended" + type: "text.ended" durable: { aggregateID: string seq: number @@ -8655,7 +8568,6 @@ export type SessionNextTextEnded2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -8669,12 +8581,13 @@ export type LlmProviderMetadata3 = { } } -export type SessionNextReasoningStarted2 = { +export type ReasoningStarted2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.reasoning.started" + type: "reasoning.started" durable: { aggregateID: string seq: number @@ -8682,7 +8595,6 @@ export type SessionNextReasoningStarted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -8696,12 +8608,13 @@ export type LlmProviderMetadata4 = { } } -export type SessionNextReasoningEnded2 = { +export type ReasoningEnded2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.reasoning.ended" + type: "reasoning.ended" durable: { aggregateID: string seq: number @@ -8709,7 +8622,6 @@ export type SessionNextReasoningEnded2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -8718,12 +8630,13 @@ export type SessionNextReasoningEnded2 = { } } -export type SessionNextToolInputStarted2 = { +export type ToolInputStarted2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.input.started" + type: "tool.input.started" durable: { aggregateID: string seq: number @@ -8731,7 +8644,6 @@ export type SessionNextToolInputStarted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -8739,12 +8651,13 @@ export type SessionNextToolInputStarted2 = { } } -export type SessionNextToolInputEnded2 = { +export type ToolInputEnded2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.input.ended" + type: "tool.input.ended" durable: { aggregateID: string seq: number @@ -8752,7 +8665,6 @@ export type SessionNextToolInputEnded2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -8766,12 +8678,13 @@ export type LlmProviderMetadata5 = { } } -export type SessionNextToolCalled2 = { +export type ToolCalled2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.called" + type: "tool.called" durable: { aggregateID: string seq: number @@ -8779,7 +8692,6 @@ export type SessionNextToolCalled2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -8794,12 +8706,13 @@ export type SessionNextToolCalled2 = { } } -export type SessionNextToolProgress2 = { +export type ToolProgress2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.progress" + type: "tool.progress" durable: { aggregateID: string seq: number @@ -8807,7 +8720,6 @@ export type SessionNextToolProgress2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -8824,12 +8736,13 @@ export type LlmProviderMetadata6 = { } } -export type SessionNextToolSuccess2 = { +export type ToolSuccess2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.success" + type: "tool.success" durable: { aggregateID: string seq: number @@ -8837,7 +8750,6 @@ export type SessionNextToolSuccess2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -8860,12 +8772,13 @@ export type LlmProviderMetadata7 = { } } -export type SessionNextToolFailed2 = { +export type ToolFailed2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.failed" + type: "tool.failed" durable: { aggregateID: string seq: number @@ -8873,7 +8786,6 @@ export type SessionNextToolFailed2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -8886,7 +8798,7 @@ export type SessionNextToolFailed2 = { } } -export type SessionNextRetryError2 = { +export type SessionRetryError2 = { message: string statusCode?: number isRetryable: boolean @@ -8899,12 +8811,13 @@ export type SessionNextRetryError2 = { } } -export type SessionNextRetried2 = { +export type RetriedV2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.retried" + type: "retried" durable: { aggregateID: string seq: number @@ -8912,19 +8825,19 @@ export type SessionNextRetried2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string attempt: number - error: SessionNextRetryError2 + error: SessionRetryError2 } } -export type SessionNextCompactionStarted2 = { +export type CompactionStarted2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.compaction.started" + type: "compaction.started" durable: { aggregateID: string seq: number @@ -8932,19 +8845,18 @@ export type SessionNextCompactionStarted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" } } -export type SessionNextCompactionEnded2 = { +export type CompactionEnded2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.compaction.ended" + type: "compaction.ended" durable: { aggregateID: string seq: number @@ -8952,21 +8864,20 @@ export type SessionNextCompactionEnded2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string reason: "auto" | "manual" text: string recent: string } } -export type SessionNextRevertStaged2 = { +export type RevertStaged2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.revert.staged" + type: "revert.staged" durable: { aggregateID: string seq: number @@ -8974,18 +8885,18 @@ export type SessionNextRevertStaged2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string revert: RevertState2 } } -export type SessionNextRevertCleared2 = { +export type RevertCleared2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.revert.cleared" + type: "revert.cleared" durable: { aggregateID: string seq: number @@ -8993,17 +8904,17 @@ export type SessionNextRevertCleared2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string } } -export type SessionNextRevertCommitted2 = { +export type RevertCommitted2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.revert.committed" + type: "revert.committed" durable: { aggregateID: string seq: number @@ -9011,44 +8922,43 @@ export type SessionNextRevertCommitted2 = { } location?: LocationRef2 data: { - timestamp: number sessionID: string messageID: string } } export type SessionDurableEventV2 = - | SessionNextAgentSwitched2 - | SessionNextModelSwitched2 - | SessionNextMoved2 - | SessionNextRenamed2 - | SessionNextForked2 - | SessionNextPrompted2 - | SessionNextPromptAdmitted2 - | SessionNextContextUpdated2 - | SessionNextSynthetic2 - | SessionNextSkillActivated2 - | SessionNextShellStarted2 - | SessionNextShellEnded2 - | SessionNextStepStarted2 - | SessionNextStepEnded2 - | SessionNextStepFailed2 - | SessionNextTextStarted2 - | SessionNextTextEnded2 - | SessionNextReasoningStarted2 - | SessionNextReasoningEnded2 - | SessionNextToolInputStarted2 - | SessionNextToolInputEnded2 - | SessionNextToolCalled2 - | SessionNextToolProgress2 - | SessionNextToolSuccess2 - | SessionNextToolFailed2 - | SessionNextRetried2 - | SessionNextCompactionStarted2 - | SessionNextCompactionEnded2 - | SessionNextRevertStaged2 - | SessionNextRevertCleared2 - | SessionNextRevertCommitted2 + | AgentSelected2 + | ModelSelected2 + | SessionMoved2 + | RenamedV2 + | ForkedV2 + | PromptPromoted2 + | PromptAdmitted2 + | SessionContextUpdated2 + | SyntheticV2 + | SkillActivated2 + | ShellStarted2 + | ShellEnded2 + | StepStarted2 + | StepEnded2 + | StepFailed2 + | TextStarted2 + | TextEnded2 + | ReasoningStarted2 + | ReasoningEnded2 + | ToolInputStarted2 + | ToolInputEnded2 + | ToolCalled2 + | ToolProgress2 + | ToolSuccess2 + | ToolFailed2 + | RetriedV2 + | CompactionStarted2 + | CompactionEnded2 + | RevertStaged2 + | RevertCleared2 + | RevertCommitted2 /** * Marker emitted once when a log read reaches its captured watermark. The reader holds every event committed at or below seq. @@ -9565,6 +9475,7 @@ export type SkillV2Info2 = { export type ModelsDevRefreshed2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9579,6 +9490,7 @@ export type ModelsDevRefreshed2 = { export type IntegrationUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9593,6 +9505,7 @@ export type IntegrationUpdated2 = { export type IntegrationConnectionUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9605,6 +9518,7 @@ export type IntegrationConnectionUpdated2 = { export type CatalogUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9619,6 +9533,7 @@ export type CatalogUpdated2 = { export type AgentUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9704,6 +9619,7 @@ export type SessionV2 = { export type SessionCreated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9722,6 +9638,7 @@ export type SessionCreated2 = { export type SessionUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9740,6 +9657,7 @@ export type SessionUpdated2 = { export type SessionDeleted2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9914,6 +9832,7 @@ export type MessageV2 = UserMessageV2 | AssistantMessageV2 export type MessageUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -9932,6 +9851,7 @@ export type MessageUpdated2 = { export type MessageRemoved2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10213,6 +10133,7 @@ export type PartV2 = export type MessagePartUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10232,6 +10153,7 @@ export type MessagePartUpdated2 = { export type MessagePartRemoved2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10249,30 +10171,30 @@ export type MessagePartRemoved2 = { } } -export type SessionNextExecutionSettled2 = { +export type ExecutionSettled2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.execution.settled" + type: "execution.settled" location?: LocationRef2 data: { - timestamp: number sessionID: string outcome: "success" | "failure" | "interrupted" error?: SessionErrorUnknown2 } } -export type SessionNextTextDelta2 = { +export type TextDelta2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.text.delta" + type: "text.delta" location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string textID: string @@ -10280,15 +10202,15 @@ export type SessionNextTextDelta2 = { } } -export type SessionNextReasoningDelta2 = { +export type ReasoningDelta2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.reasoning.delta" + type: "reasoning.delta" location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string reasoningID: string @@ -10296,15 +10218,15 @@ export type SessionNextReasoningDelta2 = { } } -export type SessionNextToolInputDelta2 = { +export type ToolInputDelta2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.tool.input.delta" + type: "tool.input.delta" location?: LocationRef2 data: { - timestamp: number sessionID: string assistantMessageID: string callID: string @@ -10312,23 +10234,23 @@ export type SessionNextToolInputDelta2 = { } } -export type SessionNextCompactionDelta2 = { +export type CompactionDelta2 = { id: string + created: number metadata?: { [key: string]: unknown } - type: "session.next.compaction.delta" + type: "compaction.delta" location?: LocationRef2 data: { - timestamp: number sessionID: string - messageID: string text: string } } export type FileEdited2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10341,6 +10263,7 @@ export type FileEdited2 = { export type ReferenceUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10355,6 +10278,7 @@ export type ReferenceUpdated2 = { export type PermissionV2Asked2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10375,6 +10299,7 @@ export type PermissionV2Asked2 = { export type PermissionV2Replied2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10389,6 +10314,7 @@ export type PermissionV2Replied2 = { export type PluginAdded2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10401,6 +10327,7 @@ export type PluginAdded2 = { export type ProjectDirectoriesUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10413,6 +10340,7 @@ export type ProjectDirectoriesUpdated2 = { export type CommandUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10427,6 +10355,7 @@ export type CommandUpdated2 = { export type SkillUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10441,6 +10370,7 @@ export type SkillUpdated2 = { export type FileWatcherUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10465,6 +10395,7 @@ export type PtyV2 = { export type PtyCreated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10477,6 +10408,7 @@ export type PtyCreated2 = { export type PtyUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10489,6 +10421,7 @@ export type PtyUpdated2 = { export type PtyExited2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10502,6 +10435,7 @@ export type PtyExited2 = { export type PtyDeleted2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10532,6 +10466,7 @@ export type ShellV2 = { export type ShellCreated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10544,6 +10479,7 @@ export type ShellCreated2 = { export type ShellExited2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10558,6 +10494,7 @@ export type ShellExited2 = { export type ShellDeleted2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10603,6 +10540,7 @@ export type QuestionV2Tool2 = { export type QuestionV2Asked2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10623,6 +10561,7 @@ export type QuestionV2Answer2 = Array export type QuestionV2Replied2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10637,6 +10576,7 @@ export type QuestionV2Replied2 = { export type QuestionV2Rejected2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10743,6 +10683,7 @@ export type FormUrlInfo1 = { export type FormCreated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10761,6 +10702,7 @@ export type FormAnswer1 = { export type FormReplied2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10775,6 +10717,7 @@ export type FormReplied2 = { export type FormCancelled2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10803,6 +10746,7 @@ export type TodoV2 = { export type TodoUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10838,6 +10782,7 @@ export type SessionStatusV2 = export type SessionStatusV22 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10851,6 +10796,7 @@ export type SessionStatusV22 = { export type SessionIdle2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10863,6 +10809,7 @@ export type SessionIdle2 = { export type TuiPromptAppend2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10875,6 +10822,7 @@ export type TuiPromptAppend2 = { export type TuiCommandExecute2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10905,6 +10853,7 @@ export type TuiCommandExecute2 = { export type TuiToastShow2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10920,6 +10869,7 @@ export type TuiToastShow2 = { export type TuiSessionSelect2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10935,6 +10885,7 @@ export type TuiSessionSelect2 = { export type InstallationUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10947,6 +10898,7 @@ export type InstallationUpdated2 = { export type InstallationUpdateAvailable2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10959,6 +10911,7 @@ export type InstallationUpdateAvailable2 = { export type VcsBranchUpdated2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10971,6 +10924,7 @@ export type VcsBranchUpdated2 = { export type McpStatusChanged2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -10983,6 +10937,7 @@ export type McpStatusChanged2 = { export type PermissionAsked2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -11006,6 +10961,7 @@ export type PermissionAsked2 = { export type PermissionReplied2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -11059,6 +11015,7 @@ export type QuestionToolV2 = { export type QuestionAsked2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -11079,6 +11036,7 @@ export type QuestionAnswerV2 = Array export type QuestionRepliedV2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -11093,6 +11051,7 @@ export type QuestionRepliedV2 = { export type QuestionRejectedV2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -11106,6 +11065,7 @@ export type QuestionRejectedV2 = { export type SessionError2 = { id: string + created: number metadata?: { [key: string]: unknown } @@ -11153,42 +11113,42 @@ export type V2EventV2 = | MessageRemoved2 | MessagePartUpdated2 | MessagePartRemoved2 - | SessionNextAgentSwitched2 - | SessionNextModelSwitched2 - | SessionNextMoved2 - | SessionNextRenamed2 - | SessionNextForked2 - | SessionNextPrompted2 - | SessionNextPromptAdmitted2 - | SessionNextExecutionSettled2 - | SessionNextContextUpdated2 - | SessionNextSynthetic2 - | SessionNextSkillActivated2 - | SessionNextShellStarted2 - | SessionNextShellEnded2 - | SessionNextStepStarted2 - | SessionNextStepEnded2 - | SessionNextStepFailed2 - | SessionNextTextStarted2 - | SessionNextTextDelta2 - | SessionNextTextEnded2 - | SessionNextReasoningStarted2 - | SessionNextReasoningDelta2 - | SessionNextReasoningEnded2 - | SessionNextToolInputStarted2 - | SessionNextToolInputDelta2 - | SessionNextToolInputEnded2 - | SessionNextToolCalled2 - | SessionNextToolProgress2 - | SessionNextToolSuccess2 - | SessionNextToolFailed2 - | SessionNextRetried2 - | SessionNextCompactionStarted2 - | SessionNextCompactionDelta2 - | SessionNextCompactionEnded2 - | SessionNextRevertStaged2 - | SessionNextRevertCleared2 - | SessionNextRevertCommitted2 + | AgentSelected2 + | ModelSelected2 + | SessionMoved2 + | RenamedV2 + | ForkedV2 + | PromptPromoted2 + | PromptAdmitted2 + | ExecutionSettled2 + | SessionContextUpdated2 + | SyntheticV2 + | SkillActivated2 + | ShellStarted2 + | ShellEnded2 + | StepStarted2 + | StepEnded2 + | StepFailed2 + | TextStarted2 + | TextDelta2 + | TextEnded2 + | ReasoningStarted2 + | ReasoningDelta2 + | ReasoningEnded2 + | ToolInputStarted2 + | ToolInputDelta2 + | ToolInputEnded2 + | ToolCalled2 + | ToolProgress2 + | ToolSuccess2 + | ToolFailed2 + | RetriedV2 + | CompactionStarted2 + | CompactionDelta2 + | CompactionEnded2 + | RevertStaged2 + | RevertCleared2 + | RevertCommitted2 | FileEdited2 | ReferenceUpdated2 | PermissionV2Asked2 diff --git a/packages/tui/src/context/data.tsx b/packages/tui/src/context/data.tsx index d70a71be5c..cc9378dbac 100644 --- a/packages/tui/src/context/data.tsx +++ b/packages/tui/src/context/data.tsx @@ -27,6 +27,8 @@ import { createSignal, onCleanup } from "solid-js" export type DataSessionStatus = "idle" | "running" +const messageIDFromEvent = (eventID: string) => eventID.replace(/^evt_/, "msg_") + type LocationData = { agent?: AgentV2Info[] command?: CommandV2Info[] @@ -181,17 +183,21 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ const info = store.session.info[sessionID] if (!info) return const rootID = resolveRoot(sessionID) - setStore("session", "family", produce((draft) => { - if (sessionID !== rootID && draft[sessionID]) { - const members = draft[rootID] ??= [] - for (const id of draft[sessionID]) { - if (!members.includes(id)) members.push(id) + setStore( + "session", + "family", + produce((draft) => { + if (sessionID !== rootID && draft[sessionID]) { + const members = (draft[rootID] ??= []) + for (const id of draft[sessionID]) { + if (!members.includes(id)) members.push(id) + } + delete draft[sessionID] } - delete draft[sessionID] - } - const family = draft[rootID] ??= [] - if (!family.includes(sessionID)) family.push(sessionID) - })) + const family = (draft[rootID] ??= []) + if (!family.includes(sessionID)) family.push(sessionID) + }), + ) } function handleEvent(event: V2Event) { @@ -214,124 +220,113 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ case "skill.updated": void result.location.skill.refresh(event.location) break - case "session.next.agent.switched": + case "agent.selected": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "agent", event.data.agent) message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { - id: event.data.messageID, + id: messageIDFromEvent(event.id), type: "agent-switched", agent: event.data.agent, - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break - case "session.next.model.switched": + case "model.selected": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "model", event.data.model) message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { - id: event.data.messageID, + id: messageIDFromEvent(event.id), type: "model-switched", model: event.data.model, - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break - case "session.next.renamed": + case "renamed": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "title", event.data.title) break - case "session.next.prompted": { + case "prompt.promoted": { setStore("session", "status", event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { - const position = index.get(event.data.messageID) + const position = index.get(event.data.inputID) const existing = position === undefined ? undefined : draft[position] if (existing?.type === "user") { - existing.text = event.data.prompt.text - existing.files = event.data.prompt.files - existing.agents = event.data.prompt.agents - existing.time.created = event.data.timestamp + existing.time.created = event.created if (existing.metadata?.queued === true) { delete existing.metadata.queued if (Object.keys(existing.metadata).length === 0) existing.metadata = undefined } return } - message.append(draft, index, { - id: event.data.messageID, - type: "user", - text: event.data.prompt.text, - files: event.data.prompt.files, - agents: event.data.prompt.agents, - time: { created: event.data.timestamp }, - }) }) break } - case "session.next.prompt.admitted": + case "prompt.admitted": message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { - id: event.data.messageID, + id: event.data.inputID, type: "user", text: event.data.prompt.text, files: event.data.prompt.files, agents: event.data.prompt.agents, metadata: { queued: true }, - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break - case "session.next.context.updated": + case "session.context.updated": message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { - id: event.data.messageID, + id: messageIDFromEvent(event.id), type: "system", text: event.data.text, - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break - case "session.next.synthetic": + case "synthetic": message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { - id: event.data.messageID, + id: messageIDFromEvent(event.id), type: "synthetic", sessionID: event.data.sessionID, text: event.data.text, description: event.data.description, - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break - case "session.next.shell.started": + case "shell.started": setStore("session", "status", event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { - id: event.data.messageID, + id: messageIDFromEvent(event.id), type: "shell", callID: event.data.callID, command: event.data.command, output: "", - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break - case "session.next.shell.ended": + case "shell.ended": setStore("session", "status", event.data.sessionID, "idle") message.update(event.data.sessionID, (draft, index) => { const match = message.activeShell(draft, event.data.callID) if (!match) return match.output = event.data.output - match.time.completed = event.data.timestamp + match.time.completed = event.created }) break - case "session.next.step.started": + case "step.started": setStore("session", "status", event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { if (index.has(event.data.assistantMessageID)) return const currentAssistant = message.activeAssistant(draft) - if (currentAssistant) currentAssistant.time.completed = event.data.timestamp + if (currentAssistant) currentAssistant.time.completed = event.created message.append(draft, index, { id: event.data.assistantMessageID, type: "assistant", @@ -339,16 +334,16 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ model: event.data.model, content: [], snapshot: event.data.snapshot ? { start: event.data.snapshot } : undefined, - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break - case "session.next.step.ended": + case "step.ended": setStore("session", "status", event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { const currentAssistant = message.assistant(draft, index, event.data.assistantMessageID) if (!currentAssistant) return - currentAssistant.time.completed = event.data.timestamp + currentAssistant.time.completed = event.created currentAssistant.finish = event.data.finish currentAssistant.cost = event.data.cost currentAssistant.tokens = event.data.tokens @@ -356,16 +351,16 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ currentAssistant.snapshot = { ...currentAssistant.snapshot, end: event.data.snapshot } }) break - case "session.next.step.failed": + case "step.failed": message.update(event.data.sessionID, (draft, index) => { const currentAssistant = message.assistant(draft, index, event.data.assistantMessageID) if (!currentAssistant) return - currentAssistant.time.completed = event.data.timestamp + currentAssistant.time.completed = event.created currentAssistant.finish = "error" currentAssistant.error = event.data.error }) break - case "session.next.text.started": + case "text.started": message.update(event.data.sessionID, (draft, index) => { message.assistant(draft, index, event.data.assistantMessageID)?.content.push({ type: "text", @@ -374,7 +369,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "session.next.text.delta": + case "text.delta": message.update(event.data.sessionID, (draft, index) => { const match = message.latestText( message.assistant(draft, index, event.data.assistantMessageID), @@ -383,7 +378,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match) match.text += event.data.delta }) break - case "session.next.text.ended": + case "text.ended": message.update(event.data.sessionID, (draft, index) => { const match = message.latestText( message.assistant(draft, index, event.data.assistantMessageID), @@ -392,18 +387,18 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match) match.text = event.data.text }) break - case "session.next.tool.input.started": + case "tool.input.started": message.update(event.data.sessionID, (draft, index) => { message.assistant(draft, index, event.data.assistantMessageID)?.content.push({ type: "tool", id: event.data.callID, name: event.data.name, - time: { created: event.data.timestamp }, + time: { created: event.created }, state: { status: "pending", input: "" }, }) }) break - case "session.next.tool.input.delta": + case "tool.input.delta": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -412,7 +407,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match?.state.status === "pending") match.state.input += event.data.delta }) break - case "session.next.tool.input.ended": + case "tool.input.ended": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -421,19 +416,19 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match?.state.status === "pending") match.state.input = event.data.text }) break - case "session.next.tool.called": + case "tool.called": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), event.data.callID, ) if (!match) return - match.time.ran = event.data.timestamp + match.time.ran = event.created match.provider = event.data.provider match.state = { status: "running", input: event.data.input, structured: {}, content: [] } }) break - case "session.next.tool.progress": + case "tool.progress": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -444,7 +439,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ match.state.content = [...event.data.content] }) break - case "session.next.tool.success": + case "tool.success": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -463,10 +458,10 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ metadata: match.provider?.metadata, resultMetadata: event.data.provider.metadata, } - match.time.completed = event.data.timestamp + match.time.completed = event.created }) break - case "session.next.tool.failed": + case "tool.failed": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -486,21 +481,21 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ metadata: match.provider?.metadata, resultMetadata: event.data.provider.metadata, } - match.time.completed = event.data.timestamp + match.time.completed = event.created }) break - case "session.next.reasoning.started": + case "reasoning.started": message.update(event.data.sessionID, (draft, index) => { message.assistant(draft, index, event.data.assistantMessageID)?.content.push({ type: "reasoning", id: event.data.reasoningID, text: "", providerMetadata: event.data.providerMetadata, - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break - case "session.next.reasoning.delta": + case "reasoning.delta": message.update(event.data.sessionID, (draft, index) => { const match = message.latestReasoning( message.assistant(draft, index, event.data.assistantMessageID), @@ -509,7 +504,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match) match.text += event.data.delta }) break - case "session.next.reasoning.ended": + case "reasoning.ended": message.update(event.data.sessionID, (draft, index) => { const match = message.latestReasoning( message.assistant(draft, index, event.data.assistantMessageID), @@ -517,38 +512,38 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ ) if (match) { match.text = event.data.text - match.time = { created: match.time?.created ?? event.data.timestamp, completed: event.data.timestamp } + match.time = { created: match.time?.created ?? event.created, completed: event.created } if (event.data.providerMetadata !== undefined) match.providerMetadata = event.data.providerMetadata } }) break - case "session.next.retried": - case "session.next.compaction.started": + case "retried": + case "compaction.started": setStore("session", "status", event.data.sessionID, "running") break - case "session.next.execution.settled": + case "execution.settled": setStore("session", "status", event.data.sessionID, "idle") break - case "session.next.revert.staged": + case "revert.staged": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "revert", event.data.revert) break - case "session.next.revert.cleared": - case "session.next.revert.committed": + case "revert.cleared": + case "revert.committed": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "revert", undefined) break - case "session.next.compaction.delta": + case "compaction.delta": break - case "session.next.compaction.ended": + case "compaction.ended": message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { - id: event.data.messageID, + id: messageIDFromEvent(event.id), type: "compaction", reason: event.data.reason, summary: event.data.text, recent: event.data.recent, - time: { created: event.data.timestamp }, + time: { created: event.created }, }) }) break @@ -692,8 +687,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ return liveByID.get(message.id) ?? message }), ...live.filter((message) => !loadedIDs.has(message.id)), - ] - .toSorted((a, b) => a.time.created - b.time.created) + ].toSorted((a, b) => a.time.created - b.time.created) messageIndex.set(sessionID, new Map(messages.map((message, index) => [message.id, index]))) setStore("session", "message", sessionID, messages) }, diff --git a/packages/tui/src/feature-plugins/system/notifications.ts b/packages/tui/src/feature-plugins/system/notifications.ts index 81c696ef13..aa8dcace19 100644 --- a/packages/tui/src/feature-plugins/system/notifications.ts +++ b/packages/tui/src/feature-plugins/system/notifications.ts @@ -74,17 +74,17 @@ const tui: TuiPlugin = async (api) => { notify(api, sessionID, "Session done", session?.parentID ? "subagent_done" : "done") } - api.event.on("session.next.prompted", (event) => started(event.data.sessionID)) - api.event.on("session.next.shell.started", (event) => started(event.data.sessionID)) - api.event.on("session.next.step.started", (event) => started(event.data.sessionID)) - api.event.on("session.next.retried", (event) => started(event.data.sessionID)) - api.event.on("session.next.compaction.started", (event) => started(event.data.sessionID)) - api.event.on("session.next.shell.ended", (event) => ended(event.data.sessionID)) - api.event.on("session.next.step.ended", (event) => { + api.event.on("prompt.promoted", (event) => started(event.data.sessionID)) + api.event.on("shell.started", (event) => started(event.data.sessionID)) + api.event.on("step.started", (event) => started(event.data.sessionID)) + api.event.on("retried", (event) => started(event.data.sessionID)) + api.event.on("compaction.started", (event) => started(event.data.sessionID)) + api.event.on("shell.ended", (event) => ended(event.data.sessionID)) + api.event.on("step.ended", (event) => { if (event.data.finish === "tool-calls") return ended(event.data.sessionID) }) - api.event.on("session.next.step.failed", (event) => { + api.event.on("step.failed", (event) => { const sessionID = event.data.sessionID if (!active.has(sessionID)) return errored.add(sessionID) diff --git a/packages/tui/src/routes/session/rows.ts b/packages/tui/src/routes/session/rows.ts index f1c4714276..23b43c3b17 100644 --- a/packages/tui/src/routes/session/rows.ts +++ b/packages/tui/src/routes/session/rows.ts @@ -126,45 +126,49 @@ export function createSessionRows(sessionID: Accessor) { return index === -1 ? rows.length : index } - const message = (event: { data: { sessionID: string; messageID: string } }) => { - if (event.data.sessionID === sessionID()) appendMessage(event.data.messageID) + const message = (event: { id: string; data: { sessionID: string } }) => { + if (event.data.sessionID === sessionID()) appendMessage(event.id.replace(/^evt_/, "msg_")) + } + const input = (event: { data: { sessionID: string; inputID: string } }) => { + if (event.data.sessionID === sessionID()) appendMessage(event.data.inputID) } const subscriptions = [ - data.on("session.next.prompt.admitted", message), - data.on("session.next.prompted", message), - data.on("session.next.context.updated", message), - data.on("session.next.synthetic", (event) => { - if (event.data.sessionID === sessionID() && event.data.description?.trim()) appendMessage(event.data.messageID) + data.on("prompt.admitted", input), + data.on("prompt.promoted", input), + data.on("session.context.updated", message), + data.on("synthetic", (event) => { + if (event.data.sessionID === sessionID() && event.data.description?.trim()) + appendMessage(event.id.replace(/^evt_/, "msg_")) }), - data.on("session.next.shell.started", message), - data.on("session.next.agent.switched", message), - data.on("session.next.model.switched", message), - data.on("session.next.compaction.ended", message), - data.on("session.next.text.delta", (event) => { + data.on("shell.started", message), + data.on("agent.selected", message), + data.on("model.selected", message), + data.on("compaction.ended", message), + data.on("text.delta", (event) => { if (event.data.sessionID === sessionID()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.textID }) }), - data.on("session.next.text.ended", (event) => { + data.on("text.ended", (event) => { if (event.data.sessionID === sessionID() && event.data.text.trim()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.textID }) }), - data.on("session.next.reasoning.delta", (event) => { + data.on("reasoning.delta", (event) => { if (event.data.sessionID === sessionID()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.reasoningID }) }), - data.on("session.next.reasoning.ended", (event) => { + data.on("reasoning.ended", (event) => { if (event.data.sessionID === sessionID() && event.data.text.trim()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.reasoningID }) }), - data.on("session.next.tool.input.started", (event) => { + data.on("tool.input.started", (event) => { if (event.data.sessionID === sessionID()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.callID }, event.data.name) }), - data.on("session.next.step.ended", (event) => { + data.on("step.ended", (event) => { if (event.data.sessionID !== sessionID() || ["tool-calls", "unknown"].includes(event.data.finish)) return appendFooter(event.data.assistantMessageID) }), - data.on("session.next.step.failed", (event) => { + data.on("step.failed", (event) => { if (event.data.sessionID === sessionID()) appendFooter(event.data.assistantMessageID) }), ] @@ -229,8 +233,6 @@ function hasPart(rows: SessionRow[], ref: PartRef) { return rows.some((row) => { if (row.type === "part") return row.ref.messageID === ref.messageID && row.ref.partID === ref.partID if (row.type !== "group") return false - return [...row.refs, ...row.pending].some( - (item) => item.messageID === ref.messageID && item.partID === ref.partID, - ) + return [...row.refs, ...row.pending].some((item) => item.messageID === ref.messageID && item.partID === ref.partID) }) } diff --git a/packages/tui/test/cli/cmd/tui/notifications.test.ts b/packages/tui/test/cli/cmd/tui/notifications.test.ts index a914b34dbc..5f1c6355b3 100644 --- a/packages/tui/test/cli/cmd/tui/notifications.test.ts +++ b/packages/tui/test/cli/cmd/tui/notifications.test.ts @@ -90,12 +90,12 @@ function durable(sessionID: string) { function stepStarted(id: string, sessionID = "session"): V2Event { return { id, - type: "session.next.step.started", + created: 0, + type: "step.started", durable: durable(sessionID), data: { sessionID, assistantMessageID: `msg_${id}`, - timestamp: 0, agent: "build", model: { id: "model", providerID: "provider" }, }, @@ -105,12 +105,12 @@ function stepStarted(id: string, sessionID = "session"): V2Event { function stepEnded(id: string, sessionID = "session", finish = "stop"): V2Event { return { id, - type: "session.next.step.ended", + created: 0, + type: "step.ended", durable: durable(sessionID), data: { sessionID, assistantMessageID: `msg_${id}`, - timestamp: 0, finish, cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, @@ -121,12 +121,12 @@ function stepEnded(id: string, sessionID = "session", finish = "stop"): V2Event function stepFailed(id: string, sessionID = "session"): V2Event { return { id, - type: "session.next.step.failed", + created: 0, + type: "step.failed", durable: durable(sessionID), data: { sessionID, assistantMessageID: `msg_${id}`, - timestamp: 0, error: { type: "unknown", message: "boom" }, }, } @@ -150,8 +150,8 @@ describe("internal notifications TUI plugin", () => { test("notifies for question and permission requests with blurred notifications and always-on sounds", async () => { const harness = await setup() - harness.emit({ id: "event-1", type: "question.asked", data: question("question-1") }) - harness.emit({ id: "event-2", type: "permission.asked", data: permission("permission-1") }) + harness.emit({ id: "event-1", created: 0, type: "question.asked", data: question("question-1") }) + harness.emit({ id: "event-2", created: 0, type: "permission.asked", data: permission("permission-1") }) expect(harness.notifications).toEqual([questionNotification, permissionNotification]) }) @@ -159,23 +159,25 @@ describe("internal notifications TUI plugin", () => { test("dedupes pending questions and permissions until they are resolved", async () => { const harness = await setup() - harness.emit({ id: "event-1", type: "question.asked", data: question("question-1") }) - harness.emit({ id: "event-2", type: "question.asked", data: question("question-1") }) + harness.emit({ id: "event-1", created: 0, type: "question.asked", data: question("question-1") }) + harness.emit({ id: "event-2", created: 0, type: "question.asked", data: question("question-1") }) harness.emit({ id: "event-3", + created: 0, type: "question.replied", data: { sessionID: "session", requestID: "question-1", answers: [] }, }) - harness.emit({ id: "event-4", type: "question.asked", data: question("question-1") }) + harness.emit({ id: "event-4", created: 0, type: "question.asked", data: question("question-1") }) - harness.emit({ id: "event-5", type: "permission.asked", data: permission("permission-1") }) - harness.emit({ id: "event-6", type: "permission.asked", data: permission("permission-1") }) + harness.emit({ id: "event-5", created: 0, type: "permission.asked", data: permission("permission-1") }) + harness.emit({ id: "event-6", created: 0, type: "permission.asked", data: permission("permission-1") }) harness.emit({ id: "event-7", + created: 0, type: "permission.replied", data: { sessionID: "session", requestID: "permission-1", reply: "once" }, }) - harness.emit({ id: "event-8", type: "permission.asked", data: permission("permission-1") }) + harness.emit({ id: "event-8", created: 0, type: "permission.asked", data: permission("permission-1") }) expect(harness.notifications).toEqual([ questionNotification, @@ -205,7 +207,7 @@ describe("internal notifications TUI plugin", () => { test("uses sound-only notifications and subagent_done sound for subagent sessions", async () => { const harness = await setup() - harness.emit({ id: "event-1", type: "question.asked", data: question("question-1", "subagent") }) + harness.emit({ id: "event-1", created: 0, type: "question.asked", data: question("question-1", "subagent") }) harness.emit(stepStarted("event-2", "subagent")) harness.emit(stepEnded("event-3", "subagent")) @@ -248,12 +250,14 @@ describe("internal notifications TUI plugin", () => { harness.emit(stepStarted("event-1", "abort")) harness.emit({ id: "event-2", + created: 0, type: "session.error", data: { sessionID: "abort", error: { name: "MessageAbortedError", data: { message: "Aborted" } } }, }) harness.emit(stepStarted("event-3", "timeout")) harness.emit({ id: "event-4", + created: 0, type: "session.error", data: { sessionID: "timeout", error: { name: "UnknownError", data: { message: "SSE read timed out" } } }, }) diff --git a/packages/tui/test/cli/tui/data.test.tsx b/packages/tui/test/cli/tui/data.test.tsx index b2bacfc0dd..a71bdc47d8 100644 --- a/packages/tui/test/cli/tui/data.test.tsx +++ b/packages/tui/test/cli/tui/data.test.tsx @@ -2,6 +2,8 @@ import { expect, test } from "bun:test" import { testRender } from "@opentui/solid" import type { V2Event } from "@opencode-ai/sdk/v2" +import { SessionMessage } from "@opencode-ai/core/session/message" +import { EventV2 } from "@opencode-ai/core/event" import { onMount } from "solid-js" import { ProjectProvider } from "../../../src/context/project" import { SDKProvider } from "../../../src/context/sdk" @@ -47,8 +49,8 @@ test("refreshes resources into reactive getters", async () => { if (url.pathname === "/api/session/ses_test/message") return json({ data: [ - { id: "msg_second", type: "user", text: "Second", time: { created: 2 } }, - { id: "msg_first", type: "user", text: "First", time: { created: 1 } }, + { id: "msg_second", created: 0, type: "user", text: "Second", time: { created: 2 } }, + { id: "msg_first", created: 0, type: "user", text: "First", time: { created: 1 } }, ], cursor: {}, }) @@ -187,7 +189,9 @@ test("connectedOnce is false until first connect and persists across disconnect" ) const connect = () => stream?.enqueue( - encoder.encode(`data: ${JSON.stringify({ id: "evt_connected", type: "server.connected", data: {} })}\n\n`), + encoder.encode( + `data: ${JSON.stringify({ id: "evt_connected", created: 0, type: "server.connected", data: {} })}\n\n`, + ), ) const disconnect = () => { stream?.close() @@ -264,12 +268,12 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_started", - type: "session.next.step.started", + created: 0, + type: "step.started", durable: durable("session-live"), data: { sessionID: "session-live", assistantMessageID: "message-live", - timestamp: 1, agent: "build", model: { id: "model", providerID: "provider" }, }, @@ -278,12 +282,12 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_ended", - type: "session.next.step.ended", + created: 0, + type: "step.ended", durable: durable("session-live", 1, 2), data: { sessionID: "session-live", assistantMessageID: "message-live", - timestamp: 2, finish: "stop", cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, @@ -297,10 +301,10 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_execution_settled", - type: "session.next.execution.settled", + created: 0, + type: "execution.settled", data: { sessionID: "session-live", - timestamp: 3, outcome: "success", }, }) @@ -308,12 +312,12 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_failed_step_started", - type: "session.next.step.started", + created: 0, + type: "step.started", durable: durable("session-failed"), data: { sessionID: "session-failed", assistantMessageID: "message-failed", - timestamp: 3, agent: "build", model: { id: "model", providerID: "provider" }, }, @@ -322,12 +326,12 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_failed", - type: "session.next.step.failed", + created: 0, + type: "step.failed", durable: durable("session-failed", 1, 2), data: { sessionID: "session-failed", assistantMessageID: "message-failed", - timestamp: 4, error: { type: "unknown", message: "Provider unavailable" }, }, }) @@ -339,10 +343,10 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_failed_execution_settled", - type: "session.next.execution.settled", + created: 0, + type: "execution.settled", data: { sessionID: "session-failed", - timestamp: 5, outcome: "failure", error: { type: "unknown", message: "Provider unavailable" }, }, @@ -411,7 +415,7 @@ test("refreshes integrations after integration updates", async () => { expect(data.location.integration.list()).toEqual([]) const before = { ...requests } - emitEvent(events, { id: "evt_integration", type: "integration.updated", data: {} }) + emitEvent(events, { id: "evt_integration", created: 0, type: "integration.updated", data: {} }) await wait(() => data.location.integration.list()?.length === 1) await wait(() => requests.model > before.model && requests.provider > before.provider) expect(data.location.integration.list()?.[0]).toMatchObject({ id: "openai", name: "OpenAI" }) @@ -449,7 +453,7 @@ test("refreshes effective catalog data after catalog updates", async () => { try { await wait(() => requests.model > 0 && requests.provider > 0) const before = { ...requests } - emitEvent(events, { id: "evt_catalog", type: "catalog.updated", data: {} }) + emitEvent(events, { id: "evt_catalog", created: 0, type: "catalog.updated", data: {} }) await wait(() => requests.model > before.model && requests.provider > before.provider) } finally { app.renderer.destroy() @@ -496,7 +500,7 @@ test("refreshes agents after agent updates", async () => { try { await wait(() => data.location.agent.list()?.[0]?.id === "build") - emitEvent(events, { id: "evt_agent", type: "agent.updated", data: {} }) + emitEvent(events, { id: "evt_agent", created: 0, type: "agent.updated", data: {} }) await wait(() => data.location.agent.list()?.[0]?.id === "reviewer") } finally { app.renderer.destroy() @@ -541,7 +545,7 @@ test("refreshes references after updates", async () => { try { await mounted await wait(() => requests === 1) - emitEvent(events, { id: "evt_reference_1", type: "reference.updated", data: {} }) + emitEvent(events, { id: "evt_reference_1", created: 0, type: "reference.updated", data: {} }) await wait(() => data.location.reference.list()?.length === 1) expect(data.location.reference.list()?.[0]?.name).toBe("docs") } finally { @@ -602,6 +606,7 @@ test("keeps shell state scoped to location", async () => { events.emit({ id: "evt_shell_created", + created: 0, type: "shell.created", location: { directory: other }, data: { @@ -650,6 +655,7 @@ test("adds and dismisses permission requests from live events", async () => { await wait(() => data.connection.status() === "connected") emitEvent(events, { id: "evt_permission_asked_1", + created: 0, type: "permission.v2.asked", data: { id: "per_1", @@ -660,6 +666,7 @@ test("adds and dismisses permission requests from live events", async () => { }) emitEvent(events, { id: "evt_permission_asked_2", + created: 0, type: "permission.v2.asked", data: { id: "per_2", @@ -672,6 +679,7 @@ test("adds and dismisses permission requests from live events", async () => { emitEvent(events, { id: "evt_permission_replied_1", + created: 0, type: "permission.v2.replied", data: { sessionID: "ses_1", requestID: "per_1", reply: "once" }, }) @@ -680,6 +688,7 @@ test("adds and dismisses permission requests from live events", async () => { emitEvent(events, { id: "evt_permission_replied_2", + created: 0, type: "permission.v2.replied", data: { sessionID: "ses_1", requestID: "per_2", reply: "reject" }, }) @@ -715,6 +724,7 @@ test("adds and dismisses question requests from live events", async () => { await wait(() => data.connection.status() === "connected") emitEvent(events, { id: "evt_question_asked_1", + created: 0, type: "question.v2.asked", data: { id: "que_1", @@ -724,6 +734,7 @@ test("adds and dismisses question requests from live events", async () => { }) emitEvent(events, { id: "evt_question_asked_2", + created: 0, type: "question.v2.asked", data: { id: "que_2", @@ -735,6 +746,7 @@ test("adds and dismisses question requests from live events", async () => { emitEvent(events, { id: "evt_question_replied_1", + created: 0, type: "question.v2.replied", data: { sessionID: "ses_1", requestID: "que_1", answers: [["First"]] }, }) @@ -743,6 +755,7 @@ test("adds and dismisses question requests from live events", async () => { emitEvent(events, { id: "evt_question_rejected_2", + created: 0, type: "question.v2.rejected", data: { sessionID: "ses_1", requestID: "que_2" }, }) @@ -783,52 +796,52 @@ test("settles pending tools when a live failure arrives", async () => { await mounted emitEvent(events, { id: "evt_agent_1", - type: "session.next.agent.switched", + created: 0, + type: "agent.selected", durable: durable("session-1"), - data: { sessionID: "session-1", messageID: "msg_agent_1", timestamp: 0, agent: "build" }, + data: { sessionID: "session-1", agent: "build" }, }) emitEvent(events, { id: "evt_model_1", - type: "session.next.model.switched", + created: 0, + type: "model.selected", durable: durable("session-1", 1), data: { sessionID: "session-1", - messageID: "msg_model_1", - timestamp: 0, model: { id: "model-1", providerID: "provider-1" }, }, }) emitEvent(events, { id: "evt_step_started_1", - type: "session.next.step.started", + created: 0, + type: "step.started", durable: durable("session-1", 2), data: { sessionID: "session-1", assistantMessageID: "msg_explicit_assistant_9", - timestamp: 1, agent: "build", model: { id: "model-1", providerID: "provider-1" }, }, }) emitEvent(events, { id: "evt_input_1", - type: "session.next.tool.input.started", + created: 0, + type: "tool.input.started", durable: durable("session-1", 3), data: { sessionID: "session-1", assistantMessageID: "msg_explicit_assistant_9", - timestamp: 2, callID: "call-1", name: "bash", }, }) emitEvent(events, { id: "evt_called_1", - type: "session.next.tool.called", + created: 0, + type: "tool.called", durable: durable("session-1", 4), data: { sessionID: "session-1", - timestamp: 2, assistantMessageID: "msg_explicit_assistant_9", callID: "call-1", tool: "bash", @@ -838,11 +851,11 @@ test("settles pending tools when a live failure arrives", async () => { }) emitEvent(events, { id: "evt_failed_1", - type: "session.next.tool.failed", + created: 0, + type: "tool.failed", durable: durable("session-1", 5), data: { sessionID: "session-1", - timestamp: 3, assistantMessageID: "msg_explicit_assistant_9", callID: "call-1", error: { type: "unknown", message: "aborted" }, @@ -928,12 +941,12 @@ test("renders admitted prompts immediately with queued marker and clears when pr const unsubscribe = sync.listen((event) => received.push(event.name)) emitEvent(events, { id: "evt_admitted_1", - type: "session.next.prompt.admitted", + created: 0, + type: "prompt.admitted", durable: durable(sessionID), data: { sessionID, - messageID, - timestamp: 0, + inputID: messageID, prompt: { text: "hello" }, delivery: "steer", }, @@ -947,19 +960,17 @@ test("renders admitted prompts immediately with queued marker and clears when pr emitEvent(events, { id: "evt_prompted_1", - type: "session.next.prompted", + created: 0, + type: "prompt.promoted", durable: durable(sessionID, 1), data: { sessionID, - messageID, - timestamp: 0, - prompt: { text: "hello" }, - delivery: "steer", + inputID: messageID, }, }) - await wait(() => received.at(-1) === "session.next.prompted") - expect(received.slice(-2)).toEqual(["session.next.prompt.admitted", "session.next.prompted"]) + await wait(() => received.at(-1) === "prompt.promoted") + expect(received.slice(-2)).toEqual(["prompt.admitted", "prompt.promoted"]) unsubscribe() const message = sync.session.message.list(sessionID)?.[0] expect(message?.type).toBe("user") @@ -1007,21 +1018,21 @@ test("projects live context updates with their message ID", async () => { await mounted emitEvent(events, { id: "evt_context_1", - type: "session.next.context.updated", + created: 0, + type: "session.context.updated", durable: durable("session-1"), data: { sessionID: "session-1", - messageID: "msg_context_1", - timestamp: 1, text: "Updated context", }, }) await wait(() => sync.session.message.list("session-1")?.length === 1) expect(sync.session.message.list("session-1")?.[0]).toMatchObject({ - id: "msg_context_1", + id: SessionMessage.ID.fromEvent(EventV2.ID.make("evt_context_1")), type: "system", text: "Updated context", + time: { created: 0 }, }) } finally { app.renderer.destroy() diff --git a/packages/tui/test/cli/tui/use-event.test.tsx b/packages/tui/test/cli/tui/use-event.test.tsx index 6ba38a83b8..7a4465c927 100644 --- a/packages/tui/test/cli/tui/use-event.test.tsx +++ b/packages/tui/test/cli/tui/use-event.test.tsx @@ -30,6 +30,7 @@ function event(payload: V2Event, input: { directory: string; project?: string; w function vcs(branch: string): V2Event { return { id: `evt_vcs_${branch}`, + created: 0, type: "vcs.branch.updated", data: { branch, @@ -40,6 +41,7 @@ function vcs(branch: string): V2Event { function update(version: string): V2Event { return { id: `evt_update_${version}`, + created: 0, type: "installation.update-available", data: { version, diff --git a/specs/v2/schema-changelog.md b/specs/v2/schema-changelog.md index d526b5d8e7..466cc73a8a 100644 --- a/specs/v2/schema-changelog.md +++ b/specs/v2/schema-changelog.md @@ -904,3 +904,17 @@ Compatibility: - Existing Context Epoch rows migrate in place by dropping the obsolete selection and pending-replacement columns. - Model and agent switches no longer discard earlier chronological System Context updates by forcing a new baseline. + +## 2026-07-03: Normalize Session Event Names And Envelope Time + +- Drop the experimental `session.next.` prefix from current Session event names. +- Rename `agent.switched` to `agent.selected`, `model.switched` to `model.selected`, and `prompted` to `prompt.promoted`; add `prompt.admitted` as the durable prompt admission record. +- Add an envelope-level `created` timestamp stored on each event row; payload-level `timestamp` fields are removed. +- Remove projection-only `messageID` fields from selected/message-producing events; projected message IDs derive from the event ID. `revert.committed.messageID` remains, and `forked.messageID` is now `forked.from`. +- Rename `session.moved.subdirectory` to `subpath` and normalize event-related schema identifiers. + +Compatibility: + +- V2 durable events and projections are experimental and are reset by `20260703090000_reset_v2_event_rename_sweep`; existing V2 event rows, event sequences, projected session messages, and admitted inputs are wiped. +- All renamed durable event types restart at version 1 under their normalized names. +- Generated Promise, Effect, and legacy JavaScript SDK surfaces were regenerated from the normalized schemas. diff --git a/specs/v2/session.md b/specs/v2/session.md index 15bc970b47..bb04c21356 100644 --- a/specs/v2/session.md +++ b/specs/v2/session.md @@ -114,7 +114,7 @@ Before each provider turn, the runner estimates the complete model-visible reque Compaction keeps the full transcript durable while replacing its active model representation with one hidden checkpoint containing a structured rolling summary and token-bounded serialized recent context. Provider-native assistant, reasoning, and tool messages never survive across the boundary, avoiding signature and encrypted-reasoning failures when the earlier prefix changes. -`session.next.compaction.started.1` durably identifies the attempt. Compaction deltas are live-only progress. `session.next.compaction.ended.1` durably stores the final summary and serialized recent context; only this completed event projects a model-visible compaction message. On the next provider attempt, the runner observes that completed compaction and directly renders a fresh Context Epoch baseline. A failed or interrupted attempt therefore leaves the previous history boundary active. +`compaction.started.1` durably identifies the attempt. Compaction deltas are live-only progress. `compaction.ended.1` durably stores the final summary and serialized recent context; only this completed event projects a model-visible compaction message. On the next provider attempt, the runner observes that completed compaction and directly renders a fresh Context Epoch baseline. A failed or interrupted attempt therefore leaves the previous history boundary active. Repeated compactions update the previous structured summary with newly compacted messages. The runner then reloads projected history and executes the original pending turn. @@ -170,9 +170,9 @@ The coordinator's active registry is also the source for `sessions.active()`. It Inbox promotion coalesces pending steers in durable admission order. Once continuation would otherwise end, it promotes one queued input at a time in FIFO order. Add explicit inbox backlog and steering-batch limits before exposing broad multi-caller admission or untrusted queue growth. -Eager local-tool execution is intentionally unbounded in the current local slice. This minimizes tool latency but does not increase SQLite settlement throughput: Session-event publication remains serialized per provider turn. Before broadening exposure, revisit per-turn call limits, output truncation, and operational backpressure using observed workloads. The `session.next.*` event schemas remain experimental and unshipped; databases created by earlier experimental builds are disposable rather than compatibility targets. +Eager local-tool execution is intentionally unbounded in the current local slice. This minimizes tool latency but does not increase SQLite settlement throughput: Session-event publication remains serialized per provider turn. Before broadening exposure, revisit per-turn call limits, output truncation, and operational backpressure using observed workloads. The normalized Session event schemas remain experimental and unshipped; databases created by earlier experimental builds are disposable rather than compatibility targets. -The synchronized `session.next.*` event family and projected Session-message model predate this branch. This slice refines their replay contract: projected Session messages retain their source aggregate sequence so canonical context ordering and `sessions.messages(...)` pagination follow durable event order even when caller-supplied IDs or timestamps do not. Consumers can use `sessions.log({ sessionID, after? })` to replay durable `session.next.*` events after an aggregate sequence cursor, then tail durable events without a race. Live-only text, reasoning, and tool-input fragments remain available through EventV2 subscriptions for connected renderers; they are intentionally absent from the replayable Session stream. +The normalized Session event family and projected Session-message model predate this branch. This slice refines their replay contract: projected Session messages retain their source aggregate sequence so canonical context ordering and `sessions.messages(...)` pagination follow durable event order even when caller-supplied IDs differ; event time is carried by the envelope `created` field rather than duplicated in payloads. Consumers can use `sessions.log({ sessionID, after? })` to replay durable Session events after an aggregate sequence cursor, then tail durable events without a race. Live-only text, reasoning, and tool-input fragments remain available through EventV2 subscriptions for connected renderers; they are intentionally absent from the replayable Session stream. The first `sessions.log(...)` contract is durable-only during both replay and live tailing. This keeps one cursor equal to one persisted aggregate sequence and is sufficient for reconnect-safe consumers. A later UI-facing API may optionally interleave live-only deltas while connected, but those fragments must remain explicitly ephemeral: they cannot advance the durable cursor, replay after reconnect, or be mistaken for publication boundaries. From bf3ae45439ccd97f2991c87457081648e75cff71 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 3 Jul 2026 13:43:21 -0500 Subject: [PATCH 21/82] fix(core): clean up mcp event surface (#35221) --- packages/core/src/mcp/client.ts | 6 +++- packages/core/src/mcp/index.ts | 6 +++- packages/core/test/mcp.test.ts | 14 +++++++++ packages/schema/src/mcp-event.ts | 2 +- packages/schema/test/event-manifest.test.ts | 3 ++ packages/sdk/js/src/v2/gen/types.gen.ts | 33 --------------------- 6 files changed, 28 insertions(+), 36 deletions(-) create mode 100644 packages/core/test/mcp.test.ts diff --git a/packages/core/src/mcp/client.ts b/packages/core/src/mcp/client.ts index fcd0814fb8..84ccbd70bb 100644 --- a/packages/core/src/mcp/client.ts +++ b/packages/core/src/mcp/client.ts @@ -46,7 +46,11 @@ const TolerantListPromptsResult = ListPromptsResultSchema.extend({ export class NeedsAuthError extends Schema.TaggedErrorClass()("MCP.NeedsAuthError", { server: Schema.String, -}) {} +}) { + override get message() { + return `MCP server requires authentication: ${this.server}` + } +} export class ConnectError extends Schema.TaggedErrorClass()("MCP.ConnectError", { server: Schema.String, diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index 2075c8dd19..d4935dc512 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -127,7 +127,11 @@ export class ResourceContent extends Schema.Class("MCP.Resource export class NotFoundError extends Schema.TaggedErrorClass()("MCP.NotFoundError", { server: ServerName, -}) {} +}) { + override get message() { + return `MCP server not found: ${this.server}` + } +} export class ToolCallError extends Schema.TaggedErrorClass()("MCP.ToolCallError", { server: ServerName, diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts new file mode 100644 index 0000000000..15ff95a28f --- /dev/null +++ b/packages/core/test/mcp.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, test } from "bun:test" +import { MCP } from "@opencode-ai/core/mcp/index" +import { MCPClient } from "@opencode-ai/core/mcp/client" + +describe("MCP errors", () => { + test("expose useful messages", () => { + expect(new MCP.NotFoundError({ server: MCP.ServerName.make("demo") }).message).toBe("MCP server not found: demo") + expect(new MCP.ToolCallError({ server: MCP.ServerName.make("demo"), tool: "search", message: "failed" }).message).toBe( + "failed", + ) + expect(new MCPClient.NeedsAuthError({ server: "demo" }).message).toBe("MCP server requires authentication: demo") + expect(new MCPClient.ConnectError({ server: "demo", message: "offline" }).message).toBe("offline") + }) +}) diff --git a/packages/schema/src/mcp-event.ts b/packages/schema/src/mcp-event.ts index f4221335e9..ae1e82656d 100644 --- a/packages/schema/src/mcp-event.ts +++ b/packages/schema/src/mcp-event.ts @@ -27,4 +27,4 @@ export const StatusChanged = Event.ephemeral({ }, }) -export const Definitions = Event.inventory(ToolsChanged, BrowserOpenFailed, StatusChanged) +export const Definitions = Event.inventory(ToolsChanged, StatusChanged) diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 9cdf3a787a..4fa23e75f7 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -12,6 +12,7 @@ import { } from "../src/index.js" import { EventManifest } from "../src/event-manifest.js" import { IdeEvent } from "../src/ide-event.js" +import { McpEvent } from "../src/mcp-event.js" import { SessionEvent } from "../src/session-event.js" import { SessionTodo } from "../src/session-todo.js" import { SessionV1 } from "../src/session-v1.js" @@ -63,6 +64,8 @@ describe("public event manifest", () => { expect(Permission.Event.Definitions).toEqual([Permission.Event.Asked, Permission.Event.Replied]) expect(Form.Event.Definitions).toEqual([Form.Event.Created, Form.Event.Replied, Form.Event.Cancelled]) expect(Reference.Event.Definitions).toEqual([Reference.Event.Updated]) + expect(McpEvent.Definitions).toEqual([McpEvent.ToolsChanged, McpEvent.StatusChanged]) + expect(EventManifest.Latest.has("mcp.browser.open.failed")).toBe(false) expect(EventManifest.Latest.has("ide.installed")).toBe(false) expect(IdeEvent.Definitions).toEqual([IdeEvent.Installed]) const sessionV1TailStart = EventManifest.Definitions.indexOf(SessionV1.Event.PartDelta) diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index d97eb59298..56cdccf087 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -89,7 +89,6 @@ export type Event = | EventTuiToastShow2 | EventTuiSessionSelect2 | EventMcpToolsChanged - | EventMcpBrowserOpenFailed | EventMcpStatusChanged | EventCommandExecuted | EventProjectUpdated @@ -1556,14 +1555,6 @@ export type GlobalEvent = { server: string } } - | { - id: string - type: "mcp.browser.open.failed" - properties: { - mcpName: string - url: string - } - } | { id: string type: "mcp.status.changed" @@ -3177,7 +3168,6 @@ export type V2Event = | TuiToastShow | TuiSessionSelect | McpToolsChanged - | McpBrowserOpenFailed | McpStatusChanged | CommandExecuted | ProjectUpdated @@ -6373,20 +6363,6 @@ export type McpToolsChanged = { } } -export type McpBrowserOpenFailed = { - id: string - created: number - metadata?: { - [key: string]: unknown - } - type: "mcp.browser.open.failed" - location?: LocationRef - data: { - mcpName: string - url: string - } -} - export type McpStatusChanged = { id: string created: number @@ -7493,15 +7469,6 @@ export type EventMcpToolsChanged = { } } -export type EventMcpBrowserOpenFailed = { - id: string - type: "mcp.browser.open.failed" - properties: { - mcpName: string - url: string - } -} - export type EventMcpStatusChanged = { id: string type: "mcp.status.changed" From 34a08cbdb807a3e3bcdd43ac7f570a75df0a899d Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 14:45:56 -0400 Subject: [PATCH 22/82] fix(core): tolerate missing models.dev temperature --- packages/core/src/models-dev.ts | 2 +- packages/core/test/models.test.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index 8a3fb965bf..a88aebfe07 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -67,7 +67,7 @@ export const Model = Schema.Struct({ attachment: Schema.Boolean, reasoning: Schema.Boolean, reasoning_options: Schema.optional(Schema.Array(ReasoningOption)), - temperature: Schema.Boolean, + temperature: Schema.optional(Schema.Boolean), tool_call: Schema.Boolean, interleaved: Schema.optional( Schema.Union([ diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index d9b7ed5582..9aa1cedc4d 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -149,6 +149,22 @@ describe("ModelsDev Service", () => { }), ) + it.effect("allows models.dev entries without temperature metadata", () => + Effect.sync(() => { + const result = Schema.decodeUnknownSync(ModelsDev.Model)({ + id: "no-temperature-model", + name: "No Temperature Model", + release_date: "2026-01-01", + attachment: false, + reasoning: false, + tool_call: true, + limit: { context: 128000, output: 8192 }, + }) + + expect(result.temperature).toBeUndefined() + }), + ) + it.live("get() returns providers from disk when cache file exists", () => Effect.gen(function* () { yield* writeCache(fixture) From ca861fdf43500ff7a59489b7aa01cb45b8780abb Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 14:49:05 -0400 Subject: [PATCH 23/82] docs: consolidate session work-unit vocabulary (#35218) --- AGENTS.md | 5 +- CONTEXT.md | 61 +++++++++++++++---------- packages/core/src/session/runner/llm.ts | 6 ++- specs/v2/session.md | 46 +++++++++---------- specs/v2/todo.md | 16 +++---- specs/v2/tools.md | 4 +- 6 files changed, 79 insertions(+), 59 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 703bae8912..8c72fe65a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -155,9 +155,10 @@ const table = sqliteTable("session", { - Reusing a Session ID adopts the existing Session. Reusing a prompt message ID reconciles an exact retry only when Session, prompt, and delivery mode match; conflicting reuse fails. Historical projected prompts lazily synthesize promoted inbox records during exact retry. - Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; idle or missing interruption is a no-op. - Keep `SessionRunner`, model resolution, tool registry, permissions, and filesystem Location-scoped. Omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics. -- Preserve one explicit `llm.stream(request)` call per provider turn and reload projected history before durable continuation. Do not bridge through legacy `SessionPrompt.loop(...)` or delegate orchestration to an in-memory tool loop. +- Preserve one explicit `llm.stream(request)` call per step and reload projected history before durable continuation. Do not bridge through legacy `SessionPrompt.loop(...)` or delegate orchestration to an in-memory tool loop. - Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. Advisory wakes drain eligible durable inbox rows only; post-crash continuation recovery requires a separate explicit design before it may retry provider work. A drain has no durable identity or transcript boundary. -- Keep delivery vocabulary explicit. Prompts steer by default and promote at the next safe provider-turn boundary while the current drain requires continuation. An explicit `queue` input remains pending until the Session would otherwise become idle; promote one queued input at that boundary, then reevaluate continuation before promoting another. Promoting any new user input resets the selected agent's provider-turn allowance; a batch of steers resets it once. +- Keep delivery vocabulary explicit. Prompts steer by default and promote at the next safe step boundary while the current drain requires continuation. An explicit `queue` input remains pending until the Session would otherwise become idle; promote one queued input at that boundary, then reevaluate continuation before promoting another. Promoting any new user input resets the selected agent's step allowance; a batch of steers resets it once. +- One step is one logical LLM call; its durable record covers only the model-visible span. Do not write "provider turn", and do not use bare "turn" for a single call: "turn" is reserved for the future assistant-turn unit containing all steps from prompt promotion until the session would go idle. - Keep EventV2 replay owner claims separate from clustered Session execution ownership. - Keep the System Context algebra and built-ins in `src/system-context`; keep Context Source producers with their observed domains, and keep Session History selection plus Context Checkpoint persistence Session-owned. The runner composes all context producers explicitly in `loadSystemContext`; there is no context registry. - The durable Applied record is what the model was last told, per source. Reconcile narrates drift as chronological System updates and never rewrites the baseline; only completed compaction rebaselines, and move or committed revert resets the checkpoint. Unavailable sources keep the model's prior belief, blocking only a session's first baseline. diff --git a/CONTEXT.md b/CONTEXT.md index 5e5955d344..712e91bf10 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -9,7 +9,7 @@ The structured collection of contextual facts presented to the model as initial _Avoid_: System prompt **Session History**: -The projected chronological conversation selected for a provider turn after applying the active compaction and **Context Epoch** cutoffs. +The projected chronological conversation selected for a **Step** after applying the active compaction and **Context Epoch** cutoffs. _Avoid_: Session Context **Context Source**: @@ -31,13 +31,13 @@ The full **System Context** rendered at the start of a **Context Epoch**. _Avoid_: Live system prompt **Context Snapshot**: -The overwriteable model-hidden JSON state used to compare each **Context Source** with the value last admitted to a provider turn. +The overwriteable model-hidden JSON state used to compare each **Context Source** with the value last admitted to a **Step**. **Unavailable Context**: An expected temporary inability to observe a **Context Source** value; the runtime retains its prior effective state and emits no update, or omits it until first successfully loaded. -**Safe Provider-Turn Boundary**: -The point immediately before a provider call, after durable input promotion and any required tool settlement, where context changes may be admitted chronologically. +**Safe Step Boundary**: +The point immediately before a provider request, after durable input promotion and any required tool settlement, where context changes may be admitted chronologically. **Admitted Prompt**: A durable user input accepted into the Session inbox but not yet included in **Session History**. @@ -45,11 +45,24 @@ A durable user input accepted into the Session inbox but not yet included in **S **Prompt Promotion**: The durable transition that removes an **Admitted Prompt** from pending input and appends its user message to **Session History**. -**Provider Turn**: -One request to a model provider and the response projected from that request. +**Step**: +One logical LLM call spanning pre-flight context checkpoint preparation, input promotion, request build, and compaction check; the provider stream; and tool settlement. +_Avoid_: provider turn, turn (unqualified) + +**Physical Attempt**: +One actual provider request on the wire in service of a **Step**; most Steps have one Physical Attempt, while overflow-triggered compaction recovery may give one Step two. + +**Assistant Turn**: +A reserved name for the not-yet-modeled unit containing all **Steps** from prompt promotion until the assistant yields the floor; do not reify it until something durable needs it. + +**Settlement**: +The terminal transition for a unit of work: Step and tool settlement are durable, while drain and execution settlement are coordinator-observed. + +**Execution**: +One session-scoped coordinator busy period from first wake until idle. An Execution is process-local coordination rather than a durable domain entity. **Session Drain**: -One process-local execution span that promotes eligible input and runs required **Provider Turns** until no immediate continuation remains. A Session Drain has no durable identity or transcript boundary. +One process-local execution span that promotes eligible input and runs required **Steps** until no immediate continuation remains. A Session Drain has no durable identity or transcript boundary. **Model Tool Output**: The bounded projection of a Core-executed tool result persisted in Session history and replayed to the model. A tool may shape this projection semantically, but the Tool Registry enforces the final size limit. @@ -89,23 +102,25 @@ _Avoid_: Response envelope - A **System Context** is an opaque carrier composed from zero or more **Context Sources**. - **Session History** contains projected conversational messages and admitted **Mid-Conversation System Messages**; the active **Baseline System Context** remains separate provider-request state. -- The **System Context Registry** uses stable-keyed scoped contributions to assemble the current **System Context**; contributor removal naturally removes its sources at the next **Safe Provider-Turn Boundary**. +- The **System Context Registry** uses stable-keyed scoped contributions to assemble the current **System Context**; contributor removal naturally removes its sources at the next **Safe Step Boundary**. - A changed **Context Source** may produce one **Mid-Conversation System Message** containing its newly effective state. - A **Mid-Conversation System Message** persists the exact combined rendered text sent to the model. - The current **Context Snapshot** advances atomically with the corresponding durable **Mid-Conversation System Message**. - A **Context Snapshot** stores one codec-encoded JSON value and, for removable dynamic sources, a pre-rendered removal message per stable **Context Source** key. - Changes from multiple **Context Sources** admitted at one safe boundary combine into one **Mid-Conversation System Message**. -- Context changes are sampled and admitted lazily at a **Safe Provider-Turn Boundary**, never pushed asynchronously when their source changes. -- At a **Safe Provider-Turn Boundary**, newly promoted user input or settled tool results precede any combined **Mid-Conversation System Message**. +- Context changes are sampled and admitted lazily at a **Safe Step Boundary**, never pushed asynchronously when their source changes. +- At a **Safe Step Boundary**, newly promoted user input or settled tool results precede any combined **Mid-Conversation System Message**. - An **Admitted Prompt** is replayable pending input, not yet model-visible **Session History**. - **Prompt Promotion** atomically consumes the pending inbox entry and appends its model-visible user message. -- Steering prompts promote at the next **Safe Provider-Turn Boundary** while the current **Session Drain** still requires continuation. Promoting any newly admitted user input resets the selected agent's provider-turn allowance; multiple prompts promoted at one boundary reset it once. +- Steering prompts promote at the next **Safe Step Boundary** while the current **Session Drain** still requires continuation. Promoting any newly admitted user input resets the selected agent's step allowance; multiple prompts promoted at one boundary reset it once. - A queued prompt does not promote while the current **Session Drain** requires continuation. The runner promotes one queued prompt when the Session would otherwise become idle, then reevaluates continuation before promoting another. -- A **Session Drain** is process-local coordination rather than a durable domain entity. Durable recovery must reason from prompts, projected history, provider attempts, and tool state rather than inventing an enclosing execution identity. -- The first provider turn renders the latest complete **Baseline System Context** and initializes its **Context Snapshot** without emitting a redundant **Mid-Conversation System Message**; unavailable initial context blocks the turn instead of persisting an incomplete baseline. +- A **Session Drain** is process-local coordination rather than a durable domain entity. Durable recovery must reason from prompts, projected history, physical attempts, and tool state rather than inventing an enclosing execution identity. +- An **Execution** contains one or more **Session Drains**; a **Session Drain** contains one reserved assistant-turn span at a time; that span contains **Steps**; and each **Step** contains one or more **Physical Attempts** plus any tool calls it requires. +- A **Step** record covers only the model-visible span from first assistant output through tool settlement; pre-flight leaves no record, and one Step settles at most one record. +- The first **Step** renders the latest complete **Baseline System Context** and initializes its **Context Snapshot** without emitting a redundant **Mid-Conversation System Message**; unavailable initial context blocks the Step instead of persisting an incomplete baseline. - Initial **System Context** preparation precedes the first durable input promotion so an unavailable baseline leaves that input pending and retryable; ordinary reconciliation remains after promotion. - Compaction starts a new **Context Epoch** with a freshly rendered **Baseline System Context** and **Context Snapshot**; prior **Mid-Conversation System Messages** remain durable audit history but leave projected model history. -- A newly registered core or plugin-defined **Context Source** absent from the current snapshot emits its baseline rendering once at the next **Safe Provider-Turn Boundary**. +- A newly registered core or plugin-defined **Context Source** absent from the current snapshot emits its baseline rendering once at the next **Safe Step Boundary**. - **Context Source** keys are stable and namespaced; duplicate keys fail composition. `SystemContext.combine(...)` preserves caller order; the **System Context Registry** evaluates producers concurrently and combines them in stable contribution-key order so rendered context remains deterministic. - Each **Context Source** loader returns one coherent typed value. `SystemContext.make(...)` hides that value type so differently typed sources compose uniformly. Its codec compares and stores that value; its pure renderers produce model-visible baseline, update, and removal text only when needed. - `SystemContext.initialize(...)` observes a composed **System Context** once and produces a fresh **Baseline System Context** with its **Context Snapshot**. @@ -113,26 +128,26 @@ _Avoid_: Response envelope - `SystemContext.replace(...)` renders a fresh generation after completed compaction or another baseline-replacing transition; it reports replacement blocked while previously admitted context is unavailable. - **Unavailable Context** uses stale-while-revalidate semantics and is distinct from a successfully loaded absence, which may emit removal text. - Ordinary **Context Source** loaders return values directly; loaders that intentionally use stale-while-revalidate may explicitly return **Unavailable Context**. -- Nested project instruction discovery after successful reads remains a follow-up; when implemented, discovered instructions must be admitted durably at the next **Safe Provider-Turn Boundary**. +- Nested project instruction discovery after successful reads remains a follow-up; when implemented, discovered instructions must be admitted durably at the next **Safe Step Boundary**. - Location-scoped services naturally re-resolve effective context when a moved session next runs in its destination location. - Moving a Session clears its active **Context Epoch**, so the destination must initialize a complete baseline before another prompt can promote. - Instruction discovery, source identity, persistence, and file loading belong to the instruction service; the **System Context** abstraction only composes effectful producers and renders loaded values. -- The first instruction-service slice observes global and upward project `AGENTS.md` files as one ordered aggregate **Context Source** at each **Safe Provider-Turn Boundary**. +- The first instruction-service slice observes global and upward project `AGENTS.md` files as one ordered aggregate **Context Source** at each **Safe Step Boundary**. - Built-in and instruction context producers register through the **System Context Registry** with stable contribution keys. Plugin-defined context registration and hot-reload lifecycle remain a follow-up built on the same scoped registry seam. - Selected-agent available-skill guidance is a **Context Source** composed with Location-wide registry sources immediately before Context Epoch admission. It lists only names and descriptions permitted for that agent; skill bodies and locations are exposed only through the permission-checked `skill` tool. -- The selected agent and model are sampled when a provider turn starts. Changes admitted after that boundary apply to the next provider turn and do not restart the current turn. +- The selected agent and model are sampled when a **Step** starts. Changes admitted after that boundary apply to the next Step and do not restart the current Step. - Selected-agent available-skill guidance remains a **Context Source**. An agent switch that changes that guidance produces a **Mid-Conversation System Message** while preserving the current baseline. -- Local tool authorization and pending permission requests retain the effective agent of the provider turn that issued the call; a later agent switch cannot change that call's policy. -- Context source changes never wake idle sessions; the next naturally scheduled **Safe Provider-Turn Boundary** loads and compares current values lazily. -- Once admitted, a **Mid-Conversation System Message** remains durable even if the following provider attempt fails and is replayed unchanged on retry. +- Local tool authorization and pending permission requests retain the effective agent of the **Step** that issued the call; a later agent switch cannot change that call's policy. +- Context source changes never wake idle sessions; the next naturally scheduled **Safe Step Boundary** loads and compares current values lazily. +- Once admitted, a **Mid-Conversation System Message** remains durable even if the following **Physical Attempt** fails and is replayed unchanged on retry. - **Mid-Conversation System Messages** remain durable Session-message history; normal user-facing transcript surfaces may hide them. - The date **Context Source** initially preserves host-local calendar-date behavior; a configured user timezone may replace that default later. - A **Context Epoch** begins with one immutable **Baseline System Context**. - A **Baseline System Context** is stored durably and reused verbatim across process restarts within its **Context Epoch**. - A **Baseline System Context** durably preserves the exact joined text used for the active provider-cache prefix. -- Completed compaction starts a new **Context Epoch** on the next provider attempt, folding the current complete **System Context** into a fresh baseline and removing earlier **Mid-Conversation System Messages** from active model history. -- A model/provider switch preserves the current **Context Epoch** and chronological conversation history; the new selection applies to the next provider turn. -- **Native Continuation Metadata** remains in durable history. Provider-turn projection includes it only for a successful exact originating provider/model match; failed turns and incompatible models omit opaque metadata, while non-empty visible reasoning lowers to ordinary assistant text after a model switch. This conservative relation may widen only when recorded provider tests establish compatibility. +- Completed compaction starts a new **Context Epoch** on the next **Physical Attempt**, folding the current complete **System Context** into a fresh baseline and removing earlier **Mid-Conversation System Messages** from active model history. +- A model/provider switch preserves the current **Context Epoch** and chronological conversation history; the new selection applies to the next **Step**. +- **Native Continuation Metadata** remains in durable history. Step projection includes it only for a successful exact originating provider/model match; failed Steps and incompatible models omit opaque metadata, while non-empty visible reasoning lowers to ordinary assistant text after a model switch. This conservative relation may widen only when recorded provider tests establish compatibility. - **Model Request Options** remain provider-semantic through Catalog resolution. The Session runner maps them into the LLM package's provider-option namespace; the selected protocol adapter alone owns provider wire encoding. - **Generation Controls**, protocol-semantic **Model Request Options**, and compatibility request body fields are separate Catalog domains. A shared ingestion adapter partitions legacy and models.dev AI-SDK-shaped options before routing. - The **PTY Environment** is a server concern rather than a Core PTY concern. PTY creation merges caller values, then the host overlay, then Core-forced terminal invariants such as `TERM` and `OPENCODE_TERMINAL`. diff --git a/packages/core/src/session/runner/llm.ts b/packages/core/src/session/runner/llm.ts index ba575b8146..12c73832c8 100644 --- a/packages/core/src/session/runner/llm.ts +++ b/packages/core/src/session/runner/llm.ts @@ -166,7 +166,7 @@ const layer = Layer.effect( { concurrency: "unbounded" }, ).pipe(Effect.map(SystemContext.combine)) - const runTurnAttempt = Effect.fn("SessionRunner.runTurn")(function* ( + const runTurnAttempt = Effect.fn("SessionRunner.runTurnAttempt")(function* ( sessionID: SessionSchema.ID, promotion: SessionInput.Delivery | undefined, step: number, @@ -423,6 +423,10 @@ const layer = Layer.effect( while (shouldRun) { let needsContinuation = true let step = 1 + // Repeat steps while continuation is needed. A step needs continuation only + // when it recorded local tool calls whose results the model has not yet seen; + // a provider error suppresses it. Pending steers also continue the loop so + // interjections are answered before the session goes idle. while (needsContinuation) { const result = yield* runTurn(input.sessionID, promotion, step) // Steer/queue promotion inside runTurn has already made the pending input a visible diff --git a/specs/v2/session.md b/specs/v2/session.md index bb04c21356..4abc7104fe 100644 --- a/specs/v2/session.md +++ b/specs/v2/session.md @@ -47,7 +47,7 @@ SessionExecution.resume(sessionID) `SessionExecution` and the read-side `SessionStore` are process-global. `SessionRunner`, catalog, model resolver, tool registry, permission state, and filesystem are cached per Location. No layer takes a Session ID. An omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics. -The local runner issues one explicit `llm.stream(request)` per provider turn, projects each complete local tool call durably before eagerly starting its structured child execution, awaits every started tool fiber after provider-stream closure, and reloads projected history once before continuation. Promoting any new user input resets the selected agent's configured provider-turn allowance; multiple steers promoted at one boundary reset it once. Tool settlement events carry the owning assistant message ID because provider-local call IDs may repeat across turns. Before assembling a provider request, the runner durably fails any local tool still projected as `running` from a previous process with `Tool execution interrupted`; abandoned side effects are never silently replayed. +The local runner issues one explicit `llm.stream(request)` per step, projects each complete local tool call durably before eagerly starting its structured child execution, awaits every started tool fiber after provider-stream closure, and reloads projected history once before continuation. Promoting any new user input resets the selected agent's configured step allowance; multiple steers promoted at one boundary reset it once. Tool settlement events carry the owning assistant message ID because provider-local call IDs may repeat across steps. Before assembling a provider request, the runner durably fails any local tool still projected as `running` from a previous process with `Tool execution interrupted`; abandoned side effects are never silently replayed. Projected hosted tools preserve call-side and settlement-side provider metadata separately so settlement and interruption recovery cannot erase continuation identifiers. Provider-native reasoning and provider metadata replay only while the historical assistant model matches the selected continuation model; after a model switch, visible reasoning text remains ordinary assistant text and provider-native metadata is omitted. @@ -55,7 +55,7 @@ Projected hosted tools preserve call-side and settlement-side provider metadata V2 Sessions persist the exact privileged System Context shown to the model. A Context Epoch stores one immutable provider-cache baseline and a model-hidden structured snapshot used to compare independently observed Context Sources. Environment facts, the host-local date, ambient global/upward-project `AGENTS.md` files, and selected-agent available-skill guidance are the initial sources. Location-wide sources come from the System Context Registry; selected-agent guidance composes with them immediately before Context Epoch admission. -The first complete observation initializes the epoch before any pending prompt becomes model-visible. If initial context is temporarily unavailable, execution stops while the prompt remains pending and retryable. On later provider turns, the runner promotes eligible input first, then reconciles current sources at the safe boundary. Changed context becomes one durable chronological System message, and its event commit advances the epoch snapshot atomically. +The first complete observation initializes the epoch before any pending prompt becomes model-visible. If initial context is temporarily unavailable, execution stops while the prompt remains pending and retryable. On later steps, the runner promotes eligible input first, then reconciles current sources at the safe boundary. Changed context becomes one durable chronological System message, and its event commit advances the epoch snapshot atomically. ```text Client Runner System Context Registry Context Epoch Store Session History LLM @@ -79,7 +79,7 @@ Client Runner System Context Registry C │ ├─ Baseline + chronological history ─────────────────────────────────────────────────────────────────────────▶ ``` -Agent and model selection are provider-turn scoped. A switch admitted after the current safe provider-turn boundary applies to the next provider turn without restarting the current turn or replacing the baseline. Agent-specific skill guidance remains a Context Source, so changed guidance is admitted as a chronological System message. A completed compaction causes the next provider attempt to render a fresh baseline directly from current complete context. A Session move clears the epoch so the destination Location initializes a complete baseline on its next run. +Agent and model selection are step-scoped. A switch admitted after the current safe step boundary applies to the next step without restarting the current step or replacing the baseline. Agent-specific skill guidance remains a Context Source, so changed guidance is admitted as a chronological System message. A completed compaction causes the next physical attempt to render a fresh baseline directly from current complete context. A Session move clears the epoch so the destination Location initializes a complete baseline on its next run. ```text Session Epoch @@ -110,15 +110,15 @@ Current Context Epoch follow-ups: ## Automatic Compaction -Before each provider turn, the runner estimates the complete model-visible request and compares it with the selected model's context window minus absolute reserved headroom. The reserve is the greater of the requested/model output allowance and configured `compaction.buffer`. When the request exceeds that budget and older complete turns are available, the runner compacts before executing the pending turn. +Before each step, the runner estimates the complete model-visible request and compares it with the selected model's context window minus absolute reserved headroom. The reserve is the greater of the requested/model output allowance and configured `compaction.buffer`. When the request exceeds that budget and older complete steps are available, the runner compacts before executing the pending step. Compaction keeps the full transcript durable while replacing its active model representation with one hidden checkpoint containing a structured rolling summary and token-bounded serialized recent context. Provider-native assistant, reasoning, and tool messages never survive across the boundary, avoiding signature and encrypted-reasoning failures when the earlier prefix changes. -`compaction.started.1` durably identifies the attempt. Compaction deltas are live-only progress. `compaction.ended.1` durably stores the final summary and serialized recent context; only this completed event projects a model-visible compaction message. On the next provider attempt, the runner observes that completed compaction and directly renders a fresh Context Epoch baseline. A failed or interrupted attempt therefore leaves the previous history boundary active. +`compaction.started.1` durably identifies the attempt. Compaction deltas are live-only progress. `compaction.ended.1` durably stores the final summary and serialized recent context; only this completed event projects a model-visible compaction message. On the next physical attempt, the runner observes that completed compaction and directly renders a fresh Context Epoch baseline. A failed or interrupted attempt therefore leaves the previous history boundary active. -Repeated compactions update the previous structured summary with newly compacted messages. The runner then reloads projected history and executes the original pending turn. +Repeated compactions update the previous structured summary with newly compacted messages. The runner then reloads projected history and executes the original pending step. -When a provider rejects a request as context overflow before durable assistant output or tool execution, the runner attempts one overflow-triggered compaction even when the local estimate did not predict pressure. A completed checkpoint rebuilds the same logical provider turn with one remaining physical attempt. A second overflow, unavailable compaction, or overflow after durable output becomes the ordinary terminal failure; recovery never loops or replays partial side effects. Deterministic old tool-result pruning remains a separate follow-up. +When a provider rejects a request as context overflow before durable assistant output or tool execution, the runner attempts one overflow-triggered compaction even when the local estimate did not predict pressure. A completed checkpoint rebuilds the same logical step with one remaining physical attempt. A second overflow, unavailable compaction, or overflow after durable output becomes the ordinary terminal failure; recovery never loops or replays partial side effects. Deterministic old tool-result pruning remains a separate follow-up. ## V1 Runtime Context Parity @@ -131,18 +131,18 @@ Status: `complete` is usable in the native V2 path, `partial` covers only part o | Durable Context Source | Environment facts and host-local date | partial | Add selected provider/model identity without making model selection a stale Location-wide value. | | Durable Context Source | Global and upward project instructions | partial | Decide whether V2 also discovers legacy `CLAUDE.md` and deprecated `CONTEXT.md`. | | Durable Context Source | Configured local/glob and remote URL instructions | missing | Add independent sources with explicit precedence, unavailable, and removal semantics. | -| Durable Context Source | Nearby nested instructions discovered after successful reads | missing | Persist discoveries and admit them at the next safe provider-turn boundary. | +| Durable Context Source | Nearby nested instructions discovered after successful reads | missing | Persist discoveries and admit them at the next safe step boundary. | | Durable Context Source | Selected-agent available skill guidance and skill-body loading | partial | Guidance and body exposure are permission-filtered; remove globally denied skill definitions during request-time tool materialization. | -| Per-turn request assembly | Placement, selected model, chronological history, and canonical lowering | complete | None. | -| Per-turn request assembly | Selected agent, agent prompt, and effective permissions | partial | V2 uses selected-agent permissions for skill guidance and tool authorization; still apply the agent system prompt and request policy. | -| Per-turn request assembly | Provider/model-specific base instructions | complete | Native V2 selects the provider-family baseline unless the effective agent overrides it. | -| Per-turn request assembly | Policy-filtered built-in, MCP, plugin, and structured-output tools | partial | Materialize definitions for the effective agent and request. | -| Per-turn request assembly | Per-prompt system text and tool overrides | missing | Design admission and durable replay semantics before exposing them. | -| Per-turn request assembly | Steering, plan/build-switch, and final-step reminders | missing | Add only reminders whose behavior remains part of V2. | -| Per-turn request assembly | Plugin message, system, parameter, and header transforms | missing | Design V2 plugin hooks and lifecycle semantics. | -| Per-turn request assembly | Model variants and request settings | partial | Apply effective agent options and future plugin-mutated request settings. | -| Per-turn request assembly | Structured-output policy | missing | Add prompt format, generated tool, tool choice, and model-visible policy together. | -| Per-turn request assembly | Automatic/context-pressure compaction | complete | V2 initiates automatic and overflow-triggered compaction, then rebuilds the baseline from the completed checkpoint. | +| Step request assembly | Placement, selected model, chronological history, and canonical lowering | complete | None. | +| Step request assembly | Selected agent, agent prompt, and effective permissions | partial | V2 uses selected-agent permissions for skill guidance and tool authorization; still apply the agent system prompt and request policy. | +| Step request assembly | Provider/model-specific base instructions | complete | Native V2 selects the provider-family baseline unless the effective agent overrides it. | +| Step request assembly | Policy-filtered built-in, MCP, plugin, and structured-output tools | partial | Materialize definitions for the effective agent and request. | +| Step request assembly | Per-prompt system text and tool overrides | missing | Design admission and durable replay semantics before exposing them. | +| Step request assembly | Steering, plan/build-switch, and final-step reminders | missing | Add only reminders whose behavior remains part of V2. | +| Step request assembly | Plugin message, system, parameter, and header transforms | missing | Design V2 plugin hooks and lifecycle semantics. | +| Step request assembly | Model variants and request settings | partial | Apply effective agent options and future plugin-mutated request settings. | +| Step request assembly | Structured-output policy | missing | Add prompt format, generated tool, tool choice, and model-visible policy together. | +| Step request assembly | Automatic/context-pressure compaction | complete | V2 initiates automatic and overflow-triggered compaction, then rebuilds the baseline from the completed checkpoint. | | Prompt/reference expansion | Durable typed prompt attachments | complete | None. | | Prompt/reference expansion | Native template and `@` mention expansion | missing | Parse and resolve native V2 prompt input before durable admission. | | Prompt/reference expansion | File, directory, media, and MCP-resource materialization | partial | Materialize and normalize sources instead of lowering unresolved attachment metadata. | @@ -154,23 +154,23 @@ Provider timeout, retry, and watchdog policy is intentionally deferred. The runn Inbox delivery is explicit: -- `steer` inputs promote at the next safe provider-turn boundary, including continuation inside the current drain. +- `steer` inputs promote at the next safe step boundary, including continuation inside the current drain. - `queue` inputs remain in a FIFO while the current drain requires continuation. When the Session would otherwise become idle, the runner promotes exactly one queued input, then reevaluates continuation before promoting another. Execution has two entry points: -- `run` is an explicit resume. It joins any active execution or starts a forced drain while idle. A forced drain bypasses the no-eligible-input guard, but preparation may still fail before a provider attempt. +- `run` is an explicit resume. It joins any active execution or starts a forced drain while idle. A forced drain bypasses the no-eligible-input guard, but preparation may still fail before a physical attempt. - `wake` reports newly recorded durable inbox work. Repeated wakes coalesce. A wake calls the provider only when it can promote eligible input. Post-crash continuation recovery is intentionally deferred. A wake does not infer that ambiguous provider work is safe to retry after an input has already been promoted. Explicit `run` may deliberately continue from durable projected history. A future recovery slice should model provider-dispatch ambiguity, required continuation, queued-input promotion, retry policy, and visible recovery status together. It must not assume an enclosing durable execution identity that the Session model does not otherwise need. -A process-global `SessionRunCoordinator` serializes execution for each local Session while allowing different Sessions to run concurrently. Resumes join active execution, overlapping wakes coalesce into one follow-up, and interruption stops current process-local execution without deleting durable inbox work. The runner enters the Session's current Location when execution starts and fences each new provider turn against that Location. +A process-global `SessionRunCoordinator` serializes execution for each local Session while allowing different Sessions to run concurrently. Resumes join active execution, overlapping wakes coalesce into one follow-up, and interruption stops current process-local execution without deleting durable inbox work. The runner enters the Session's current Location when execution starts and fences each new step against that Location. The coordinator's active registry is also the source for `sessions.active()`. It represents only foreground Session drains owned by the current process; background subagents and tasks do not add parent Sessions to this registry. The snapshot is runtime state and is empty after a process restart. Inbox promotion coalesces pending steers in durable admission order. Once continuation would otherwise end, it promotes one queued input at a time in FIFO order. Add explicit inbox backlog and steering-batch limits before exposing broad multi-caller admission or untrusted queue growth. -Eager local-tool execution is intentionally unbounded in the current local slice. This minimizes tool latency but does not increase SQLite settlement throughput: Session-event publication remains serialized per provider turn. Before broadening exposure, revisit per-turn call limits, output truncation, and operational backpressure using observed workloads. The normalized Session event schemas remain experimental and unshipped; databases created by earlier experimental builds are disposable rather than compatibility targets. +Eager local-tool execution is intentionally unbounded in the current local slice. This minimizes tool latency but does not increase SQLite settlement throughput: Session-event publication remains serialized per step. Before broadening exposure, revisit per-step call limits, output truncation, and operational backpressure using observed workloads. The normalized Session event schemas remain experimental and unshipped; databases created by earlier experimental builds are disposable rather than compatibility targets. The normalized Session event family and projected Session-message model predate this branch. This slice refines their replay contract: projected Session messages retain their source aggregate sequence so canonical context ordering and `sessions.messages(...)` pagination follow durable event order even when caller-supplied IDs differ; event time is carried by the envelope `created` field rather than duplicated in payloads. Consumers can use `sessions.log({ sessionID, after? })` to replay durable Session events after an aggregate sequence cursor, then tail durable events without a race. Live-only text, reasoning, and tool-input fragments remain available through EventV2 subscriptions for connected renderers; they are intentionally absent from the replayable Session stream. @@ -209,7 +209,7 @@ The first V2 `apply_patch` leaf supports add, update, and delete hunks. It parse ### Current Runner Follow-Ups -- Keep eager structured local-tool settlement: durably record each complete call, start its child execution immediately, await all started settlements after provider-turn consumption, persist every result, and reload history once before continuation. +- Keep eager structured local-tool settlement: durably record each complete call, start its child execution immediately, await all started settlements after step consumption, persist every result, and reload history once before continuation. - Buffer or coalesce streamed deltas before rewriting growing assistant projections. - Revisit additional covering indexes as larger-history query shapes become concrete. - Design any global multi-Session event stream separately; the finite history API deliberately reads one authorized Session aggregate and does not change global Event publication. diff --git a/specs/v2/todo.md b/specs/v2/todo.md index ee7f9dff2a..6f09684a1b 100644 --- a/specs/v2/todo.md +++ b/specs/v2/todo.md @@ -21,17 +21,17 @@ through legacy `SessionPrompt.loop(...)`: - process-global `SessionExecution.resume(sessionID)` discovers Location from the Session read model - cached Location-scoped `SessionRunner` resolves one supported catalog model - and issues one explicit `llm.stream(request)` provider turn at a time + and issues one explicit `llm.stream(request)` step at a time - durable V2 projections record text, reasoning, provider failures, tool calls, tool results, and assistant output - a scoped `ToolRegistry` advertises definitions and the first permission-checked `read` built-in -- local continuation reloads projected history, and promoting new user input resets the selected agent's configured provider-turn allowance +- local continuation reloads projected history, and promoting new user input resets the selected agent's configured step allowance - concurrent resumes for one Session join one process-local run while different Sessions remain concurrent Prompt admission now uses a durable `session_input` inbox rather than immediate -transcript projection. `steer` inputs promote at the next safe provider-turn +transcript projection. `steer` inputs promote at the next safe step boundary while the current drain requires continuation. `queue` inputs remain in a FIFO until the Session would otherwise become idle and then promote one at a time. @@ -39,12 +39,12 @@ Next reviewed slices: - preserve eager structured local-tool settlement: durably record each complete call, start its child execution immediately, await every settlement after the - provider turn closes, then reload projected history once -- revisit per-turn tool-call limits, output truncation, and operational + step closes, then reload projected history once +- revisit per-step tool-call limits, output truncation, and operational backpressure before broadening exposure; eager local execution is deliberately unbounded in the current local slice while SQLite publication stays serialized - remove the public in-memory `@opencode-ai/llm` tool loop after replacing its - remaining one-turn native-adapter use with a narrow typed dispatcher + remaining single-step native-adapter use with a narrow typed dispatcher - batch streamed deltas and add covering context indexes - expose replayable Session event cursors over HTTP and the generated SDK where remote consumers need them - integrate the new Job service with V2 tool execution: support background @@ -56,14 +56,14 @@ Next reviewed slices: ### Deferred durable continuation recovery Do not infer that ambiguous provider work is safe to retry from an advisory wake. -The first inbox-driven runner intentionally omits outer provider-attempt markers +The first inbox-driven runner intentionally omits outer physical-attempt markers until they have a concrete consumer and a complete recovery policy. Design post-crash continuation recovery as one explicit slice. It should model: - promoted input and projected-history state - queued-input promotion and steering assignment -- provider-attempt preparation versus provider-dispatch ambiguity +- physical-attempt preparation versus provider-dispatch ambiguity - required post-tool continuation across process loss - explicit `retry` and `abandon` decisions for unknown outcomes - bounded automatic retry only where provider and tool idempotency make it safe diff --git a/specs/v2/tools.md b/specs/v2/tools.md index 4dc7bfac22..6be14d2f7b 100644 --- a/specs/v2/tools.md +++ b/specs/v2/tools.md @@ -148,7 +148,7 @@ Invalid input never invokes the tool. Invalid output never produces a successful `toModelOutput` is pure and total. When omitted, the encoded output remains structured output; an encoded string is also projected as text. Projection does not receive invocation identity because presentation depends only on validated input and output. -Provider-turn materialization captures the effective registration identity for each advertised name without retaining its handler. Settlement rejects the call as stale if that registration was removed or replaced, including when closing an overlay reveals the previously effective registration. The current handler is captured only after this check; removing or replacing its registration afterward does not affect the running invocation. +Step materialization captures the effective registration identity for each advertised name without retaining its handler. Settlement rejects the call as stale if that registration was removed or replaced, including when closing an overlay reveals the previously effective registration. The current handler is captured only after this check; removing or replacing its registration afterward does not affect the running invocation. ## Output Bounding @@ -176,7 +176,7 @@ Leaf tools translate only errors they deliberately classify as recoverable. Broa - **Durable identity:** invocation-owned records use the exact Session, agent, assistant message, and call IDs supplied by the runner. - **Scoped registration:** closing a Scope removes exactly its registration and reveals any prior active overlay. - **Captured execution:** registration changes cannot alter an invocation after effective lookup. -- **Stale rejection:** a call never executes a registration other than the one advertised for its provider turn. +- **Stale rejection:** a call never executes a registration other than the one advertised for its step. - **Storage encapsulation:** domain output does not change according to model-output bounding or retention policy. ## Follow-Up From a644e0e7a095efcca87e6bbd079fc1acf86f0bf4 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 14:57:40 -0400 Subject: [PATCH 24/82] sync --- packages/cli/src/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index e515424183..64116b9b76 100755 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -47,6 +47,7 @@ Effect.logInfo("cli starting", { version: InstallationVersion, channel: InstallationChannel, local: InstallationLocal, + args: process.argv.slice(2), }).pipe( Effect.flatMap(() => Runtime.run(Commands, Handlers, { version: InstallationVersion })), Effect.annotateLogs({ role: "cli" }), From 50977dd4fe85e89802313741d643f2255236c80c Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 15:13:37 -0400 Subject: [PATCH 25/82] server: emit logs for every HTTP request to help debug API traffic --- packages/cli/src/commands/handlers/serve.ts | 2 +- packages/server/src/routes.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/commands/handlers/serve.ts b/packages/cli/src/commands/handlers/serve.ts index 8a6b1c2ceb..546c5de7c5 100644 --- a/packages/cli/src/commands/handlers/serve.ts +++ b/packages/cli/src/commands/handlers/serve.ts @@ -142,7 +142,7 @@ function listen(hostname: string, port: Option.Option, password: string) function bind(hostname: string, port: number, password: string) { const server = createServer() return Layer.build( - HttpRouter.serve(createRoutes(password), { disableListenLog: true, disableLogger: true }).pipe( + HttpRouter.serve(createRoutes(password), { disableListenLog: true }).pipe( Layer.provideMerge(NodeHttpServer.layer(() => server, { port, host: hostname })), Layer.provide(AppNodeBuilder.build(LayerNode.group([Credential.node, PermissionSaved.node]))), ), diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index 2157dd0b04..18ab2878f7 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -97,4 +97,4 @@ function simulationEnabled() { export const routes = createRoutes() export const webHandler = () => - HttpRouter.toWebHandler(routes.pipe(Layer.provide(HttpServer.layerServices)), { disableLogger: true }) + HttpRouter.toWebHandler(routes.pipe(Layer.provide(HttpServer.layerServices))) From e66cbf36e97d02b25ca8794b4313e679ca411967 Mon Sep 17 00:00:00 2001 From: James Long Date: Fri, 3 Jul 2026 15:34:30 -0400 Subject: [PATCH 26/82] fix(core): constrain location services (#35228) --- packages/cli/src/commands/handlers/serve.ts | 3 ++- packages/core/src/location-services.ts | 8 ++++---- packages/sdk-next/src/opencode.ts | 5 ++++- packages/server/src/routes.ts | 2 ++ 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/commands/handlers/serve.ts b/packages/cli/src/commands/handlers/serve.ts index 546c5de7c5..8d263880c5 100644 --- a/packages/cli/src/commands/handlers/serve.ts +++ b/packages/cli/src/commands/handlers/serve.ts @@ -3,6 +3,7 @@ import { Credential } from "@opencode-ai/core/credential" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { PermissionSaved } from "@opencode-ai/core/permission/saved" +import { Project } from "@opencode-ai/core/project" import { Global } from "@opencode-ai/core/global" import { Context, Effect, FileSystem, Layer, Option, Redacted, Schedule, Schema } from "effect" import { HttpRouter, HttpServer } from "effect/unstable/http" @@ -144,7 +145,7 @@ function bind(hostname: string, port: number, password: string) { return Layer.build( HttpRouter.serve(createRoutes(password), { disableListenLog: true }).pipe( Layer.provideMerge(NodeHttpServer.layer(() => server, { port, host: hostname })), - Layer.provide(AppNodeBuilder.build(LayerNode.group([Credential.node, PermissionSaved.node]))), + Layer.provide(AppNodeBuilder.build(LayerNode.group([Credential.node, PermissionSaved.node, Project.node]))), ), ).pipe( Effect.tap(() => Effect.addFinalizer(() => Effect.sync(() => server.closeAllConnections()))), diff --git a/packages/core/src/location-services.ts b/packages/core/src/location-services.ts index ffb7db2cf1..f0f2d63e7f 100644 --- a/packages/core/src/location-services.ts +++ b/packages/core/src/location-services.ts @@ -22,7 +22,6 @@ import { PermissionV2 } from "./permission" import { PluginV2 } from "./plugin" import { PluginInternal } from "./plugin/internal" import { Policy } from "./policy" -import { Project } from "./project" import { ProjectCopy } from "./project/copy" import { Pty } from "./pty" import { QuestionV2 } from "./question" @@ -49,8 +48,7 @@ import { Vcs } from "./vcs" export { LocationServiceMap } from "./location-service-map" -export const locationServices = LayerNode.group([ - Project.node, +const locationServiceNodes = [ Location.node, Policy.node, Config.node, @@ -96,7 +94,9 @@ export const locationServices = LayerNode.group([ Snapshot.node, SessionRunnerLLM.node, Vcs.node, -]) +] as const satisfies readonly Node.LocationNode[] + +export const locationServices = LayerNode.group(locationServiceNodes) export type LocationServices = LayerNode.Output export type LocationError = LayerNode.Error diff --git a/packages/sdk-next/src/opencode.ts b/packages/sdk-next/src/opencode.ts index 4737852ff4..087f689366 100644 --- a/packages/sdk-next/src/opencode.ts +++ b/packages/sdk-next/src/opencode.ts @@ -3,6 +3,7 @@ import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { PermissionSaved } from "@opencode-ai/core/permission/saved" import { SdkPlugins } from "@opencode-ai/core/plugin/sdk" +import { Project } from "@opencode-ai/core/project" import { createEmbeddedRoutes } from "@opencode-ai/server/routes" import { Context, Effect, Layer, Scope } from "effect" import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http" @@ -12,7 +13,7 @@ export const create = Effect.fn("OpenCode.create")(function* () { const memoMap = yield* Layer.makeMemoMap const sdkPlugins = SdkPlugins.makeStore() const context = yield* Layer.buildWithMemoMap( - AppNodeBuilder.build(LayerNode.group([PermissionSaved.node, SdkPlugins.node]), [ + AppNodeBuilder.build(LayerNode.group([PermissionSaved.node, Project.node, SdkPlugins.node]), [ [SdkPlugins.node, SdkPlugins.layerWithStore(sdkPlugins)], ]), memoMap, @@ -20,11 +21,13 @@ export const create = Effect.fn("OpenCode.create")(function* () { ) const plugins = Context.get(context, SdkPlugins.Service) const permissions = Context.get(context, PermissionSaved.Service) + const project = Context.get(context, Project.Service) const web = yield* Effect.acquireRelease( Effect.sync(() => HttpRouter.toWebHandler( createEmbeddedRoutes(sdkPlugins).pipe( HttpRouter.provideRequest(Layer.succeed(PermissionSaved.Service, permissions)), + HttpRouter.provideRequest(Layer.succeed(Project.Service, project)), Layer.provide(HttpServer.layerServices), ), { disableLogger: true, memoMap }, diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index 18ab2878f7..c5e43989d0 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -6,6 +6,7 @@ import { EventV2 } from "@opencode-ai/core/event" import { Credential } from "@opencode-ai/core/credential" import { PermissionSaved } from "@opencode-ai/core/permission/saved" import { PtyTicket } from "@opencode-ai/core/pty/ticket" +import { Project } from "@opencode-ai/core/project" import { SessionV2 } from "@opencode-ai/core/session" import { SessionExecution } from "@opencode-ai/core/session/execution" import { Job } from "@opencode-ai/core/job" @@ -33,6 +34,7 @@ const applicationServices = LayerNode.group([ httpClient, ToolOutputStore.cleanupNode, Job.node, + Project.node, SessionV2.node, PluginRuntime.providerNode, PermissionSaved.node, From 5d14c7a18550e1f886caf5b14e6962ee22ad6bdf Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 15:41:50 -0400 Subject: [PATCH 27/82] refactor(core): align runner naming with step vocabulary (#35227) --- .../core/src/session/context-checkpoint.ts | 2 +- packages/core/src/session/execution/local.ts | 2 +- packages/core/src/session/history.ts | 2 +- packages/core/src/session/instructions.ts | 4 +- packages/core/src/session/message-updater.ts | 2 +- packages/core/src/session/projector.ts | 5 ++- packages/core/src/session/runner/index.ts | 10 ++--- packages/core/src/session/runner/llm.ts | 44 +++++++++---------- .../src/session/runner/publish-llm-event.ts | 2 +- packages/core/src/system-context/index.ts | 2 +- .../core/test/session-runner-message.test.ts | 6 +-- .../core/test/session-runner-recorded.test.ts | 2 +- packages/core/test/session-runner.test.ts | 12 ++--- specs/v2/session.md | 2 +- 14 files changed, 47 insertions(+), 50 deletions(-) diff --git a/packages/core/src/session/context-checkpoint.ts b/packages/core/src/session/context-checkpoint.ts index fa3b24aedb..977514e8ca 100644 --- a/packages/core/src/session/context-checkpoint.ts +++ b/packages/core/src/session/context-checkpoint.ts @@ -18,7 +18,7 @@ const decodeApplied = Schema.decodeUnknownOption(SystemContext.Applied) * Loads or creates the session's durable context checkpoint, narrating any * drift since the model was last told as a chronological update. Completed * compaction rebaselines; nothing else rewrites the baseline. Runs before - * input promotion so a blocked first turn leaves pending inputs untouched. + * input promotion so a blocked first step leaves pending inputs untouched. */ export const prepare = Effect.fn("SessionContextCheckpoint.prepare")(function* ( db: DatabaseService, diff --git a/packages/core/src/session/execution/local.ts b/packages/core/src/session/execution/local.ts index 1a45537490..4e68e6c3d9 100644 --- a/packages/core/src/session/execution/local.ts +++ b/packages/core/src/session/execution/local.ts @@ -20,7 +20,7 @@ const layer = Layer.effect( drain: Effect.fnUntraced(function* (sessionID: SessionSchema.ID, force) { const session = yield* store.get(sessionID) if (!session) return yield* Effect.die(new Error(`Session not found: ${sessionID}`)) - return yield* SessionRunner.Service.use((runner) => runner.run({ sessionID, force })).pipe( + return yield* SessionRunner.Service.use((runner) => runner.drain({ sessionID, force })).pipe( Effect.provide(locations.get(session.location)), Effect.tapCause((cause) => Cause.hasInterruptsOnly(cause) diff --git a/packages/core/src/session/history.ts b/packages/core/src/session/history.ts index a704a631f7..9a6a75fe2f 100644 --- a/packages/core/src/session/history.ts +++ b/packages/core/src/session/history.ts @@ -34,7 +34,7 @@ const messageRows = Effect.fnUntraced(function* ( and( eq(SessionMessageTable.session_id, sessionID), // Keep system updates visible in the gap between a completed compaction - // and the next prepared turn's rebaseline, when their content is not yet + // and the next prepared step's rebaseline, when their content is not yet // folded into a new baseline. compaction ? or( diff --git a/packages/core/src/session/instructions.ts b/packages/core/src/session/instructions.ts index a75074ae04..22f003e5ea 100644 --- a/packages/core/src/session/instructions.ts +++ b/packages/core/src/session/instructions.ts @@ -36,9 +36,9 @@ const layer = Layer.effect( // absolute paths, but the human-facing description shows paths relative to the project // root so opening a subdirectory still describes paths from the project root. const root = yield* fs.resolve(location.project.directory) - // Same-turn parallel reads settle concurrently, so an in-memory claim guards each + // Same-step parallel reads settle concurrently, so an in-memory claim guards each // Session/path pair before any filesystem work. The durable history check below covers - // paths injected in earlier turns after this Location layer was reopened. + // paths injected in earlier steps after this Location layer was reopened. const injected = yield* Ref.make>>(new Map()) const load = Effect.fn("SessionInstructions.load")(function* (input: { diff --git a/packages/core/src/session/message-updater.ts b/packages/core/src/session/message-updater.ts index b07d0d1234..a23ecb224c 100644 --- a/packages/core/src/session/message-updater.ts +++ b/packages/core/src/session/message-updater.ts @@ -19,7 +19,7 @@ export interface Adapter { export function memory(state: MemoryState): Adapter { const assistantIndex = (messageID: SessionMessage.ID) => state.messages.findLastIndex((message) => message.id === messageID) - // A newer turn supersedes stale incomplete rows; never resume an older assistant projection. + // A newer step supersedes stale incomplete rows; never resume an older assistant projection. const latestAssistantIndex = () => state.messages.findLastIndex((message) => message.type === "assistant") const activeShellIndex = (callID: string) => state.messages.findLastIndex((message) => message.type === "shell" && message.callID === callID) diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index 62ad7ec2ce..c5b552e8b4 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -168,7 +168,8 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( .get() .pipe(Effect.orDie) : undefined - if (event.data.from && !boundary) return yield* Effect.die(new Error(`Fork boundary message not found: ${event.data.from}`)) + if (event.data.from && !boundary) + return yield* Effect.die(new Error(`Fork boundary message not found: ${event.data.from}`)) const copied = yield* db .select({ seq: SessionMessageTable.seq }) .from(SessionMessageTable) @@ -357,7 +358,7 @@ function run(db: DatabaseService, event: MessageEvent) { const adapter: SessionMessageUpdater.Adapter = { getCurrentAssistant() { return Effect.gen(function* () { - // A newer turn supersedes stale incomplete rows; never resume an older assistant projection. + // A newer step supersedes stale incomplete rows; never resume an older assistant projection. const row = yield* db .select() .from(SessionMessageTable) diff --git a/packages/core/src/session/runner/index.ts b/packages/core/src/session/runner/index.ts index 11141c3447..7c2a6f463d 100644 --- a/packages/core/src/session/runner/index.ts +++ b/packages/core/src/session/runner/index.ts @@ -9,16 +9,12 @@ import type { SystemContext } from "../../system-context/index" import type { ToolOutputStore } from "../../tool-output-store" export type RunError = - | LLMError - | SessionRunnerModel.Error - | MessageDecodeError - | SystemContext.InitializationBlocked - | ToolOutputStore.Error + LLMError | SessionRunnerModel.Error | MessageDecodeError | SystemContext.InitializationBlocked | ToolOutputStore.Error /** Runs one local continuation from already-recorded Session history. */ export interface Interface { - /** Drains eligible durable work. Explicit runs perform one provider attempt even when no work is eligible. */ - readonly run: (input: { + /** Drains eligible durable work. Explicit runs perform one physical attempt even when no work is eligible. */ + readonly drain: (input: { readonly sessionID: SessionSchema.ID readonly force: boolean }) => Effect.Effect diff --git a/packages/core/src/session/runner/llm.ts b/packages/core/src/session/runner/llm.ts index 12c73832c8..0aeaa0e052 100644 --- a/packages/core/src/session/runner/llm.ts +++ b/packages/core/src/session/runner/llm.ts @@ -61,11 +61,11 @@ import { llmClient } from "../../effect/app-node-platform" * - Runtime context assembly * - Track V1 runtime-context parity canonically in `specs/v2/session.md`. * - * - One provider turn + * - One step * - [x] Translate every projected V2 Session message variant into canonical * `@opencode-ai/llm` messages. * - [ ] Resolve policy-filtered built-in, MCP, plugin, and structured-output tool definitions. - * - [x] Stream exactly one `llm.stream(request)` provider turn. + * - [x] Stream exactly one `llm.stream(request)` physical attempt. * - [x] Persist assistant text and usage events incrementally as they arrive. * - [ ] Persist snapshots, patches, and retry notices incrementally as they arrive. * - [x] Persist reasoning, provider errors, and tool-call events incrementally as they arrive. @@ -77,8 +77,8 @@ import { llmClient } from "../../effect/app-node-platform" * - [x] Start each recorded local call eagerly and await all settlements before continuation. * - [ ] Add scoped runtime context, progress updates, attachment normalization, * plugins, and cancellation settlement. - * - [x] Reload projected history and start the next explicit provider turn after local tool results. - * - [x] Continue for durable user steering accepted during an active provider turn. + * - [x] Reload projected history and start the next explicit step after local tool results. + * - [x] Continue for durable user steering accepted during an active step. * - [ ] Continue for compaction or another continuation condition when required. * * - Post-run maintenance @@ -86,12 +86,12 @@ import { llmClient } from "../../effect/app-node-platform" * - [ ] Coalesce streamed deltas and add covering projected-history indexes. * - [ ] Update title, summaries, compaction state, and cleanup in bounded background work. * - * Use `llm.stream(request)` for each provider turn. Keep tool execution and continuation here. + * Use `llm.stream(request)` for each physical attempt. Keep tool execution and continuation here. * Durable continuation recovery remains a separate future slice with an explicit retry policy. * * The current slice loads V2 history, translates it, resolves a model through a core service, and persists one - * provider turn. Registry definitions are advertised, local tool calls are settled durably, and an - * explicit loop starts the next provider turn after local settlement. Configured agent step limits bound the loop. + * step. Registry definitions are advertised, local tool calls are settled durably, and an + * explicit loop starts the next step after local settlement. Configured agent step limits bound the loop. */ const layer = Layer.effect( @@ -114,7 +114,7 @@ const layer = Layer.effect( const db = (yield* Database.Service).db const compaction = yield* SessionCompaction.Service const title = yield* SessionTitle.Service - // Title generation is a side effect of the first turn; it must not delay turn continuation. + // Title generation is a side effect of the first step; it must not delay step continuation. // Tracked per process so repeated wakes before the second user message arrives don't // re-fire a redundant LLM call; `SessionTitle` itself is idempotent based on durable history. const titleAttempted = new Set() @@ -166,7 +166,7 @@ const layer = Layer.effect( { concurrency: "unbounded" }, ).pipe(Effect.map(SystemContext.combine)) - const runTurnAttempt = Effect.fn("SessionRunner.runTurnAttempt")(function* ( + const attemptStep = Effect.fn("SessionRunner.attemptStep")(function* ( sessionID: SessionSchema.ID, promotion: SessionInput.Delivery | undefined, step: number, @@ -177,7 +177,7 @@ const layer = Layer.effect( return yield* Effect.interrupt const agent = yield* agents.select(session.agent) // Establish what the model knows before admitting what the user said, so - // a blocked first turn leaves pending inputs untouched. + // a blocked first step leaves pending inputs untouched. const checkpoint = yield* SessionContextCheckpoint.prepare( db, events, @@ -231,7 +231,7 @@ const layer = Layer.effect( snapshot: startSnapshot, }) const publication = Semaphore.makeUnsafe(1) - // Durable publishes are serialized so tool fibers and turn settlement never interleave + // Durable publishes are serialized so tool fibers and step settlement never interleave // mid-event. const serialized = (effect: Effect.Effect) => publication.withPermit(effect) const publish = (event: LLMEvent, outputPaths: ReadonlyArray = []) => @@ -282,7 +282,7 @@ const layer = Layer.effect( Effect.ensuring(serialized(publisher.flush())), ) - // Captures the end snapshot, diffs it against the turn's start, and durably ends the + // Captures the end snapshot, diffs it against the step's start, and durably ends the // assistant step. const publishStepEnd = (settlement: NonNullable>) => Effect.gen(function* () { @@ -316,7 +316,7 @@ const layer = Layer.effect( const streamInterrupted = stream._tag === "Failure" && Cause.hasInterrupts(stream.cause) // A context overflow before any assistant output is recoverable: compact and - // restart the turn instead of surfacing the provider error. + // restart the step instead of surfacing the provider error. if ( recoverOverflow && !publisher.hasAssistantStarted() && @@ -325,7 +325,7 @@ const layer = Layer.effect( ) return { _tag: "RestartAfterOverflowCompaction", step: currentStep } as const - // An unrecovered held-back overflow becomes the turn's durable provider error. A + // An unrecovered held-back overflow becomes the step's durable provider error. A // thrown LLM failure fails hosted tool calls and the assistant unless a provider // error was already recorded from the stream. if (overflowFailure) yield* publish(overflowFailure) @@ -346,12 +346,12 @@ const layer = Layer.effect( if (questionDismissed || streamInterrupted || toolsInterrupted) { yield* FiberSet.clear(toolFibers) yield* serialized(publisher.failUnsettledTools("Tool execution interrupted")) - yield* serialized(publisher.failAssistant("Provider turn interrupted")) + yield* serialized(publisher.failAssistant("Step interrupted")) // Match V1: dismissing a question halts the loop like an interruption. if (questionDismissed) return yield* Effect.interrupt } // A settled tool fiber failure is one of two things. A defect from a tool - // implementation becomes a failed tool call the model can read, and the turn still + // implementation becomes a failed tool call the model can read, and the step still // settles so the model may recover. A typed infrastructure failure (tool output // could not be persisted) also fails the assistant and then fails the drain. const settledFailure = settled._tag === "Failure" && !toolsInterrupted ? settled.cause : undefined @@ -387,7 +387,7 @@ const layer = Layer.effect( ) }, Effect.scoped) - const runTurn = Effect.fnUntraced(function* ( + const runStep = Effect.fnUntraced(function* ( sessionID: SessionSchema.ID, promotion: SessionInput.Delivery | undefined, step: number, @@ -399,7 +399,7 @@ const layer = Layer.effect( let currentPromotion = promotion let currentStep = step while (true) { - const attempt = yield* runTurnAttempt(sessionID, currentPromotion, currentStep, recoverOverflow) + const attempt = yield* attemptStep(sessionID, currentPromotion, currentStep, recoverOverflow) if (attempt._tag === "Completed") return { needsContinuation: attempt.needsContinuation, step: attempt.step } if (attempt._tag === "RestartAfterOverflowCompaction") recoverOverflow = undefined yield* Effect.yieldNow @@ -410,7 +410,7 @@ const layer = Layer.effect( // ExecutionSettled is published per execution (busy period) by SessionExecution, not per // drain here. - const run = Effect.fn("SessionRunner.run")(function* (input: { + const drain = Effect.fn("SessionRunner.drain")(function* (input: { readonly sessionID: SessionSchema.ID readonly force: boolean }) { @@ -428,8 +428,8 @@ const layer = Layer.effect( // a provider error suppresses it. Pending steers also continue the loop so // interjections are answered before the session goes idle. while (needsContinuation) { - const result = yield* runTurn(input.sessionID, promotion, step) - // Steer/queue promotion inside runTurn has already made the pending input a visible + const result = yield* runStep(input.sessionID, promotion, step) + // Steer/queue promotion inside runStep has already made the pending input a visible // user message by this point, so the first-user-message check below is reliable. if (!titleAttempted.has(input.sessionID)) { titleAttempted.add(input.sessionID) @@ -445,7 +445,7 @@ const layer = Layer.effect( } }) - return Service.of({ run }) + return Service.of({ drain }) }), ) diff --git a/packages/core/src/session/runner/publish-llm-event.ts b/packages/core/src/session/runner/publish-llm-event.ts index 4b7b6fb92c..9a334a0a6d 100644 --- a/packages/core/src/session/runner/publish-llm-event.ts +++ b/packages/core/src/session/runner/publish-llm-event.ts @@ -50,7 +50,7 @@ const settledOutput = (value: ToolOutput | undefined, result: ToolResultValue): return { structured: record(settled.structured), content: settled.content } } -/** Persist one provider turn without executing tools or starting a continuation turn. */ +/** Persist one step without executing tools or starting a continuation step. */ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) => { const tools = new Map< string, diff --git a/packages/core/src/system-context/index.ts b/packages/core/src/system-context/index.ts index ce6aaae454..d86efceb91 100644 --- a/packages/core/src/system-context/index.ts +++ b/packages/core/src/system-context/index.ts @@ -12,7 +12,7 @@ import { Effect, Option, Schema } from "effect" * The durable `Applied` record tracks what the model was last told, per source: * it is the model's current belief. Interpreters uphold one invariant — * `reconcile` never rewrites the baseline; it only narrates drift as update - * text. Only `rebaseline` (compaction) and `initialize` (first turn) produce + * text. Only `rebaseline` (compaction) and `initialize` (first step) produce * baseline text. * * Returning `unavailable` means observation failed temporarily. It differs from diff --git a/packages/core/test/session-runner-message.test.ts b/packages/core/test/session-runner-message.test.ts index 840a4e424c..d33b44728d 100644 --- a/packages/core/test/session-runner-message.test.ts +++ b/packages/core/test/session-runner-message.test.ts @@ -354,7 +354,7 @@ Recent work state: SessionMessage.ToolStateError.make({ status: "error", input: { query: "Effect" }, - error: { type: "unknown", message: "Provider turn interrupted" }, + error: { type: "unknown", message: "Step interrupted" }, content: [], structured: {}, }), @@ -362,7 +362,7 @@ Recent work }), ], finish: "error", - error: { type: "unknown", message: "Provider turn interrupted" }, + error: { type: "unknown", message: "Step interrupted" }, time: { created, completed: created }, }), ], @@ -386,7 +386,7 @@ Recent work result: { type: "error", value: { - error: { type: "unknown", message: "Provider turn interrupted" }, + error: { type: "unknown", message: "Step interrupted" }, content: [], structured: {}, }, diff --git a/packages/core/test/session-runner-recorded.test.ts b/packages/core/test/session-runner-recorded.test.ts index 2768be820a..4f82baba96 100644 --- a/packages/core/test/session-runner-recorded.test.ts +++ b/packages/core/test/session-runner-recorded.test.ts @@ -98,7 +98,7 @@ const execution = Layer.effect( Effect.gen(function* () { const sessionRunner = yield* SessionRunner.Service const coordinator = yield* SessionRunCoordinator.make({ - drain: (sessionID, force) => sessionRunner.run({ sessionID, force }), + drain: (sessionID, force) => sessionRunner.drain({ sessionID, force }), }) return SessionExecution.Service.of({ active: coordinator.active, diff --git a/packages/core/test/session-runner.test.ts b/packages/core/test/session-runner.test.ts index ca8ec42775..e6f14c8e19 100644 --- a/packages/core/test/session-runner.test.ts +++ b/packages/core/test/session-runner.test.ts @@ -260,7 +260,7 @@ const execution = Layer.effect( Effect.gen(function* () { const sessionRunner = yield* SessionRunner.Service const coordinator = yield* SessionRunCoordinator.make({ - drain: (sessionID, force) => sessionRunner.run({ sessionID, force }), + drain: (sessionID, force) => sessionRunner.drain({ sessionID, force }), }) return SessionExecution.Service.of({ active: coordinator.active, @@ -575,7 +575,7 @@ const verifyPartialFlushOnInterruption = (kind: FragmentKind) => ) const runner = yield* SessionRunner.Service - const fiber = yield* runner.run({ sessionID, force: true }).pipe(Effect.forkChild) + const fiber = yield* runner.drain({ sessionID, force: true }).pipe(Effect.forkChild) yield* Deferred.await(streamed) yield* Fiber.interrupt(fiber) expect(yield* session.context(sessionID)).toMatchObject([ @@ -583,7 +583,7 @@ const verifyPartialFlushOnInterruption = (kind: FragmentKind) => { type: "assistant", finish: "error", - error: { type: "unknown", message: "Provider turn interrupted" }, + error: { type: "unknown", message: "Step interrupted" }, content: [ kind === "tool input" ? { type: "tool", id: fragmentID(kind, "interrupted"), state: { status: "error" } } @@ -2983,7 +2983,7 @@ describe("SessionRunnerLLM", () => { expect(requests).toHaveLength(1) expect(yield* session.context(sessionID)).toMatchObject([ { type: "user", text: "Interrupt provider" }, - { type: "assistant", finish: "error", error: { type: "unknown", message: "Provider turn interrupted" } }, + { type: "assistant", finish: "error", error: { type: "unknown", message: "Step interrupted" } }, ]) expect(yield* recordedEventTypes(sessionID)).toContain("step.failed.1") yield* session.interrupt(sessionID) @@ -3007,7 +3007,7 @@ describe("SessionRunnerLLM", () => { ] const runner = yield* SessionRunner.Service - const run = yield* runner.run({ sessionID, force: true }).pipe(Effect.forkChild) + const run = yield* runner.drain({ sessionID, force: true }).pipe(Effect.forkChild) yield* Deferred.await(toolExecutionsStarted) yield* Fiber.interrupt(run) toolExecutionGate = undefined @@ -3018,7 +3018,7 @@ describe("SessionRunnerLLM", () => { { type: "assistant", finish: "error", - error: { type: "unknown", message: "Provider turn interrupted" }, + error: { type: "unknown", message: "Step interrupted" }, content: [ { type: "tool", diff --git a/specs/v2/session.md b/specs/v2/session.md index 4abc7104fe..b4b91ace09 100644 --- a/specs/v2/session.md +++ b/specs/v2/session.md @@ -42,7 +42,7 @@ Execution routing starts from only the Session ID: SessionExecution.resume(sessionID) -> SessionStore.get(sessionID) -> LocationServiceMap.get(session.location) --> SessionRunner.run({ sessionID, force? }) +-> SessionRunner.drain({ sessionID, force? }) ``` `SessionExecution` and the read-side `SessionStore` are process-global. `SessionRunner`, catalog, model resolver, tool registry, permission state, and filesystem are cached per Location. No layer takes a Session ID. An omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics. From 37b26e495ba857e0727e7124221e54f940b509d8 Mon Sep 17 00:00:00 2001 From: James Long Date: Fri, 3 Jul 2026 15:46:04 -0400 Subject: [PATCH 28/82] feat(simulation): share control protocol schemas (#35230) --- packages/simulation/package.json | 3 +- packages/simulation/src/backend/control.ts | 56 ++------ packages/simulation/src/frontend/actions.ts | 31 +---- packages/simulation/src/frontend/server.ts | 83 ++--------- packages/simulation/src/protocol/index.ts | 145 ++++++++++++++++++++ 5 files changed, 170 insertions(+), 148 deletions(-) create mode 100644 packages/simulation/src/protocol/index.ts diff --git a/packages/simulation/package.json b/packages/simulation/package.json index 93bab0540e..29613ff28a 100644 --- a/packages/simulation/package.json +++ b/packages/simulation/package.json @@ -9,7 +9,8 @@ "./backend": "./src/backend/index.ts", "./backend/*": "./src/backend/*.ts", "./frontend": "./src/frontend/simulation.ts", - "./frontend/*": "./src/frontend/*.ts" + "./frontend/*": "./src/frontend/*.ts", + "./protocol": "./src/protocol/index.ts" }, "scripts": { "typecheck": "tsgo --noEmit" diff --git a/packages/simulation/src/backend/control.ts b/packages/simulation/src/backend/control.ts index f3fc67116c..10bded13af 100644 --- a/packages/simulation/src/backend/control.ts +++ b/packages/simulation/src/backend/control.ts @@ -1,4 +1,5 @@ -import { Effect, Schema } from "effect" +import { Effect } from "effect" +import { SimulationProtocol } from "../protocol" import { SimulationLLMExchange } from "./llm-exchange" import { SimulationNetwork } from "./network" @@ -23,43 +24,13 @@ import { SimulationNetwork } from "./network" const DefaultPort = 40950 const MaxPortAttempts = 100 -const ChunkItem = Schema.Union([ - Schema.Struct({ type: Schema.Literal("textDelta"), text: Schema.String }), - Schema.Struct({ type: Schema.Literal("reasoningDelta"), text: Schema.String }), - Schema.Struct({ type: Schema.Literal("toolCall"), id: Schema.String, name: Schema.String, input: Schema.Unknown }), - Schema.Struct({ type: Schema.Literal("raw"), chunk: Schema.Unknown }), -]) - -const ChunkParams = Schema.Struct({ id: Schema.String, items: Schema.Array(ChunkItem) }) - -const FinishParams = Schema.Struct({ - id: Schema.String, - reason: Schema.Literals(["stop", "tool-calls", "length", "content-filter"]).pipe( - Schema.withDecodingDefault(Effect.succeed("stop" as const)), - ), -}) - -const decodeChunkParams = Schema.decodeUnknownPromise(ChunkParams) -const decodeFinishParams = Schema.decodeUnknownPromise(FinishParams) - -type JsonRpcRequest = { - readonly jsonrpc: "2.0" - readonly id?: string | number | null - readonly method: string - readonly params?: unknown -} - type ControlSocket = Bun.ServerWebSocket<{ unsubscribe?: () => void }> -function parseRequest(input: string | Buffer): JsonRpcRequest { - const value = JSON.parse(typeof input === "string" ? input : input.toString()) as unknown - if (typeof value !== "object" || value === null) throw new Error("Invalid JSON-RPC request") - if (!("jsonrpc" in value) || value.jsonrpc !== "2.0") throw new Error("Invalid JSON-RPC version") - if (!("method" in value) || typeof value.method !== "string") throw new Error("Invalid JSON-RPC method") - return value as JsonRpcRequest +function parseRequest(input: string | Buffer) { + return SimulationProtocol.JsonRpc.decodeRequest(JSON.parse(typeof input === "string" ? input : input.toString())) } -async function handle(socket: ControlSocket, request: JsonRpcRequest): Promise { +async function handle(socket: ControlSocket, request: SimulationProtocol.JsonRpc.Request): Promise { switch (request.method) { case "llm.attach": { socket.data.unsubscribe?.() @@ -69,7 +40,7 @@ async function handle(socket: ControlSocket, request: JsonRpcRequest): Promise void @@ -36,63 +19,15 @@ function isPortUnavailable(error: unknown) { return message.includes("eaddrinuse") || message.includes("address already in use") || message.includes(" in use") } -function parseRequest(input: string | Buffer): JsonRpcRequest { - const value = JSON.parse(typeof input === "string" ? input : input.toString()) as unknown - if (typeof value !== "object" || value === null) throw new Error("Invalid JSON-RPC request") - if (!("jsonrpc" in value) || value.jsonrpc !== "2.0") throw new Error("Invalid JSON-RPC version") - if (!("method" in value) || typeof value.method !== "string") throw new Error("Invalid JSON-RPC method") - return value as JsonRpcRequest -} - -function isAction(input: unknown): input is Action { - if (typeof input !== "object" || input === null || !("type" in input)) return false - switch (input.type) { - case "typeText": - return "text" in input && typeof input.text === "string" - case "pressKey": - return "key" in input && typeof input.key === "string" - case "pressEnter": - return true - case "pressArrow": - return "direction" in input && ["up", "down", "left", "right"].includes(String(input.direction)) - case "focus": - return "target" in input && typeof input.target === "number" - case "click": - return ( - "target" in input && - typeof input.target === "number" && - "x" in input && - typeof input.x === "number" && - "y" in input && - typeof input.y === "number" - ) - } - return false -} - function actionParam(params: unknown) { - if (typeof params !== "object" || params === null || !("action" in params)) throw new Error("Missing action") - if (!isAction(params.action)) throw new Error("Invalid action") - return params.action + return SimulationProtocol.Frontend.decodeActionParams(params).action } -function response(id: JsonRpcRequest["id"], result: unknown): JsonRpcResponse | undefined { - if (id === undefined) return undefined - return { jsonrpc: "2.0", id, result } +function parseRequest(input: string | Buffer) { + return SimulationProtocol.JsonRpc.decodeRequest(JSON.parse(typeof input === "string" ? input : input.toString())) } -function errorResponse(id: JsonRpcRequest["id"], error: unknown): JsonRpcResponse { - return { - jsonrpc: "2.0", - id: id ?? null, - error: { - code: -32000, - message: error instanceof Error ? error.message : String(error), - }, - } -} - -async function handle(harness: Harness, request: JsonRpcRequest) { +async function handle(harness: Harness, request: SimulationProtocol.JsonRpc.Request) { switch (request.method) { case "ui.state": { const result = SimulationActions.state(harness) @@ -139,14 +74,14 @@ function serve( SimulationTrace.add("control.disconnect") }, async message(socket, message) { - let request: JsonRpcRequest | undefined + let request: SimulationProtocol.JsonRpc.Request | undefined try { request = parseRequest(message) const result = await handle(harness, request) - const next = response(request.id, result) + const next = SimulationProtocol.JsonRpc.success(request.id, result) if (next) socket.send(JSON.stringify(next)) } catch (error) { - socket.send(JSON.stringify(errorResponse(request?.id, error))) + socket.send(JSON.stringify(SimulationProtocol.JsonRpc.failure(request?.id, error))) } }, }, diff --git a/packages/simulation/src/protocol/index.ts b/packages/simulation/src/protocol/index.ts new file mode 100644 index 0000000000..6ff63c9bb3 --- /dev/null +++ b/packages/simulation/src/protocol/index.ts @@ -0,0 +1,145 @@ +import { Effect, Schema } from "effect" + +const JsonRpcID = Schema.Union([Schema.String, Schema.Number, Schema.Null]) +type Json = Schema.Schema.Type + +export namespace JsonRpc { + export const Request = Schema.Struct({ + jsonrpc: Schema.Literal("2.0"), + id: Schema.optional(JsonRpcID), + method: Schema.String, + params: Schema.optional(Schema.Json), + }) + export interface Request extends Schema.Schema.Type {} + + export const ErrorObject = Schema.Struct({ + code: Schema.Number, + message: Schema.String, + data: Schema.optional(Schema.Json), + }) + + export const Response = Schema.Struct({ + jsonrpc: Schema.Literal("2.0"), + id: JsonRpcID, + result: Schema.optional(Schema.Json), + error: Schema.optional(ErrorObject), + }) + export interface Response extends Schema.Schema.Type {} + + export const decodeRequest = Schema.decodeUnknownSync(Request) + + export function success(id: Request["id"], result: unknown): Response | undefined { + if (id === undefined) return undefined + return { jsonrpc: "2.0", id, result: result as Json } + } + + export function failure(id: Request["id"], error: unknown): Response { + return { + jsonrpc: "2.0", + id: id ?? null, + error: { + code: -32000, + message: error instanceof Error ? error.message : String(error), + }, + } + } +} + +export namespace Frontend { + export const KeyModifiers = Schema.Struct({ + ctrl: Schema.optional(Schema.Boolean), + shift: Schema.optional(Schema.Boolean), + meta: Schema.optional(Schema.Boolean), + super: Schema.optional(Schema.Boolean), + hyper: Schema.optional(Schema.Boolean), + }) + export interface KeyModifiers extends Schema.Schema.Type {} + + export const Action = Schema.Union([ + Schema.Struct({ type: Schema.Literal("typeText"), text: Schema.String }), + Schema.Struct({ type: Schema.Literal("pressKey"), key: Schema.String, modifiers: Schema.optional(KeyModifiers) }), + Schema.Struct({ type: Schema.Literal("pressEnter") }), + Schema.Struct({ type: Schema.Literal("pressArrow"), direction: Schema.Literals(["up", "down", "left", "right"]) }), + Schema.Struct({ type: Schema.Literal("focus"), target: Schema.Number }), + Schema.Struct({ type: Schema.Literal("click"), target: Schema.Number, x: Schema.Number, y: Schema.Number }), + ]) + export type Action = Schema.Schema.Type + + export const Element = Schema.Struct({ + id: Schema.String, + num: Schema.Number, + x: Schema.Number, + y: Schema.Number, + width: Schema.Number, + height: Schema.Number, + focusable: Schema.Boolean, + focused: Schema.Boolean, + clickable: Schema.Boolean, + editor: Schema.Boolean, + }) + export interface Element extends Schema.Schema.Type {} + + export const State = Schema.Struct({ + screen: Schema.String, + focused: Schema.Struct({ + renderable: Schema.optional(Schema.Number), + editor: Schema.Boolean, + }), + elements: Schema.Array(Element), + actions: Schema.Array(Action), + }) + export interface State extends Schema.Schema.Type {} + + export const ActionParams = Schema.Struct({ action: Action }) + export interface ActionParams extends Schema.Schema.Type {} + export const decodeActionParams = Schema.decodeUnknownSync(ActionParams) + + export const TraceRecord = Schema.Struct({ + id: Schema.Number, + time: Schema.String, + type: Schema.String, + data: Schema.optional(Schema.Json), + }) + export interface TraceRecord extends Schema.Schema.Type {} + + export const TraceList = Schema.Struct({ records: Schema.Array(TraceRecord) }) + export interface TraceList extends Schema.Schema.Type {} +} + +export namespace Backend { + export const Item = Schema.Union([ + Schema.Struct({ type: Schema.Literal("textDelta"), text: Schema.String }), + Schema.Struct({ type: Schema.Literal("reasoningDelta"), text: Schema.String }), + Schema.Struct({ type: Schema.Literal("toolCall"), id: Schema.String, name: Schema.String, input: Schema.Json }), + Schema.Struct({ type: Schema.Literal("raw"), chunk: Schema.Json }), + ]) + export type Item = Schema.Schema.Type + + export const FinishReason = Schema.Literals(["stop", "tool-calls", "length", "content-filter"]) + export type FinishReason = Schema.Schema.Type + + export const ChunkParams = Schema.Struct({ id: Schema.String, items: Schema.Array(Item) }) + export interface ChunkParams extends Schema.Schema.Type {} + + export const FinishParams = Schema.Struct({ + id: Schema.String, + reason: FinishReason.pipe(Schema.withDecodingDefault(Effect.succeed("stop" as const))), + }) + export interface FinishParams extends Schema.Schema.Type {} + + export const OpenedExchange = Schema.Struct({ id: Schema.String, url: Schema.String, body: Schema.Json }) + export interface OpenedExchange extends Schema.Schema.Type {} + + export const NetworkLogEntry = Schema.Struct({ + time: Schema.Number, + method: Schema.String, + url: Schema.String, + matched: Schema.Boolean, + }) + export interface NetworkLogEntry extends Schema.Schema.Type {} + + export const decodeChunkParams = Schema.decodeUnknownPromise(ChunkParams) + export const decodeFinishParams = Schema.decodeUnknownPromise(FinishParams) +} + +export * as SimulationProtocol from "./index" From 438654768c767d3d81b21d0c0181cf039e9d43d4 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 3 Jul 2026 14:55:03 -0500 Subject: [PATCH 29/82] fix(codemode): require exact tool paths in guidance (#35224) --- packages/codemode/src/tool-runtime.ts | 13 ++++---- packages/codemode/test/codemode.test.ts | 10 +++--- packages/codemode/test/signature.test.ts | 40 ++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 11 deletions(-) diff --git a/packages/codemode/src/tool-runtime.ts b/packages/codemode/src/tool-runtime.ts index fa3ddc6c2f..d79d0182b5 100644 --- a/packages/codemode/src/tool-runtime.ts +++ b/packages/codemode/src/tool-runtime.ts @@ -458,8 +458,8 @@ export const discoveryPlan = ( // Section order is deliberate: workflow first (the top is the least likely part of a long // description to be truncated or skimmed away), then rules, then syntax, with the budgeted - // catalog at the bottom. Example call forms use explicit `.` placeholders - - // never a real or fabricated tool name. + // catalog at the bottom. Example call forms use placeholders - never a real or fabricated + // tool name - and show both dot and bracket notation so non-identifier names are not normalized. const intro = [ "Write a CodeMode program to answer the request. Return code only.", empty @@ -467,6 +467,7 @@ export const discoveryPlan = ( : complete ? "Execute JavaScript in a confined runtime. Inside this program, `tools` contains only the host-provided tools listed below; surrounding agent tools are not available unless listed here." : "Execute JavaScript in a confined runtime. Inside this program, `tools` contains only the host-provided tools listed or searchable below; surrounding agent tools are not available unless listed here.", + ...(empty ? [] : ["Do not infer or normalize tool names; use only exact signatures shown below or returned by search."]), ] // The search step exists only when search is advertised (PARTIAL catalog); a COMPLETE @@ -480,14 +481,14 @@ export const discoveryPlan = ( ...(complete ? [ "1. Pick a tool from the list under `## Available tools` - each line is the exact call signature; use it as-is rather than guessing segments.", - "2. Call it using the exact signature shown: `const res = await tools..(input)` - bracket notation may appear for names that are not JavaScript identifiers.", + '2. Call it using the exact signature shown; bracket notation and quotes are part of the path.', '3. Parse text results: `const data = typeof res === "string" ? JSON.parse(res) : res` - most tools return JSON as a string.', "4. Return only the fields you need: `return { : data. }` - raw payloads get truncated and waste context.", ] : [ - '1. Find a tool (skip when it is already listed below): `const { items } = await tools.$codemode.search({ query: "" })` - short phrases like "list issues" work best.', + '1. If the exact signature is not listed below, first search: `const { items } = await tools.$codemode.search({ query: "" })`.', "2. Read the matches: each item is `{ path, description, signature }` - read the description before using an unfamiliar tool.", - "3. Call it with the result's `path` as-is (never guess segments): `const res = await tools..(input)` - bracket notation may appear for names that are not JavaScript identifiers.", + "3. Call the result's `path` as-is; bracket notation and quotes are part of the path.", '4. Parse text results: `const data = typeof res === "string" ? JSON.parse(res) : res` - most tools return JSON as a string.', "5. Return only the fields you need: `return { : data. }` - raw payloads get truncated and waste context.", ]), @@ -504,7 +505,7 @@ export const discoveryPlan = ( : "- Only tools listed here or returned by `tools.$codemode.search` are available inside `tools`; tools from the surrounding agent/runtime are not implicitly exposed.", "- Filter, aggregate, and transform collections in code - never return them raw or call a tool per item across messages.", "- A result typed `Promise` has no guaranteed shape - verify what actually came back before relying on its fields.", - "- Run independent calls in parallel: `await Promise.all(items.map((item) => tools..(item)))`.", + '- Run independent calls in parallel: `await Promise.all(items.map((item) => tools..(item)))`, or use `tools.["tool-name"](item)` when the listed signature uses bracket notation.', "- `Object.keys(tools)` lists namespaces; `Object.keys(tools.)` lists its tools; `for...in` works on both.", ...(complete ? [] diff --git a/packages/codemode/test/codemode.test.ts b/packages/codemode/test/codemode.test.ts index eaa834e0a4..4fda88b384 100644 --- a/packages/codemode/test/codemode.test.ts +++ b/packages/codemode/test/codemode.test.ts @@ -622,12 +622,12 @@ describe("CodeMode public contract", () => { ) expect(instructions).toContain("Return only the fields you need") expect(instructions).toContain("raw payloads get truncated and waste context") - expect(instructions).toContain("`const res = await tools..(input)`") + expect(instructions).toContain("Do not infer or normalize tool names") + expect(instructions).toContain("bracket notation and quotes are part of the path") expect(instructions).toContain("surrounding agent tools are not available unless listed here") expect(instructions).toContain("Only tools listed here are available inside `tools`") - expect(instructions).toContain("bracket notation may appear for names that are not JavaScript identifiers") - // Placeholders use the ./ style ONLY - no fabricated tool - // names, and no real catalog tools cherry-picked into example lines. + // Placeholders use generic namespace/tool/field names only - no fabricated real tools + // and no real catalog tools cherry-picked into example lines. expect(instructions).toContain("`return { : data. }`") expect(instructions).not.toContain("total_count") expect(instructions).not.toContain("list_issues") @@ -640,7 +640,7 @@ describe("CodeMode public contract", () => { // PARTIAL: the workflow starts with search (with query-style guidance that is clearly // a query string, never a tool name) and the browse-namespace rule appears. expect(partial).toContain( - '1. Find a tool (skip when it is already listed below): `const { items } = await tools.$codemode.search({ query: "" })` - short phrases like "list issues" work best.', + '1. If the exact signature is not listed below, first search: `const { items } = await tools.$codemode.search({ query: "" })`.', ) expect(partial).toContain( "Only tools listed here or returned by `tools.$codemode.search` are available inside `tools`", diff --git a/packages/codemode/test/signature.test.ts b/packages/codemode/test/signature.test.ts index 9c45371d93..edf4c442c4 100644 --- a/packages/codemode/test/signature.test.ts +++ b/packages/codemode/test/signature.test.ts @@ -339,3 +339,43 @@ describe("pretty signatures in search results", () => { expect(instructions).not.toContain("/**") }) }) + +describe("non-identifier tool paths", () => { + const resolveLibrary = Tool.make({ + description: "Resolve a Context7 library ID", + input: { + type: "object", + properties: { + query: { type: "string" }, + libraryName: { type: "string" }, + }, + required: ["query", "libraryName"], + } as const, + run: () => Effect.succeed("/reactjs/react.dev"), + }) + const runtime = CodeMode.make({ tools: { context7: { "resolve-library-id": resolveLibrary } } }) + + test("inline catalog uses bracket notation for dashed tool names", () => { + const instructions = runtime.instructions() + + expect(instructions).toContain( + 'tools.context7["resolve-library-id"](input: { query: string; libraryName: string }): Promise', + ) + expect(instructions).toContain("Do not infer or normalize tool names") + expect(instructions).toContain("bracket notation and quotes are part of the path") + expect(instructions).not.toContain("tools.context7.resolve-library-id") + expect(instructions).not.toContain("tools.context7.resolve_library_id") + }) + + test("search results return callable bracket-notation paths and signatures", async () => { + const result = await Effect.runPromise( + runtime.execute(`return await tools.$codemode.search({ query: "resolve library" })`), + ) + expect(result.ok).toBe(true) + if (!result.ok) throw new Error("search failed") + + const value = result.value as { items: Array<{ path: string; signature: string }> } + expect(value.items[0]?.path).toBe('tools.context7["resolve-library-id"]') + expect(value.items[0]?.signature).toContain('tools.context7["resolve-library-id"](input: {') + }) +}) From d097cc806508c6bdcfd3d9332a781d688c313ff4 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 3 Jul 2026 15:10:25 -0500 Subject: [PATCH 30/82] feat(tui): render execute child calls on v2 (#35231) --- packages/tui/src/routes/session/index.tsx | 63 +++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index d406fe664e..b0f337c2d4 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -1810,6 +1810,9 @@ function ToolPart(props: { part: SessionMessageAssistantTool }) { + + + @@ -2296,6 +2299,65 @@ export function formatCompletedSubagentDetail(toolcalls: number, duration: strin return `${formatSubagentToolcalls(toolcalls)} · ${duration}` } +type ExecuteCall = { tool: string; status: "running" | "completed" | "error"; input?: Record } + +function executeCalls(value: unknown): ExecuteCall[] { + if (!Array.isArray(value)) return [] + return value.flatMap((call) => { + const item = recordValue(call) + const tool = stringValue(item?.tool) + const status = stringValue(item?.status) + if (!tool || !status || !["running", "completed", "error"].includes(status)) return [] + return [{ tool, status: status as ExecuteCall["status"], input: recordValue(item?.input) }] + }) +} + +function Execute(props: ToolProps) { + const ctx = use() + const { theme } = useTheme() + const isLoading = createMemo(() => props.part.state.status === "pending" || props.part.state.status === "running") + const calls = createMemo(() => executeCalls(props.metadata.toolCalls)) + const output = createMemo(() => stripAnsi(props.output?.trim() ?? "")) + const hasRuntimeError = createMemo(() => props.metadata.error === true) + const outputPreview = createMemo(() => collapseToolOutput(output(), 4, 4 * Math.max(20, ctx.width - 6)).output) + const showOutput = createMemo(() => output() && hasRuntimeError()) + const content = createMemo(() => { + const lines = ["execute"] + for (const call of calls()) { + const args = input(call.input ?? {}) + lines.push(`↳ ${call.tool}${args ? ` ${args}` : ""}${call.status === "error" ? " (failed)" : ""}`) + } + return lines.join("\n") + }) + + return ( + <> + + {content()} + + + + + {(line, index) => ( + + {index() === 0 ? "↳ " : " "} + {line} + + )} + + + + + ) +} + function Edit(props: ToolProps) { const ctx = use() const { theme, syntax } = useTheme() @@ -2571,6 +2633,7 @@ const toolDisplays = new Set([ "write", "edit", "subagent", + "execute", "apply_patch", "todowrite", "question", From 64e4f6f91b951680320a6cbe07e059a550c95261 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Fri, 3 Jul 2026 22:47:04 +0200 Subject: [PATCH 31/82] cli: route run commands through v2 APIs (#35234) --- .../src/cli/cmd/run/footer.prompt.tsx | 17 +- .../opencode/src/cli/cmd/run/footer.view.tsx | 1 + packages/opencode/src/cli/cmd/run/runtime.ts | 4 +- .../src/cli/cmd/run/stream-v2.transport.ts | 378 +++++++++++++---- packages/opencode/src/cli/cmd/run/types.ts | 2 + .../test/cli/run/footer.view.test.tsx | 49 ++- .../test/cli/run/stream-v2.transport.test.ts | 389 ++++++++++++++++++ 7 files changed, 763 insertions(+), 77 deletions(-) diff --git a/packages/opencode/src/cli/cmd/run/footer.prompt.tsx b/packages/opencode/src/cli/cmd/run/footer.prompt.tsx index 90efdc5695..9d10a5266a 100644 --- a/packages/opencode/src/cli/cmd/run/footer.prompt.tsx +++ b/packages/opencode/src/cli/cmd/run/footer.prompt.tsx @@ -175,14 +175,18 @@ function parseSlashCommand(text: string, commands: RunCommand[] | undefined) { return { type: "pending" as const } } - if (!commands.some((item) => item.name === head.name)) { + const item = commands.find((entry) => entry.name === head.name) + if (!item) { return { type: "none" as const } } - return { type: "command" as const, command: { name: head.name, arguments: head.arguments } } + return { + type: "command" as const, + command: { name: head.name, arguments: head.arguments, ...(item.source ? { source: item.source } : {}) }, + } } -function selectedCommand(text: string, command: RunPrompt["command"]) { +export function selectedCommand(text: string, command: RunPrompt["command"], commands?: RunCommand[]) { if (!command) { return } @@ -192,9 +196,14 @@ function selectedCommand(text: string, command: RunPrompt["command"]) { return } + // Bound drafts (e.g. the skill picker) may predate or omit the catalog + // source; resolve it at submit time so routing never degrades to a plain + // command for a skill entry. + const source = command.source ?? commands?.find((item) => item.name === command.name)?.source return { name: command.name, arguments: head.arguments, + ...(source ? { source } : {}), } } @@ -1178,7 +1187,7 @@ export function createPromptState(input: PromptInput): PromptState { return } - const command = next.mode === "shell" ? undefined : selectedCommand(next.text, next.command) + const command = next.mode === "shell" ? undefined : selectedCommand(next.text, next.command, input.commands()) if (!command && next.mode !== "shell" && isExitCommand(next.text)) { input.onExit() return diff --git a/packages/opencode/src/cli/cmd/run/footer.view.tsx b/packages/opencode/src/cli/cmd/run/footer.view.tsx index 245a24816d..a7c1321494 100644 --- a/packages/opencode/src/cli/cmd/run/footer.view.tsx +++ b/packages/opencode/src/cli/cmd/run/footer.view.tsx @@ -781,6 +781,7 @@ export function RunFooterView(props: RunFooterViewProps) { command: { name, arguments: "", + source: "skill", }, }) closePanel() diff --git a/packages/opencode/src/cli/cmd/run/runtime.ts b/packages/opencode/src/cli/cmd/run/runtime.ts index 8f3704fd41..e340a89cc3 100644 --- a/packages/opencode/src/cli/cmd/run/runtime.ts +++ b/packages/opencode/src/cli/cmd/run/runtime.ts @@ -665,7 +665,9 @@ async function runInteractiveRuntime(input: RunRuntimeInput, deps: RunRuntimeDep (row) => row.commit.kind !== "user" || row.commit.messageID !== prompt.messageID, ) } - includeFiles = false + // Shell and skill turns never send CLI file attachments; keep them + // pending for the next prompt-shaped turn. + if (prompt.mode !== "shell" && prompt.command?.source !== "skill") includeFiles = false } catch (error) { if (signal.aborted || footer.isClosed) { return diff --git a/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts b/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts index 614a960634..c15ed48e5b 100644 --- a/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts +++ b/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts @@ -77,6 +77,15 @@ type Wait = { onVisibleOutput?: (anchor: LocalReplayAnchor) => void } +// One active session.shell call. The HTTP response is the completion signal; +// callID correlates the live shell events once shell.started is observed, and +// abort cancels the blocking request when the user interrupts the turn. +type ShellWait = { + callID?: string + resolve: () => void + abort: () => void +} + type RunV2Event = V2Event type PromptFilePart = Extract @@ -99,6 +108,11 @@ type State = { projectedReasoning: Map tools: Map finishedTools: Set + skillMessages: Set + shellCommands: Map + shellStarted: Set + shellEnded: Set + shellWait?: ShellWait wait?: Wait connected: boolean closed: boolean @@ -179,10 +193,71 @@ function promptFileSource(part: PromptFilePart) { } } +function promptFiles(next: SessionTurnInput) { + return next.prompt.parts.flatMap((part) => + part.type === "file" + ? [ + { + uri: part.url, + name: part.filename, + source: promptFileSource(part), + }, + ] + : [], + ) +} + +function promptAgents(next: SessionTurnInput) { + return next.prompt.parts.flatMap((part) => + part.type === "agent" + ? [ + { + name: part.name, + source: part.source ? { start: part.source.start, end: part.source.end, text: part.source.value } : undefined, + }, + ] + : [], + ) +} + function streamPartKey(messageID: string, partID: string) { return `${messageID}\u0000${partID}` } +// Matches the commit shapes the legacy session-data reducer produced for direct +// shell calls: one "start" commit rendering `$ command` and one "progress" +// commit rendering the merged output (see toolEntryBody in tool.ts). +function shellCommit( + callID: string, + command: string, + next: { text: string; phase: "start" | "progress"; toolState: "running" | "completed" }, +): StreamCommit { + return { + kind: "tool", + source: "tool", + partID: `shell:${callID}`, + tool: "bash", + shell: { callID, command }, + ...next, + } +} + +// session.shell resolves after the command settled server-side; the matching +// live shell.ended event usually lands within the same tick, but hold the turn +// briefly so the output commit renders inside it. +const SHELL_OUTPUT_GRACE_MS = 1500 + +function skillCommit(messageID: string, name: string): StreamCommit { + return { + kind: "system", + source: "system", + messageID, + partID: `skill:${messageID}`, + text: `→ Skill "${name}"`, + phase: "start", + } +} + async function resolveSelectedModel(input: StreamInput, next: Pick) { if (next.model) return { providerID: next.model.providerID, id: next.model.modelID, variant: next.variant } if (!next.variant) return @@ -213,6 +288,10 @@ export async function createSessionTransport(input: StreamInput): Promise { + if (state.wait || state.shellWait) throw new Error("prompt already running") + if (!state.connected) throw new Error("Event stream is reconnecting") + const abort = new AbortController() + const onAbort = () => abort.abort() + next.signal?.addEventListener("abort", onAbort, { once: true }) + let rendered!: () => void + const output = new Promise((resolve) => { + rendered = resolve + }) + const active: ShellWait = { resolve: rendered, abort: () => abort.abort() } + state.shellWait = active + input.trace?.write("send.shell", { sessionID: input.sessionID, command: next.prompt.text }) + write([], { phase: "running", status: "running shell" }) + try { + await input.sdk.v2.session.shell( + { sessionID: input.sessionID, command: next.prompt.text }, + { throwOnError: true, signal: abort.signal }, + ) + await Promise.race([output, wait(SHELL_OUTPUT_GRACE_MS, abort.signal)]) + } catch (error) { + if (abort.signal.aborted) return + throw error + } finally { + next.signal?.removeEventListener("abort", onAbort) + if (state.shellWait === active) state.shellWait = undefined + } + } + + // Shared settlement scaffolding for prompt-shaped turns: registers the wait, + // wires interruption, sends, then blocks until the live settled event (or a + // hydration pass over an idle session) resolves it. + const runTurnWait = async ( + next: SessionTurnInput, + messageID: string, + turn: { promoted?: boolean; send: () => Promise }, + ) => { + let resolve!: () => void + let reject!: (error: unknown) => void + const done = new Promise((ok, fail) => { + resolve = ok + reject = fail + }) + const active: Wait = { + messageID, + promoted: turn.promoted === true, + interrupted: false, + failureRendered: false, + resolve, + reject, + onVisibleOutput: next.onVisibleOutput, + } + state.wait = active + const interrupt = () => { + active.interrupted = true + void input.sdk.v2.session.interrupt({ sessionID: input.sessionID }).catch(() => {}) + } + next.signal?.addEventListener("abort", interrupt, { once: true }) + try { + await turn.send() + await done + } catch (error) { + if (state.wait === active) state.wait = undefined + if (next.signal?.aborted) return + throw error + } finally { + next.signal?.removeEventListener("abort", interrupt) + } + } + return { async runPromptTurn(next) { - if (next.prompt.mode === "shell") throw new Error("Shell is not yet available for current Session transcripts") - if (next.prompt.command) throw new Error("Commands are not yet available for current Session transcripts") - if (state.wait) throw new Error("prompt already running") + if (next.prompt.mode === "shell") { + await runShellTurn(next) + return + } + if (state.wait || state.shellWait) throw new Error("prompt already running") if (!state.connected) throw new Error("Event stream is reconnecting") + const messageID = next.prompt.messageID + if (!messageID) throw new Error("Prompt message ID is required") + + const command = next.prompt.command + if (command?.source === "skill") { + input.trace?.write("send.skill", { sessionID: input.sessionID, messageID, skill: command.name }) + await runTurnWait(next, messageID, { + send: () => + input.sdk.v2.session.skill( + { sessionID: input.sessionID, id: messageID, skill: command.name }, + { throwOnError: true, signal: next.signal }, + ), + }) + return + } + if (command) { + const selected = await resolveSelectedModel(input, next) + if (next.variant && !selected) throw new Error("Cannot select a variant before selecting a model") + // Agent and model ride the command payload; the server switches only + // when the command itself does not pin them. + const files = [ + ...(next.includeFiles ? next.files : []).map((file) => ({ uri: file.url, name: file.filename })), + ...promptFiles(next), + ] + const agents = promptAgents(next) + input.trace?.write("send.command", { sessionID: input.sessionID, messageID, command: command.name }) + await runTurnWait(next, messageID, { + send: () => + input.sdk.v2.session.command( + { + sessionID: input.sessionID, + id: messageID, + command: command.name, + arguments: command.arguments, + agent: next.agent, + model: selected, + files: files.length ? files : undefined, + agents: agents.length ? agents : undefined, + delivery: "steer", + }, + { throwOnError: true, signal: next.signal }, + ), + }) + return + } if (next.agent) { await input.sdk.v2.session.switchAgent( @@ -695,78 +964,41 @@ export async function createSessionTransport(input: StreamInput): Promise - part.type === "file" - ? [ - { - uri: part.url, - name: part.filename, - source: promptFileSource(part), + const attachments = [ + ...prepared.flatMap((file) => (file.attachment ? [file.attachment] : [])), + ...promptFiles(next), + ] + const agents = promptAgents(next) + input.trace?.write("send.prompt", { sessionID: input.sessionID, messageID }) + await runTurnWait(next, messageID, { + send: () => + input.sdk.v2.session.prompt( + { + sessionID: input.sessionID, + id: messageID, + prompt: { + text: [ + next.prompt.text, + ...prepared.flatMap((file) => (file.text ? [file.text] : [])), + ].join("\n\n"), + files: attachments.length ? attachments : undefined, + agents: agents.length ? agents : undefined, }, - ] - : [], - ) - const attachments = [...prepared.flatMap((file) => (file.attachment ? [file.attachment] : [])), ...promptFiles] - const agents = next.prompt.parts.flatMap((part) => - part.type === "agent" - ? [ - { - name: part.name, - source: part.source - ? { start: part.source.start, end: part.source.end, text: part.source.value } - : undefined, - }, - ] - : [], - ) - const messageID = next.prompt.messageID - if (!messageID) throw new Error("Prompt message ID is required") - let resolve!: () => void - let reject!: (error: unknown) => void - const done = new Promise((done, fail) => { - resolve = done - reject = fail - }) - const active: Wait = { - messageID, - promoted: false, - interrupted: false, - failureRendered: false, - resolve, - reject, - onVisibleOutput: next.onVisibleOutput, - } - state.wait = active - const interrupt = () => { - active.interrupted = true - void input.sdk.v2.session.interrupt({ sessionID: input.sessionID }).catch(() => {}) - } - next.signal?.addEventListener("abort", interrupt, { once: true }) - try { - input.trace?.write("send.prompt", { sessionID: input.sessionID, messageID }) - await input.sdk.v2.session.prompt( - { - sessionID: input.sessionID, - id: messageID, - prompt: { - text: [next.prompt.text, ...prepared.flatMap((file) => (file.text ? [file.text] : []))].join("\n\n"), - files: attachments.length ? attachments : undefined, - agents: agents.length ? agents : undefined, + delivery: "steer", }, - delivery: "steer", - }, - { throwOnError: true, signal: next.signal }, - ) - await done - } catch (error) { - if (state.wait === active) state.wait = undefined - if (next.signal?.aborted) return - throw error - } finally { - next.signal?.removeEventListener("abort", interrupt) - } + { throwOnError: true, signal: next.signal }, + ), + }) }, async interruptActiveTurn() { + // A running shell holds no drain, so session.interrupt cannot reach it; + // abort the blocking request instead. The server-side command keeps its + // own lifecycle and simply loses its waiter. + const shell = state.shellWait + if (shell) { + shell.abort() + return + } if (state.wait) state.wait.interrupted = true await input.sdk.v2.session.interrupt({ sessionID: input.sessionID }).catch(() => {}) }, @@ -787,6 +1019,10 @@ export async function createSessionTransport(input: StreamInput): Promise } }) +test("selectedCommand backfills the catalog source for bound drafts", () => { + const catalog = [command({ name: "opencode-ts", description: "TS skill", source: "skill" })] + + // The skill picker binds `/name ` drafts; older drafts may lack source. + expect(selectedCommand("/opencode-ts fix it", { name: "opencode-ts", arguments: "" }, catalog)).toEqual({ + name: "opencode-ts", + arguments: "fix it", + source: "skill", + }) + // An explicit source wins without a catalog lookup. + expect(selectedCommand("/opencode-ts", { name: "opencode-ts", arguments: "", source: "skill" })).toEqual({ + name: "opencode-ts", + arguments: "", + source: "skill", + }) + // Plain commands stay untagged. + expect(selectedCommand("/deploy prod", { name: "deploy", arguments: "" }, [ + command({ name: "deploy", description: "Deploy" }), + ])).toEqual({ name: "deploy", arguments: "prod" }) +}) + +test("direct footer tags skill slash submissions with their catalog source", async () => { + const submits: RunPrompt[] = [] + const app = await renderFooter({ + commands: [command({ name: "formatter", description: "Apply formatter fixes", source: "skill" })], + onSubmit(prompt) { + submits.push(prompt) + return true + }, + }) + + try { + await app.renderOnce() + "/formatter src".split("").forEach((key) => app.mockInput.pressKey(key)) + await app.renderOnce() + app.mockInput.pressEnter() + await app.renderOnce() + + expect(submits).toEqual([ + { text: "/formatter src", parts: [], command: { name: "formatter", arguments: "src", source: "skill" } }, + ]) + } finally { + app.cleanup() + } +}) + // OpenTUI currently segfaults Bun while tearing down this composer-to-skill-panel transition. // Re-enable after the upstream renderer teardown fix lands. test.skip("direct footer skill picker inserts an editable bound skill command", async () => { @@ -864,7 +911,7 @@ test.skip("direct footer skill picker inserts an editable bound skill command", app.mockInput.pressEnter() await app.renderOnce() - expect(submits).toEqual([{ text: "/new task", parts: [], command: { name: "new", arguments: "task" } }]) + expect(submits).toEqual([{ text: "/new task", parts: [], command: { name: "new", arguments: "task", source: "skill" } }]) } finally { app.cleanup() } diff --git a/packages/opencode/test/cli/run/stream-v2.transport.test.ts b/packages/opencode/test/cli/run/stream-v2.transport.test.ts index 8bf429e500..e43e88f934 100644 --- a/packages/opencode/test/cli/run/stream-v2.transport.test.ts +++ b/packages/opencode/test/cli/run/stream-v2.transport.test.ts @@ -1002,6 +1002,395 @@ describe("V2 mini transport", () => { await transport.close() }) + test("runs a shell turn through v2.session.shell and renders live output", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ streams: [events] }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + let request: Parameters[0] | undefined + spyOn(client.v2.session, "shell").mockImplementation((input) => { + request = input + queueMicrotask(() => { + events.push({ + id: "evt_shell_start", + created: 0, + type: "shell.started", + durable: durable("ses_1"), + data: { sessionID: "ses_1", callID: "call_shell", command: "ls" }, + }) + events.push({ + id: "evt_shell_end", + created: 0, + type: "shell.ended", + durable: durable("ses_1", 1), + data: { sessionID: "ses_1", callID: "call_shell", output: "file.txt" }, + }) + }) + return ok(undefined) as never + }) + + await transport.runPromptTurn({ + agent: undefined, + model: undefined, + variant: undefined, + prompt: { text: "ls", parts: [], mode: "shell" }, + files: [], + includeFiles: true, + }) + + expect(request).toMatchObject({ sessionID: "ses_1", command: "ls" }) + expect(ui.commits.filter((item) => item.shell)).toMatchObject([ + { phase: "start", tool: "bash", toolState: "running", shell: { callID: "call_shell", command: "ls" } }, + { phase: "progress", text: "file.txt", toolState: "completed", shell: { callID: "call_shell", command: "ls" } }, + ]) + expect(ui.events).toContainEqual({ type: "stream.patch", patch: { phase: "running", status: "running shell" } }) + await transport.close() + }) + + test("aborts an active shell turn without interrupting the session", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ streams: [events] }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + let started = false + let aborted = false + spyOn(client.v2.session, "shell").mockImplementation( + (_input, options) => + new Promise((_, reject) => { + started = true + options?.signal?.addEventListener("abort", () => { + aborted = true + reject(new Error("aborted")) + }) + }) as never, + ) + const interrupted = spyOn(client.v2.session, "interrupt").mockImplementation(() => ok(undefined)) + + const turn = transport.runPromptTurn({ + agent: undefined, + model: undefined, + variant: undefined, + prompt: { text: "sleep 100", parts: [], mode: "shell" }, + files: [], + includeFiles: true, + }) + while (!started) await Bun.sleep(0) + await transport.interruptActiveTurn() + await turn + + expect(aborted).toBe(true) + expect(interrupted).not.toHaveBeenCalled() + await transport.close() + }) + + test("hydrates projected shell transcripts once and dedupes live redelivery", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ + streams: [events], + messages: { + ses_1: [ + { + id: "msg_shell", + type: "shell" as const, + callID: "call_1", + command: "ls", + output: "file.txt", + time: { created: 1, completed: 2 }, + }, + ], + }, + }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + events.push({ + id: "evt_shell_end", + created: 0, + type: "shell.ended", + durable: durable("ses_1", 1), + data: { sessionID: "ses_1", callID: "call_1", output: "file.txt" }, + }) + await Bun.sleep(0) + await Bun.sleep(0) + + expect(ui.commits.filter((item) => item.shell)).toMatchObject([ + { phase: "start", shell: { callID: "call_1", command: "ls" } }, + { phase: "progress", text: "file.txt", toolState: "completed" }, + ]) + await transport.close() + }) + + test("routes command prompts through v2.session.command", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ streams: [events] }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + let request: Parameters[0] | undefined + spyOn(client.v2.session, "command").mockImplementation((input) => { + request = input + queueMicrotask(() => { + events.push({ + id: "evt_prompted", + created: 0, + type: "prompt.promoted", + durable: durable("ses_1"), + data: { + sessionID: "ses_1", + inputID: "msg_cmd", + }, + }) + events.push({ + id: "evt_settled", + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, + }) + }) + return ok({ + data: { + admittedSeq: 1, + id: input.id ?? "msg_cmd", + sessionID: "ses_1", + prompt: { text: "evaluated template" }, + delivery: "steer" as const, + timeCreated: 2, + }, + }) + }) + + await transport.runPromptTurn({ + agent: "build", + model: { providerID: "test", modelID: "model" }, + variant: undefined, + prompt: { + messageID: "msg_cmd", + text: "/deploy prod", + parts: [], + command: { name: "deploy", arguments: "prod" }, + }, + files: [], + includeFiles: true, + }) + + expect(request).toMatchObject({ + sessionID: "ses_1", + id: "msg_cmd", + command: "deploy", + arguments: "prod", + agent: "build", + model: { providerID: "test", id: "model" }, + delivery: "steer", + }) + // Selection rides the command payload; no separate client-side switch. + expect(client.v2.session.switchAgent).not.toHaveBeenCalled() + expect(client.v2.session.switchModel).not.toHaveBeenCalled() + await transport.close() + }) + + test("routes skill prompts through v2.session.skill and settles without promotion", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ streams: [events] }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + let request: Parameters[0] | undefined + const command = spyOn(client.v2.session, "command") + const prompt = spyOn(client.v2.session, "prompt") + spyOn(client.v2.session, "skill").mockImplementation((input) => { + request = input + queueMicrotask(() => { + events.push({ + id: "evt_skill", + created: 0, + type: "skill.activated", + durable: durable("ses_1"), + data: { + sessionID: "ses_1", + name: input.skill ?? "tigerstyle", + text: "skill instructions", + }, + }) + events.push({ + id: "evt_settled", + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, + }) + }) + return ok(undefined) as never + }) + + await transport.runPromptTurn({ + agent: undefined, + model: undefined, + variant: undefined, + prompt: { + messageID: "msg_skill", + text: "/tigerstyle", + parts: [], + command: { name: "tigerstyle", arguments: "", source: "skill" }, + }, + files: [], + includeFiles: true, + }) + + expect(request).toMatchObject({ sessionID: "ses_1", id: "msg_skill", skill: "tigerstyle" }) + expect(command).not.toHaveBeenCalled() + expect(prompt).not.toHaveBeenCalled() + expect(ui.commits).toContainEqual( + expect.objectContaining({ kind: "system", text: '→ Skill "tigerstyle"', messageID: "msg_skill" }), + ) + await transport.close() + }) + + test("does not resolve a skill turn before the matching activation is observed", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ streams: [events] }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + let sent = false + spyOn(client.v2.session, "skill").mockImplementation(() => { + sent = true + return ok(undefined) as never + }) + + let done = false + const turn = transport + .runPromptTurn({ + agent: undefined, + model: undefined, + variant: undefined, + prompt: { + messageID: "msg_skill", + text: "/tigerstyle", + parts: [], + command: { name: "tigerstyle", arguments: "", source: "skill" }, + }, + files: [], + includeFiles: true, + }) + .then(() => { + done = true + }) + while (!sent) await Bun.sleep(0) + events.push({ + id: "evt_unrelated_settled", + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, + }) + await Bun.sleep(0) + await Bun.sleep(0) + expect(done).toBe(false) + + events.push({ + id: "evt_skill", + created: 0, + type: "skill.activated", + durable: durable("ses_1"), + data: { + sessionID: "ses_1", + name: "tigerstyle", + text: "skill instructions", + }, + }) + events.push({ + id: "evt_skill_settled", + created: 0, + type: "execution.settled", + data: { sessionID: "ses_1", outcome: "success" }, + }) + await turn + + expect(done).toBe(true) + await transport.close() + }) + + test("hydrates skill activation messages once and dedupes live redelivery", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ + streams: [events], + messages: { + ses_1: [ + { + id: "msg_skill", + type: "skill" as const, + name: "tigerstyle", + text: "skill instructions", + time: { created: 2 }, + }, + ], + }, + }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + events.push({ + id: "evt_skill", + created: 0, + type: "skill.activated", + durable: durable("ses_1"), + data: { + sessionID: "ses_1", + name: "tigerstyle", + text: "skill instructions", + }, + }) + await Bun.sleep(0) + await Bun.sleep(0) + + expect(ui.commits.filter((item) => item.text === '→ Skill "tigerstyle"')).toHaveLength(1) + await transport.close() + }) + test("discovers a live child session and tracks its tab and selected detail", async () => { const events = feed() events.push(connected()) From 650d7743726dada59c30c56d0118783e34ad65ff Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 17:30:25 -0400 Subject: [PATCH 32/82] refactor(schema): session shell payloads and event prefix restore (#35229) --- .../src/components/dialog-custom-provider.tsx | 2 +- .../app/src/components/settings-providers.tsx | 2 +- .../src/components/settings-v2/providers.tsx | 2 +- .../client/src/promise/generated/types.ts | 274 +++- packages/client/test/effect.test.ts | 10 +- packages/client/test/promise.test.ts | 4 +- packages/core/src/database/migration.gen.ts | 1 + ...703190000_reset_v2_shell_event_payloads.ts | 14 + packages/core/src/session.ts | 66 +- packages/core/src/session/compaction.ts | 2 +- packages/core/src/session/message-updater.ts | 106 +- packages/core/src/session/projector.ts | 21 +- .../core/src/session/runner/to-llm-message.ts | 2 +- packages/core/test/session-create.test.ts | 18 +- packages/core/test/session-log.test.ts | 8 +- packages/core/test/session-projector.test.ts | 31 +- packages/core/test/session-prompt.test.ts | 10 +- .../core/test/session-runner-message.test.ts | 16 +- .../core/test/session-runner-recorded.test.ts | 12 +- .../test/session-runner-tool-events.test.ts | 8 +- packages/core/test/session-runner.test.ts | 6 +- .../src/cli/cmd/run/noninteractive.ts | 30 +- .../opencode/src/cli/cmd/run/session-data.ts | 30 +- .../src/cli/cmd/run/stream-v2.subagent.ts | 30 +- .../src/cli/cmd/run/stream-v2.transport.ts | 125 +- .../test/cli/run/noninteractive.test.ts | 4 +- .../test/cli/run/session-data.test.ts | 12 +- .../test/cli/run/stream-v2.transport.test.ts | 139 +- .../opencode/test/server/httpapi-pty.test.ts | 4 +- .../opencode/test/server/httpapi-sdk.test.ts | 2 +- .../opencode/test/tool/apply_patch.test.ts | 4 +- .../test/tool/fixtures/models-api.json | 4 +- .../test/v2/session-message-updater.test.ts | 26 +- packages/schema/src/session-event.ts | 76 +- packages/schema/src/session-message.ts | 6 +- packages/schema/test/event-manifest.test.ts | 64 +- packages/sdk-next/test/embedded.test.ts | 12 +- packages/sdk/js/script/build.ts | 4 +- packages/sdk/js/src/v2/gen/types.gen.ts | 1324 +++++++++-------- packages/sdk/openapi.json | 6 +- packages/tui/src/context/data.tsx | 77 +- .../feature-plugins/system/notifications.ts | 16 +- packages/tui/src/routes/session/index.tsx | 18 +- packages/tui/src/routes/session/rows.ts | 28 +- .../test/cli/cmd/tui/notifications.test.ts | 6 +- packages/tui/test/cli/tui/data.test.tsx | 32 +- packages/ui/src/components/provider-icon.tsx | 2 +- specs/v2/schema-changelog.md | 23 +- specs/v2/session.md | 2 +- 49 files changed, 1521 insertions(+), 1200 deletions(-) create mode 100644 packages/core/src/database/migration/20260703190000_reset_v2_shell_event_payloads.ts diff --git a/packages/app/src/components/dialog-custom-provider.tsx b/packages/app/src/components/dialog-custom-provider.tsx index 647e5002a2..dfc1bb8c22 100644 --- a/packages/app/src/components/dialog-custom-provider.tsx +++ b/packages/app/src/components/dialog-custom-provider.tsx @@ -177,7 +177,7 @@ export function DialogCustomProvider(props: Props) { >
- +
{language.t("provider.custom.title")}
diff --git a/packages/app/src/components/settings-providers.tsx b/packages/app/src/components/settings-providers.tsx index 24e7a60104..ca6413e4ba 100644 --- a/packages/app/src/components/settings-providers.tsx +++ b/packages/app/src/components/settings-providers.tsx @@ -226,7 +226,7 @@ const SettingsProvidersContent: Component = () => { >
- + {language.t("provider.custom.title")} {language.t("settings.providers.tag.custom")}
diff --git a/packages/app/src/components/settings-v2/providers.tsx b/packages/app/src/components/settings-v2/providers.tsx index cd24bbd455..e244581b97 100644 --- a/packages/app/src/components/settings-v2/providers.tsx +++ b/packages/app/src/components/settings-v2/providers.tsx @@ -223,7 +223,7 @@ export const SettingsProvidersV2: Component = () => {
event.type)).toEqual(["server.connected", "model.selected"]) + expect(Array.from(events).map((event) => event.type)).toEqual(["server.connected", "session.model.selected"]) const durable = events[1] - if (durable?.type !== "model.selected") throw new Error("Expected model event") + if (durable?.type !== "session.model.selected") throw new Error("Expected model event") expect(DateTime.toEpochMillis(durable.created)).toBe(1_717_171_717_000) expect(durable.durable).toEqual({ aggregateID: "ses_test", seq: 1, version: 1 }) }) @@ -159,8 +159,8 @@ test("session methods retain decoded Effect inputs and outputs", async () => { expect(result.context).toEqual([]) expect(logQueries[0]).toEqual({ after: "0" }) const logged = Array.from(result.log) - expect(logged.map((item) => item.type)).toEqual(["model.selected", "log.synced"]) - expect(logged[0]?.type === "model.selected" && DateTime.toEpochMillis(logged[0].created)).toBe( + expect(logged.map((item) => item.type)).toEqual(["session.model.selected", "log.synced"]) + expect(logged[0]?.type === "session.model.selected" && DateTime.toEpochMillis(logged[0].created)).toBe( 1_717_171_717_000, ) expect(logged.at(-1)).toEqual(synced) @@ -228,7 +228,7 @@ const modelSwitchedMessage = { const modelSwitchedEvent = { id: "evt_model", created: 1_717_171_717_000, - type: "model.selected", + type: "session.model.selected", durable: { aggregateID: "ses_test", seq: 1, version: 1 }, data: { sessionID: "ses_test", diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index 9e8ea7acfe..d445a69c08 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -160,7 +160,7 @@ test("event.subscribe exposes the Promise event stream wire projection", async ( for await (const event of client.event.subscribe()) events.push(event) expect(events).toEqual([{ id: "evt_connected", created: 0, type: "server.connected", data: {} }, modelSwitchedEvent]) - expect(events[1]?.type === "model.selected" && events[1].created).toBe(1_717_171_717_000) + expect(events[1]?.type === "session.model.selected" && events[1].created).toBe(1_717_171_717_000) }) test("event.subscribe terminates on malformed Promise SSE data", async () => { @@ -329,7 +329,7 @@ const synced = { type: "log.synced", aggregateID: "ses_test", seq: 1 } const modelSwitchedEvent = { id: "evt_model", created: 1_717_171_717_000, - type: "model.selected", + type: "session.model.selected", durable: { aggregateID: "ses_test", seq: 1, version: 1 }, data: { sessionID: "ses_test", diff --git a/packages/core/src/database/migration.gen.ts b/packages/core/src/database/migration.gen.ts index 7956b64f4d..e6a236f527 100644 --- a/packages/core/src/database/migration.gen.ts +++ b/packages/core/src/database/migration.gen.ts @@ -43,5 +43,6 @@ export const migrations = ( import("./migration/20260702134641_add_session_context_entry"), import("./migration/20260703090000_reset_v2_event_rename_sweep"), import("./migration/20260703181610_event_created_column"), + import("./migration/20260703190000_reset_v2_shell_event_payloads"), ]) ).map((module) => module.default) satisfies DatabaseMigration.Migration[] diff --git a/packages/core/src/database/migration/20260703190000_reset_v2_shell_event_payloads.ts b/packages/core/src/database/migration/20260703190000_reset_v2_shell_event_payloads.ts new file mode 100644 index 0000000000..ffbe40652c --- /dev/null +++ b/packages/core/src/database/migration/20260703190000_reset_v2_shell_event_payloads.ts @@ -0,0 +1,14 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260703190000_reset_v2_shell_event_payloads", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`DELETE FROM \`session_input\`;`) + yield* tx.run(`DELETE FROM \`session_message\`;`) + yield* tx.run(`DELETE FROM \`event\`;`) + yield* tx.run(`DELETE FROM \`event_sequence\`;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 108d36707a..e8928a7520 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -41,8 +41,8 @@ import type { EventLog } from "@opencode-ai/schema/event-log" import { SkillV2 } from "./skill" import { Job } from "./job" import { CommandV2 } from "./command" -import { Identifier } from "./util/identifier" import { Shell } from "./shell" +import { Shell as ShellSchema } from "@opencode-ai/schema/shell" import { KeyedMutex } from "./effect/keyed-mutex" export const RevertState = Revert.State @@ -272,19 +272,6 @@ const layer = Layer.effect( ), ) - // Session shell is user-initiated and synchronous at the API boundary, while - // the Location shell service owns process lifecycle and file-backed output. - const runShellCommand = (command: string, cwd: string) => - Effect.gen(function* () { - const shell = yield* Shell.Service - const info = yield* shell.create({ command, cwd }) - yield* shell.wait(info.id) - const output = yield* shell.output(info.id, { limit: SHELL_MAX_CAPTURE_BYTES }) - return output.output || "(no output)" - }).pipe( - Effect.catchTag("Shell.NotFoundError", () => Effect.succeed("Shell command output is no longer available.")), - ) - const result = Service.of({ create: Effect.fn("V2Session.create")(function* (input) { const sessionID = input.id ?? SessionSchema.ID.create() @@ -550,23 +537,38 @@ const layer = Layer.effect( Effect.gen(function* () { activeShells.add(input.sessionID) if ((yield* execution.active).has(input.sessionID)) yield* execution.awaitIdle(input.sessionID) - const callID = Identifier.ascending() + const started = yield* Effect.gen(function* () { + const shell = yield* Shell.Service + return yield* shell.create({ command: input.command, cwd: session.location.directory }) + }).pipe(Effect.provide(locations.get(session.location))) yield* events.publish( SessionEvent.Shell.Started, { sessionID: input.sessionID, - callID, - command: input.command, + shell: started, }, { id: input.id }, ) - const output = yield* runShellCommand(input.command, session.location.directory).pipe( - Effect.provide(locations.get(session.location)), - ) + const completed = yield* Effect.gen(function* () { + const shell = yield* Shell.Service + const terminal = yield* shell.wait(started.id).pipe( + Effect.map((info) => ({ info, retained: true as const })), + Effect.catchTag("Shell.NotFoundError", () => + Effect.succeed({ info: synthesizeTerminalShellInfo(started), retained: false as const }), + ), + ) + const output = terminal.retained + ? yield* shell + .output(started.id, { limit: SHELL_MAX_CAPTURE_BYTES }) + .pipe(Effect.catchTag("Shell.NotFoundError", () => Effect.succeed(missingShellOutput()))) + : missingShellOutput() + return { shell: terminal.info, output } + }) + .pipe(Effect.provide(locations.get(session.location))) yield* events.publish(SessionEvent.Shell.Ended, { sessionID: input.sessionID, - callID, - output, + shell: completed.shell, + output: completed.output, }) }).pipe( Effect.ensuring( @@ -706,6 +708,26 @@ const layer = Layer.effect( }), ) +function missingShellOutput() { + const output = "Shell command output is no longer available." + return { + output, + cursor: Buffer.byteLength(output), + size: Buffer.byteLength(output), + truncated: false, + } +} + +function synthesizeTerminalShellInfo(started: ShellSchema.Info): ShellSchema.Info { + return { + ...started, + // The Shell record was removed before waiters could observe it; publish a terminal + // boundary instead of leaving the Session shell message permanently running. + status: "killed", + time: { ...started.time, completed: Date.now() }, + } +} + const resolvePrompt = (input: PromptInput.Prompt) => Prompt.make({ text: input.text, diff --git a/packages/core/src/session/compaction.ts b/packages/core/src/session/compaction.ts index 1174b65f40..9ad9ddc81a 100644 --- a/packages/core/src/session/compaction.ts +++ b/packages/core/src/session/compaction.ts @@ -129,7 +129,7 @@ const serialize = (message: SessionMessage.Message) => { if (message.type === "system") return `[System update]: ${message.text}` if (message.type === "synthetic") return `[Synthetic context]: ${message.text}` if (message.type === "skill") return `[Skill activated: ${message.name}]\n${message.text}` - if (message.type === "shell") return `[Shell]: ${message.command}\n${truncate(message.output)}` + if (message.type === "shell") return `[Shell]: ${message.shell.command}\n${truncate(message.output?.output ?? "")}` return "" } diff --git a/packages/core/src/session/message-updater.ts b/packages/core/src/session/message-updater.ts index a23ecb224c..3658e67c0f 100644 --- a/packages/core/src/session/message-updater.ts +++ b/packages/core/src/session/message-updater.ts @@ -8,21 +8,25 @@ export type MemoryState = { } export interface Adapter { - readonly getCurrentAssistant: () => Effect.Effect - readonly getAssistant: (messageID: SessionMessage.ID) => Effect.Effect - readonly getCurrentShell: (callID: string) => Effect.Effect - readonly updateAssistant: (assistant: SessionMessage.Assistant) => Effect.Effect - readonly updateShell: (shell: SessionMessage.Shell) => Effect.Effect - readonly appendMessage: (message: SessionMessage.Message) => Effect.Effect + readonly getCurrentAssistant: () => Effect.Effect + readonly getAssistant: ( + messageID: SessionMessage.ID, + ) => Effect.Effect + readonly getShell: ( + shellID: SessionMessage.Shell["shell"]["id"], + ) => Effect.Effect + readonly updateAssistant: (assistant: SessionMessage.Assistant) => Effect.Effect + readonly updateShell: (shell: SessionMessage.Shell) => Effect.Effect + readonly appendMessage: (message: SessionMessage.Message) => Effect.Effect } export function memory(state: MemoryState): Adapter { const assistantIndex = (messageID: SessionMessage.ID) => state.messages.findLastIndex((message) => message.id === messageID) + const shellIndex = (messageID: SessionMessage.ID) => + state.messages.findLastIndex((message) => message.id === messageID) // A newer step supersedes stale incomplete rows; never resume an older assistant projection. const latestAssistantIndex = () => state.messages.findLastIndex((message) => message.type === "assistant") - const activeShellIndex = (callID: string) => - state.messages.findLastIndex((message) => message.type === "shell" && message.callID === callID) return { getCurrentAssistant() { @@ -41,12 +45,11 @@ export function memory(state: MemoryState): Adapter { return assistant?.type === "assistant" ? assistant : undefined }) }, - getCurrentShell(callID) { + getShell(shellID) { return Effect.sync(() => { - const index = activeShellIndex(callID) - if (index < 0) return - const shell = state.messages[index] - return shell?.type === "shell" ? shell : undefined + return state.messages.find((message): message is SessionMessage.Shell => { + return message.type === "shell" && message.shell.id === shellID + }) }) }, updateAssistant(assistant) { @@ -60,7 +63,7 @@ export function memory(state: MemoryState): Adapter { }, updateShell(shell) { return Effect.sync(() => { - const index = activeShellIndex(shell.callID) + const index = shellIndex(shell.id) if (index < 0) return const current = state.messages[index] if (current?.type !== "shell") return @@ -100,7 +103,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { return Effect.gen(function* () { yield* SessionEvent.All.match(event, { - "agent.selected": (event) => { + "session.agent.selected": (event) => { return adapter.appendMessage( SessionMessage.AgentSelected.make({ id: SessionMessage.ID.fromEvent(event.id), @@ -111,7 +114,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { }), ) }, - "model.selected": (event) => { + "session.model.selected": (event) => { return adapter.appendMessage( SessionMessage.ModelSelected.make({ id: SessionMessage.ID.fromEvent(event.id), @@ -123,11 +126,11 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { ) }, "session.moved": () => Effect.void, - renamed: () => Effect.void, - forked: () => Effect.void, - "prompt.promoted": () => Effect.void, - "prompt.admitted": () => Effect.void, - "execution.settled": () => Effect.void, + "session.renamed": () => Effect.void, + "session.forked": () => Effect.void, + "session.prompt.promoted": () => Effect.void, + "session.prompt.admitted": () => Effect.void, + "session.execution.settled": () => Effect.void, "session.context.updated": (event) => adapter.appendMessage( SessionMessage.System.make({ @@ -137,7 +140,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { time: { created: event.created }, }), ), - synthetic: (event) => { + "session.synthetic": (event) => { return adapter.appendMessage( SessionMessage.Synthetic.make({ sessionID: event.data.sessionID, @@ -150,7 +153,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { }), ) }, - "skill.activated": (event) => { + "session.skill.activated": (event) => { return adapter.appendMessage( SessionMessage.Skill.make({ id: SessionMessage.ID.fromEvent(event.id), @@ -161,25 +164,24 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { }), ) }, - "shell.started": (event) => { + "session.shell.started": (event) => { return adapter.appendMessage( SessionMessage.Shell.make({ id: SessionMessage.ID.fromEvent(event.id), type: "shell", metadata: event.metadata, - callID: event.data.callID, - command: event.data.command, - output: "", + shell: event.data.shell, time: { created: event.created }, }), ) }, - "shell.ended": (event) => { + "session.shell.ended": (event) => { return Effect.gen(function* () { - const currentShell = yield* adapter.getCurrentShell(event.data.callID) + const currentShell = yield* adapter.getShell(event.data.shell.id) if (currentShell) { yield* adapter.updateShell( produce(currentShell, (draft) => { + draft.shell = castDraft(event.data.shell) draft.output = event.data.output draft.time.completed = event.created }), @@ -187,7 +189,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "step.started": (event) => { + "session.step.started": (event) => { return Effect.gen(function* () { const currentAssistant = yield* adapter.getCurrentAssistant() if (currentAssistant) { @@ -210,7 +212,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { ) }) }, - "step.ended": (event) => { + "session.step.ended": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { draft.time.completed = event.created draft.finish = event.data.finish @@ -224,33 +226,33 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "step.failed": (event) => { + "session.step.failed": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { draft.time.completed = event.created draft.finish = "error" draft.error = event.data.error }) }, - "text.started": (event) => { + "session.text.started": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { draft.content.push( castDraft(SessionMessage.AssistantText.make({ type: "text", id: event.data.textID, text: "" })), ) }) }, - "text.delta": (event) => { + "session.text.delta": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestText(draft, event.data.textID) if (match) match.text += event.data.delta }) }, - "text.ended": (event) => { + "session.text.ended": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestText(draft, event.data.textID) if (match) match.text = event.data.text }) }, - "tool.input.started": (event) => { + "session.tool.input.started": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { draft.content.push( castDraft( @@ -265,14 +267,14 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { ) }) }, - "tool.input.delta": () => Effect.void, - "tool.input.ended": (event) => { + "session.tool.input.delta": () => Effect.void, + "session.tool.input.ended": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match && match.state.status === "pending") match.state.input = event.data.text }) }, - "tool.called": (event) => { + "session.tool.called": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match) { @@ -289,7 +291,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "tool.progress": (event) => { + "session.tool.progress": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match && match.state.status === "running") { @@ -298,7 +300,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "tool.success": (event) => { + "session.tool.success": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match && match.state.status === "running") { @@ -321,7 +323,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "tool.failed": (event) => { + "session.tool.failed": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestTool(draft, event.data.callID) if (match && (match.state.status === "pending" || match.state.status === "running")) { @@ -344,7 +346,7 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - "reasoning.started": (event) => { + "session.reasoning.started": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { draft.content.push( castDraft( @@ -359,13 +361,13 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { ) }) }, - "reasoning.delta": (event) => { + "session.reasoning.delta": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestReasoning(draft, event.data.reasoningID) if (match) match.text += event.data.delta }) }, - "reasoning.ended": (event) => { + "session.reasoning.ended": (event) => { return updateOwnedAssistant(event.data.assistantMessageID, (draft) => { const match = latestReasoning(draft, event.data.reasoningID) if (match) { @@ -375,10 +377,10 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { } }) }, - retried: () => Effect.void, - "compaction.started": () => Effect.void, - "compaction.delta": () => Effect.void, - "compaction.ended": (event) => { + "session.retried": () => Effect.void, + "session.compaction.started": () => Effect.void, + "session.compaction.delta": () => Effect.void, + "session.compaction.ended": (event) => { return adapter.appendMessage( SessionMessage.Compaction.make({ id: SessionMessage.ID.fromEvent(event.id), @@ -391,9 +393,9 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { }), ) }, - "revert.staged": () => Effect.void, - "revert.cleared": () => Effect.void, - "revert.committed": () => Effect.void, + "session.revert.staged": () => Effect.void, + "session.revert.cleared": () => Effect.void, + "session.revert.committed": () => Effect.void, }) }) } diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index c5b552e8b4..746e448a3b 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -393,18 +393,25 @@ function run(db: DatabaseService, event: MessageEvent) { return message.type === "assistant" ? message : undefined }) }, - getCurrentShell(callID) { + getShell(shellID) { return Effect.gen(function* () { - const rows = yield* db + const row = yield* db .select() .from(SessionMessageTable) - .where(and(eq(SessionMessageTable.session_id, event.data.sessionID), eq(SessionMessageTable.type, "shell"))) + .where( + and( + eq(SessionMessageTable.session_id, event.data.sessionID), + eq(SessionMessageTable.type, "shell"), + sql`json_extract(${SessionMessageTable.data}, '$.shell.id') = ${shellID}`, + ), + ) .orderBy(desc(SessionMessageTable.seq)) - .all() + .limit(1) + .get() .pipe(Effect.orDie) - return rows - .map(decodeRow) - .find((message): message is SessionMessage.Shell => message.type === "shell" && message.callID === callID) + if (!row) return + const message = decodeRow(row) + return message.type === "shell" ? message : undefined }) }, updateAssistant: updateMessage, diff --git a/packages/core/src/session/runner/to-llm-message.ts b/packages/core/src/session/runner/to-llm-message.ts index 0d9055e480..e6a91a9ef1 100644 --- a/packages/core/src/session/runner/to-llm-message.ts +++ b/packages/core/src/session/runner/to-llm-message.ts @@ -139,7 +139,7 @@ function toLLMMessage(message: SessionMessage.Message, model: Model): Message[] Message.make({ id: message.id, role: "user", - content: `Shell command: ${message.command}\n\n${message.output}`, + content: `Shell command: ${message.shell.command}\n\n${message.output?.output ?? ""}`, metadata: message.metadata, }), ] diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index 0100ca4ae9..d18c2c8e81 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -213,7 +213,7 @@ describe("SessionV2.create", () => { expect(forkContext.map((message) => message.id)).not.toEqual(parentContext.map((message) => message.id)) expect(history).toHaveLength(1) expect(history[0]).toMatchObject({ - type: "forked", + type: "session.forked", durable: { seq: 0 }, data: { sessionID: forked.id, parentID: parent.id }, }) @@ -378,8 +378,8 @@ describe("SessionV2.create", () => { expect( Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(2), Stream.runCollect)), ).toMatchObject([ - { durable: { seq: 1 }, type: "prompt.admitted", data: { prompt: { text: "Hello" } } }, - { durable: { seq: 2 }, type: "prompt.promoted" }, + { durable: { seq: 1 }, type: "session.prompt.admitted", data: { prompt: { text: "Hello" } } }, + { durable: { seq: 2 }, type: "session.prompt.promoted" }, ]) }), ) @@ -494,8 +494,9 @@ describe("SessionV2.create", () => { const messages = yield* session.messages({ sessionID: created.id, order: "asc" }) const shell = messages.find((message): message is SessionMessage.Shell => message.type === "shell") - expect(shell).toMatchObject({ type: "shell", command: "echo hello" }) - expect(shell?.output).toContain("hello") + expect(shell).toMatchObject({ type: "shell", shell: { command: "echo hello", status: "exited", exit: 0 } }) + expect(shell?.output?.output).toContain("hello") + expect(shell?.output?.truncated).toBe(false) expect(shell?.time.completed).toBeDefined() }), ), @@ -513,7 +514,8 @@ describe("SessionV2.create", () => { const messages = yield* session.messages({ sessionID: created.id, order: "asc" }) const shell = messages.find((message): message is SessionMessage.Shell => message.type === "shell") - expect(shell).toMatchObject({ type: "shell", command: "false" }) + expect(shell).toMatchObject({ type: "shell", shell: { command: "false", status: "exited" } }) + expect(shell?.shell.exit).not.toBe(0) expect(shell?.time.completed).toBeDefined() }), ), @@ -529,7 +531,7 @@ describe("SessionV2.create", () => { expect(yield* session.get(created.id)).toMatchObject({ agent: "plan" }) expect( Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)), - ).toMatchObject([{ type: "agent.selected", data: { agent: "plan" } }]) + ).toMatchObject([{ type: "session.agent.selected", data: { agent: "plan" } }]) }), ) @@ -562,7 +564,7 @@ describe("SessionV2.create", () => { expect(yield* session.get(created.id)).toMatchObject({ model }) expect( Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)), - ).toMatchObject([{ type: "model.selected", data: { model } }]) + ).toMatchObject([{ type: "session.model.selected", data: { model } }]) }), ) diff --git a/packages/core/test/session-log.test.ts b/packages/core/test/session-log.test.ts index 8c49b94582..ed8dda7f4d 100644 --- a/packages/core/test/session-log.test.ts +++ b/packages/core/test/session-log.test.ts @@ -40,14 +40,14 @@ describe("SessionV2.log", () => { const session = yield* SessionV2.Service const events = yield* EventV2.Service const created = yield* session.create({ location }) - yield* session.rename({ sessionID: created.id, title: "renamed" }) + yield* session.rename({ sessionID: created.id, title: "session.renamed" }) const items = Array.from(yield* Stream.runCollect(session.log({ sessionID: created.id }))) const watermark = (yield* events.sequences([created.id])).get(created.id) // Session creation commits a non-public durable event, so the marker's // seq covers more of the aggregate than the public events emitted. - expect(items.map((item) => item.type)).toEqual(["renamed", "log.synced"]) + expect(items.map((item) => item.type)).toEqual(["session.renamed", "log.synced"]) expect(items.at(-1)).toEqual({ type: "log.synced", aggregateID: created.id, seq: watermark }) }), ) @@ -64,7 +64,7 @@ describe("SessionV2.log", () => { yield* session.rename({ sessionID: created.id, title: "renamed live" }) const items = Array.from(yield* Fiber.join(fiber)) - expect(items.map((item) => item.type)).toEqual(["log.synced", "renamed"]) + expect(items.map((item) => item.type)).toEqual(["log.synced", "session.renamed"]) }), ) @@ -137,7 +137,7 @@ describe("SessionV2 watermarks", () => { const events = yield* EventV2.Service const first = yield* session.create({ location }) const second = yield* session.create({ location }) - yield* session.rename({ sessionID: first.id, title: "renamed" }) + yield* session.rename({ sessionID: first.id, title: "session.renamed" }) const page = yield* session.list() const sequences = yield* events.sequences([first.id, second.id]) diff --git a/packages/core/test/session-projector.test.ts b/packages/core/test/session-projector.test.ts index c0d172088e..c17b979076 100644 --- a/packages/core/test/session-projector.test.ts +++ b/packages/core/test/session-projector.test.ts @@ -19,6 +19,7 @@ import { SessionMessageUpdater } from "@opencode-ai/core/session/message-updater import { SessionProjector } from "@opencode-ai/core/session/projector" import { SessionExecution } from "@opencode-ai/core/session/execution" import { SessionInput } from "@opencode-ai/core/session/input" +import { Shell } from "@opencode-ai/schema/shell" import { SessionContextCheckpointTable, SessionInputTable, @@ -257,15 +258,32 @@ describe("SessionProjector", () => { }) yield* events.publish(SessionEvent.Shell.Started, { sessionID, - callID: "shell-1", - command: "pwd", + shell: Shell.Info.make({ + id: Shell.ID.make("sh_projector"), + status: "running", + command: "pwd", + cwd: "/project", + shell: "/bin/sh", + file: "/tmp/sh_projector.out", + metadata: {}, + time: { started: 0 }, + }), }) yield* events.publish(SessionEvent.Shell.Ended, { sessionID, - callID: "shell-1", - output: "/project", + shell: Shell.Info.make({ + id: Shell.ID.make("sh_projector"), + status: "exited", + command: "pwd", + cwd: "/project", + shell: "/bin/sh", + file: "/tmp/sh_projector.out", + exit: 0, + metadata: {}, + time: { started: 0, completed: 1 }, + }), + output: { output: "/project", cursor: 8, size: 8, truncated: false }, }) - const compactionID = SessionMessage.ID.create() yield* events.publish(SessionEvent.Compaction.Started, { sessionID, reason: "manual", @@ -320,7 +338,8 @@ describe("SessionProjector", () => { metadata: { source: "projector-test" }, }) expect(messages.find((message) => message.type === "shell")).toMatchObject({ - output: "/project", + shell: { command: "pwd", status: "exited", exit: 0 }, + output: { output: "/project", truncated: false }, time: { completed: DateTime.makeUnsafe(0) }, }) expect(messages.find((message) => message.type === "compaction")).toMatchObject({ diff --git a/packages/core/test/session-prompt.test.ts b/packages/core/test/session-prompt.test.ts index 58a613a324..e7d3f5189f 100644 --- a/packages/core/test/session-prompt.test.ts +++ b/packages/core/test/session-prompt.test.ts @@ -256,16 +256,16 @@ describe("SessionV2.prompt", () => { const streamed = Array.from(yield* Fiber.join(fiber)) expect(streamed.map((event): [number | undefined, string] => [event.durable?.seq, event.type])).toEqual([ - [0, "prompt.admitted"], - [1, "prompt.admitted"], - [2, "prompt.promoted"], - [3, "prompt.promoted"], + [0, "session.prompt.admitted"], + [1, "session.prompt.admitted"], + [2, "session.prompt.promoted"], + [3, "session.prompt.promoted"], ]) expect( Array.from( yield* publicEvents({ sessionID, after: streamed[0].durable?.seq }).pipe(Stream.take(1), Stream.runCollect), ).map((event): [number | undefined, string] => [event.durable?.seq, event.type]), - ).toEqual([[1, "prompt.admitted"]]) + ).toEqual([[1, "session.prompt.admitted"]]) }), ) diff --git a/packages/core/test/session-runner-message.test.ts b/packages/core/test/session-runner-message.test.ts index d33b44728d..9aed484858 100644 --- a/packages/core/test/session-runner-message.test.ts +++ b/packages/core/test/session-runner-message.test.ts @@ -7,6 +7,7 @@ import { SessionMessage } from "@opencode-ai/core/session/message" import { AgentAttachment, FileAttachment } from "@opencode-ai/core/session/prompt" import { toLLMMessages } from "@opencode-ai/core/session/runner/to-llm-message" import { SessionV2 } from "@opencode-ai/core/session" +import { Shell } from "@opencode-ai/schema/shell" import { DateTime } from "effect" const created = DateTime.makeUnsafe(0) @@ -87,9 +88,18 @@ describe("toLLMMessages", () => { SessionMessage.Shell.make({ id: id("shell"), type: "shell", - callID: "shell-1", - command: "pwd", - output: "/project", + shell: Shell.Info.make({ + id: Shell.ID.make("sh_test"), + status: "exited", + command: "pwd", + cwd: "/project", + shell: "/bin/sh", + file: "/tmp/sh_test.out", + exit: 0, + metadata: {}, + time: { started: 0, completed: 0 }, + }), + output: { output: "/project", cursor: 8, size: 8, truncated: false }, time: { created, completed: created }, }), SessionMessage.Compaction.make({ diff --git a/packages/core/test/session-runner-recorded.test.ts b/packages/core/test/session-runner-recorded.test.ts index 4f82baba96..35e84fcb6c 100644 --- a/packages/core/test/session-runner-recorded.test.ts +++ b/packages/core/test/session-runner-recorded.test.ts @@ -193,12 +193,12 @@ describe("SessionRunnerLLM recorded", () => { .orderBy(EventTable.seq) .all()).map((event) => event.type), ).toEqual([ - "prompt.admitted.1", - "prompt.promoted.1", - "step.started.1", - "text.started.1", - "text.ended.1", - "step.ended.1", + "session.prompt.admitted.1", + "session.prompt.promoted.1", + "session.step.started.1", + "session.text.started.1", + "session.text.ended.1", + "session.step.ended.1", ]) }), ) diff --git a/packages/core/test/session-runner-tool-events.test.ts b/packages/core/test/session-runner-tool-events.test.ts index 5c8d7e07f4..d016b2694b 100644 --- a/packages/core/test/session-runner-tool-events.test.ts +++ b/packages/core/test/session-runner-tool-events.test.ts @@ -76,7 +76,7 @@ test("local tool success serializes media base64 once and reconstructs from stru await Effect.runPromise(publisher.publish(call)) await Effect.runPromise(publisher.publish(result)) - const success = published.find((event) => event.type === "tool.success.1") + const success = published.find((event) => event.type === "session.tool.success.1") expect(success).toBeDefined() const serialized = JSON.stringify(success) expect(serialized.split(base64)).toHaveLength(2) @@ -94,7 +94,7 @@ test("provider-executed success retains its compatibility result", async () => { const { published, publisher } = capture() await Effect.runPromise(publisher.publish(LLMEvent.toolCall({ ...call, providerExecuted: true }))) await Effect.runPromise(publisher.publish(LLMEvent.toolResult({ ...result, providerExecuted: true }))) - const success = published.find((event) => event.type === "tool.success.1") + const success = published.find((event) => event.type === "session.tool.success.1") expect(success?.data).toHaveProperty("result") }) @@ -110,8 +110,8 @@ test("binary failure emits no success event", async () => { }), ), ) - expect(published.some((event) => event.type === "tool.success.1")).toBe(false) - expect(published.some((event) => event.type === "tool.failed.1")).toBe(true) + expect(published.some((event) => event.type === "session.tool.success.1")).toBe(false) + expect(published.some((event) => event.type === "session.tool.failed.1")).toBe(true) }) test("old success event data containing result still decodes", () => { diff --git a/packages/core/test/session-runner.test.ts b/packages/core/test/session-runner.test.ts index e6f14c8e19..6856b6a7ce 100644 --- a/packages/core/test/session-runner.test.ts +++ b/packages/core/test/session-runner.test.ts @@ -2985,7 +2985,7 @@ describe("SessionRunnerLLM", () => { { type: "user", text: "Interrupt provider" }, { type: "assistant", finish: "error", error: { type: "unknown", message: "Step interrupted" } }, ]) - expect(yield* recordedEventTypes(sessionID)).toContain("step.failed.1") + expect(yield* recordedEventTypes(sessionID)).toContain("session.step.failed.1") yield* session.interrupt(sessionID) }), ) @@ -3029,8 +3029,8 @@ describe("SessionRunnerLLM", () => { }, ]) const eventTypes = yield* recordedEventTypes(sessionID) - expect(eventTypes).toContain("step.failed.1") - expect(eventTypes).not.toContain("step.ended.1") + expect(eventTypes).toContain("session.step.failed.1") + expect(eventTypes).not.toContain("session.step.ended.1") }), ) diff --git a/packages/opencode/src/cli/cmd/run/noninteractive.ts b/packages/opencode/src/cli/cmd/run/noninteractive.ts index 60ded4ebd9..6874527222 100644 --- a/packages/opencode/src/cli/cmd/run/noninteractive.ts +++ b/packages/opencode/src/cli/cmd/run/noninteractive.ts @@ -158,14 +158,14 @@ export async function runNonInteractivePrompt(input: Input) { if (!("sessionID" in event.data) || event.data.sessionID !== input.sessionID) continue const time = toMillis(event.created) - if (event.type === "prompt.promoted") { + if (event.type === "session.prompt.promoted") { if (event.data.inputID === messageID) { promoted = true continue } } if ( - event.type === "execution.settled" && + event.type === "session.execution.settled" && event.data.outcome === "interrupted" && (interrupted || permissionRejected || questionRejected || formCancelled) ) { @@ -173,7 +173,7 @@ export async function runNonInteractivePrompt(input: Input) { } if (!promoted) continue - if (event.type === "step.started") { + if (event.type === "session.step.started") { const part: StepStartPart = { id: partID(event.id), sessionID: input.sessionID, @@ -189,11 +189,11 @@ export async function runNonInteractivePrompt(input: Input) { continue } - if (event.type === "text.started") { + if (event.type === "session.text.started") { starts.set(event.data.textID, { id: partID(event.id), timestamp: time }) continue } - if (event.type === "text.ended") { + if (event.type === "session.text.ended") { const started = starts.get(event.data.textID) const part: TextPart = { id: started?.id ?? partID(event.id), @@ -207,11 +207,11 @@ export async function runNonInteractivePrompt(input: Input) { continue } - if (event.type === "reasoning.started") { + if (event.type === "session.reasoning.started") { starts.set(event.data.reasoningID, { id: partID(event.id), timestamp: time }) continue } - if (event.type === "reasoning.ended" && input.thinking) { + if (event.type === "session.reasoning.ended" && input.thinking) { const started = starts.get(event.data.reasoningID) const part: ReasoningPart = { id: started?.id ?? partID(event.id), @@ -236,7 +236,7 @@ export async function runNonInteractivePrompt(input: Input) { continue } - if (event.type === "tool.input.started") { + if (event.type === "session.tool.input.started") { tools.set(event.data.callID, { id: partID(event.id), timestamp: time, @@ -246,12 +246,12 @@ export async function runNonInteractivePrompt(input: Input) { }) continue } - if (event.type === "tool.input.ended") { + if (event.type === "session.tool.input.ended") { const current = tools.get(event.data.callID) if (current) current.raw = event.data.text continue } - if (event.type === "tool.called") { + if (event.type === "session.tool.called") { const current = tools.get(event.data.callID) tools.set(event.data.callID, { id: current?.id ?? partID(event.id), @@ -264,7 +264,7 @@ export async function runNonInteractivePrompt(input: Input) { }) continue } - if (event.type === "tool.success") { + if (event.type === "session.tool.success") { const current = tools.get(event.data.callID) ?? fallbackTool(event) const part: ToolPart = { id: current.id, @@ -297,7 +297,7 @@ export async function runNonInteractivePrompt(input: Input) { if (!emit("tool_use", time, { part })) await input.renderTool(part) continue } - if (event.type === "tool.failed") { + if (event.type === "session.tool.failed") { const current = tools.get(event.data.callID) ?? fallbackTool(event) const error = event.data.error.message const part: ToolPart = { @@ -328,7 +328,7 @@ export async function runNonInteractivePrompt(input: Input) { continue } - if (event.type === "step.ended") { + if (event.type === "session.step.ended") { const part: StepFinishPart = { id: partID(event.id), sessionID: input.sessionID, @@ -342,14 +342,14 @@ export async function runNonInteractivePrompt(input: Input) { emit("step_finish", time, { part }) continue } - if (event.type === "step.failed") { + if (event.type === "session.step.failed") { if (interrupted || permissionRejected || questionRejected || formCancelled) continue emittedError = true process.exitCode = 1 if (!emit("error", time, { error: event.data.error })) UI.error(event.data.error.message) continue } - if (event.type === "execution.settled") { + if (event.type === "session.execution.settled") { if (event.data.outcome === "failure" && !emittedError && !questionRejected && !formCancelled) { emittedError = true process.exitCode = 1 diff --git a/packages/opencode/src/cli/cmd/run/session-data.ts b/packages/opencode/src/cli/cmd/run/session-data.ts index 9450f6cf78..ffce45bc94 100644 --- a/packages/opencode/src/cli/cmd/run/session-data.ts +++ b/packages/opencode/src/cli/cmd/run/session-data.ts @@ -62,7 +62,7 @@ type SessionCommit = StreamCommit // - sent: part ID → byte offset of last flushed text (for incremental output) // - visible: part ID → rendered text for an active part after display transforms // - end: part IDs whose time.end has arrived (part is finished) -// - shell: shell call ID → chosen transcript source for direct shell calls +// - shell: shell ID → chosen transcript source for direct shell calls // - echo: message ID → bash outputs to strip from the next assistant chunk type ShellCall = { source: "shell" | "tool" @@ -607,12 +607,12 @@ function toolCommit( } } -function shellPartID(callID: string): string { - return `shell:${callID}` +function shellPartID(shellID: string): string { + return `shell:${shellID}` } -function claimShell(data: SessionData, callID: string, source: ShellCall["source"], command?: string): ShellCall { - const current = data.shell.get(callID) +function claimShell(data: SessionData, shellID: string, source: ShellCall["source"], command?: string): ShellCall { + const current = data.shell.get(shellID) if (current) { if (command && !current.command) { current.command = command @@ -625,7 +625,7 @@ function claimShell(data: SessionData, callID: string, source: ShellCall["source source, ...(command ? { command } : {}), } satisfies ShellCall - data.shell.set(callID, next) + data.shell.set(shellID, next) return next } @@ -728,37 +728,37 @@ export function reduceSessionData(input: SessionDataInput): SessionDataOutput { const data = input.data const event = input.event - if (event.type === "shell.started") { + if (event.type === "session.shell.started") { if (event.properties.sessionID !== input.sessionID) { return out(data, commits) } - const shell = claimShell(data, event.properties.callID, "shell", event.properties.command) + const shell = claimShell(data, event.properties.shell.id, "shell", event.properties.shell.command) if (shell.source !== "shell") { return out(data, commits) } - const partID = shellPartID(event.properties.callID) + const partID = shellPartID(event.properties.shell.id) if (data.ids.has(partID) || data.tools.has(partID)) { return out(data, commits, patch({ status: "running shell" })) } data.tools.add(partID) - commits.push(startShell(event.properties.callID, shell.command ?? event.properties.command)) + commits.push(startShell(event.properties.shell.id, shell.command ?? event.properties.shell.command)) return out(data, commits, patch({ status: "running shell" })) } - if (event.type === "shell.ended") { + if (event.type === "session.shell.ended") { if (event.properties.sessionID !== input.sessionID) { return out(data, commits) } - const shell = claimShell(data, event.properties.callID, "shell") + const shell = claimShell(data, event.properties.shell.id, "shell") if (shell.source !== "shell") { return out(data, commits) } - const partID = shellPartID(event.properties.callID) + const partID = shellPartID(event.properties.shell.id) const seen = data.tools.has(partID) const command = shell.command ?? "" data.tools.delete(partID) @@ -767,11 +767,11 @@ export function reduceSessionData(input: SessionDataInput): SessionDataOutput { } if (!seen && command) { - commits.push(startShell(event.properties.callID, command)) + commits.push(startShell(event.properties.shell.id, command)) } data.ids.add(partID) - commits.push(doneShell(event.properties.callID, command, event.properties.output)) + commits.push(doneShell(event.properties.shell.id, command, event.properties.output.output)) return out(data, commits) } diff --git a/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts b/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts index ac652423a1..1e7b039fd8 100644 --- a/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts +++ b/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts @@ -424,21 +424,21 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac } const reduce = (child: ChildState, event: V2Event) => { - if (event.type === "prompt.promoted") { + if (event.type === "session.prompt.promoted") { if (userFrame(child, event.data.inputID, "")) { touch(child, event.created) notifyDetail(child) } return } - if (event.type === "step.started") { + 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 === "text.delta") { + if (event.type === "session.text.delta") { const projected = child.projectedText.get(event.data.textID) const covered = projected?.indexOf(event.data.delta) ?? -1 if (projected && covered >= 0) { @@ -459,7 +459,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "text.ended") { + if (event.type === "session.text.ended") { child.text.set(event.data.textID, event.data.text) child.projectedText.delete(event.data.textID) setFrame(child, `text:${event.data.textID}`, { @@ -474,7 +474,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "reasoning.delta") { + if (event.type === "session.reasoning.delta") { const projected = child.projectedReasoning.get(event.data.reasoningID) const covered = projected?.indexOf(event.data.delta) ?? -1 if (projected && covered >= 0) { @@ -495,7 +495,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "reasoning.ended") { + if (event.type === "session.reasoning.ended") { child.reasoning.set(event.data.reasoningID, event.data.text) child.projectedReasoning.delete(event.data.reasoningID) if (!input.thinking) return @@ -510,11 +510,11 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "tool.input.started") { + if (event.type === "session.tool.input.started") { child.tools.set(event.data.callID, { name: event.data.name, input: {}, started: event.created }) return } - if (event.type === "tool.called") { + if (event.type === "session.tool.called") { const current = child.tools.get(event.data.callID) child.tools.set(event.data.callID, { name: event.data.tool, @@ -537,10 +537,10 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "tool.success" || event.type === "tool.failed") { + 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 === "tool.failed" + const failed = event.type === "session.tool.failed" childTool( child, { @@ -577,7 +577,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "step.failed") { + if (event.type === "session.step.failed") { setFrame(child, `error:step:${event.data.assistantMessageID}`, { kind: "error", source: "system", @@ -589,7 +589,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac notifyDetail(child) return } - if (event.type === "execution.settled") { + if (event.type === "session.execution.settled") { child.status = event.data.outcome === "success" ? "completed" : event.data.outcome === "interrupted" ? "cancelled" : "error" touch(child, event.created) @@ -613,15 +613,15 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac return { main(event) { - if (event.type === "tool.called") { + if (event.type === "session.tool.called") { if (event.data.tool === "subagent") pendingCalls.set(event.data.callID, event.data.input) return } - if (event.type === "tool.failed") { + if (event.type === "session.tool.failed") { pendingCalls.delete(event.data.callID) return } - if (event.type !== "tool.success") 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)) diff --git a/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts b/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts index c15ed48e5b..42e2c7bd53 100644 --- a/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts +++ b/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts @@ -213,7 +213,9 @@ function promptAgents(next: SessionTurnInput) { ? [ { name: part.name, - source: part.source ? { start: part.source.start, end: part.source.end, text: part.source.value } : undefined, + source: part.source + ? { start: part.source.start, end: part.source.end, text: part.source.value } + : undefined, }, ] : [], @@ -404,27 +406,39 @@ export async function createSessionTransport(input: StreamInput): Promise previous.length) @@ -604,7 +636,7 @@ export async function createSessionTransport(input: StreamInput): Promise previous.length) @@ -645,7 +677,7 @@ export async function createSessionTransport(input: StreamInput): Promise (file.text ? [file.text] : [])), - ].join("\n\n"), + text: [next.prompt.text, ...prepared.flatMap((file) => (file.text ? [file.text] : []))].join("\n\n"), files: attachments.length ? attachments : undefined, agents: agents.length ? agents : undefined, }, diff --git a/packages/opencode/test/cli/run/noninteractive.test.ts b/packages/opencode/test/cli/run/noninteractive.test.ts index 839b99656b..4462c53a97 100644 --- a/packages/opencode/test/cli/run/noninteractive.test.ts +++ b/packages/opencode/test/cli/run/noninteractive.test.ts @@ -25,7 +25,7 @@ function prompted(inputID: string): V2Event { return { id: "evt_prompted", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: { aggregateID: "ses_1", seq: 0, version: 1 }, data: { sessionID: "ses_1", inputID }, } @@ -35,7 +35,7 @@ function settled(outcome: "success" | "interrupted" = "success"): V2Event { return { id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome }, } } diff --git a/packages/opencode/test/cli/run/session-data.test.ts b/packages/opencode/test/cli/run/session-data.test.ts index 89a6751d1b..805bcd486f 100644 --- a/packages/opencode/test/cli/run/session-data.test.ts +++ b/packages/opencode/test/cli/run/session-data.test.ts @@ -329,7 +329,7 @@ describe("run session data", () => { test("renders direct shell mode from first-class shell events", () => { let data = createSessionData() const started = reduce(data, { - type: "shell.started", + type: "session.shell.started", properties: { sessionID: "session-1", timestamp: 1, @@ -353,7 +353,7 @@ describe("run session data", () => { data = started.data const ended = reduce(data, { - type: "shell.ended", + type: "session.shell.ended", properties: { sessionID: "session-1", timestamp: 2, @@ -380,7 +380,7 @@ describe("run session data", () => { test("suppresses legacy bash part updates once shell events claim the call", () => { let data = reduce(createSessionData(), { - type: "shell.started", + type: "session.shell.started", properties: { sessionID: "session-1", timestamp: 1, @@ -409,7 +409,7 @@ describe("run session data", () => { ).toEqual([]) data = reduce(data, { - type: "shell.ended", + type: "session.shell.ended", properties: { sessionID: "session-1", timestamp: 2, @@ -463,7 +463,7 @@ describe("run session data", () => { expect( reduce(data, { - type: "shell.started", + type: "session.shell.started", properties: { sessionID: "session-1", timestamp: 1, @@ -497,7 +497,7 @@ describe("run session data", () => { expect( reduce(data, { - type: "shell.ended", + type: "session.shell.ended", properties: { sessionID: "session-1", timestamp: 2, diff --git a/packages/opencode/test/cli/run/stream-v2.transport.test.ts b/packages/opencode/test/cli/run/stream-v2.transport.test.ts index e43e88f934..cd2d131642 100644 --- a/packages/opencode/test/cli/run/stream-v2.transport.test.ts +++ b/packages/opencode/test/cli/run/stream-v2.transport.test.ts @@ -200,7 +200,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -210,7 +210,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_text", created: 0, - type: "text.delta", + type: "session.text.delta", data: { sessionID: "ses_1", assistantMessageID: "msg_assistant", @@ -221,7 +221,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -259,7 +259,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -269,7 +269,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) }) @@ -353,7 +353,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -363,7 +363,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) }) @@ -450,7 +450,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -460,7 +460,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) }) @@ -724,7 +724,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_text", created: 0, - type: "text.delta", + type: "session.text.delta", data: { sessionID: "ses_1", assistantMessageID: "msg_assistant", @@ -809,7 +809,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_reasoning", created: 0, - type: "reasoning.ended", + type: "session.reasoning.ended", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -865,7 +865,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -921,7 +921,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -931,7 +931,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -981,7 +981,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -993,7 +993,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -1021,16 +1021,42 @@ describe("V2 mini transport", () => { events.push({ id: "evt_shell_start", created: 0, - type: "shell.started", + type: "session.shell.started", durable: durable("ses_1"), - data: { sessionID: "ses_1", callID: "call_shell", command: "ls" }, + data: { + sessionID: "ses_1", + shell: { + id: "sh_shell", + status: "running", + command: "ls", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/opencode-shell", + metadata: {}, + time: { started: 0 }, + }, + }, }) events.push({ id: "evt_shell_end", created: 0, - type: "shell.ended", + type: "session.shell.ended", durable: durable("ses_1", 1), - data: { sessionID: "ses_1", callID: "call_shell", output: "file.txt" }, + data: { + sessionID: "ses_1", + shell: { + id: "sh_shell", + status: "exited", + command: "ls", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/opencode-shell", + exit: 0, + metadata: {}, + time: { started: 0, completed: 1 }, + }, + output: { output: "file.txt", cursor: 8, size: 8, truncated: false }, + }, }) }) return ok(undefined) as never @@ -1047,8 +1073,8 @@ describe("V2 mini transport", () => { expect(request).toMatchObject({ sessionID: "ses_1", command: "ls" }) expect(ui.commits.filter((item) => item.shell)).toMatchObject([ - { phase: "start", tool: "bash", toolState: "running", shell: { callID: "call_shell", command: "ls" } }, - { phase: "progress", text: "file.txt", toolState: "completed", shell: { callID: "call_shell", command: "ls" } }, + { phase: "start", tool: "bash", toolState: "running", shell: { callID: "sh_shell", command: "ls" } }, + { phase: "progress", text: "file.txt", toolState: "completed", shell: { callID: "sh_shell", command: "ls" } }, ]) expect(ui.events).toContainEqual({ type: "stream.patch", patch: { phase: "running", status: "running shell" } }) await transport.close() @@ -1107,9 +1133,18 @@ describe("V2 mini transport", () => { { id: "msg_shell", type: "shell" as const, - callID: "call_1", - command: "ls", - output: "file.txt", + shell: { + id: "sh_1", + status: "exited", + command: "ls", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/opencode-shell", + exit: 0, + metadata: {}, + time: { started: 0, completed: 1 }, + }, + output: { output: "file.txt", cursor: 8, size: 8, truncated: false }, time: { created: 1, completed: 2 }, }, ], @@ -1127,15 +1162,29 @@ describe("V2 mini transport", () => { events.push({ id: "evt_shell_end", created: 0, - type: "shell.ended", + type: "session.shell.ended", durable: durable("ses_1", 1), - data: { sessionID: "ses_1", callID: "call_1", output: "file.txt" }, + data: { + sessionID: "ses_1", + shell: { + id: "sh_1", + status: "exited", + command: "ls", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/opencode-shell", + exit: 0, + metadata: {}, + time: { started: 0, completed: 1 }, + }, + output: { output: "file.txt", cursor: 8, size: 8, truncated: false }, + }, }) await Bun.sleep(0) await Bun.sleep(0) expect(ui.commits.filter((item) => item.shell)).toMatchObject([ - { phase: "start", shell: { callID: "call_1", command: "ls" } }, + { phase: "start", shell: { callID: "sh_1", command: "ls" } }, { phase: "progress", text: "file.txt", toolState: "completed" }, ]) await transport.close() @@ -1160,7 +1209,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_prompted", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -1170,7 +1219,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) }) @@ -1236,7 +1285,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_skill", created: 0, - type: "skill.activated", + type: "session.skill.activated", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -1247,7 +1296,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) }) @@ -1317,7 +1366,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_unrelated_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) await Bun.sleep(0) @@ -1327,7 +1376,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_skill", created: 0, - type: "skill.activated", + type: "session.skill.activated", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -1338,7 +1387,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_skill_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_1", outcome: "success" }, }) await turn @@ -1376,7 +1425,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_skill", created: 0, - type: "skill.activated", + type: "session.skill.activated", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -1438,7 +1487,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_step", created: 0, - type: "step.started", + type: "session.step.started", durable: durable("ses_child"), data: { sessionID: "ses_child", @@ -1456,7 +1505,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_text", created: 0, - type: "text.delta", + type: "session.text.delta", data: { sessionID: "ses_child", assistantMessageID: "msg_child_a", @@ -1470,7 +1519,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_child", outcome: "success" }, }) while (!states().some((state) => state.tabs.some((tab) => tab.status === "completed"))) await Bun.sleep(0) @@ -1515,7 +1564,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_step", created: 0, - type: "step.started", + type: "session.step.started", durable: durable("ses_child"), data: { sessionID: "ses_child", @@ -1527,7 +1576,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_child", outcome: "interrupted" }, }) await Bun.sleep(0) @@ -1574,7 +1623,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_step", created: 0, - type: "step.started", + type: "session.step.started", durable: durable("ses_child"), data: { sessionID: "ses_child", @@ -1587,7 +1636,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_parent_call", created: 0, - type: "tool.called", + type: "session.tool.called", durable: durable("ses_1"), data: { sessionID: "ses_1", @@ -1601,7 +1650,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_parent_success", created: 0, - type: "tool.success", + type: "session.tool.success", durable: durable("ses_1", 1), data: { sessionID: "ses_1", @@ -1616,7 +1665,7 @@ describe("V2 mini transport", () => { events.push({ id: "evt_child_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "ses_child", outcome: "interrupted" }, }) while (!states().some((state) => state.tabs.some((tab) => tab.status === "cancelled"))) await Bun.sleep(0) diff --git a/packages/opencode/test/server/httpapi-pty.test.ts b/packages/opencode/test/server/httpapi-pty.test.ts index 3eec0c9682..ac18a8a2cf 100644 --- a/packages/opencode/test/server/httpapi-pty.test.ts +++ b/packages/opencode/test/server/httpapi-pty.test.ts @@ -99,10 +99,10 @@ describe("pty HttpApi bridge", () => { const updated = await app().request(PtyPaths.update.replace(":ptyID", info.id), { method: "PUT", headers: { ...headers, "content-type": "application/json" }, - body: JSON.stringify({ title: "renamed", size: { cols: 80, rows: 24 } }), + body: JSON.stringify({ title: "session.renamed", size: { cols: 80, rows: 24 } }), }) expect(updated.status).toBe(200) - expect(await updated.json()).toMatchObject({ id: info.id, title: "renamed" }) + expect(await updated.json()).toMatchObject({ id: info.id, title: "session.renamed" }) } finally { await app().request(PtyPaths.remove.replace(":ptyID", info.id), { method: "DELETE", headers }) } diff --git a/packages/opencode/test/server/httpapi-sdk.test.ts b/packages/opencode/test/server/httpapi-sdk.test.ts index c81b3b771b..0af92ae382 100644 --- a/packages/opencode/test/server/httpapi-sdk.test.ts +++ b/packages/opencode/test/server/httpapi-sdk.test.ts @@ -573,7 +573,7 @@ describe("HttpApi SDK", () => { const child = yield* capture(() => sdk.session.create({ title: "child", parentID })) const childID = String(record(child.data).id) const get = yield* capture(() => sdk.session.get({ sessionID: parentID })) - const update = yield* capture(() => sdk.session.update({ sessionID: parentID, title: "renamed" })) + const update = yield* capture(() => sdk.session.update({ sessionID: parentID, title: "session.renamed" })) const roots = yield* capture(() => sdk.session.list({ roots: true, limit: 10 })) const all = yield* capture(() => sdk.session.list({ roots: false, limit: 10 })) const children = yield* capture(() => sdk.session.children({ sessionID: parentID })) diff --git a/packages/opencode/test/tool/apply_patch.test.ts b/packages/opencode/test/tool/apply_patch.test.ts index e394d8084f..57febfa06e 100644 --- a/packages/opencode/test/tool/apply_patch.test.ts +++ b/packages/opencode/test/tool/apply_patch.test.ts @@ -271,7 +271,7 @@ describe("tool.apply_patch freeform", () => { yield* execute({ patchText }, ctx) - const moved = path.join(test.directory, "renamed", "dir", "name.txt") + const moved = path.join(test.directory, "session.renamed", "dir", "name.txt") yield* expectReadFailure(original) expect(yield* readText(moved)).toBe("new content\n") }), @@ -282,7 +282,7 @@ describe("tool.apply_patch freeform", () => { const test = yield* TestInstance const { ctx } = makeCtx() const original = path.join(test.directory, "old", "name.txt") - const destination = path.join(test.directory, "renamed", "dir", "name.txt") + const destination = path.join(test.directory, "session.renamed", "dir", "name.txt") yield* makeDir(path.dirname(original)) yield* makeDir(path.dirname(destination)) yield* writeText(original, "from\n") diff --git a/packages/opencode/test/tool/fixtures/models-api.json b/packages/opencode/test/tool/fixtures/models-api.json index 6302a951dd..9432ee6635 100644 --- a/packages/opencode/test/tool/fixtures/models-api.json +++ b/packages/opencode/test/tool/fixtures/models-api.json @@ -79593,8 +79593,8 @@ } } }, - "synthetic": { - "id": "synthetic", + "session.synthetic": { + "id": "session.synthetic", "env": ["SYNTHETIC_API_KEY"], "npm": "@ai-sdk/openai-compatible", "api": "https://api.synthetic.new/openai/v1", diff --git a/packages/opencode/test/v2/session-message-updater.test.ts b/packages/opencode/test/v2/session-message-updater.test.ts index 4da4dc9d13..1fc3dda0df 100644 --- a/packages/opencode/test/v2/session-message-updater.test.ts +++ b/packages/opencode/test/v2/session-message-updater.test.ts @@ -22,7 +22,7 @@ test.skip("step snapshots carry over to assistant messages", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "step.started", + type: "session.step.started", durable: durable(sessionID), data: { sessionID, @@ -44,7 +44,7 @@ test.skip("step snapshots carry over to assistant messages", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "step.ended", + type: "session.step.ended", durable: durable(sessionID, 1, 2), data: { sessionID, @@ -77,7 +77,7 @@ test.skip("text ended populates assistant text content", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "step.started", + type: "session.step.started", durable: durable(sessionID), data: { sessionID, @@ -96,7 +96,7 @@ test.skip("text ended populates assistant text content", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "text.started", + type: "session.text.started", durable: durable(sessionID, 1), data: { sessionID, @@ -110,7 +110,7 @@ test.skip("text ended populates assistant text content", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "text.ended", + type: "session.text.ended", durable: durable(sessionID, 2), data: { sessionID, @@ -136,7 +136,7 @@ test.skip("tool completion stores completed timestamp", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "step.started", + type: "session.step.started", durable: durable(sessionID), data: { sessionID, @@ -155,7 +155,7 @@ test.skip("tool completion stores completed timestamp", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "tool.input.started", + type: "session.tool.input.started", durable: durable(sessionID, 1), data: { sessionID, @@ -170,7 +170,7 @@ test.skip("tool completion stores completed timestamp", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "tool.called", + type: "session.tool.called", durable: durable(sessionID, 2), data: { sessionID, @@ -187,7 +187,7 @@ test.skip("tool completion stores completed timestamp", () => { SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "tool.success", + type: "session.tool.success", durable: durable(sessionID, 3), data: { sessionID, @@ -218,7 +218,7 @@ test("compaction events reduce to compaction message only when completed", () => SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id, created: DateTime.makeUnsafe(0), - type: "compaction.started", + type: "session.compaction.started", durable: durable(sessionID), data: { sessionID, @@ -233,7 +233,7 @@ test("compaction events reduce to compaction message only when completed", () => SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "compaction.delta", + type: "session.compaction.delta", data: { sessionID, text: "hello ", @@ -245,7 +245,7 @@ test("compaction events reduce to compaction message only when completed", () => SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: EventV2.ID.create(), created: DateTime.makeUnsafe(0), - type: "compaction.delta", + type: "session.compaction.delta", data: { sessionID, text: "summary", @@ -257,7 +257,7 @@ test("compaction events reduce to compaction message only when completed", () => SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { id: endedID, created: DateTime.makeUnsafe(0), - type: "compaction.ended", + type: "session.compaction.ended", durable: durable(sessionID, 1), data: { sessionID, diff --git a/packages/schema/src/session-event.ts b/packages/schema/src/session-event.ts index fce091545a..824b1690db 100644 --- a/packages/schema/src/session-event.ts +++ b/packages/schema/src/session-event.ts @@ -12,6 +12,7 @@ import { SessionID } from "./session-id.js" import { Location } from "./location.js" import { SessionMessage } from "./session-message.js" import { Revert } from "./revert.js" +import { Shell as ShellSchema } from "./shell.js" export { FileAttachment } @@ -51,7 +52,7 @@ export const UnknownError = SessionMessage.UnknownError export type UnknownError = SessionMessage.UnknownError export const AgentSelected = Event.durable({ - type: "agent.selected", + type: "session.agent.selected", ...options, schema: { ...Base, @@ -61,7 +62,7 @@ export const AgentSelected = Event.durable({ export type AgentSelected = typeof AgentSelected.Type export const ModelSelected = Event.durable({ - type: "model.selected", + type: "session.model.selected", ...options, schema: { ...Base, @@ -82,7 +83,7 @@ export const Moved = Event.durable({ export type Moved = typeof Moved.Type export const Renamed = Event.durable({ - type: "renamed", + type: "session.renamed", ...options, schema: { ...Base, @@ -92,7 +93,7 @@ export const Renamed = Event.durable({ export type Renamed = typeof Renamed.Type export const Forked = Event.durable({ - type: "forked", + type: "session.forked", ...options, schema: { ...Base, @@ -103,7 +104,7 @@ export const Forked = Event.durable({ export type Forked = typeof Forked.Type export const PromptPromoted = Event.durable({ - type: "prompt.promoted", + type: "session.prompt.promoted", ...options, schema: { sessionID: SessionID, @@ -113,14 +114,14 @@ export const PromptPromoted = Event.durable({ export type PromptPromoted = typeof PromptPromoted.Type export const PromptAdmitted = Event.durable({ - type: "prompt.admitted", + type: "session.prompt.admitted", ...options, schema: PromptFields, }) export type PromptAdmitted = typeof PromptAdmitted.Type export const ExecutionSettled = Event.ephemeral({ - type: "execution.settled", + type: "session.execution.settled", schema: { ...Base, outcome: Schema.Literals(["success", "failure", "interrupted"]), @@ -140,7 +141,7 @@ export const ContextUpdated = Event.durable({ export type ContextUpdated = typeof ContextUpdated.Type export const Synthetic = Event.durable({ - type: "synthetic", + type: "session.synthetic", ...options, schema: { ...Base, @@ -153,7 +154,7 @@ export type Synthetic = typeof Synthetic.Type export namespace Skill { export const Activated = Event.durable({ - type: "skill.activated", + type: "session.skill.activated", ...options, schema: { ...Base, @@ -166,23 +167,22 @@ export namespace Skill { export namespace Shell { export const Started = Event.durable({ - type: "shell.started", + type: "session.shell.started", ...options, schema: { ...Base, - callID: Schema.String, - command: Schema.String, + shell: ShellSchema.Info, }, }) export type Started = typeof Started.Type export const Ended = Event.durable({ - type: "shell.ended", + type: "session.shell.ended", ...options, schema: { ...Base, - callID: Schema.String, - output: Schema.String, + shell: ShellSchema.Info, + output: ShellSchema.Output, }, }) export type Ended = typeof Ended.Type @@ -190,7 +190,7 @@ export namespace Shell { export namespace Step { export const Started = Event.durable({ - type: "step.started", + type: "session.step.started", ...options, schema: { ...Base, @@ -203,7 +203,7 @@ export namespace Step { export type Started = typeof Started.Type export const Ended = Event.durable({ - type: "step.ended", + type: "session.step.ended", ...stepSettlementOptions, schema: { ...Base, @@ -226,7 +226,7 @@ export namespace Step { export type Ended = typeof Ended.Type export const Failed = Event.durable({ - type: "step.failed", + type: "session.step.failed", ...stepSettlementOptions, schema: { ...Base, @@ -239,7 +239,7 @@ export namespace Step { export namespace Text { export const Started = Event.durable({ - type: "text.started", + type: "session.text.started", ...options, schema: { ...Base, @@ -251,7 +251,7 @@ export namespace Text { // Stream fragments are live-only; Text.Ended is the replayable full-value boundary. export const Delta = Event.ephemeral({ - type: "text.delta", + type: "session.text.delta", schema: { ...Base, assistantMessageID: SessionMessage.ID, @@ -262,7 +262,7 @@ export namespace Text { export type Delta = typeof Delta.Type export const Ended = Event.durable({ - type: "text.ended", + type: "session.text.ended", ...options, schema: { ...Base, @@ -276,7 +276,7 @@ export namespace Text { export namespace Reasoning { export const Started = Event.durable({ - type: "reasoning.started", + type: "session.reasoning.started", ...options, schema: { ...Base, @@ -289,7 +289,7 @@ export namespace Reasoning { // Stream fragments are live-only; Reasoning.Ended is the replayable full-value boundary. export const Delta = Event.ephemeral({ - type: "reasoning.delta", + type: "session.reasoning.delta", schema: { ...Base, assistantMessageID: SessionMessage.ID, @@ -300,7 +300,7 @@ export namespace Reasoning { export type Delta = typeof Delta.Type export const Ended = Event.durable({ - type: "reasoning.ended", + type: "session.reasoning.ended", ...options, schema: { ...Base, @@ -322,7 +322,7 @@ export namespace Tool { export namespace Input { export const Started = Event.durable({ - type: "tool.input.started", + type: "session.tool.input.started", ...options, schema: { ...ToolBase, @@ -333,7 +333,7 @@ export namespace Tool { // Stream fragments are live-only; Input.Ended is the replayable raw-input boundary. export const Delta = Event.ephemeral({ - type: "tool.input.delta", + type: "session.tool.input.delta", schema: { ...ToolBase, delta: Schema.String, @@ -342,7 +342,7 @@ export namespace Tool { export type Delta = typeof Delta.Type export const Ended = Event.durable({ - type: "tool.input.ended", + type: "session.tool.input.ended", ...options, schema: { ...ToolBase, @@ -353,7 +353,7 @@ export namespace Tool { } export const Called = Event.durable({ - type: "tool.called", + type: "session.tool.called", ...options, schema: { ...ToolBase, @@ -372,7 +372,7 @@ export namespace Tool { * transitions or at a bounded cadence, not persist every stdout/stderr chunk. */ export const Progress = Event.durable({ - type: "tool.progress", + type: "session.tool.progress", ...options, schema: { ...ToolBase, @@ -383,7 +383,7 @@ export namespace Tool { export type Progress = typeof Progress.Type export const Success = Event.durable({ - type: "tool.success", + type: "session.tool.success", ...options, schema: { ...ToolBase, @@ -400,7 +400,7 @@ export namespace Tool { export type Success = typeof Success.Type export const Failed = Event.durable({ - type: "tool.failed", + type: "session.tool.failed", ...options, schema: { ...ToolBase, @@ -428,7 +428,7 @@ export const RetryError = Schema.Struct({ export interface RetryError extends Schema.Schema.Type {} export const Retried = Event.durable({ - type: "retried", + type: "session.retried", ...options, schema: { ...Base, @@ -440,7 +440,7 @@ export type Retried = typeof Retried.Type export namespace Compaction { export const Started = Event.durable({ - type: "compaction.started", + type: "session.compaction.started", ...options, schema: { ...Base, @@ -450,7 +450,7 @@ export namespace Compaction { export type Started = typeof Started.Type export const Delta = Event.ephemeral({ - type: "compaction.delta", + type: "session.compaction.delta", schema: { ...Base, text: Schema.String, @@ -459,7 +459,7 @@ export namespace Compaction { export type Delta = typeof Delta.Type export const Ended = Event.durable({ - type: "compaction.ended", + type: "session.compaction.ended", ...options, schema: { ...Base, @@ -473,13 +473,13 @@ export namespace Compaction { export namespace RevertEvent { export const Staged = Event.durable({ - type: "revert.staged", + type: "session.revert.staged", ...options, schema: { ...Base, revert: Revert.State }, }) - export const Cleared = Event.durable({ type: "revert.cleared", ...options, schema: Base }) + export const Cleared = Event.durable({ type: "session.revert.cleared", ...options, schema: Base }) export const Committed = Event.durable({ - type: "revert.committed", + type: "session.revert.committed", ...options, schema: { ...Base, messageID: SessionMessage.ID }, }) diff --git a/packages/schema/src/session-message.ts b/packages/schema/src/session-message.ts index 349d04d06e..e3d81a31d7 100644 --- a/packages/schema/src/session-message.ts +++ b/packages/schema/src/session-message.ts @@ -9,6 +9,7 @@ import { DateTimeUtcFromMillis, RelativePath, statics } from "./schema.js" import { SessionID } from "./session-id.js" import { ascending } from "./identifier.js" import { Event } from "./event.js" +import { Shell as ShellSchema } from "./shell.js" export const ID = Schema.String.check(Schema.isStartsWith("msg_")).pipe( Schema.brand("Session.Message.ID"), @@ -82,9 +83,8 @@ export interface Shell extends Schema.Schema.Type {} export const Shell = Schema.Struct({ ...Base, type: Schema.Literal("shell"), - callID: Schema.String, - command: Schema.String, - output: Schema.String, + shell: ShellSchema.Info, + output: ShellSchema.Output.pipe(optional), time: Schema.Struct({ created: DateTimeUtcFromMillis, completed: DateTimeUtcFromMillis.pipe(optional), diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 4fa23e75f7..873e415c61 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -53,7 +53,7 @@ describe("public event manifest", () => { expect(Session.Event.Definitions).toBe(SessionEvent.Definitions) expect(Workspace.Event).toBe(WorkspaceEvent) expect(Workspace.Event.Definitions).toBe(WorkspaceEvent.Definitions) - expect(EventManifest.Latest.get("step.ended")).toBe(SessionEvent.Step.Ended) + expect(EventManifest.Latest.get("session.step.ended")).toBe(SessionEvent.Step.Ended) expect(EventManifest.Latest.get("todo.updated")).toBe(SessionTodo.Event.Updated) expect(EventManifest.Latest.get("agent.updated")).toBe(Agent.Event.Updated) expect(EventManifest.Latest.get("project.updated")).toBe(Project.Event.Updated) @@ -74,8 +74,8 @@ describe("public event manifest", () => { SessionV1.Event.Diff, SessionV1.Event.Error, ]) - expect(EventManifest.Durable.get("step.ended.1")).toBe(SessionEvent.Step.Ended) - expect(EventManifest.Durable.has("step.ended.2")).toBe(false) + expect(EventManifest.Durable.get("session.step.ended.1")).toBe(SessionEvent.Step.Ended) + expect(EventManifest.Durable.has("session.step.ended.2")).toBe(false) }) test("derives durable definitions from explicit definition durability", () => { @@ -88,37 +88,37 @@ describe("public event manifest", () => { "message.removed.1", "message.part.updated.1", "message.part.removed.1", - "agent.selected.1", - "model.selected.1", + "session.agent.selected.1", + "session.model.selected.1", "session.moved.1", - "renamed.1", - "forked.1", - "prompt.promoted.1", - "prompt.admitted.1", + "session.renamed.1", + "session.forked.1", + "session.prompt.promoted.1", + "session.prompt.admitted.1", "session.context.updated.1", - "synthetic.1", - "skill.activated.1", - "shell.started.1", - "shell.ended.1", - "step.started.1", - "step.ended.1", - "step.failed.1", - "text.started.1", - "text.ended.1", - "tool.input.started.1", - "tool.input.ended.1", - "tool.called.1", - "tool.progress.1", - "tool.success.1", - "tool.failed.1", - "reasoning.started.1", - "reasoning.ended.1", - "retried.1", - "compaction.started.1", - "compaction.ended.1", - "revert.staged.1", - "revert.cleared.1", - "revert.committed.1", + "session.synthetic.1", + "session.skill.activated.1", + "session.shell.started.1", + "session.shell.ended.1", + "session.step.started.1", + "session.step.ended.1", + "session.step.failed.1", + "session.text.started.1", + "session.text.ended.1", + "session.tool.input.started.1", + "session.tool.input.ended.1", + "session.tool.called.1", + "session.tool.progress.1", + "session.tool.success.1", + "session.tool.failed.1", + "session.reasoning.started.1", + "session.reasoning.ended.1", + "session.retried.1", + "session.compaction.started.1", + "session.compaction.ended.1", + "session.revert.staged.1", + "session.revert.cleared.1", + "session.revert.committed.1", ].toSorted(), ) expect(SessionEvent.DurableDefinitions).toEqual( diff --git a/packages/sdk-next/test/embedded.test.ts b/packages/sdk-next/test/embedded.test.ts index 5419b7e838..4ac31b70ab 100644 --- a/packages/sdk-next/test/embedded.test.ts +++ b/packages/sdk-next/test/embedded.test.ts @@ -78,7 +78,7 @@ it.live( prompt: fixture.sdk.Prompt.make({ text: "Promote this input" }), }) const prompted = yield* opencode.sessions.log({ sessionID: id, follow: true }).pipe( - Stream.filter((event) => event.type === "prompt.promoted" && event.data.inputID === wake.id), + Stream.filter((event) => event.type === "session.prompt.promoted" && event.data.inputID === wake.id), Stream.runHead, Effect.timeout("10 seconds"), Effect.map(Option.getOrThrow), @@ -119,7 +119,7 @@ it.live( expect(page.data.some((session) => session.id === id)).toBe(true) expect(active).toEqual({ data: {}, watermarks: {} }) expect(admitted.sessionID).toBe(id) - expect(prompted.type).toBe("prompt.promoted") + expect(prompted.type).toBe("session.prompt.promoted") expect(wakeContext).toContainEqual(expect.objectContaining({ id: wake.id, type: "user" })) expect(contextEntries).toEqual([ { key: "deploy-target", value: "production" }, @@ -127,7 +127,7 @@ it.live( ]) expect(remainingContextEntries).toEqual([{ key: "deploy-target", value: "production" }]) expect(context.some((message) => message.type === "model-switched")).toBe(true) - expect(event).toMatchObject({ type: "model.selected", durable: { seq: 1 } }) + expect(event).toMatchObject({ type: "session.model.selected", durable: { seq: 1 } }) expect(message).toEqual(modelMessage) expect(missing.map((error) => error._tag)).toEqual([ "SessionNotFoundError", @@ -149,13 +149,13 @@ it.live( const opencode = yield* fixture.sdk.OpenCode.create() const id = sessionID(fixture) const connected = yield* Latch.make(false) - const prompted = yield* Deferred.make>() + const prompted = yield* Deferred.make>() yield* opencode.events.subscribe().pipe( Stream.runForEach((event) => event.type === "server.connected" ? connected.open - : event.type === "prompt.promoted" && event.data.sessionID === id + : event.type === "session.prompt.promoted" && event.data.sessionID === id ? Deferred.succeed(prompted, event).pipe(Effect.asVoid) : Effect.void, ), @@ -191,7 +191,7 @@ it.live( Stream.runForEach((notification: OpenCodeEvent) => notification.type === "server.connected" ? ready.open - : notification.type === "agent.selected" && notification.data.sessionID === id + : notification.type === "session.agent.selected" && notification.data.sessionID === id ? event.open : Effect.void, ) diff --git a/packages/sdk/js/script/build.ts b/packages/sdk/js/script/build.ts index d87f8bf98a..220bf43da3 100755 --- a/packages/sdk/js/script/build.ts +++ b/packages/sdk/js/script/build.ts @@ -60,7 +60,7 @@ if (schemas) { visit({ ...document, components: { ...document.components, schemas: undefined } }) for (const name of Object.keys(schemas)) { if ( - /^(AgentSelected|ModelSelected|SessionMoved|Renamed|Forked|PromptPromoted|PromptAdmitted|ExecutionSettled|ContextUpdated|Synthetic|SkillActivated|ShellStarted|ShellEnded|StepStarted|StepEnded|StepFailed|TextStarted|TextDelta|TextEnded|ReasoningStarted|ReasoningDelta|ReasoningEnded|ToolInputStarted|ToolInputDelta|ToolInputEnded|ToolCalled|ToolProgress|ToolSuccess|ToolFailed|Retried|CompactionStarted|CompactionDelta|CompactionEnded|RevertStaged|RevertCleared|RevertCommitted)1$/.test( + /^(SessionAgentSelected|SessionModelSelected|SessionMoved|SessionRenamed|SessionForked|SessionPromptPromoted|SessionPromptAdmitted|SessionExecutionSettled|SessionContextUpdated|SessionSynthetic|SessionSkillActivated|SessionShellStarted|SessionShellEnded|SessionStepStarted|SessionStepEnded|SessionStepFailed|SessionTextStarted|SessionTextDelta|SessionTextEnded|SessionReasoningStarted|SessionReasoningDelta|SessionReasoningEnded|SessionToolInputStarted|SessionToolInputDelta|SessionToolInputEnded|SessionToolCalled|SessionToolProgress|SessionToolSuccess|SessionToolFailed|SessionRetried|SessionCompactionStarted|SessionCompactionDelta|SessionCompactionEnded|SessionRevertStaged|SessionRevertCleared|SessionRevertCommitted)1$/.test( name, ) && !reachable.has(name) @@ -100,7 +100,7 @@ await createClient({ const generatedTypesPath = "./src/v2/gen/types.gen.ts" const generatedTypes = await Bun.file(generatedTypesPath).text() if ( - /export type (AgentSelected|ModelSelected|SessionMoved|Renamed|Forked|PromptPromoted|PromptAdmitted|ExecutionSettled|ContextUpdated|Synthetic|SkillActivated|ShellStarted|ShellEnded|StepStarted|StepEnded|StepFailed|TextStarted|TextDelta|TextEnded|ReasoningStarted|ReasoningDelta|ReasoningEnded|ToolInputStarted|ToolInputDelta|ToolInputEnded|ToolCalled|ToolProgress|ToolSuccess|ToolFailed|Retried|CompactionStarted|CompactionDelta|CompactionEnded|RevertStaged|RevertCleared|RevertCommitted)1 =/.test( + /export type (SessionAgentSelected|SessionModelSelected|SessionMoved|SessionRenamed|SessionForked|SessionPromptPromoted|SessionPromptAdmitted|SessionExecutionSettled|SessionContextUpdated|SessionSynthetic|SessionSkillActivated|SessionShellStarted|SessionShellEnded|SessionStepStarted|SessionStepEnded|SessionStepFailed|SessionTextStarted|SessionTextDelta|SessionTextEnded|SessionReasoningStarted|SessionReasoningDelta|SessionReasoningEnded|SessionToolInputStarted|SessionToolInputDelta|SessionToolInputEnded|SessionToolCalled|SessionToolProgress|SessionToolSuccess|SessionToolFailed|SessionRetried|SessionCompactionStarted|SessionCompactionDelta|SessionCompactionEnded|SessionRevertStaged|SessionRevertCleared|SessionRevertCommitted)1 =/.test( generatedTypes, ) ) { diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 56cdccf087..27ca0f00cd 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -17,42 +17,42 @@ export type Event = | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved - | EventAgentSelected - | EventModelSelected + | EventSessionAgentSelected + | EventSessionModelSelected | EventSessionMoved - | EventRenamed - | EventForked - | EventPromptPromoted - | EventPromptAdmitted - | EventExecutionSettled + | EventSessionRenamed + | EventSessionForked + | EventSessionPromptPromoted + | EventSessionPromptAdmitted + | EventSessionExecutionSettled | EventSessionContextUpdated - | EventSynthetic - | EventSkillActivated - | EventShellStarted - | EventShellEnded - | EventStepStarted - | EventStepEnded - | EventStepFailed - | EventTextStarted - | EventTextDelta - | EventTextEnded - | EventReasoningStarted - | EventReasoningDelta - | EventReasoningEnded - | EventToolInputStarted - | EventToolInputDelta - | EventToolInputEnded - | EventToolCalled - | EventToolProgress - | EventToolSuccess - | EventToolFailed - | EventRetried - | EventCompactionStarted - | EventCompactionDelta - | EventCompactionEnded - | EventRevertStaged - | EventRevertCleared - | EventRevertCommitted + | EventSessionSynthetic + | EventSessionSkillActivated + | EventSessionShellStarted + | EventSessionShellEnded + | EventSessionStepStarted + | EventSessionStepEnded + | EventSessionStepFailed + | EventSessionTextStarted + | EventSessionTextDelta + | EventSessionTextEnded + | EventSessionReasoningStarted + | EventSessionReasoningDelta + | EventSessionReasoningEnded + | EventSessionToolInputStarted + | EventSessionToolInputDelta + | EventSessionToolInputEnded + | EventSessionToolCalled + | EventSessionToolProgress + | EventSessionToolSuccess + | EventSessionToolFailed + | EventSessionRetried + | EventSessionCompactionStarted + | EventSessionCompactionDelta + | EventSessionCompactionEnded + | EventSessionRevertStaged + | EventSessionRevertCleared + | EventSessionRevertCommitted | EventMessagePartDelta | EventSessionDiff | EventSessionError @@ -657,17 +657,6 @@ export type Prompt = { agents?: Array } -export type Pty = { - id: string - title: string - command: string - args: Array - cwd: string - status: "running" | "exited" - pid: number - exitCode?: number -} - export type Shell = { id: string status: "running" | "exited" | "timeout" | "killed" @@ -686,6 +675,17 @@ export type Shell = { } } +export type Pty = { + id: string + title: string + command: string + args: Array + cwd: string + status: "running" | "exited" + pid: number + exitCode?: number +} + export type Todo = { /** * Brief description of the task @@ -858,7 +858,7 @@ export type GlobalEvent = { } | { id: string - type: "agent.selected" + type: "session.agent.selected" properties: { sessionID: string agent: string @@ -866,7 +866,7 @@ export type GlobalEvent = { } | { id: string - type: "model.selected" + type: "session.model.selected" properties: { sessionID: string model: ModelRef @@ -883,7 +883,7 @@ export type GlobalEvent = { } | { id: string - type: "renamed" + type: "session.renamed" properties: { sessionID: string title: string @@ -891,7 +891,7 @@ export type GlobalEvent = { } | { id: string - type: "forked" + type: "session.forked" properties: { sessionID: string parentID: string @@ -900,7 +900,7 @@ export type GlobalEvent = { } | { id: string - type: "prompt.promoted" + type: "session.prompt.promoted" properties: { sessionID: string inputID: string @@ -908,7 +908,7 @@ export type GlobalEvent = { } | { id: string - type: "prompt.admitted" + type: "session.prompt.admitted" properties: { sessionID: string inputID: string @@ -918,7 +918,7 @@ export type GlobalEvent = { } | { id: string - type: "execution.settled" + type: "session.execution.settled" properties: { sessionID: string outcome: "success" | "failure" | "interrupted" @@ -935,7 +935,7 @@ export type GlobalEvent = { } | { id: string - type: "synthetic" + type: "session.synthetic" properties: { sessionID: string text: string @@ -947,7 +947,7 @@ export type GlobalEvent = { } | { id: string - type: "skill.activated" + type: "session.skill.activated" properties: { sessionID: string name: string @@ -956,25 +956,29 @@ export type GlobalEvent = { } | { id: string - type: "shell.started" + type: "session.shell.started" properties: { sessionID: string - callID: string - command: string + shell: Shell } } | { id: string - type: "shell.ended" + type: "session.shell.ended" properties: { sessionID: string - callID: string - output: string + shell: Shell + output: { + output: string + cursor: number + size: number + truncated: boolean + } } } | { id: string - type: "step.started" + type: "session.step.started" properties: { sessionID: string assistantMessageID: string @@ -985,7 +989,7 @@ export type GlobalEvent = { } | { id: string - type: "step.ended" + type: "session.step.ended" properties: { sessionID: string assistantMessageID: string @@ -1006,7 +1010,7 @@ export type GlobalEvent = { } | { id: string - type: "step.failed" + type: "session.step.failed" properties: { sessionID: string assistantMessageID: string @@ -1015,7 +1019,7 @@ export type GlobalEvent = { } | { id: string - type: "text.started" + type: "session.text.started" properties: { sessionID: string assistantMessageID: string @@ -1024,7 +1028,7 @@ export type GlobalEvent = { } | { id: string - type: "text.delta" + type: "session.text.delta" properties: { sessionID: string assistantMessageID: string @@ -1034,7 +1038,7 @@ export type GlobalEvent = { } | { id: string - type: "text.ended" + type: "session.text.ended" properties: { sessionID: string assistantMessageID: string @@ -1044,7 +1048,7 @@ export type GlobalEvent = { } | { id: string - type: "reasoning.started" + type: "session.reasoning.started" properties: { sessionID: string assistantMessageID: string @@ -1054,7 +1058,7 @@ export type GlobalEvent = { } | { id: string - type: "reasoning.delta" + type: "session.reasoning.delta" properties: { sessionID: string assistantMessageID: string @@ -1064,7 +1068,7 @@ export type GlobalEvent = { } | { id: string - type: "reasoning.ended" + type: "session.reasoning.ended" properties: { sessionID: string assistantMessageID: string @@ -1075,7 +1079,7 @@ export type GlobalEvent = { } | { id: string - type: "tool.input.started" + type: "session.tool.input.started" properties: { sessionID: string assistantMessageID: string @@ -1085,7 +1089,7 @@ export type GlobalEvent = { } | { id: string - type: "tool.input.delta" + type: "session.tool.input.delta" properties: { sessionID: string assistantMessageID: string @@ -1095,7 +1099,7 @@ export type GlobalEvent = { } | { id: string - type: "tool.input.ended" + type: "session.tool.input.ended" properties: { sessionID: string assistantMessageID: string @@ -1105,7 +1109,7 @@ export type GlobalEvent = { } | { id: string - type: "tool.called" + type: "session.tool.called" properties: { sessionID: string assistantMessageID: string @@ -1122,7 +1126,7 @@ export type GlobalEvent = { } | { id: string - type: "tool.progress" + type: "session.tool.progress" properties: { sessionID: string assistantMessageID: string @@ -1135,7 +1139,7 @@ export type GlobalEvent = { } | { id: string - type: "tool.success" + type: "session.tool.success" properties: { sessionID: string assistantMessageID: string @@ -1154,7 +1158,7 @@ export type GlobalEvent = { } | { id: string - type: "tool.failed" + type: "session.tool.failed" properties: { sessionID: string assistantMessageID: string @@ -1169,7 +1173,7 @@ export type GlobalEvent = { } | { id: string - type: "retried" + type: "session.retried" properties: { sessionID: string attempt: number @@ -1178,7 +1182,7 @@ export type GlobalEvent = { } | { id: string - type: "compaction.started" + type: "session.compaction.started" properties: { sessionID: string reason: "auto" | "manual" @@ -1186,7 +1190,7 @@ export type GlobalEvent = { } | { id: string - type: "compaction.delta" + type: "session.compaction.delta" properties: { sessionID: string text: string @@ -1194,7 +1198,7 @@ export type GlobalEvent = { } | { id: string - type: "compaction.ended" + type: "session.compaction.ended" properties: { sessionID: string reason: "auto" | "manual" @@ -1204,7 +1208,7 @@ export type GlobalEvent = { } | { id: string - type: "revert.staged" + type: "session.revert.staged" properties: { sessionID: string revert: RevertState @@ -1212,14 +1216,14 @@ export type GlobalEvent = { } | { id: string - type: "revert.cleared" + type: "session.revert.cleared" properties: { sessionID: string } } | { id: string - type: "revert.committed" + type: "session.revert.committed" properties: { sessionID: string messageID: string @@ -1704,37 +1708,37 @@ export type GlobalEvent = { | SyncEventMessageRemoved | SyncEventMessagePartUpdated | SyncEventMessagePartRemoved - | SyncEventAgentSelected - | SyncEventModelSelected + | SyncEventSessionAgentSelected + | SyncEventSessionModelSelected | SyncEventSessionMoved - | SyncEventRenamed - | SyncEventForked - | SyncEventPromptPromoted - | SyncEventPromptAdmitted + | SyncEventSessionRenamed + | SyncEventSessionForked + | SyncEventSessionPromptPromoted + | SyncEventSessionPromptAdmitted | SyncEventSessionContextUpdated - | SyncEventSynthetic - | SyncEventSkillActivated - | SyncEventShellStarted - | SyncEventShellEnded - | SyncEventStepStarted - | SyncEventStepEnded - | SyncEventStepFailed - | SyncEventTextStarted - | SyncEventTextEnded - | SyncEventReasoningStarted - | SyncEventReasoningEnded - | SyncEventToolInputStarted - | SyncEventToolInputEnded - | SyncEventToolCalled - | SyncEventToolProgress - | SyncEventToolSuccess - | SyncEventToolFailed - | SyncEventRetried - | SyncEventCompactionStarted - | SyncEventCompactionEnded - | SyncEventRevertStaged - | SyncEventRevertCleared - | SyncEventRevertCommitted + | SyncEventSessionSynthetic + | SyncEventSessionSkillActivated + | SyncEventSessionShellStarted + | SyncEventSessionShellEnded + | SyncEventSessionStepStarted + | SyncEventSessionStepEnded + | SyncEventSessionStepFailed + | SyncEventSessionTextStarted + | SyncEventSessionTextEnded + | SyncEventSessionReasoningStarted + | SyncEventSessionReasoningEnded + | SyncEventSessionToolInputStarted + | SyncEventSessionToolInputEnded + | SyncEventSessionToolCalled + | SyncEventSessionToolProgress + | SyncEventSessionToolSuccess + | SyncEventSessionToolFailed + | SyncEventSessionRetried + | SyncEventSessionCompactionStarted + | SyncEventSessionCompactionEnded + | SyncEventSessionRevertStaged + | SyncEventSessionRevertCleared + | SyncEventSessionRevertCommitted } /** @@ -2854,120 +2858,56 @@ export type UnknownError1 = { ref?: string } -export type Renamed = { +export type Shell1 = { id: string - created: number - metadata?: { + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number | "NaN" | "Infinity" | "-Infinity" + metadata: { [key: string]: unknown } - type: "renamed" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - sessionID: string - title: string - } -} - -export type Forked = { - id: string - created: number - metadata?: { - [key: string]: unknown - } - type: "forked" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - sessionID: string - parentID: string - from?: string - } -} - -export type Synthetic = { - id: string - created: number - metadata?: { - [key: string]: unknown - } - type: "synthetic" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - sessionID: string - text: string - description?: string - metadata?: { - [key: string]: unknown - } - } -} - -export type Retried = { - id: string - created: number - metadata?: { - [key: string]: unknown - } - type: "retried" - durable: { - aggregateID: string - seq: number - version: number - } - location?: LocationRef - data: { - sessionID: string - attempt: number - error: SessionRetryError + time: { + started: number | "NaN" | "Infinity" | "-Infinity" + completed?: number | "NaN" | "Infinity" | "-Infinity" } } export type SessionDurableEvent = - | AgentSelected - | ModelSelected + | SessionAgentSelected + | SessionModelSelected | SessionMoved - | Renamed - | Forked - | PromptPromoted - | PromptAdmitted + | SessionRenamed + | SessionForked + | SessionPromptPromoted + | SessionPromptAdmitted | SessionContextUpdated - | Synthetic - | SkillActivated - | ShellStarted - | ShellEnded - | StepStarted - | StepEnded - | StepFailed - | TextStarted - | TextEnded - | ReasoningStarted - | ReasoningEnded - | ToolInputStarted - | ToolInputEnded - | ToolCalled - | ToolProgress - | ToolSuccess - | ToolFailed - | Retried - | CompactionStarted - | CompactionEnded - | RevertStaged - | RevertCleared - | RevertCommitted + | SessionSynthetic + | SessionSkillActivated + | SessionShellStarted + | SessionShellEnded + | SessionStepStarted + | SessionStepEnded + | SessionStepFailed + | SessionTextStarted + | SessionTextEnded + | SessionReasoningStarted + | SessionReasoningEnded + | SessionToolInputStarted + | SessionToolInputEnded + | SessionToolCalled + | SessionToolProgress + | SessionToolSuccess + | SessionToolFailed + | SessionRetried + | SessionCompactionStarted + | SessionCompactionEnded + | SessionRevertStaged + | SessionRevertCleared + | SessionRevertCommitted export type SessionLogItem = SessionDurableEvent | EventLogSynced @@ -3022,24 +2962,6 @@ export type OutputFormat1 = retryCount?: number } -export type Shell1 = { - id: string - status: "running" | "exited" | "timeout" | "killed" - command: string - cwd: string - shell: string - file: string - pid?: number - exit?: number | "NaN" | "Infinity" | "-Infinity" - metadata: { - [key: string]: unknown - } - time: { - started: number | "NaN" | "Infinity" | "-Infinity" - completed?: number | "NaN" | "Infinity" | "-Infinity" - } -} - export type SessionStatus2 = { id: string created: number @@ -3096,42 +3018,42 @@ export type V2Event = | MessageRemoved | MessagePartUpdated | MessagePartRemoved - | AgentSelected - | ModelSelected + | SessionAgentSelected + | SessionModelSelected | SessionMoved - | Renamed - | Forked - | PromptPromoted - | PromptAdmitted - | ExecutionSettled + | SessionRenamed + | SessionForked + | SessionPromptPromoted + | SessionPromptAdmitted + | SessionExecutionSettled | SessionContextUpdated - | Synthetic - | SkillActivated - | ShellStarted - | ShellEnded - | StepStarted - | StepEnded - | StepFailed - | TextStarted - | TextDelta - | TextEnded - | ReasoningStarted - | ReasoningDelta - | ReasoningEnded - | ToolInputStarted - | ToolInputDelta - | ToolInputEnded - | ToolCalled - | ToolProgress - | ToolSuccess - | ToolFailed - | Retried - | CompactionStarted - | CompactionDelta - | CompactionEnded - | RevertStaged - | RevertCleared - | RevertCommitted + | SessionSynthetic + | SessionSkillActivated + | SessionShellStarted + | SessionShellEnded + | SessionStepStarted + | SessionStepEnded + | SessionStepFailed + | SessionTextStarted + | SessionTextDelta + | SessionTextEnded + | SessionReasoningStarted + | SessionReasoningDelta + | SessionReasoningEnded + | SessionToolInputStarted + | SessionToolInputDelta + | SessionToolInputEnded + | SessionToolCalled + | SessionToolProgress + | SessionToolSuccess + | SessionToolFailed + | SessionRetried + | SessionCompactionStarted + | SessionCompactionDelta + | SessionCompactionEnded + | SessionRevertStaged + | SessionRevertCleared + | SessionRevertCommitted | MessagePartDelta | SessionDiff | SessionError @@ -3689,11 +3611,11 @@ export type SyncEventMessagePartRemoved = { } } -export type SyncEventAgentSelected = { +export type SyncEventSessionAgentSelected = { type: "sync" id: string syncEvent: { - type: "agent.selected.1" + type: "session.agent.selected.1" id: string seq: number aggregateID: string @@ -3704,11 +3626,11 @@ export type SyncEventAgentSelected = { } } -export type SyncEventModelSelected = { +export type SyncEventSessionModelSelected = { type: "sync" id: string syncEvent: { - type: "model.selected.1" + type: "session.model.selected.1" id: string seq: number aggregateID: string @@ -3735,11 +3657,11 @@ export type SyncEventSessionMoved = { } } -export type SyncEventRenamed = { +export type SyncEventSessionRenamed = { type: "sync" id: string syncEvent: { - type: "renamed.1" + type: "session.renamed.1" id: string seq: number aggregateID: string @@ -3750,11 +3672,11 @@ export type SyncEventRenamed = { } } -export type SyncEventForked = { +export type SyncEventSessionForked = { type: "sync" id: string syncEvent: { - type: "forked.1" + type: "session.forked.1" id: string seq: number aggregateID: string @@ -3766,11 +3688,11 @@ export type SyncEventForked = { } } -export type SyncEventPromptPromoted = { +export type SyncEventSessionPromptPromoted = { type: "sync" id: string syncEvent: { - type: "prompt.promoted.1" + type: "session.prompt.promoted.1" id: string seq: number aggregateID: string @@ -3781,11 +3703,11 @@ export type SyncEventPromptPromoted = { } } -export type SyncEventPromptAdmitted = { +export type SyncEventSessionPromptAdmitted = { type: "sync" id: string syncEvent: { - type: "prompt.admitted.1" + type: "session.prompt.admitted.1" id: string seq: number aggregateID: string @@ -3813,11 +3735,11 @@ export type SyncEventSessionContextUpdated = { } } -export type SyncEventSynthetic = { +export type SyncEventSessionSynthetic = { type: "sync" id: string syncEvent: { - type: "synthetic.1" + type: "session.synthetic.1" id: string seq: number aggregateID: string @@ -3832,11 +3754,11 @@ export type SyncEventSynthetic = { } } -export type SyncEventSkillActivated = { +export type SyncEventSessionSkillActivated = { type: "sync" id: string syncEvent: { - type: "skill.activated.1" + type: "session.skill.activated.1" id: string seq: number aggregateID: string @@ -3848,43 +3770,47 @@ export type SyncEventSkillActivated = { } } -export type SyncEventShellStarted = { +export type SyncEventSessionShellStarted = { type: "sync" id: string syncEvent: { - type: "shell.started.1" + type: "session.shell.started.1" id: string seq: number aggregateID: string data: { sessionID: string - callID: string - command: string + shell: Shell } } } -export type SyncEventShellEnded = { +export type SyncEventSessionShellEnded = { type: "sync" id: string syncEvent: { - type: "shell.ended.1" + type: "session.shell.ended.1" id: string seq: number aggregateID: string data: { sessionID: string - callID: string - output: string + shell: Shell + output: { + output: string + cursor: number + size: number + truncated: boolean + } } } } -export type SyncEventStepStarted = { +export type SyncEventSessionStepStarted = { type: "sync" id: string syncEvent: { - type: "step.started.1" + type: "session.step.started.1" id: string seq: number aggregateID: string @@ -3898,11 +3824,11 @@ export type SyncEventStepStarted = { } } -export type SyncEventStepEnded = { +export type SyncEventSessionStepEnded = { type: "sync" id: string syncEvent: { - type: "step.ended.1" + type: "session.step.ended.1" id: string seq: number aggregateID: string @@ -3926,11 +3852,11 @@ export type SyncEventStepEnded = { } } -export type SyncEventStepFailed = { +export type SyncEventSessionStepFailed = { type: "sync" id: string syncEvent: { - type: "step.failed.1" + type: "session.step.failed.1" id: string seq: number aggregateID: string @@ -3942,11 +3868,11 @@ export type SyncEventStepFailed = { } } -export type SyncEventTextStarted = { +export type SyncEventSessionTextStarted = { type: "sync" id: string syncEvent: { - type: "text.started.1" + type: "session.text.started.1" id: string seq: number aggregateID: string @@ -3958,11 +3884,11 @@ export type SyncEventTextStarted = { } } -export type SyncEventTextEnded = { +export type SyncEventSessionTextEnded = { type: "sync" id: string syncEvent: { - type: "text.ended.1" + type: "session.text.ended.1" id: string seq: number aggregateID: string @@ -3975,11 +3901,11 @@ export type SyncEventTextEnded = { } } -export type SyncEventReasoningStarted = { +export type SyncEventSessionReasoningStarted = { type: "sync" id: string syncEvent: { - type: "reasoning.started.1" + type: "session.reasoning.started.1" id: string seq: number aggregateID: string @@ -3992,11 +3918,11 @@ export type SyncEventReasoningStarted = { } } -export type SyncEventReasoningEnded = { +export type SyncEventSessionReasoningEnded = { type: "sync" id: string syncEvent: { - type: "reasoning.ended.1" + type: "session.reasoning.ended.1" id: string seq: number aggregateID: string @@ -4010,11 +3936,11 @@ export type SyncEventReasoningEnded = { } } -export type SyncEventToolInputStarted = { +export type SyncEventSessionToolInputStarted = { type: "sync" id: string syncEvent: { - type: "tool.input.started.1" + type: "session.tool.input.started.1" id: string seq: number aggregateID: string @@ -4027,11 +3953,11 @@ export type SyncEventToolInputStarted = { } } -export type SyncEventToolInputEnded = { +export type SyncEventSessionToolInputEnded = { type: "sync" id: string syncEvent: { - type: "tool.input.ended.1" + type: "session.tool.input.ended.1" id: string seq: number aggregateID: string @@ -4044,11 +3970,11 @@ export type SyncEventToolInputEnded = { } } -export type SyncEventToolCalled = { +export type SyncEventSessionToolCalled = { type: "sync" id: string syncEvent: { - type: "tool.called.1" + type: "session.tool.called.1" id: string seq: number aggregateID: string @@ -4068,11 +3994,11 @@ export type SyncEventToolCalled = { } } -export type SyncEventToolProgress = { +export type SyncEventSessionToolProgress = { type: "sync" id: string syncEvent: { - type: "tool.progress.1" + type: "session.tool.progress.1" id: string seq: number aggregateID: string @@ -4088,11 +4014,11 @@ export type SyncEventToolProgress = { } } -export type SyncEventToolSuccess = { +export type SyncEventSessionToolSuccess = { type: "sync" id: string syncEvent: { - type: "tool.success.1" + type: "session.tool.success.1" id: string seq: number aggregateID: string @@ -4114,11 +4040,11 @@ export type SyncEventToolSuccess = { } } -export type SyncEventToolFailed = { +export type SyncEventSessionToolFailed = { type: "sync" id: string syncEvent: { - type: "tool.failed.1" + type: "session.tool.failed.1" id: string seq: number aggregateID: string @@ -4136,11 +4062,11 @@ export type SyncEventToolFailed = { } } -export type SyncEventRetried = { +export type SyncEventSessionRetried = { type: "sync" id: string syncEvent: { - type: "retried.1" + type: "session.retried.1" id: string seq: number aggregateID: string @@ -4152,11 +4078,11 @@ export type SyncEventRetried = { } } -export type SyncEventCompactionStarted = { +export type SyncEventSessionCompactionStarted = { type: "sync" id: string syncEvent: { - type: "compaction.started.1" + type: "session.compaction.started.1" id: string seq: number aggregateID: string @@ -4167,11 +4093,11 @@ export type SyncEventCompactionStarted = { } } -export type SyncEventCompactionEnded = { +export type SyncEventSessionCompactionEnded = { type: "sync" id: string syncEvent: { - type: "compaction.ended.1" + type: "session.compaction.ended.1" id: string seq: number aggregateID: string @@ -4184,11 +4110,11 @@ export type SyncEventCompactionEnded = { } } -export type SyncEventRevertStaged = { +export type SyncEventSessionRevertStaged = { type: "sync" id: string syncEvent: { - type: "revert.staged.1" + type: "session.revert.staged.1" id: string seq: number aggregateID: string @@ -4199,11 +4125,11 @@ export type SyncEventRevertStaged = { } } -export type SyncEventRevertCleared = { +export type SyncEventSessionRevertCleared = { type: "sync" id: string syncEvent: { - type: "revert.cleared.1" + type: "session.revert.cleared.1" id: string seq: number aggregateID: string @@ -4213,11 +4139,11 @@ export type SyncEventRevertCleared = { } } -export type SyncEventRevertCommitted = { +export type SyncEventSessionRevertCommitted = { type: "sync" id: string syncEvent: { - type: "revert.committed.1" + type: "session.revert.committed.1" id: string seq: number aggregateID: string @@ -4449,9 +4375,13 @@ export type SessionMessageShell = { completed?: number } type: "shell" - callID: string - command: string - output: string + shell: Shell + output?: { + output: string + cursor: number + size: number + truncated: boolean + } } export type SessionMessageAssistantText = { @@ -4600,13 +4530,13 @@ export type SessionContextEntryInfo = { value: unknown } -export type AgentSelected = { +export type SessionAgentSelected = { id: string created: number metadata?: { [key: string]: unknown } - type: "agent.selected" + type: "session.agent.selected" durable: { aggregateID: string seq: number @@ -4619,13 +4549,13 @@ export type AgentSelected = { } } -export type ModelSelected = { +export type SessionModelSelected = { id: string created: number metadata?: { [key: string]: unknown } - type: "model.selected" + type: "session.model.selected" durable: { aggregateID: string seq: number @@ -4658,13 +4588,52 @@ export type SessionMoved = { } } -export type PromptPromoted = { +export type SessionRenamed = { id: string created: number metadata?: { [key: string]: unknown } - type: "prompt.promoted" + type: "session.renamed" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + sessionID: string + title: string + } +} + +export type SessionForked = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "session.forked" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + sessionID: string + parentID: string + from?: string + } +} + +export type SessionPromptPromoted = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "session.prompt.promoted" durable: { aggregateID: string seq: number @@ -4677,13 +4646,13 @@ export type PromptPromoted = { } } -export type PromptAdmitted = { +export type SessionPromptAdmitted = { id: string created: number metadata?: { [key: string]: unknown } - type: "prompt.admitted" + type: "session.prompt.admitted" durable: { aggregateID: string seq: number @@ -4717,13 +4686,36 @@ export type SessionContextUpdated = { } } -export type SkillActivated = { +export type SessionSynthetic = { id: string created: number metadata?: { [key: string]: unknown } - type: "skill.activated" + type: "session.synthetic" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + sessionID: string + text: string + description?: string + metadata?: { + [key: string]: unknown + } + } +} + +export type SessionSkillActivated = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "session.skill.activated" durable: { aggregateID: string seq: number @@ -4737,13 +4729,13 @@ export type SkillActivated = { } } -export type ShellStarted = { +export type SessionShellStarted = { id: string created: number metadata?: { [key: string]: unknown } - type: "shell.started" + type: "session.shell.started" durable: { aggregateID: string seq: number @@ -4752,18 +4744,17 @@ export type ShellStarted = { location?: LocationRef data: { sessionID: string - callID: string - command: string + shell: Shell1 } } -export type ShellEnded = { +export type SessionShellEnded = { id: string created: number metadata?: { [key: string]: unknown } - type: "shell.ended" + type: "session.shell.ended" durable: { aggregateID: string seq: number @@ -4772,18 +4763,23 @@ export type ShellEnded = { location?: LocationRef data: { sessionID: string - callID: string - output: string + shell: Shell1 + output: { + output: string + cursor: number + size: number + truncated: boolean + } } } -export type StepStarted = { +export type SessionStepStarted = { id: string created: number metadata?: { [key: string]: unknown } - type: "step.started" + type: "session.step.started" durable: { aggregateID: string seq: number @@ -4799,13 +4795,13 @@ export type StepStarted = { } } -export type StepEnded = { +export type SessionStepEnded = { id: string created: number metadata?: { [key: string]: unknown } - type: "step.ended" + type: "session.step.ended" durable: { aggregateID: string seq: number @@ -4831,13 +4827,13 @@ export type StepEnded = { } } -export type StepFailed = { +export type SessionStepFailed = { id: string created: number metadata?: { [key: string]: unknown } - type: "step.failed" + type: "session.step.failed" durable: { aggregateID: string seq: number @@ -4851,13 +4847,13 @@ export type StepFailed = { } } -export type TextStarted = { +export type SessionTextStarted = { id: string created: number metadata?: { [key: string]: unknown } - type: "text.started" + type: "session.text.started" durable: { aggregateID: string seq: number @@ -4871,13 +4867,13 @@ export type TextStarted = { } } -export type TextEnded = { +export type SessionTextEnded = { id: string created: number metadata?: { [key: string]: unknown } - type: "text.ended" + type: "session.text.ended" durable: { aggregateID: string seq: number @@ -4892,13 +4888,13 @@ export type TextEnded = { } } -export type ReasoningStarted = { +export type SessionReasoningStarted = { id: string created: number metadata?: { [key: string]: unknown } - type: "reasoning.started" + type: "session.reasoning.started" durable: { aggregateID: string seq: number @@ -4913,13 +4909,13 @@ export type ReasoningStarted = { } } -export type ReasoningEnded = { +export type SessionReasoningEnded = { id: string created: number metadata?: { [key: string]: unknown } - type: "reasoning.ended" + type: "session.reasoning.ended" durable: { aggregateID: string seq: number @@ -4935,13 +4931,13 @@ export type ReasoningEnded = { } } -export type ToolInputStarted = { +export type SessionToolInputStarted = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.input.started" + type: "session.tool.input.started" durable: { aggregateID: string seq: number @@ -4956,13 +4952,13 @@ export type ToolInputStarted = { } } -export type ToolInputEnded = { +export type SessionToolInputEnded = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.input.ended" + type: "session.tool.input.ended" durable: { aggregateID: string seq: number @@ -4977,13 +4973,13 @@ export type ToolInputEnded = { } } -export type ToolCalled = { +export type SessionToolCalled = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.called" + type: "session.tool.called" durable: { aggregateID: string seq: number @@ -5005,13 +5001,13 @@ export type ToolCalled = { } } -export type ToolProgress = { +export type SessionToolProgress = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.progress" + type: "session.tool.progress" durable: { aggregateID: string seq: number @@ -5029,13 +5025,13 @@ export type ToolProgress = { } } -export type ToolSuccess = { +export type SessionToolSuccess = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.success" + type: "session.tool.success" durable: { aggregateID: string seq: number @@ -5059,13 +5055,13 @@ export type ToolSuccess = { } } -export type ToolFailed = { +export type SessionToolFailed = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.failed" + type: "session.tool.failed" durable: { aggregateID: string seq: number @@ -5085,13 +5081,33 @@ export type ToolFailed = { } } -export type CompactionStarted = { +export type SessionRetried = { id: string created: number metadata?: { [key: string]: unknown } - type: "compaction.started" + type: "session.retried" + durable: { + aggregateID: string + seq: number + version: number + } + location?: LocationRef + data: { + sessionID: string + attempt: number + error: SessionRetryError + } +} + +export type SessionCompactionStarted = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "session.compaction.started" durable: { aggregateID: string seq: number @@ -5104,13 +5120,13 @@ export type CompactionStarted = { } } -export type CompactionEnded = { +export type SessionCompactionEnded = { id: string created: number metadata?: { [key: string]: unknown } - type: "compaction.ended" + type: "session.compaction.ended" durable: { aggregateID: string seq: number @@ -5125,13 +5141,13 @@ export type CompactionEnded = { } } -export type RevertStaged = { +export type SessionRevertStaged = { id: string created: number metadata?: { [key: string]: unknown } - type: "revert.staged" + type: "session.revert.staged" durable: { aggregateID: string seq: number @@ -5144,13 +5160,13 @@ export type RevertStaged = { } } -export type RevertCleared = { +export type SessionRevertCleared = { id: string created: number metadata?: { [key: string]: unknown } - type: "revert.cleared" + type: "session.revert.cleared" durable: { aggregateID: string seq: number @@ -5162,13 +5178,13 @@ export type RevertCleared = { } } -export type RevertCommitted = { +export type SessionRevertCommitted = { id: string created: number metadata?: { [key: string]: unknown } - type: "revert.committed" + type: "session.revert.committed" durable: { aggregateID: string seq: number @@ -5708,13 +5724,13 @@ export type MessagePartRemoved = { } } -export type ExecutionSettled = { +export type SessionExecutionSettled = { id: string created: number metadata?: { [key: string]: unknown } - type: "execution.settled" + type: "session.execution.settled" location?: LocationRef data: { sessionID: string @@ -5723,13 +5739,13 @@ export type ExecutionSettled = { } } -export type TextDelta = { +export type SessionTextDelta = { id: string created: number metadata?: { [key: string]: unknown } - type: "text.delta" + type: "session.text.delta" location?: LocationRef data: { sessionID: string @@ -5739,13 +5755,13 @@ export type TextDelta = { } } -export type ReasoningDelta = { +export type SessionReasoningDelta = { id: string created: number metadata?: { [key: string]: unknown } - type: "reasoning.delta" + type: "session.reasoning.delta" location?: LocationRef data: { sessionID: string @@ -5755,13 +5771,13 @@ export type ReasoningDelta = { } } -export type ToolInputDelta = { +export type SessionToolInputDelta = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.input.delta" + type: "session.tool.input.delta" location?: LocationRef data: { sessionID: string @@ -5771,13 +5787,13 @@ export type ToolInputDelta = { } } -export type CompactionDelta = { +export type SessionCompactionDelta = { id: string created: number metadata?: { [key: string]: unknown } - type: "compaction.delta" + type: "session.compaction.delta" location?: LocationRef data: { sessionID: string @@ -6730,18 +6746,18 @@ export type EventMessagePartRemoved = { } } -export type EventAgentSelected = { +export type EventSessionAgentSelected = { id: string - type: "agent.selected" + type: "session.agent.selected" properties: { sessionID: string agent: string } } -export type EventModelSelected = { +export type EventSessionModelSelected = { id: string - type: "model.selected" + type: "session.model.selected" properties: { sessionID: string model: ModelRef @@ -6758,18 +6774,18 @@ export type EventSessionMoved = { } } -export type EventRenamed = { +export type EventSessionRenamed = { id: string - type: "renamed" + type: "session.renamed" properties: { sessionID: string title: string } } -export type EventForked = { +export type EventSessionForked = { id: string - type: "forked" + type: "session.forked" properties: { sessionID: string parentID: string @@ -6777,18 +6793,18 @@ export type EventForked = { } } -export type EventPromptPromoted = { +export type EventSessionPromptPromoted = { id: string - type: "prompt.promoted" + type: "session.prompt.promoted" properties: { sessionID: string inputID: string } } -export type EventPromptAdmitted = { +export type EventSessionPromptAdmitted = { id: string - type: "prompt.admitted" + type: "session.prompt.admitted" properties: { sessionID: string inputID: string @@ -6797,9 +6813,9 @@ export type EventPromptAdmitted = { } } -export type EventExecutionSettled = { +export type EventSessionExecutionSettled = { id: string - type: "execution.settled" + type: "session.execution.settled" properties: { sessionID: string outcome: "success" | "failure" | "interrupted" @@ -6816,9 +6832,9 @@ export type EventSessionContextUpdated = { } } -export type EventSynthetic = { +export type EventSessionSynthetic = { id: string - type: "synthetic" + type: "session.synthetic" properties: { sessionID: string text: string @@ -6829,9 +6845,9 @@ export type EventSynthetic = { } } -export type EventSkillActivated = { +export type EventSessionSkillActivated = { id: string - type: "skill.activated" + type: "session.skill.activated" properties: { sessionID: string name: string @@ -6839,29 +6855,33 @@ export type EventSkillActivated = { } } -export type EventShellStarted = { +export type EventSessionShellStarted = { id: string - type: "shell.started" + type: "session.shell.started" properties: { sessionID: string - callID: string - command: string + shell: Shell2 } } -export type EventShellEnded = { +export type EventSessionShellEnded = { id: string - type: "shell.ended" + type: "session.shell.ended" properties: { sessionID: string - callID: string - output: string + shell: Shell2 + output: { + output: string + cursor: number + size: number + truncated: boolean + } } } -export type EventStepStarted = { +export type EventSessionStepStarted = { id: string - type: "step.started" + type: "session.step.started" properties: { sessionID: string assistantMessageID: string @@ -6871,9 +6891,9 @@ export type EventStepStarted = { } } -export type EventStepEnded = { +export type EventSessionStepEnded = { id: string - type: "step.ended" + type: "session.step.ended" properties: { sessionID: string assistantMessageID: string @@ -6893,9 +6913,9 @@ export type EventStepEnded = { } } -export type EventStepFailed = { +export type EventSessionStepFailed = { id: string - type: "step.failed" + type: "session.step.failed" properties: { sessionID: string assistantMessageID: string @@ -6903,9 +6923,9 @@ export type EventStepFailed = { } } -export type EventTextStarted = { +export type EventSessionTextStarted = { id: string - type: "text.started" + type: "session.text.started" properties: { sessionID: string assistantMessageID: string @@ -6913,9 +6933,9 @@ export type EventTextStarted = { } } -export type EventTextDelta = { +export type EventSessionTextDelta = { id: string - type: "text.delta" + type: "session.text.delta" properties: { sessionID: string assistantMessageID: string @@ -6924,9 +6944,9 @@ export type EventTextDelta = { } } -export type EventTextEnded = { +export type EventSessionTextEnded = { id: string - type: "text.ended" + type: "session.text.ended" properties: { sessionID: string assistantMessageID: string @@ -6935,9 +6955,9 @@ export type EventTextEnded = { } } -export type EventReasoningStarted = { +export type EventSessionReasoningStarted = { id: string - type: "reasoning.started" + type: "session.reasoning.started" properties: { sessionID: string assistantMessageID: string @@ -6946,9 +6966,9 @@ export type EventReasoningStarted = { } } -export type EventReasoningDelta = { +export type EventSessionReasoningDelta = { id: string - type: "reasoning.delta" + type: "session.reasoning.delta" properties: { sessionID: string assistantMessageID: string @@ -6957,9 +6977,9 @@ export type EventReasoningDelta = { } } -export type EventReasoningEnded = { +export type EventSessionReasoningEnded = { id: string - type: "reasoning.ended" + type: "session.reasoning.ended" properties: { sessionID: string assistantMessageID: string @@ -6969,9 +6989,9 @@ export type EventReasoningEnded = { } } -export type EventToolInputStarted = { +export type EventSessionToolInputStarted = { id: string - type: "tool.input.started" + type: "session.tool.input.started" properties: { sessionID: string assistantMessageID: string @@ -6980,9 +7000,9 @@ export type EventToolInputStarted = { } } -export type EventToolInputDelta = { +export type EventSessionToolInputDelta = { id: string - type: "tool.input.delta" + type: "session.tool.input.delta" properties: { sessionID: string assistantMessageID: string @@ -6991,9 +7011,9 @@ export type EventToolInputDelta = { } } -export type EventToolInputEnded = { +export type EventSessionToolInputEnded = { id: string - type: "tool.input.ended" + type: "session.tool.input.ended" properties: { sessionID: string assistantMessageID: string @@ -7002,9 +7022,9 @@ export type EventToolInputEnded = { } } -export type EventToolCalled = { +export type EventSessionToolCalled = { id: string - type: "tool.called" + type: "session.tool.called" properties: { sessionID: string assistantMessageID: string @@ -7020,9 +7040,9 @@ export type EventToolCalled = { } } -export type EventToolProgress = { +export type EventSessionToolProgress = { id: string - type: "tool.progress" + type: "session.tool.progress" properties: { sessionID: string assistantMessageID: string @@ -7034,9 +7054,9 @@ export type EventToolProgress = { } } -export type EventToolSuccess = { +export type EventSessionToolSuccess = { id: string - type: "tool.success" + type: "session.tool.success" properties: { sessionID: string assistantMessageID: string @@ -7054,9 +7074,9 @@ export type EventToolSuccess = { } } -export type EventToolFailed = { +export type EventSessionToolFailed = { id: string - type: "tool.failed" + type: "session.tool.failed" properties: { sessionID: string assistantMessageID: string @@ -7070,9 +7090,9 @@ export type EventToolFailed = { } } -export type EventRetried = { +export type EventSessionRetried = { id: string - type: "retried" + type: "session.retried" properties: { sessionID: string attempt: number @@ -7080,27 +7100,27 @@ export type EventRetried = { } } -export type EventCompactionStarted = { +export type EventSessionCompactionStarted = { id: string - type: "compaction.started" + type: "session.compaction.started" properties: { sessionID: string reason: "auto" | "manual" } } -export type EventCompactionDelta = { +export type EventSessionCompactionDelta = { id: string - type: "compaction.delta" + type: "session.compaction.delta" properties: { sessionID: string text: string } } -export type EventCompactionEnded = { +export type EventSessionCompactionEnded = { id: string - type: "compaction.ended" + type: "session.compaction.ended" properties: { sessionID: string reason: "auto" | "manual" @@ -7109,26 +7129,26 @@ export type EventCompactionEnded = { } } -export type EventRevertStaged = { +export type EventSessionRevertStaged = { id: string - type: "revert.staged" + type: "session.revert.staged" properties: { sessionID: string revert: RevertState } } -export type EventRevertCleared = { +export type EventSessionRevertCleared = { id: string - type: "revert.cleared" + type: "session.revert.cleared" properties: { sessionID: string } } -export type EventRevertCommitted = { +export type EventSessionRevertCommitted = { id: string - type: "revert.committed" + type: "session.revert.committed" properties: { sessionID: string messageID: string @@ -7999,6 +8019,24 @@ export type SessionMessageSkill2 = { text: string } +export type ShellV2 = { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" + metadata: { + [key: string]: unknown + } + time: { + started: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" + completed?: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" + } +} + export type SessionMessageShell2 = { id: string metadata?: { @@ -8009,9 +8047,13 @@ export type SessionMessageShell2 = { completed?: number } type: "shell" - callID: string - command: string - output: string + shell: ShellV2 + output?: { + output: string + cursor: number + size: number + truncated: boolean + } } export type SessionMessageAssistantText2 = { @@ -8188,13 +8230,13 @@ export type SessionContextEntryInfo2 = { value: unknown } -export type AgentSelected2 = { +export type SessionAgentSelected2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "agent.selected" + type: "session.agent.selected" durable: { aggregateID: string seq: number @@ -8207,13 +8249,13 @@ export type AgentSelected2 = { } } -export type ModelSelected2 = { +export type SessionModelSelected2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "model.selected" + type: "session.model.selected" durable: { aggregateID: string seq: number @@ -8246,13 +8288,13 @@ export type SessionMoved2 = { } } -export type RenamedV2 = { +export type SessionRenamed2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "renamed" + type: "session.renamed" durable: { aggregateID: string seq: number @@ -8265,13 +8307,13 @@ export type RenamedV2 = { } } -export type ForkedV2 = { +export type SessionForked2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "forked" + type: "session.forked" durable: { aggregateID: string seq: number @@ -8285,13 +8327,13 @@ export type ForkedV2 = { } } -export type PromptPromoted2 = { +export type SessionPromptPromoted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "prompt.promoted" + type: "session.prompt.promoted" durable: { aggregateID: string seq: number @@ -8304,13 +8346,13 @@ export type PromptPromoted2 = { } } -export type PromptAdmitted2 = { +export type SessionPromptAdmitted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "prompt.admitted" + type: "session.prompt.admitted" durable: { aggregateID: string seq: number @@ -8344,13 +8386,13 @@ export type SessionContextUpdated2 = { } } -export type SyntheticV2 = { +export type SessionSynthetic2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "synthetic" + type: "session.synthetic" durable: { aggregateID: string seq: number @@ -8367,13 +8409,13 @@ export type SyntheticV2 = { } } -export type SkillActivated2 = { +export type SessionSkillActivated2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "skill.activated" + type: "session.skill.activated" durable: { aggregateID: string seq: number @@ -8387,13 +8429,31 @@ export type SkillActivated2 = { } } -export type ShellStarted2 = { +export type Shell1V2 = { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number | "NaN" | "Infinity" | "-Infinity" + metadata: { + [key: string]: unknown + } + time: { + started: number | "NaN" | "Infinity" | "-Infinity" + completed?: number | "NaN" | "Infinity" | "-Infinity" + } +} + +export type SessionShellStarted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "shell.started" + type: "session.shell.started" durable: { aggregateID: string seq: number @@ -8402,18 +8462,17 @@ export type ShellStarted2 = { location?: LocationRef2 data: { sessionID: string - callID: string - command: string + shell: Shell1V2 } } -export type ShellEnded2 = { +export type SessionShellEnded2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "shell.ended" + type: "session.shell.ended" durable: { aggregateID: string seq: number @@ -8422,18 +8481,23 @@ export type ShellEnded2 = { location?: LocationRef2 data: { sessionID: string - callID: string - output: string + shell: Shell1V2 + output: { + output: string + cursor: number + size: number + truncated: boolean + } } } -export type StepStarted2 = { +export type SessionStepStarted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "step.started" + type: "session.step.started" durable: { aggregateID: string seq: number @@ -8449,13 +8513,13 @@ export type StepStarted2 = { } } -export type StepEnded2 = { +export type SessionStepEnded2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "step.ended" + type: "session.step.ended" durable: { aggregateID: string seq: number @@ -8481,13 +8545,13 @@ export type StepEnded2 = { } } -export type StepFailed2 = { +export type SessionStepFailed2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "step.failed" + type: "session.step.failed" durable: { aggregateID: string seq: number @@ -8501,13 +8565,13 @@ export type StepFailed2 = { } } -export type TextStarted2 = { +export type SessionTextStarted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "text.started" + type: "session.text.started" durable: { aggregateID: string seq: number @@ -8521,13 +8585,13 @@ export type TextStarted2 = { } } -export type TextEnded2 = { +export type SessionTextEnded2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "text.ended" + type: "session.text.ended" durable: { aggregateID: string seq: number @@ -8548,13 +8612,13 @@ export type LlmProviderMetadata3 = { } } -export type ReasoningStarted2 = { +export type SessionReasoningStarted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "reasoning.started" + type: "session.reasoning.started" durable: { aggregateID: string seq: number @@ -8575,13 +8639,13 @@ export type LlmProviderMetadata4 = { } } -export type ReasoningEnded2 = { +export type SessionReasoningEnded2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "reasoning.ended" + type: "session.reasoning.ended" durable: { aggregateID: string seq: number @@ -8597,13 +8661,13 @@ export type ReasoningEnded2 = { } } -export type ToolInputStarted2 = { +export type SessionToolInputStarted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.input.started" + type: "session.tool.input.started" durable: { aggregateID: string seq: number @@ -8618,13 +8682,13 @@ export type ToolInputStarted2 = { } } -export type ToolInputEnded2 = { +export type SessionToolInputEnded2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.input.ended" + type: "session.tool.input.ended" durable: { aggregateID: string seq: number @@ -8645,13 +8709,13 @@ export type LlmProviderMetadata5 = { } } -export type ToolCalled2 = { +export type SessionToolCalled2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.called" + type: "session.tool.called" durable: { aggregateID: string seq: number @@ -8673,13 +8737,13 @@ export type ToolCalled2 = { } } -export type ToolProgress2 = { +export type SessionToolProgress2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.progress" + type: "session.tool.progress" durable: { aggregateID: string seq: number @@ -8703,13 +8767,13 @@ export type LlmProviderMetadata6 = { } } -export type ToolSuccess2 = { +export type SessionToolSuccess2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.success" + type: "session.tool.success" durable: { aggregateID: string seq: number @@ -8739,13 +8803,13 @@ export type LlmProviderMetadata7 = { } } -export type ToolFailed2 = { +export type SessionToolFailed2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.failed" + type: "session.tool.failed" durable: { aggregateID: string seq: number @@ -8778,13 +8842,13 @@ export type SessionRetryError2 = { } } -export type RetriedV2 = { +export type SessionRetried2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "retried" + type: "session.retried" durable: { aggregateID: string seq: number @@ -8798,13 +8862,13 @@ export type RetriedV2 = { } } -export type CompactionStarted2 = { +export type SessionCompactionStarted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "compaction.started" + type: "session.compaction.started" durable: { aggregateID: string seq: number @@ -8817,13 +8881,13 @@ export type CompactionStarted2 = { } } -export type CompactionEnded2 = { +export type SessionCompactionEnded2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "compaction.ended" + type: "session.compaction.ended" durable: { aggregateID: string seq: number @@ -8838,13 +8902,13 @@ export type CompactionEnded2 = { } } -export type RevertStaged2 = { +export type SessionRevertStaged2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "revert.staged" + type: "session.revert.staged" durable: { aggregateID: string seq: number @@ -8857,13 +8921,13 @@ export type RevertStaged2 = { } } -export type RevertCleared2 = { +export type SessionRevertCleared2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "revert.cleared" + type: "session.revert.cleared" durable: { aggregateID: string seq: number @@ -8875,13 +8939,13 @@ export type RevertCleared2 = { } } -export type RevertCommitted2 = { +export type SessionRevertCommitted2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "revert.committed" + type: "session.revert.committed" durable: { aggregateID: string seq: number @@ -8895,37 +8959,37 @@ export type RevertCommitted2 = { } export type SessionDurableEventV2 = - | AgentSelected2 - | ModelSelected2 + | SessionAgentSelected2 + | SessionModelSelected2 | SessionMoved2 - | RenamedV2 - | ForkedV2 - | PromptPromoted2 - | PromptAdmitted2 + | SessionRenamed2 + | SessionForked2 + | SessionPromptPromoted2 + | SessionPromptAdmitted2 | SessionContextUpdated2 - | SyntheticV2 - | SkillActivated2 - | ShellStarted2 - | ShellEnded2 - | StepStarted2 - | StepEnded2 - | StepFailed2 - | TextStarted2 - | TextEnded2 - | ReasoningStarted2 - | ReasoningEnded2 - | ToolInputStarted2 - | ToolInputEnded2 - | ToolCalled2 - | ToolProgress2 - | ToolSuccess2 - | ToolFailed2 - | RetriedV2 - | CompactionStarted2 - | CompactionEnded2 - | RevertStaged2 - | RevertCleared2 - | RevertCommitted2 + | SessionSynthetic2 + | SessionSkillActivated2 + | SessionShellStarted2 + | SessionShellEnded2 + | SessionStepStarted2 + | SessionStepEnded2 + | SessionStepFailed2 + | SessionTextStarted2 + | SessionTextEnded2 + | SessionReasoningStarted2 + | SessionReasoningEnded2 + | SessionToolInputStarted2 + | SessionToolInputEnded2 + | SessionToolCalled2 + | SessionToolProgress2 + | SessionToolSuccess2 + | SessionToolFailed2 + | SessionRetried2 + | SessionCompactionStarted2 + | SessionCompactionEnded2 + | SessionRevertStaged2 + | SessionRevertCleared2 + | SessionRevertCommitted2 /** * Marker emitted once when a log read reaches its captured watermark. The reader holds every event committed at or below seq. @@ -10138,13 +10202,13 @@ export type MessagePartRemoved2 = { } } -export type ExecutionSettled2 = { +export type SessionExecutionSettled2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "execution.settled" + type: "session.execution.settled" location?: LocationRef2 data: { sessionID: string @@ -10153,13 +10217,13 @@ export type ExecutionSettled2 = { } } -export type TextDelta2 = { +export type SessionTextDelta2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "text.delta" + type: "session.text.delta" location?: LocationRef2 data: { sessionID: string @@ -10169,13 +10233,13 @@ export type TextDelta2 = { } } -export type ReasoningDelta2 = { +export type SessionReasoningDelta2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "reasoning.delta" + type: "session.reasoning.delta" location?: LocationRef2 data: { sessionID: string @@ -10185,13 +10249,13 @@ export type ReasoningDelta2 = { } } -export type ToolInputDelta2 = { +export type SessionToolInputDelta2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "tool.input.delta" + type: "session.tool.input.delta" location?: LocationRef2 data: { sessionID: string @@ -10201,13 +10265,13 @@ export type ToolInputDelta2 = { } } -export type CompactionDelta2 = { +export type SessionCompactionDelta2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "compaction.delta" + type: "session.compaction.delta" location?: LocationRef2 data: { sessionID: string @@ -10413,24 +10477,6 @@ export type PtyDeleted2 = { } } -export type ShellV2 = { - id: string - status: "running" | "exited" | "timeout" | "killed" - command: string - cwd: string - shell: string - file: string - pid?: number - exit?: number | "NaN" | "Infinity" | "-Infinity" - metadata: { - [key: string]: unknown - } - time: { - started: number | "NaN" | "Infinity" | "-Infinity" - completed?: number | "NaN" | "Infinity" | "-Infinity" - } -} - export type ShellCreated2 = { id: string created: number @@ -10440,7 +10486,7 @@ export type ShellCreated2 = { type: "shell.created" location?: LocationRef2 data: { - info: ShellV2 + info: Shell1V2 } } @@ -11080,42 +11126,42 @@ export type V2EventV2 = | MessageRemoved2 | MessagePartUpdated2 | MessagePartRemoved2 - | AgentSelected2 - | ModelSelected2 + | SessionAgentSelected2 + | SessionModelSelected2 | SessionMoved2 - | RenamedV2 - | ForkedV2 - | PromptPromoted2 - | PromptAdmitted2 - | ExecutionSettled2 + | SessionRenamed2 + | SessionForked2 + | SessionPromptPromoted2 + | SessionPromptAdmitted2 + | SessionExecutionSettled2 | SessionContextUpdated2 - | SyntheticV2 - | SkillActivated2 - | ShellStarted2 - | ShellEnded2 - | StepStarted2 - | StepEnded2 - | StepFailed2 - | TextStarted2 - | TextDelta2 - | TextEnded2 - | ReasoningStarted2 - | ReasoningDelta2 - | ReasoningEnded2 - | ToolInputStarted2 - | ToolInputDelta2 - | ToolInputEnded2 - | ToolCalled2 - | ToolProgress2 - | ToolSuccess2 - | ToolFailed2 - | RetriedV2 - | CompactionStarted2 - | CompactionDelta2 - | CompactionEnded2 - | RevertStaged2 - | RevertCleared2 - | RevertCommitted2 + | SessionSynthetic2 + | SessionSkillActivated2 + | SessionShellStarted2 + | SessionShellEnded2 + | SessionStepStarted2 + | SessionStepEnded2 + | SessionStepFailed2 + | SessionTextStarted2 + | SessionTextDelta2 + | SessionTextEnded2 + | SessionReasoningStarted2 + | SessionReasoningDelta2 + | SessionReasoningEnded2 + | SessionToolInputStarted2 + | SessionToolInputDelta2 + | SessionToolInputEnded2 + | SessionToolCalled2 + | SessionToolProgress2 + | SessionToolSuccess2 + | SessionToolFailed2 + | SessionRetried2 + | SessionCompactionStarted2 + | SessionCompactionDelta2 + | SessionCompactionEnded2 + | SessionRevertStaged2 + | SessionRevertCleared2 + | SessionRevertCommitted2 | FileEdited2 | ReferenceUpdated2 | PermissionV2Asked2 @@ -11195,24 +11241,6 @@ export type ForbiddenErrorV2 = { message: string } -export type Shell1V2 = { - id: string - status: "running" | "exited" | "timeout" | "killed" - command: string - cwd: string - shell: string - file: string - pid?: number - exit?: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" - metadata: { - [key: string]: unknown - } - time: { - started: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" - completed?: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" - } -} - export type ShellNotFoundErrorV2 = { _tag: "ShellNotFoundError" id: string @@ -18444,7 +18472,7 @@ export type V2ShellListResponses = { */ 200: { location: LocationInfo2 - data: Array + data: Array } } @@ -18488,7 +18516,7 @@ export type V2ShellCreateResponses = { */ 200: { location: LocationInfo2 - data: Shell1V2 + data: ShellV2 } } @@ -18571,7 +18599,7 @@ export type V2ShellGetResponses = { */ 200: { location: LocationInfo2 - data: Shell1V2 + data: ShellV2 } } diff --git a/packages/sdk/openapi.json b/packages/sdk/openapi.json index b30c3beb35..e136ef6836 100644 --- a/packages/sdk/openapi.json +++ b/packages/sdk/openapi.json @@ -16410,7 +16410,7 @@ "text": { "type": "string" }, - "synthetic": { + "session.synthetic": { "type": "boolean" }, "ignored": { @@ -23071,7 +23071,7 @@ "text": { "type": "string" }, - "synthetic": { + "session.synthetic": { "type": "boolean" }, "ignored": { @@ -27479,7 +27479,7 @@ }, "type": { "type": "string", - "enum": ["synthetic"] + "enum": ["session.synthetic"] } }, "required": ["id", "time", "sessionID", "text", "type"], diff --git a/packages/tui/src/context/data.tsx b/packages/tui/src/context/data.tsx index cc9378dbac..0ed464e561 100644 --- a/packages/tui/src/context/data.tsx +++ b/packages/tui/src/context/data.tsx @@ -126,8 +126,8 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ const item = position === undefined ? undefined : messages[position] return item?.type === "assistant" ? item : undefined }, - activeShell(messages: SessionMessage[], callID: string) { - const item = messages.findLast((item) => item.type === "shell" && item.callID === callID) + shell(messages: SessionMessage[], shellID: string) { + const item = messages.findLast((item) => item.type === "shell" && item.shell.id === shellID) return item?.type === "shell" ? item : undefined }, latestTool(assistant: SessionMessageAssistant | undefined, callID?: string) { @@ -220,7 +220,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ case "skill.updated": void result.location.skill.refresh(event.location) break - case "agent.selected": + case "session.agent.selected": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "agent", event.data.agent) message.update(event.data.sessionID, (draft, index) => { @@ -232,7 +232,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "model.selected": + case "session.model.selected": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "model", event.data.model) message.update(event.data.sessionID, (draft, index) => { @@ -244,11 +244,11 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "renamed": + case "session.renamed": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "title", event.data.title) break - case "prompt.promoted": { + case "session.prompt.promoted": { setStore("session", "status", event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { const position = index.get(event.data.inputID) @@ -264,7 +264,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) break } - case "prompt.admitted": + case "session.prompt.admitted": message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { id: event.data.inputID, @@ -287,7 +287,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "synthetic": + case "session.synthetic": message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { id: messageIDFromEvent(event.id), @@ -299,29 +299,28 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "shell.started": + case "session.shell.started": setStore("session", "status", event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { id: messageIDFromEvent(event.id), type: "shell", - callID: event.data.callID, - command: event.data.command, - output: "", + shell: event.data.shell, time: { created: event.created }, }) }) break - case "shell.ended": + case "session.shell.ended": setStore("session", "status", event.data.sessionID, "idle") - message.update(event.data.sessionID, (draft, index) => { - const match = message.activeShell(draft, event.data.callID) + message.update(event.data.sessionID, (draft) => { + const match = message.shell(draft, event.data.shell.id) if (!match) return + match.shell = event.data.shell match.output = event.data.output match.time.completed = event.created }) break - case "step.started": + case "session.step.started": setStore("session", "status", event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { if (index.has(event.data.assistantMessageID)) return @@ -338,7 +337,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "step.ended": + case "session.step.ended": setStore("session", "status", event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { const currentAssistant = message.assistant(draft, index, event.data.assistantMessageID) @@ -351,7 +350,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ currentAssistant.snapshot = { ...currentAssistant.snapshot, end: event.data.snapshot } }) break - case "step.failed": + case "session.step.failed": message.update(event.data.sessionID, (draft, index) => { const currentAssistant = message.assistant(draft, index, event.data.assistantMessageID) if (!currentAssistant) return @@ -360,7 +359,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ currentAssistant.error = event.data.error }) break - case "text.started": + case "session.text.started": message.update(event.data.sessionID, (draft, index) => { message.assistant(draft, index, event.data.assistantMessageID)?.content.push({ type: "text", @@ -369,7 +368,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "text.delta": + case "session.text.delta": message.update(event.data.sessionID, (draft, index) => { const match = message.latestText( message.assistant(draft, index, event.data.assistantMessageID), @@ -378,7 +377,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match) match.text += event.data.delta }) break - case "text.ended": + case "session.text.ended": message.update(event.data.sessionID, (draft, index) => { const match = message.latestText( message.assistant(draft, index, event.data.assistantMessageID), @@ -387,7 +386,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match) match.text = event.data.text }) break - case "tool.input.started": + case "session.tool.input.started": message.update(event.data.sessionID, (draft, index) => { message.assistant(draft, index, event.data.assistantMessageID)?.content.push({ type: "tool", @@ -398,7 +397,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "tool.input.delta": + case "session.tool.input.delta": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -407,7 +406,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match?.state.status === "pending") match.state.input += event.data.delta }) break - case "tool.input.ended": + case "session.tool.input.ended": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -416,7 +415,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match?.state.status === "pending") match.state.input = event.data.text }) break - case "tool.called": + case "session.tool.called": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -428,7 +427,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ match.state = { status: "running", input: event.data.input, structured: {}, content: [] } }) break - case "tool.progress": + case "session.tool.progress": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -439,7 +438,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ match.state.content = [...event.data.content] }) break - case "tool.success": + case "session.tool.success": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -461,7 +460,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ match.time.completed = event.created }) break - case "tool.failed": + case "session.tool.failed": message.update(event.data.sessionID, (draft, index) => { const match = message.latestTool( message.assistant(draft, index, event.data.assistantMessageID), @@ -484,7 +483,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ match.time.completed = event.created }) break - case "reasoning.started": + case "session.reasoning.started": message.update(event.data.sessionID, (draft, index) => { message.assistant(draft, index, event.data.assistantMessageID)?.content.push({ type: "reasoning", @@ -495,7 +494,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) }) break - case "reasoning.delta": + case "session.reasoning.delta": message.update(event.data.sessionID, (draft, index) => { const match = message.latestReasoning( message.assistant(draft, index, event.data.assistantMessageID), @@ -504,7 +503,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ if (match) match.text += event.data.delta }) break - case "reasoning.ended": + case "session.reasoning.ended": message.update(event.data.sessionID, (draft, index) => { const match = message.latestReasoning( message.assistant(draft, index, event.data.assistantMessageID), @@ -517,25 +516,25 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ } }) break - case "retried": - case "compaction.started": + case "session.retried": + case "session.compaction.started": setStore("session", "status", event.data.sessionID, "running") break - case "execution.settled": + case "session.execution.settled": setStore("session", "status", event.data.sessionID, "idle") break - case "revert.staged": + case "session.revert.staged": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "revert", event.data.revert) break - case "revert.cleared": - case "revert.committed": + case "session.revert.cleared": + case "session.revert.committed": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "revert", undefined) break - case "compaction.delta": + case "session.compaction.delta": break - case "compaction.ended": + case "session.compaction.ended": message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { id: messageIDFromEvent(event.id), diff --git a/packages/tui/src/feature-plugins/system/notifications.ts b/packages/tui/src/feature-plugins/system/notifications.ts index aa8dcace19..416ba8c466 100644 --- a/packages/tui/src/feature-plugins/system/notifications.ts +++ b/packages/tui/src/feature-plugins/system/notifications.ts @@ -74,17 +74,17 @@ const tui: TuiPlugin = async (api) => { notify(api, sessionID, "Session done", session?.parentID ? "subagent_done" : "done") } - api.event.on("prompt.promoted", (event) => started(event.data.sessionID)) - api.event.on("shell.started", (event) => started(event.data.sessionID)) - api.event.on("step.started", (event) => started(event.data.sessionID)) - api.event.on("retried", (event) => started(event.data.sessionID)) - api.event.on("compaction.started", (event) => started(event.data.sessionID)) - api.event.on("shell.ended", (event) => ended(event.data.sessionID)) - api.event.on("step.ended", (event) => { + api.event.on("session.prompt.promoted", (event) => started(event.data.sessionID)) + api.event.on("session.shell.started", (event) => started(event.data.sessionID)) + api.event.on("session.step.started", (event) => started(event.data.sessionID)) + api.event.on("session.retried", (event) => started(event.data.sessionID)) + api.event.on("session.compaction.started", (event) => started(event.data.sessionID)) + api.event.on("session.shell.ended", (event) => ended(event.data.sessionID)) + api.event.on("session.step.ended", (event) => { if (event.data.finish === "tool-calls") return ended(event.data.sessionID) }) - api.event.on("step.failed", (event) => { + api.event.on("session.step.failed", (event) => { const sessionID = event.data.sessionID if (!active.has(sessionID)) return errored.add(sessionID) diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index b0f337c2d4..b968f13cd3 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -1346,7 +1346,7 @@ function RevertMessage(props: { function ShellMessage(props: { message: Extract }) { const { theme } = useTheme() - const output = createMemo(() => stripAnsi(props.message.output.trim())) + const output = createMemo(() => stripAnsi(props.message.output?.output.trim() ?? "")) return ( - $ {props.message.command} + $ {props.message.shell.command} {output()} @@ -1408,13 +1408,7 @@ function UserMessage(props: { message: SessionMessageUser }) { > {props.message.text} - + {(file) => { const directory = file.mime === "application/x-directory" @@ -1744,7 +1738,8 @@ function ToolPart(props: { part: SessionMessageAssistantTool }) { return Boolean(shellID && data.shell.get(shellID)) } if (display() === "subagent") { - const sessionID = stringValue(props.part.state.structured.sessionID) ?? stringValue(props.part.state.structured.sessionId) + const sessionID = + stringValue(props.part.state.structured.sessionID) ?? stringValue(props.part.state.structured.sessionId) return Boolean(sessionID && data.session.status(sessionID) === "running") } return false @@ -2660,7 +2655,8 @@ function formatSessionTranscript( ) { const body = messages.flatMap((message) => { if (message.type === "user") return [`## User\n\n${message.text}`] - if (message.type === "shell") return [`## Shell\n\n\`\`\`\n$ ${message.command}\n${message.output}\n\`\`\``] + if (message.type === "shell") + return [`## Shell\n\n\`\`\`\n$ ${message.shell.command}\n${message.output?.output ?? ""}\n\`\`\``] if (message.type !== "assistant") return [] const content = message.content.flatMap((item) => { if (item.type === "text") return [item.text] diff --git a/packages/tui/src/routes/session/rows.ts b/packages/tui/src/routes/session/rows.ts index 23b43c3b17..783b2805f4 100644 --- a/packages/tui/src/routes/session/rows.ts +++ b/packages/tui/src/routes/session/rows.ts @@ -133,42 +133,42 @@ export function createSessionRows(sessionID: Accessor) { if (event.data.sessionID === sessionID()) appendMessage(event.data.inputID) } const subscriptions = [ - data.on("prompt.admitted", input), - data.on("prompt.promoted", input), + data.on("session.prompt.admitted", input), + data.on("session.prompt.promoted", input), data.on("session.context.updated", message), - data.on("synthetic", (event) => { + data.on("session.synthetic", (event) => { if (event.data.sessionID === sessionID() && event.data.description?.trim()) appendMessage(event.id.replace(/^evt_/, "msg_")) }), - data.on("shell.started", message), - data.on("agent.selected", message), - data.on("model.selected", message), - data.on("compaction.ended", message), - data.on("text.delta", (event) => { + data.on("session.shell.started", message), + data.on("session.agent.selected", message), + data.on("session.model.selected", message), + data.on("session.compaction.ended", message), + data.on("session.text.delta", (event) => { if (event.data.sessionID === sessionID()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.textID }) }), - data.on("text.ended", (event) => { + data.on("session.text.ended", (event) => { if (event.data.sessionID === sessionID() && event.data.text.trim()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.textID }) }), - data.on("reasoning.delta", (event) => { + data.on("session.reasoning.delta", (event) => { if (event.data.sessionID === sessionID()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.reasoningID }) }), - data.on("reasoning.ended", (event) => { + data.on("session.reasoning.ended", (event) => { if (event.data.sessionID === sessionID() && event.data.text.trim()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.reasoningID }) }), - data.on("tool.input.started", (event) => { + data.on("session.tool.input.started", (event) => { if (event.data.sessionID === sessionID()) appendPart({ messageID: event.data.assistantMessageID, partID: event.data.callID }, event.data.name) }), - data.on("step.ended", (event) => { + data.on("session.step.ended", (event) => { if (event.data.sessionID !== sessionID() || ["tool-calls", "unknown"].includes(event.data.finish)) return appendFooter(event.data.assistantMessageID) }), - data.on("step.failed", (event) => { + data.on("session.step.failed", (event) => { if (event.data.sessionID === sessionID()) appendFooter(event.data.assistantMessageID) }), ] diff --git a/packages/tui/test/cli/cmd/tui/notifications.test.ts b/packages/tui/test/cli/cmd/tui/notifications.test.ts index 5f1c6355b3..44cd98b133 100644 --- a/packages/tui/test/cli/cmd/tui/notifications.test.ts +++ b/packages/tui/test/cli/cmd/tui/notifications.test.ts @@ -91,7 +91,7 @@ function stepStarted(id: string, sessionID = "session"): V2Event { return { id, created: 0, - type: "step.started", + type: "session.step.started", durable: durable(sessionID), data: { sessionID, @@ -106,7 +106,7 @@ function stepEnded(id: string, sessionID = "session", finish = "stop"): V2Event return { id, created: 0, - type: "step.ended", + type: "session.step.ended", durable: durable(sessionID), data: { sessionID, @@ -122,7 +122,7 @@ function stepFailed(id: string, sessionID = "session"): V2Event { return { id, created: 0, - type: "step.failed", + type: "session.step.failed", durable: durable(sessionID), data: { sessionID, diff --git a/packages/tui/test/cli/tui/data.test.tsx b/packages/tui/test/cli/tui/data.test.tsx index a71bdc47d8..0587662dc3 100644 --- a/packages/tui/test/cli/tui/data.test.tsx +++ b/packages/tui/test/cli/tui/data.test.tsx @@ -269,7 +269,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_started", created: 0, - type: "step.started", + type: "session.step.started", durable: durable("session-live"), data: { sessionID: "session-live", @@ -283,7 +283,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_ended", created: 0, - type: "step.ended", + type: "session.step.ended", durable: durable("session-live", 1, 2), data: { sessionID: "session-live", @@ -302,7 +302,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_execution_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "session-live", outcome: "success", @@ -313,7 +313,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_failed_step_started", created: 0, - type: "step.started", + type: "session.step.started", durable: durable("session-failed"), data: { sessionID: "session-failed", @@ -327,7 +327,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_step_failed", created: 0, - type: "step.failed", + type: "session.step.failed", durable: durable("session-failed", 1, 2), data: { sessionID: "session-failed", @@ -344,7 +344,7 @@ test("tracks session status from active sessions and execution events", async () emitEvent(events, { id: "evt_failed_execution_settled", created: 0, - type: "execution.settled", + type: "session.execution.settled", data: { sessionID: "session-failed", outcome: "failure", @@ -797,14 +797,14 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_agent_1", created: 0, - type: "agent.selected", + type: "session.agent.selected", durable: durable("session-1"), data: { sessionID: "session-1", agent: "build" }, }) emitEvent(events, { id: "evt_model_1", created: 0, - type: "model.selected", + type: "session.model.selected", durable: durable("session-1", 1), data: { sessionID: "session-1", @@ -814,7 +814,7 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_step_started_1", created: 0, - type: "step.started", + type: "session.step.started", durable: durable("session-1", 2), data: { sessionID: "session-1", @@ -826,7 +826,7 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_input_1", created: 0, - type: "tool.input.started", + type: "session.tool.input.started", durable: durable("session-1", 3), data: { sessionID: "session-1", @@ -838,7 +838,7 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_called_1", created: 0, - type: "tool.called", + type: "session.tool.called", durable: durable("session-1", 4), data: { sessionID: "session-1", @@ -852,7 +852,7 @@ test("settles pending tools when a live failure arrives", async () => { emitEvent(events, { id: "evt_failed_1", created: 0, - type: "tool.failed", + type: "session.tool.failed", durable: durable("session-1", 5), data: { sessionID: "session-1", @@ -942,7 +942,7 @@ test("renders admitted prompts immediately with queued marker and clears when pr emitEvent(events, { id: "evt_admitted_1", created: 0, - type: "prompt.admitted", + type: "session.prompt.admitted", durable: durable(sessionID), data: { sessionID, @@ -961,7 +961,7 @@ test("renders admitted prompts immediately with queued marker and clears when pr emitEvent(events, { id: "evt_prompted_1", created: 0, - type: "prompt.promoted", + type: "session.prompt.promoted", durable: durable(sessionID, 1), data: { sessionID, @@ -969,8 +969,8 @@ test("renders admitted prompts immediately with queued marker and clears when pr }, }) - await wait(() => received.at(-1) === "prompt.promoted") - expect(received.slice(-2)).toEqual(["prompt.admitted", "prompt.promoted"]) + await wait(() => received.at(-1) === "session.prompt.promoted") + expect(received.slice(-2)).toEqual(["session.prompt.admitted", "session.prompt.promoted"]) unsubscribe() const message = sync.session.message.list(sessionID)?.[0] expect(message?.type).toBe("user") diff --git a/packages/ui/src/components/provider-icon.tsx b/packages/ui/src/components/provider-icon.tsx index 7c0eb3d047..46fb7fb6f2 100644 --- a/packages/ui/src/components/provider-icon.tsx +++ b/packages/ui/src/components/provider-icon.tsx @@ -9,7 +9,7 @@ export type ProviderIconProps = JSX.SVGElementTags["svg"] & { export const ProviderIcon: Component = (props) => { const [local, rest] = splitProps(props, ["id", "class", "classList"]) - const resolved = createMemo(() => (iconNames.includes(local.id as IconName) ? local.id : "synthetic")) + const resolved = createMemo(() => (iconNames.includes(local.id as IconName) ? local.id : "session.synthetic")) return ( ✓ Connected - case "failed": - return ✗ {props.status.error} +// Sort by how much attention a server needs: auth prompts first, then failures, +// then healthy servers, and intentionally-off servers last. +function statusMeta(status: McpServer["status"], theme: Theme) { + switch (status.status) { case "needs_auth": - return ! Needs authentication + return { rank: 0, icon: "!", label: "Needs authentication", color: theme.warning, error: undefined, bold: false } case "needs_client_registration": - return ✗ {props.status.error} - case "disabled": - return ○ Disabled + return { rank: 1, icon: "✗", label: "Needs registration", color: theme.error, error: status.error, bold: false } + case "failed": + return { rank: 2, icon: "✗", label: "Failed", color: theme.error, error: status.error, bold: false } + case "connected": + return { rank: 3, icon: "✓", label: "Connected", color: theme.success, error: undefined, bold: true } + case "pending": + return { rank: 4, icon: "◌", label: "Pending", color: theme.textMuted, error: undefined, bold: false } default: - return ○ Disconnected + return { rank: 5, icon: "○", label: "Disabled", color: theme.textMuted, error: undefined, bold: false } } } export function DialogMcp() { const data = useData() + const dialog = useDialog() + const { theme } = useTheme() + const [expanded, setExpanded] = createStore>({}) + const [focused, setFocused] = createSignal() const [, setRef] = createSignal>() - const options = createMemo(() => + onMount(() => { + dialog.setSize("large") + }) + + const servers = createMemo(() => pipe( data.location.mcp.list() ?? [], - sortBy((server) => server.name), - map((server) => ({ - value: server.name, - title: server.name, - footer: , - category: undefined, - })), + sortBy( + (server) => statusMeta(server.status, theme).rank, + (server) => server.name, + ), ), ) + createEffect(() => { + if (focused()) return + const first = servers()[0] + if (first) setFocused(first.name) + }) + + const options = createMemo(() => + servers().map((server) => { + const meta = statusMeta(server.status, theme) + return { + value: server.name, + title: server.name, + footer: ( + + {meta.icon} {meta.label} + + ), + details: meta.error && expanded[server.name] ? [meta.error] : undefined, + detailsColor: theme.error, + detailsWrap: true, + } + }), + ) + + const focusedError = createMemo(() => { + const name = focused() + const server = servers().find((entry) => entry.name === name) + return server ? statusMeta(server.status, theme).error : undefined + }) + return ( { - // Read-only view: selection does nothing, the dialog closes on escape. + preserveSelection + onMove={(option) => setFocused(option.value as string)} + onSelect={(option) => { + const name = option.value as string + const server = servers().find((entry) => entry.name === name) + if (!server || !statusMeta(server.status, theme).error) return + setExpanded(name, (open) => !open) }} + footer={ + + enter to {expanded[focused()!] ? "hide" : "view"} error + + } /> ) } diff --git a/packages/tui/src/ui/dialog-select.tsx b/packages/tui/src/ui/dialog-select.tsx index dab9103d24..28235531e2 100644 --- a/packages/tui/src/ui/dialog-select.tsx +++ b/packages/tui/src/ui/dialog-select.tsx @@ -59,6 +59,8 @@ export interface DialogSelectOption { value: T description?: string details?: string[] + detailsColor?: RGBA + detailsWrap?: boolean footer?: JSX.Element | string titleWidth?: number truncateTitle?: boolean | "left" @@ -697,8 +699,13 @@ export function DialogSelect(props: DialogSelectProps) { {(detail) => ( - - {Locale.truncateMiddle(detail, Math.max(1, Math.min(76, dimensions().width - 12)))} + + {option.detailsWrap + ? detail + : Locale.truncateMiddle(detail, Math.max(1, Math.min(76, dimensions().width - 12)))} )} From c9b24ef027dbe5b338123e43ae395892650f8cd3 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 20:34:29 -0400 Subject: [PATCH 36/82] feat(core): reload config on filesystem changes --- packages/app/src/context/file/watcher.test.ts | 10 +- packages/app/src/context/file/watcher.ts | 2 +- packages/app/src/pages/session.tsx | 2 +- packages/client/src/effect/index.ts | 1 + packages/client/src/promise/api.ts | 2 + .../client/src/promise/generated/types.ts | 10 +- packages/client/src/promise/index.ts | 1 + packages/core/src/catalog.ts | 15 +- packages/core/src/config.ts | 120 ++++++---- packages/core/src/config/experimental.ts | 20 -- packages/core/src/config/plugin/command.ts | 33 ++- .../core/src/filesystem/location-watcher.ts | 83 +++++++ packages/core/src/filesystem/watcher.ts | 220 ++++++++++-------- packages/core/src/location-services.ts | 6 +- packages/core/src/plugin/host.ts | 9 +- packages/core/src/plugin/promise.ts | 5 +- packages/core/src/policy.ts | 48 ---- packages/core/src/skill.ts | 4 +- packages/core/src/v1/config/config.ts | 4 - packages/core/src/v1/config/migrate.ts | 1 - packages/core/test/catalog.test.ts | 20 +- packages/core/test/config/command.test.ts | 19 +- packages/core/test/config/config.test.ts | 96 ++++---- packages/core/test/filesystem/watcher.test.ts | 28 ++- packages/core/test/location-layer.test.ts | 27 +-- packages/core/test/plugin.test.ts | 23 +- packages/core/test/plugin/host.ts | 5 +- packages/core/test/policy.test.ts | 85 ------- packages/core/test/skill.test.ts | 4 +- packages/opencode/src/tool/apply_patch.ts | 3 +- packages/opencode/src/tool/edit.ts | 5 +- packages/opencode/src/tool/write.ts | 3 +- .../test/server/httpapi-v2-location.test.ts | 2 +- packages/plugin/src/v2/effect/context.ts | 2 + packages/plugin/src/v2/effect/event.ts | 11 +- packages/plugin/src/v2/effect/index.ts | 1 + packages/plugin/src/v2/promise/context.ts | 2 + packages/plugin/src/v2/promise/event.ts | 3 + packages/plugin/src/v2/promise/index.ts | 1 + packages/schema/src/config.ts | 10 + packages/schema/src/event-manifest.ts | 6 +- packages/schema/src/filesystem-v1.ts | 1 + packages/schema/src/filesystem-watcher.ts | 13 -- packages/schema/src/filesystem.ts | 11 +- packages/schema/src/index.ts | 1 + packages/schema/src/v1/filesystem.ts | 11 + packages/schema/test/event-manifest.test.ts | 6 +- packages/sdk/js/src/v2/gen/types.gen.ts | 143 +++++++----- 48 files changed, 612 insertions(+), 526 deletions(-) delete mode 100644 packages/core/src/config/experimental.ts create mode 100644 packages/core/src/filesystem/location-watcher.ts delete mode 100644 packages/core/src/policy.ts delete mode 100644 packages/core/test/policy.test.ts create mode 100644 packages/plugin/src/v2/promise/event.ts create mode 100644 packages/schema/src/config.ts create mode 100644 packages/schema/src/filesystem-v1.ts delete mode 100644 packages/schema/src/filesystem-watcher.ts create mode 100644 packages/schema/src/v1/filesystem.ts diff --git a/packages/app/src/context/file/watcher.test.ts b/packages/app/src/context/file/watcher.test.ts index 9536b52536..dbe745ff7d 100644 --- a/packages/app/src/context/file/watcher.test.ts +++ b/packages/app/src/context/file/watcher.test.ts @@ -7,7 +7,7 @@ describe("file watcher invalidation", () => { const refresh: string[] = [] invalidateFromWatcher( { - type: "file.watcher.updated", + type: "filesystem.changed", properties: { file: "src/new.ts", event: "add", @@ -32,7 +32,7 @@ describe("file watcher invalidation", () => { invalidateFromWatcher( { - type: "file.watcher.updated", + type: "filesystem.changed", properties: { file: "src/open.ts", event: "change", @@ -63,7 +63,7 @@ describe("file watcher invalidation", () => { invalidateFromWatcher( { - type: "file.watcher.updated", + type: "filesystem.changed", properties: { file: "src", event: "change", @@ -81,7 +81,7 @@ describe("file watcher invalidation", () => { invalidateFromWatcher( { - type: "file.watcher.updated", + type: "filesystem.changed", properties: { file: "src/file.ts", event: "change", @@ -111,7 +111,7 @@ describe("file watcher invalidation", () => { invalidateFromWatcher( { - type: "file.watcher.updated", + type: "filesystem.changed", properties: { file: ".git/index.lock", event: "change", diff --git a/packages/app/src/context/file/watcher.ts b/packages/app/src/context/file/watcher.ts index fbf7199279..1dcaeffd25 100644 --- a/packages/app/src/context/file/watcher.ts +++ b/packages/app/src/context/file/watcher.ts @@ -16,7 +16,7 @@ type WatcherOps = { } export function invalidateFromWatcher(event: WatcherEvent, ops: WatcherOps) { - if (event.type !== "file.watcher.updated") return + if (event.type !== "filesystem.changed") return const props = typeof event.properties === "object" && event.properties ? (event.properties as Record) : undefined const rawPath = typeof props?.file === "string" ? props.file : undefined diff --git a/packages/app/src/pages/session.tsx b/packages/app/src/pages/session.tsx index 36be14546b..25b2459954 100644 --- a/packages/app/src/pages/session.tsx +++ b/packages/app/src/pages/session.tsx @@ -820,7 +820,7 @@ export default function Page() { ) const stopVcs = sdk().event.listen((evt) => { - if (evt.details.type !== "file.watcher.updated") return + if (evt.details.type !== "filesystem.changed") return const props = typeof evt.details.properties === "object" && evt.details.properties ? (evt.details.properties as Record) diff --git a/packages/client/src/effect/index.ts b/packages/client/src/effect/index.ts index 50b85da627..8cde84695c 100644 --- a/packages/client/src/effect/index.ts +++ b/packages/client/src/effect/index.ts @@ -8,6 +8,7 @@ export type { AppApi, CatalogApi, CommandApi, + EventApi, IntegrationApi, ModelApi, PluginApi, diff --git a/packages/client/src/promise/api.ts b/packages/client/src/promise/api.ts index a080156942..e7d1c27d25 100644 --- a/packages/client/src/promise/api.ts +++ b/packages/client/src/promise/api.ts @@ -1,6 +1,7 @@ import type { AgentApi as EffectAgentApi, CommandApi as EffectCommandApi, + EventApi as EffectEventApi, IntegrationApi as EffectIntegrationApi, ModelApi as EffectModelApi, PluginApi as EffectPluginApi, @@ -25,6 +26,7 @@ type PromisifyApi = { export type AgentApi = PromisifyApi> export type CommandApi = PromisifyApi> +export type EventApi = PromisifyApi> export type IntegrationApi = PromisifyApi> export type ModelApi = PromisifyApi> export type PluginApi = PromisifyApi> diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index e0372cd57e..ff06963036 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -4923,9 +4923,9 @@ export type EventSubscribeOutput = readonly id: string readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "file.edited" + readonly type: "filesystem.changed" readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly file: string } + readonly data: { readonly file: string; readonly event: "add" | "change" | "unlink" } } | { readonly id: string @@ -4991,7 +4991,7 @@ export type EventSubscribeOutput = readonly id: string readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "skill.updated" + readonly type: "config.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: {} } @@ -4999,9 +4999,9 @@ export type EventSubscribeOutput = readonly id: string readonly created: number readonly metadata?: { readonly [x: string]: unknown } - readonly type: "file.watcher.updated" + readonly type: "skill.updated" readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly file: string; readonly event: "add" | "change" | "unlink" } + readonly data: {} } | { readonly id: string diff --git a/packages/client/src/promise/index.ts b/packages/client/src/promise/index.ts index 9203fe5477..fd889c64e5 100644 --- a/packages/client/src/promise/index.ts +++ b/packages/client/src/promise/index.ts @@ -3,6 +3,7 @@ export type { AgentApi, CatalogApi, CommandApi, + EventApi, IntegrationApi, ModelApi, PluginApi, diff --git a/packages/core/src/catalog.ts b/packages/core/src/catalog.ts index 78688ce12c..ab34db8ea4 100644 --- a/packages/core/src/catalog.ts +++ b/packages/core/src/catalog.ts @@ -1,12 +1,11 @@ export * as Catalog from "./catalog" import { makeLocationNode } from "./effect/app-node" -import { Array, Context, Effect, Layer, Option, Order, pipe, Schema } from "effect" +import { Array, Context, Effect, Layer, Option, Order, pipe } from "effect" import { Catalog } from "@opencode-ai/schema/catalog" import { ModelV2 } from "./model" import { ProviderV2 } from "./provider" import { EventV2 } from "./event" -import { Policy } from "./policy" import { State } from "./state" import { Integration } from "./integration" @@ -17,8 +16,6 @@ export type ProviderRecord = { export type DefaultModel = { providerID: ProviderV2.ID; modelID: ModelV2.ID } -export const PolicyActions = Schema.Literals(["provider.use"]) - export const Event = Catalog.Event type Data = { @@ -65,7 +62,6 @@ const layer = Layer.effect( Service, Effect.gen(function* () { const events = yield* EventV2.Service - const policy = yield* Policy.Service const integrations = yield* Integration.Service const available = (provider: ProviderV2.Info, integration: Integration.Info | undefined) => { @@ -159,13 +155,6 @@ const layer = Layer.effect( return result }, finalize: Effect.fn("CatalogV2.finalize")(function* (catalog) { - if (policy.hasStatements()) { - for (const record of [...catalog.provider.list()]) { - if ((yield* policy.evaluate("provider.use", record.provider.id, "allow")) === "deny") { - catalog.provider.remove(record.provider.id) - } - } - } yield* events.publish(Event.Updated, {}) }), }) @@ -294,4 +283,4 @@ const layer = Layer.effect( const SMALL_MODEL_RE = /\b(nano|flash|lite|mini|haiku|small|fast)\b/ -export const node = makeLocationNode({ service: Service, layer, deps: [EventV2.node, Policy.node, Integration.node] }) +export const node = makeLocationNode({ service: Service, layer, deps: [EventV2.node, Integration.node] }) diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 9d03d09c38..9e829fb740 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -3,18 +3,19 @@ export * as Config from "./config" import { makeLocationNode } from "./effect/app-node" import path from "path" import { type ParseError, parse } from "jsonc-parser" -import { Context, Effect, Layer, Option, Schema } from "effect" +import { Context, Effect, Fiber, Layer, Option, PubSub, Schema, Stream } from "effect" import { Permission } from "@opencode-ai/schema/permission" +import { Config as ConfigSchema } from "@opencode-ai/schema/config" +import { EventV2 } from "./event" +import { Watcher } from "./filesystem/watcher" import { FSUtil } from "./fs-util" import { Global } from "./global" import { Location } from "./location" -import { Policy } from "./policy" import { AbsolutePath } from "./schema" import { ConfigAgent } from "./config/agent" import { ConfigAttachments } from "./config/attachments" import { ConfigCompaction } from "./config/compaction" import { ConfigCommand } from "./config/command" -import { ConfigExperimental } from "./config/experimental" import { ConfigFormatter } from "./config/formatter" import { ConfigLSP } from "./config/lsp" import { ConfigMCP } from "./config/mcp" @@ -102,7 +103,6 @@ export class Info extends Schema.Class("Config.Info")({ plugins: ConfigPlugin.Plugins.pipe(Schema.optional).annotate({ description: "Ordered external plugin packages to load", }), - experimental: ConfigExperimental.Experimental.pipe(Schema.optional), providers: Schema.Record(Schema.String, ConfigProvider.Info).pipe(Schema.optional), }) {} @@ -138,7 +138,8 @@ const layer = Layer.effect( const fs = yield* FSUtil.Service const global = yield* Global.Service const location = yield* Location.Service - const policy = yield* Policy.Service + const watcher = yield* Watcher.Service + const events = yield* EventV2.Service const names = ["opencode.json", "opencode.jsonc"] const decodeOptions = { errors: "all", onExcessProperty: "ignore", propertyOrder: "original" } as const const decodeInfo = Schema.decodeUnknownOption(Info, decodeOptions) @@ -170,45 +171,78 @@ const layer = Layer.effect( ] }) - const globalDirectory = AbsolutePath.make(global.config) - const locationIsGlobal = path.resolve(location.directory) === path.resolve(global.config) - // Read configuration once when this location opens. Later calls reuse these - // values until the location is reopened. - const discovered = locationIsGlobal - ? [] - : yield* fs - .up({ - targets: [".opencode", ...names.toReversed()], - start: location.directory, - stop: location.project.directory, - }) - .pipe(Effect.orDie) - const directories = [ - globalDirectory, - ...discovered - .filter((item) => path.basename(item) === ".opencode") - .toReversed() - .map((directory) => AbsolutePath.make(directory)), + const discover = Effect.fn("Config.discover")(function* () { + const globalDirectory = AbsolutePath.make(global.config) + const locationIsGlobal = path.resolve(location.directory) === path.resolve(global.config) + const discovered = locationIsGlobal + ? [] + : yield* fs + .up({ + targets: [".opencode", ...names.toReversed()], + start: location.directory, + stop: location.project.directory, + }) + .pipe(Effect.orDie) + const directories = [ + globalDirectory, + ...discovered + .filter((item) => path.basename(item) === ".opencode") + .toReversed() + .map((directory) => AbsolutePath.make(directory)), + ] + const directPaths = discovered.filter((item) => path.basename(item) !== ".opencode").toReversed() + const direct = yield* Effect.forEach(directPaths, loadFile).pipe( + Effect.orDie, + Effect.map((configs) => configs.filter((config): config is Document => config !== undefined)), + ) + const supplementary = yield* Effect.forEach(directories, loadDirectory).pipe(Effect.orDie) + return { + entries: [...(supplementary[0] ?? []), ...direct, ...supplementary.slice(1).flat()], + directories, + files: directPaths, + } + }) + + const initial = yield* discover() + let configs = initial.entries + const updates = yield* PubSub.unbounded() + const subscriptions = new Map>() + const targets = (snapshot: typeof initial) => [ + ...snapshot.directories.map((path) => ({ path, type: "directory" as const })), + ...snapshot.files + .filter((file) => !snapshot.directories.some((directory) => FSUtil.contains(directory, file))) + .map((path) => ({ path, type: "file" as const })), ] - // A config closer to the opened directory should win over one higher up. - // Search starts nearby, so reverse the results before applying them. - const directPaths = discovered.filter((item) => path.basename(item) !== ".opencode").toReversed() - const direct = yield* Effect.forEach(directPaths, loadFile).pipe( - Effect.orDie, - Effect.map((configs) => configs.filter((config): config is Document => config !== undefined)), - ) - const supplementary = yield* Effect.forEach(directories, loadDirectory).pipe(Effect.orDie) - // Apply general settings first and more specific settings last: - // global config, project files, then `.opencode` files. - const configs = [...(supplementary[0] ?? []), ...direct, ...supplementary.slice(1).flat()] - // Rules use the opposite order so a user-global rule can override a - // repository rule. Statement order inside each file stays unchanged. - yield* policy.load( - configs - .filter((config): config is Document => config.type === "document") - .toReversed() - .flatMap((config) => config.info.experimental?.policies ?? []), + const reconcile = Effect.fn("Config.reconcileWatches")(function* (snapshot: typeof initial) { + const next = new Map(targets(snapshot).map((target) => [JSON.stringify(target), target])) + for (const [key, stop] of subscriptions) { + if (next.has(key)) continue + yield* stop + subscriptions.delete(key) + } + for (const [key, target] of next) { + if (subscriptions.has(key)) continue + const fiber = yield* watcher.subscribe(target).pipe( + Stream.runForEach((update) => PubSub.publish(updates, update)), + Effect.forkScoped({ startImmediately: true }), + ) + subscriptions.set(key, Fiber.interrupt(fiber)) + } + }) + + yield* Stream.fromPubSub(updates).pipe( + Stream.debounce("100 millis"), + Stream.runForEach((update) => + Effect.gen(function* () { + const next = yield* discover() + configs = next.entries + yield* reconcile(next) + yield* events.publish(ConfigSchema.Event.Updated, {}) + }).pipe(Effect.catchCause((cause) => Effect.logError("failed to reload config", { path: update.path, cause }))), + ), + Effect.forkScoped({ startImmediately: true }), ) + yield* reconcile(initial) return Service.of({ entries: Effect.fn("Config.entries")(function* () { @@ -221,5 +255,5 @@ const layer = Layer.effect( export const node = makeLocationNode({ service: Service, layer, - deps: [FSUtil.node, Global.node, Location.node, Policy.node], + deps: [Watcher.node, EventV2.node, FSUtil.node, Global.node, Location.node], }) diff --git a/packages/core/src/config/experimental.ts b/packages/core/src/config/experimental.ts deleted file mode 100644 index 8b38a225b4..0000000000 --- a/packages/core/src/config/experimental.ts +++ /dev/null @@ -1,20 +0,0 @@ -export * as ConfigExperimental from "./experimental" - -import { Schema } from "effect" -import { Catalog } from "../catalog" -import { Policy } from "../policy" - -// Each core domain exports the policy actions it supports. Adding an action to -// this union makes it valid in authored config while keeping Policy generic. -export const PolicyAction = Schema.Union([Catalog.PolicyActions]) - -class PolicyConfig extends Schema.Class("ConfigV2.Experimental.Policy")({ - ...Policy.Info.fields, - action: PolicyAction, -}) {} - -export { PolicyConfig as Policy } - -export class Experimental extends Schema.Class("ConfigV2.Experimental")({ - policies: PolicyConfig.pipe(Schema.Array, Schema.optional), -}) {} diff --git a/packages/core/src/config/plugin/command.ts b/packages/core/src/config/plugin/command.ts index bb7a030cbb..43ba4cd375 100644 --- a/packages/core/src/config/plugin/command.ts +++ b/packages/core/src/config/plugin/command.ts @@ -2,7 +2,7 @@ export * as ConfigCommandPlugin from "./command" import { define } from "../../plugin/internal" import path from "path" -import { Effect, Option, Schema } from "effect" +import { Effect, Option, Schema, Stream } from "effect" import { CommandV2 } from "../../command" import { Config } from "../../config" import { FSUtil } from "../../fs-util" @@ -17,16 +17,19 @@ export const Plugin = define({ effect: Effect.fn(function* (ctx) { const config = yield* Config.Service const fs = yield* FSUtil.Service - const documents = yield* Effect.forEach(yield* config.entries(), (entry) => { - if (entry.type === "document") return Effect.succeed([{ commands: entry.info.commands }]) - return loadDirectory(fs, entry.path).pipe( - Effect.map((commands) => [ - { commands: Object.fromEntries(commands.map((command) => [command.name, command.info])) }, - ]), - ) - }).pipe(Effect.map((documents) => documents.flat())) + const load = Effect.fn("ConfigCommandPlugin.load")(function* () { + return yield* Effect.forEach(yield* config.entries(), (entry) => { + if (entry.type === "document") return Effect.succeed([{ commands: entry.info.commands }]) + return loadDirectory(fs, entry.path).pipe( + Effect.map((commands) => [ + { commands: Object.fromEntries(commands.map((command) => [command.name, command.info])) }, + ]), + ) + }).pipe(Effect.map((documents) => documents.flat())) + }) + const loaded = { documents: yield* load() } yield* ctx.command.transform((draft) => { - for (const document of documents) { + for (const document of loaded.documents) { for (const [name, command] of Object.entries(document.commands ?? {})) { draft.update(name, (item) => { item.template = command.template @@ -44,6 +47,16 @@ export const Plugin = define({ } } }) + yield* ctx.event.subscribe().pipe( + Stream.filter((event) => event.type === "config.updated"), + Stream.runForEach(() => + load().pipe( + Effect.tap((documents) => Effect.sync(() => (loaded.documents = documents))), + Effect.andThen(ctx.command.reload()), + ), + ), + Effect.forkScoped({ startImmediately: true }), + ) }), }) diff --git a/packages/core/src/filesystem/location-watcher.ts b/packages/core/src/filesystem/location-watcher.ts new file mode 100644 index 0000000000..1566d3d8ff --- /dev/null +++ b/packages/core/src/filesystem/location-watcher.ts @@ -0,0 +1,83 @@ +export * as LocationWatcher from "./location-watcher" + +import { makeLocationNode } from "../effect/app-node" +import { Context, Effect, Layer, Stream } from "effect" +import { FileSystem } from "@opencode-ai/schema/filesystem" +import os from "os" +import path from "path" +import { Config } from "../config" +import { EventV2 } from "../event" +import { FSUtil } from "../fs-util" +import { Git } from "../git" +import { Location } from "../location" +import { Watcher } from "./watcher" +import { Ignore } from "./ignore" +import { Protected } from "./protected" + +function protecteds(dir: string) { + return Protected.paths().filter((item) => { + const relative = path.relative(dir, item) + return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative) + }) +} + +export interface Interface {} + +export class Service extends Context.Service()("@opencode/LocationWatcher") {} + +const layer = Layer.effect( + Service, + Effect.gen(function* () { + const location = yield* Location.Service + const watcher = yield* Watcher.Service + const events = yield* EventV2.Service + const fs = yield* FSUtil.Service + const git = yield* Git.Service + const configService = yield* Config.Service + const config = (yield* configService.entries()) + .filter((entry): entry is Config.Document => entry.type === "document") + .flatMap((item) => item.info.watcher?.ignore ?? []) + const publish = (update: { type: "create" | "update" | "delete"; path: string }) => + events.publish(FileSystem.Event.Changed, { + file: update.path, + event: update.type === "create" ? "add" : update.type === "update" ? "change" : "unlink", + }) + + if (path.resolve(location.directory) !== path.resolve(os.homedir())) { + yield* watcher + .subscribe({ + path: location.directory, + type: "directory", + ignore: [...Ignore.PATTERNS, ...config, ...protecteds(location.directory)], + }) + .pipe(Stream.runForEach(publish), Effect.forkScoped({ startImmediately: true })) + } else { + yield* Effect.logInfo("location watcher skipped home directory", { directory: location.directory }) + } + + if (location.vcs?.type === "git") { + const resolved = (yield* git.repo.discover(location.directory))?.gitDirectory + const vcs = resolved ? yield* fs.realPath(resolved).pipe(Effect.catch(() => Effect.succeed(resolved))) : undefined + if (vcs && !config.includes(".git") && !config.includes(vcs) && (!resolved || !config.includes(resolved))) { + const ignore = (yield* fs.readDirectoryEntries(vcs).pipe(Effect.catch(() => Effect.succeed([])))).flatMap( + (entry) => (entry.name === "HEAD" ? [] : [entry.name]), + ) + yield* watcher + .subscribe({ path: vcs, type: "directory", ignore }) + .pipe(Stream.runForEach(publish), Effect.forkScoped({ startImmediately: true })) + } + } + + return Service.of({}) + }).pipe( + Effect.catchCause((cause) => + Effect.logError("failed to init location watcher service", { cause }).pipe(Effect.as(Service.of({}))), + ), + ), +) + +export const node = makeLocationNode({ + service: Service, + layer, + deps: [Watcher.node, FSUtil.node, Location.node, Config.node, Git.node, EventV2.node], +}) diff --git a/packages/core/src/filesystem/watcher.ts b/packages/core/src/filesystem/watcher.ts index 1efc9d6907..2febe93b76 100644 --- a/packages/core/src/filesystem/watcher.ts +++ b/packages/core/src/filesystem/watcher.ts @@ -3,26 +3,20 @@ export * as Watcher from "./watcher" // @ts-ignore import { createWrapper } from "@parcel/watcher/wrapper" import type ParcelWatcher from "@parcel/watcher" -import { makeLocationNode } from "../effect/app-node" -import { Cause, Context, Effect, Layer } from "effect" -import { FileSystemWatcher } from "@opencode-ai/schema/filesystem-watcher" -import os from "os" -import path from "path" -import { Config } from "../config" -import { EventV2 } from "../event" +import { FileSystem } from "@opencode-ai/schema/filesystem" +import { makeGlobalNode } from "../effect/app-node" +import { Cause, Context, Effect, Layer, PubSub, Scope, Stream } from "effect" +import { KeyedMutex } from "../effect/keyed-mutex" import { Flag } from "../flag/flag" -import { FSUtil } from "../fs-util" -import { Git } from "../git" -import { Location } from "../location" import { lazy } from "../util/lazy" -import { Ignore } from "./ignore" -import { Protected } from "./protected" +import { watch as watchFileSystem } from "node:fs" +import path from "path" declare const OPENCODE_LIBC: string | undefined const SUBSCRIBE_TIMEOUT_MS = 10_000 -export const Event = FileSystemWatcher.Event +export const Event = { Updated: FileSystem.Event.Changed } const watcher = lazy((): typeof import("@parcel/watcher") | undefined => { try { @@ -42,108 +36,132 @@ function getBackend() { if (process.platform === "linux") return "inotify" } -function protecteds(dir: string) { - return Protected.paths().filter((item) => { - const relative = path.relative(dir, item) - return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative) - }) +export const hasNativeBinding = () => !!watcher() +export type Update = ParcelWatcher.Event + +export type WatchInput = + | { readonly path: string; readonly type: "file" } + | { readonly path: string; readonly type: "directory"; readonly ignore?: readonly string[] } + +export interface Interface { + readonly subscribe: (input: WatchInput) => Stream.Stream } -export const hasNativeBinding = () => !!watcher() - -export interface Interface {} - -export class Service extends Context.Service()("@opencode/v2/FileWatcher") {} +export class Service extends Context.Service()("@opencode/Watcher") {} const layer = Layer.effect( Service, Effect.gen(function* () { - if (Flag.OPENCODE_DISABLE_FILEWATCHER) return Service.of({}) - const backend = getBackend() - const location = yield* Location.Service - if (path.resolve(location.directory) === path.resolve(os.homedir())) { - yield* Effect.logInfo("watcher skipped home directory", { directory: location.directory }) - return Service.of({}) - } - if (!backend) { - yield* Effect.logError("watcher backend not supported", { - directory: location.directory, - platform: process.platform, - }) - return Service.of({}) + const native = watcher() + if (Flag.OPENCODE_DISABLE_FILEWATCHER) { + return Service.of({ subscribe: () => Stream.empty }) } - const w = watcher() - if (!w) return Service.of({}) - - yield* Effect.logInfo("watcher backend", { directory: location.directory, platform: process.platform, backend }) - const events = yield* EventV2.Service - const fs = yield* FSUtil.Service - const git = yield* Git.Service - const context = yield* Effect.context() - const runFork = Effect.runForkWith(context) - const subscriptions: ParcelWatcher.AsyncSubscription[] = [] - yield* Effect.addFinalizer(() => - Effect.promise(() => Promise.allSettled(subscriptions.map((subscription) => subscription.unsubscribe()))), - ) - - const callback: ParcelWatcher.SubscribeCallback = (_error, updates) => { - if (_error) runFork(Effect.logError("watcher callback failed", { error: _error })) - for (const update of updates) { - if (update.type === "create") runFork(events.publish(Event.Updated, { file: update.path, event: "add" })) - if (update.type === "update") runFork(events.publish(Event.Updated, { file: update.path, event: "change" })) - if (update.type === "delete") runFork(events.publish(Event.Updated, { file: update.path, event: "unlink" })) - } + type Entry = { + readonly pubsub: PubSub.PubSub + readonly subscription: { readonly unsubscribe: () => Promise } + refs: number } + const entries = new Map() + const locks = KeyedMutex.makeUnsafe() - const subscribe = (directory: string, ignore: string[]) => { - const pending = w.subscribe(directory, callback, { ignore, backend }) - return Effect.promise(() => pending).pipe( - Effect.tap((subscription) => - Effect.sync(() => subscriptions.push(subscription)).pipe( - Effect.andThen(Effect.logInfo("watcher subscribed", { directory, backend, ignores: ignore.length })), - ), - ), - Effect.timeout(SUBSCRIBE_TIMEOUT_MS), - Effect.catchCause((cause) => { - pending.then((subscription) => subscription.unsubscribe()).catch(() => {}) - return Effect.logError("failed to subscribe", { directory, cause: Cause.pretty(cause) }) + const acquire = Effect.fn("Watcher.acquire")(function* (input: WatchInput) { + const scope = yield* Scope.Scope + const target = path.resolve(input.path) + const directory = input.type === "file" ? path.dirname(target) : target + const ignore = [...new Set(input.type === "directory" ? (input.ignore ?? []) : [])].toSorted() + const id = JSON.stringify([input.type, target, ignore]) + const pubsub = yield* locks.withLock(id)( + Effect.gen(function* () { + const existing = entries.get(id) + if (existing) { + existing.refs++ + return existing.pubsub + } + const pubsub = yield* PubSub.unbounded() + const subscription = yield* input.type === "file" + ? Effect.sync(() => { + const subscription = watchFileSystem(directory, { recursive: false }, (_event, file) => { + if (file && path.resolve(directory, file.toString()) !== target) return + PubSub.publishUnsafe(pubsub, { + path: target, + type: "update", + } satisfies Update) + }) + subscription.on("error", (error) => + Effect.runFork(Effect.logError("watcher callback failed", { path: target, error })), + ) + return { unsubscribe: () => Promise.resolve(subscription.close()) } + }) + : subscribeDirectory(native, backend, directory, ignore, pubsub) + if (subscription) { + entries.set(id, { pubsub, subscription, refs: 1 }) + yield* Effect.logInfo("watcher started", { + path: target, + type: input.type, + backend: input.type === "file" ? "node" : backend, + ignores: ignore.length, + }) + return pubsub + } + yield* PubSub.shutdown(pubsub) + return pubsub }), ) - } - const configService = yield* Config.Service - const config = (yield* configService.entries()) - .filter((entry): entry is Config.Document => entry.type === "document") - .flatMap((item) => item.info.watcher?.ignore ?? []) - yield* Effect.forkScoped( - subscribe(location.directory, [...Ignore.PATTERNS, ...config, ...protecteds(location.directory)]), - ) - - if (location.vcs?.type === "git") { - const resolved = (yield* git.repo.discover(location.directory))?.gitDirectory - const vcs = resolved ? yield* fs.realPath(resolved).pipe(Effect.catch(() => Effect.succeed(resolved))) : undefined - if (vcs && !config.includes(".git") && !config.includes(vcs) && (!resolved || !config.includes(resolved))) { - const ignore = (yield* fs.readDirectoryEntries(vcs).pipe(Effect.catch(() => Effect.succeed([])))).flatMap( - (entry) => (entry.name === "HEAD" ? [] : [entry.name]), - ) - yield* Effect.forkScoped(subscribe(vcs, ignore)) - } - } - - return Service.of({}) - }).pipe( - Effect.catchCause((cause) => { - return Effect.logError("failed to init watcher service", { cause: Cause.pretty(cause) }).pipe( - Effect.as(Service.of({})), + yield* Scope.addFinalizer( + scope, + locks.withLock(id)( + Effect.gen(function* () { + const entry = entries.get(id) + if (!entry) return + entry.refs-- + if (entry.refs > 0) return + entries.delete(id) + yield* Effect.promise(() => entry.subscription.unsubscribe()).pipe(Effect.ignore) + yield* PubSub.shutdown(entry.pubsub) + yield* Effect.logInfo("watcher stopped", { path: target, type: input.type }) + }), + ), ) - }), - ), + return pubsub + }) + + const subscribe = (input: WatchInput) => + Stream.unwrap(acquire(input).pipe(Effect.map((pubsub) => Stream.fromPubSub(pubsub)))) + + return Service.of({ subscribe }) + }), ) -export const node = makeLocationNode({ - service: Service, - layer, - deps: [FSUtil.node, Location.node, Config.node, Git.node, EventV2.node], -}) +export const node = makeGlobalNode({ service: Service, layer, deps: [] }) + +function subscribeDirectory( + native: typeof import("@parcel/watcher") | undefined, + backend: ParcelWatcher.BackendType | undefined, + directory: string, + ignore: string[], + pubsub: PubSub.PubSub, +) { + if (!native || !backend) { + return Effect.logError("watcher backend not supported", { directory, platform: process.platform }).pipe( + Effect.as(undefined), + ) + } + const callback: ParcelWatcher.SubscribeCallback = (error, updates) => { + if (error) Effect.runFork(Effect.logError("watcher callback failed", { error })) + for (const update of updates) PubSub.publishUnsafe(pubsub, update) + } + const pending = native.subscribe(directory, callback, { ignore, backend }) + return Effect.promise(() => pending).pipe( + Effect.timeout(SUBSCRIBE_TIMEOUT_MS), + Effect.catchCause((cause) => { + pending.then((subscription) => subscription.unsubscribe()).catch(() => {}) + return Effect.logError("failed to subscribe", { + directory, + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)) + }), + ) +} diff --git a/packages/core/src/location-services.ts b/packages/core/src/location-services.ts index f0f2d63e7f..2a4e0d6ef6 100644 --- a/packages/core/src/location-services.ts +++ b/packages/core/src/location-services.ts @@ -11,7 +11,7 @@ import { FileSystem } from "./filesystem" import { FileSystemSearch } from "./filesystem/search" import { Generate } from "./generate" import { Form } from "./form" -import { Watcher } from "./filesystem/watcher" +import { LocationWatcher } from "./filesystem/location-watcher" import { Image } from "./image" import { Integration } from "./integration" import { Location } from "./location" @@ -21,7 +21,6 @@ import { MCP } from "./mcp/index" import { PermissionV2 } from "./permission" import { PluginV2 } from "./plugin" import { PluginInternal } from "./plugin/internal" -import { Policy } from "./policy" import { ProjectCopy } from "./project/copy" import { Pty } from "./pty" import { QuestionV2 } from "./question" @@ -50,7 +49,6 @@ export { LocationServiceMap } from "./location-service-map" const locationServiceNodes = [ Location.node, - Policy.node, Config.node, AgentV2.node, CommandV2.node, @@ -64,7 +62,7 @@ const locationServiceNodes = [ ProjectCopy.refreshNode, FileSystemSearch.node, FileSystem.node, - Watcher.node, + LocationWatcher.node, Pty.node, Shell.node, SkillV2.node, diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index bf3420a023..d25555eb37 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -1,12 +1,14 @@ export * as PluginHost from "./host" import type { PluginContext } from "@opencode-ai/plugin/v2/effect" -import { Effect, Schema } from "effect" +import { EventManifest } from "@opencode-ai/schema/event-manifest" +import { Effect, Schema, Stream } from "effect" import { AgentV2 } from "../agent" import { AISDK } from "../aisdk" import { Catalog } from "../catalog" import { CommandV2 } from "../command" import { Credential } from "../credential" +import { EventV2 } from "../event" import { Integration } from "../integration" import { Location } from "../location" import { ModelV2 } from "../model" @@ -21,12 +23,14 @@ import { ToolHooks } from "../tool/hooks" import { WorkspaceV2 } from "../workspace" const mutable = (value: T) => value as DeepMutable +const isEvent = Schema.is(Schema.Union(EventManifest.ServerDefinitions)) export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Interface) { const agents = yield* AgentV2.Service const aisdk = yield* AISDK.Service const catalog = yield* Catalog.Service const commands = yield* CommandV2.Service + const events = yield* EventV2.Service const integration = yield* Integration.Service const location = yield* Location.Service const reference = yield* Reference.Service @@ -155,6 +159,9 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Int callback(draft) }), }, + event: { + subscribe: () => events.live().pipe(Stream.filter(isEvent)), + }, integration: { list: () => response(integration.list()), get: (input) => response(integration.get(Integration.ID.make(input.integrationID))), diff --git a/packages/core/src/plugin/promise.ts b/packages/core/src/plugin/promise.ts index 956c530176..b315d3214a 100644 --- a/packages/core/src/plugin/promise.ts +++ b/packages/core/src/plugin/promise.ts @@ -2,7 +2,7 @@ export * as PluginPromise from "./promise" import { define } from "@opencode-ai/plugin/v2/effect" import type { Plugin, PluginContext } from "@opencode-ai/plugin/v2/promise" -import { Effect, Scope } from "effect" +import { Effect, Scope, Stream } from "effect" type HostRegistration = { readonly dispose: Effect.Effect } type Registration = { readonly dispose: () => Promise } @@ -73,6 +73,9 @@ export function fromPromise(plugin: Plugin) { transform: transform(host.command), reload: () => run(host.command.reload()), }, + event: { + subscribe: () => Stream.toAsyncIterable(host.event.subscribe()), + }, integration: { list: (input) => run(host.integration.list(input)), get: (input) => run(host.integration.get(input)), diff --git a/packages/core/src/policy.ts b/packages/core/src/policy.ts deleted file mode 100644 index d1dbb3e37c..0000000000 --- a/packages/core/src/policy.ts +++ /dev/null @@ -1,48 +0,0 @@ -export * as Policy from "./policy" - -import { makeLocationNode } from "./effect/app-node" -import { Context, Effect, Layer, Schema } from "effect" -import { Wildcard } from "./util/wildcard" -import { Location } from "./location" - -const PolicyEffect = Schema.Literals(["allow", "deny"]).annotate({ identifier: "Policy.Effect" }) -export { PolicyEffect as Effect } -export type Effect = typeof PolicyEffect.Type - -export class Info extends Schema.Class("Policy.Info")({ - action: Schema.String, - effect: PolicyEffect, - resource: Schema.String, -}) {} - -export interface Interface { - readonly load: (statements: Info[]) => Effect.Effect - readonly evaluate: (action: string, resource: string, fallback: Effect) => Effect.Effect - readonly hasStatements: () => boolean -} - -export class Service extends Context.Service()("@opencode/v2/Policy") {} - -const layer = Layer.effect( - Service, - Effect.gen(function* () { - let statements: Info[] = [] - yield* Location.Service - - return Service.of({ - load: Effect.fn("Policy.load")(function* (input) { - statements = input - }), - hasStatements: () => statements.length > 0, - evaluate: Effect.fn("Policy.evaluate")(function* (action, resource, fallback) { - return ( - statements.findLast( - (statement) => Wildcard.match(action, statement.action) && Wildcard.match(resource, statement.resource), - )?.effect ?? fallback - ) - }), - }) - }), -) - -export const node = makeLocationNode({ service: Service, layer, deps: [Location.node] }) diff --git a/packages/core/src/skill.ts b/packages/core/src/skill.ts index c448eae549..511e02af87 100644 --- a/packages/core/src/skill.ts +++ b/packages/core/src/skill.ts @@ -3,7 +3,7 @@ export * as SkillV2 from "./skill" import { makeLocationNode } from "./effect/app-node" import path from "path" import { Context, Effect, Layer, Schema, Stream, Types } from "effect" -import { FileSystemWatcher } from "@opencode-ai/schema/filesystem-watcher" +import { FileSystem } from "@opencode-ai/schema/filesystem" import { Skill } from "@opencode-ai/schema/skill" import { AgentV2 } from "./agent" import { ConfigMarkdown } from "./config/markdown" @@ -153,7 +153,7 @@ const layer = Layer.effect( yield* events.publish(Event.Updated, {}).pipe(Effect.asVoid) }) - yield* events.subscribe(FileSystemWatcher.Event.Updated).pipe( + yield* events.subscribe(FileSystem.Event.Changed).pipe( Stream.runForEach((event) => invalidate(event.data.file)), Effect.forkScoped({ startImmediately: true }), ) diff --git a/packages/core/src/v1/config/config.ts b/packages/core/src/v1/config/config.ts index 2e773f71e2..d32af99812 100644 --- a/packages/core/src/v1/config/config.ts +++ b/packages/core/src/v1/config/config.ts @@ -2,7 +2,6 @@ export * as ConfigV1 from "./config" import { Schema } from "effect" import { NonNegativeInt, PositiveInt, type DeepMutable } from "../../schema" -import { ConfigExperimental } from "../../config/experimental" import { ConfigReference } from "../../config/reference" import { ConfigAgentV1 } from "./agent" import { ConfigAttachmentV1 } from "./attachment" @@ -179,9 +178,6 @@ export const Info = Schema.Struct({ mcp_timeout: Schema.optional(PositiveInt).annotate({ description: "Timeout in milliseconds for model context protocol (MCP) requests", }), - policies: Schema.optional(Schema.mutable(Schema.Array(ConfigExperimental.Policy))).annotate({ - description: "Policy statements applied to supported resources, such as provider access", - }), }), ), }).annotate({ identifier: "Config" }) diff --git a/packages/core/src/v1/config/migrate.ts b/packages/core/src/v1/config/migrate.ts index 2a9e1c7383..046f29c431 100644 --- a/packages/core/src/v1/config/migrate.ts +++ b/packages/core/src/v1/config/migrate.ts @@ -78,7 +78,6 @@ export function migrate(info: typeof ConfigV1.Info.Type) { plugins: info.plugin?.map((plugin) => typeof plugin === "string" ? plugin : { package: plugin[0], options: plugin[1] }, ), - experimental: info.experimental?.policies && { policies: info.experimental.policies }, providers: providers(info.provider), } } diff --git a/packages/core/test/catalog.test.ts b/packages/core/test/catalog.test.ts index 6c736cde1e..04bc006888 100644 --- a/packages/core/test/catalog.test.ts +++ b/packages/core/test/catalog.test.ts @@ -8,7 +8,6 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { EventV2 } from "@opencode-ai/core/event" import { Location } from "@opencode-ai/core/location" import { ModelV2 } from "@opencode-ai/core/model" -import { Policy } from "@opencode-ai/core/policy" import { ProviderV2 } from "@opencode-ai/core/provider" import { AbsolutePath } from "@opencode-ai/core/schema" import { location } from "./fixture/location" @@ -24,7 +23,7 @@ const locationLayer = Layer.succeed( Location.Service.of(location({ directory: AbsolutePath.make("test") })), ) const catalogLayer = AppNodeBuilder.build( - LayerNode.group([Catalog.node, EventV2.node, Credential.node, Integration.node, Policy.node]), + LayerNode.group([Catalog.node, EventV2.node, Credential.node, Integration.node]), [[Location.node, locationLayer]], ) const it = testEffect(catalogLayer) @@ -333,21 +332,4 @@ describe("CatalogV2", () => { expect((yield* catalog.model.small(providerID))?.id).toMatch("expensive-mini") }), ) - - it.effect("removes providers denied by policy after loading", () => - Effect.gen(function* () { - const catalog = yield* Catalog.Service - const policy = yield* Policy.Service - const providerID = ProviderV2.ID.make("blocked") - yield* policy.load([new Policy.Info({ effect: "deny", action: "provider.use", resource: "blocked" })]) - yield* catalog.transform((catalog) => { - catalog.provider.update(providerID, () => {}) - catalog.model.update(providerID, ModelV2.ID.make("model"), () => {}) - }) - - expect(yield* catalog.provider.all()).toEqual([]) - expect(yield* catalog.model.all()).toEqual([]) - expect(yield* catalog.provider.get(providerID)).toBeUndefined() - }), - ) }) diff --git a/packages/core/test/config/command.test.ts b/packages/core/test/config/command.test.ts index 6c7f2ecc02..a8126d00f6 100644 --- a/packages/core/test/config/command.test.ts +++ b/packages/core/test/config/command.test.ts @@ -1,13 +1,15 @@ import fs from "fs/promises" import path from "path" import { describe, expect } from "bun:test" -import { Effect, Schema } from "effect" +import { Effect, PubSub, Schema, Stream } from "effect" +import { Config as ConfigSchema } from "@opencode-ai/schema/config" import { CommandV2 } from "@opencode-ai/core/command" import { Config } from "@opencode-ai/core/config" import { ConfigCommandPlugin } from "@opencode-ai/core/config/plugin/command" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { FSUtil } from "@opencode-ai/core/fs-util" +import { EventV2 } from "@opencode-ai/core/event" import { Location } from "@opencode-ai/core/location" import { MCP } from "@opencode-ai/core/mcp/index" import { ModelV2 } from "@opencode-ai/core/model" @@ -19,7 +21,7 @@ import { testEffect } from "../lib/effect" import { host } from "../plugin/host" const it = testEffect( - AppNodeBuilder.build(LayerNode.group([CommandV2.node, FSUtil.node]), [ + AppNodeBuilder.build(LayerNode.group([CommandV2.node, EventV2.node, FSUtil.node]), [ [MCP.node, emptyMcpLayer], [Config.node, emptyConfigLayer], [Location.node, testLocationLayer], @@ -53,6 +55,9 @@ Review files`, }) const command = yield* CommandV2.Service + const events = yield* EventV2.Service + const update = yield* events.publish(ConfigSchema.Event.Updated, {}) + const updates = yield* PubSub.unbounded() yield* ConfigCommandPlugin.Plugin.effect( host({ command: { @@ -60,6 +65,7 @@ Review files`, transform: command.transform, reload: command.reload, }, + event: { subscribe: () => Stream.fromPubSub(updates) }, }), ).pipe( Effect.provideService( @@ -93,6 +99,15 @@ Review files`, CommandV2.Info.make({ name: "empty", template: "" }), CommandV2.Info.make({ name: "nested/docs", template: "Write docs" }), ]) + + yield* Effect.promise(() => fs.writeFile(path.join(tmp.path, "commands", "review.md"), "Review again")) + yield* Effect.sleep("10 millis") + yield* PubSub.publish(updates, update) + for (let attempt = 0; attempt < 100; attempt++) { + if ((yield* command.get("review"))?.template === "Review again") break + yield* Effect.sleep("10 millis") + } + expect((yield* command.get("review"))?.template).toBe("Review again") }), ), ), diff --git a/packages/core/test/config/config.test.ts b/packages/core/test/config/config.test.ts index e46644abae..f3c7b20909 100644 --- a/packages/core/test/config/config.test.ts +++ b/packages/core/test/config/config.test.ts @@ -1,18 +1,20 @@ import path from "path" import fs from "fs/promises" import { describe, expect } from "bun:test" -import { Effect, Layer, Schema } from "effect" +import { Effect, Fiber, Layer, PubSub, Schema, Stream } from "effect" import { FastCheck } from "effect/testing" import { Config } from "@opencode-ai/core/config" +import { Config as ConfigSchema } from "@opencode-ai/schema/config" import { ConfigProvider } from "@opencode-ai/core/config/provider" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { ConfigMigrateV1 } from "@opencode-ai/core/v1/config/migrate" import { ConfigV1 } from "@opencode-ai/core/v1/config/config" import { FSUtil } from "@opencode-ai/core/fs-util" +import { Watcher } from "@opencode-ai/core/filesystem/watcher" +import { EventV2 } from "@opencode-ai/core/event" import { Global } from "@opencode-ai/core/global" import { Location } from "@opencode-ai/core/location" -import { Policy } from "@opencode-ai/core/policy" import { Project } from "@opencode-ai/core/project" import { AbsolutePath } from "@opencode-ai/core/schema" import { location } from "../fixture/location" @@ -26,6 +28,7 @@ function testLayer( globalDirectory = path.join(directory, "global"), projectDirectory = directory, vcs?: Project.Vcs, + watcher?: Layer.Layer, ) { const locationLayer = Layer.succeed( Location.Service, @@ -36,9 +39,10 @@ function testLayer( ), ), ) - return AppNodeBuilder.build(LayerNode.group([Config.node, Policy.node]), [ + return AppNodeBuilder.build(LayerNode.group([Config.node, EventV2.node]), [ [Location.node, locationLayer], [Global.node, Global.layerWith({ config: globalDirectory })], + ...(watcher ? ([[Watcher.node, watcher]] as const) : []), ]) } @@ -52,6 +56,52 @@ const provider = { } describe("Config", () => { + it.live("reloads external config and publishes directory updates", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => + Effect.gen(function* () { + const global = path.join(tmp.path, "global") + const project = path.join(tmp.path, "project") + const file = path.join(global, "opencode.json") + yield* Effect.promise(async () => { + await fs.mkdir(global, { recursive: true }) + await fs.mkdir(project, { recursive: true }) + await fs.writeFile(file, JSON.stringify({ shell: "first" })) + }) + const updates = yield* PubSub.unbounded() + const watcher = Layer.succeed( + Watcher.Service, + Watcher.Service.of({ + subscribe: () => Stream.fromPubSub(updates), + }), + ) + + return yield* Effect.gen(function* () { + const config = yield* Config.Service + const events = yield* EventV2.Service + const changed = yield* events + .subscribe(ConfigSchema.Event.Updated) + .pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) + yield* Effect.sleep("10 millis") + + yield* PubSub.publish(updates, { + type: "update", + path: path.join(global, "commands", "review.md"), + } satisfies Watcher.Update) + yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ shell: "second" }))) + yield* PubSub.publish(updates, { type: "update", path: file } satisfies Watcher.Update) + + expect(yield* Fiber.join(changed)).toHaveLength(1) + expect(Config.latest(yield* config.entries(), "shell")).toBe("second") + }).pipe(Effect.provide(testLayer(project, global, project, undefined, watcher))) + }), + ), + ), + ) + it.effect("returns the latest defined scalar from priority-ordered documents", () => Effect.sync(() => { const entries = [ @@ -274,7 +324,6 @@ describe("Config", () => { const file = path.join(tmp.path, "opencode.json") const contents = JSON.stringify({ shell: "/bin/zsh", - experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] }, providers: { local: provider }, }) yield* Effect.promise(() => fs.writeFile(file, contents)) @@ -285,11 +334,6 @@ describe("Config", () => { expect(documents[0]?.info.$schema).toBeUndefined() expect(documents[0]?.info.shell).toBe("/bin/zsh") - expect(documents[0]?.info.experimental?.policies?.[0]).toEqual({ - effect: "deny", - action: "provider.use", - resource: "openai", - }) expect(yield* Effect.promise(() => fs.readFile(file, "utf8"))).toBe(contents) }).pipe(Effect.provide(testLayer(tmp.path))) }), @@ -723,40 +767,6 @@ describe("Config", () => { ), ) - it.live("loads policy statements in reverse config order", () => - Effect.acquireRelease( - Effect.promise(() => tmpdir()), - (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), - ).pipe( - Effect.flatMap((tmp) => { - const global = path.join(tmp.path, "global") - return Effect.gen(function* () { - yield* Effect.promise(async () => { - await fs.mkdir(global, { recursive: true }) - await fs.writeFile( - path.join(global, "opencode.json"), - JSON.stringify({ - experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] }, - }), - ) - await fs.writeFile( - path.join(tmp.path, "opencode.json"), - JSON.stringify({ - experimental: { policies: [{ effect: "allow", action: "provider.use", resource: "openai" }] }, - }), - ) - }) - - return yield* Effect.gen(function* () { - const policy = yield* Policy.Service - - expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny") - }).pipe(Effect.provide(testLayer(tmp.path, global))) - }) - }), - ), - ) - it.live("loads global, ancestor, and .opencode configuration up to the project boundary", () => Effect.acquireRelease( Effect.promise(() => tmpdir()), diff --git a/packages/core/test/filesystem/watcher.test.ts b/packages/core/test/filesystem/watcher.test.ts index 2139520468..323ba4c4ba 100644 --- a/packages/core/test/filesystem/watcher.test.ts +++ b/packages/core/test/filesystem/watcher.test.ts @@ -8,7 +8,9 @@ import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { EventV2 } from "@opencode-ai/core/event" import { FSUtil } from "@opencode-ai/core/fs-util" +import { LocationWatcher } from "@opencode-ai/core/filesystem/location-watcher" import { Watcher } from "@opencode-ai/core/filesystem/watcher" +import { FileSystem } from "@opencode-ai/schema/filesystem" import { Location } from "@opencode-ai/core/location" import { AbsolutePath } from "@opencode-ai/core/schema" import { location } from "../fixture/location" @@ -34,7 +36,7 @@ function provide(directory: string, vcs?: Location.Interface["vcs"]) { Location.Service.of(location({ directory: AbsolutePath.make(directory) }, { vcs })), ) return Effect.provide( - AppNodeBuilder.build(Watcher.node, [ + AppNodeBuilder.build(LocationWatcher.node, [ [Config.node, configLayer], [Location.node, locationLayer], ]), @@ -66,7 +68,7 @@ function wait(check: (event: WatcherEvent) => boolean) { return Effect.gen(function* () { const events = yield* EventV2.Service const deferred = yield* Deferred.make() - const fiber = yield* events.subscribe(Watcher.Event.Updated).pipe( + const fiber = yield* events.subscribe(FileSystem.Event.Changed).pipe( Stream.runForEach((event) => { if (!check(event.data)) return Effect.void return Deferred.succeed(deferred, event.data).pipe(Effect.asVoid) @@ -136,7 +138,27 @@ function ready(directory: string) { }) } -describeWatcher("Watcher", () => { +describeWatcher("LocationWatcher", () => { + it.live("limits file watches to the exact target", () => + withTmp((directory) => + Effect.gen(function* () { + const fs = yield* FSUtil.Service + const watcher = yield* Watcher.Service + const target = path.join(directory, "opencode.json") + const sibling = path.join(directory, "other.json") + const update = yield* watcher + .subscribe({ path: target, type: "file" }) + .pipe(Stream.take(1), Stream.runHead, Effect.forkScoped({ startImmediately: true })) + yield* Effect.yieldNow + + yield* fs.writeFileString(sibling, "sibling") + yield* fs.writeFileString(target, "target") + + expect((yield* Fiber.join(update)).valueOrUndefined?.path).toBe(target) + }).pipe(Effect.provide(AppNodeBuilder.build(Watcher.node))), + ), + ) + it.live("publishes root create, update, and delete events", () => withTmp( (directory) => diff --git a/packages/core/test/location-layer.test.ts b/packages/core/test/location-layer.test.ts index 77b7207c42..0f17b0dd2b 100644 --- a/packages/core/test/location-layer.test.ts +++ b/packages/core/test/location-layer.test.ts @@ -51,27 +51,18 @@ describe("LocationServiceMap", () => { ), ) - it.live("isolates location state while sharing location policy with catalog", () => + it.live("isolates catalog state by location", () => Effect.acquireRelease( Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), (dirs) => Effect.promise(() => Promise.all(dirs.map((dir) => dir[Symbol.asyncDispose]())).then(() => undefined)), ).pipe( Effect.flatMap(([blocked, allowed]) => Effect.gen(function* () { - yield* Effect.promise(() => - fs.writeFile( - path.join(blocked.path, "opencode.json"), - JSON.stringify({ - experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "test" }] }, - }), - ), - ) - - const update = (directory: string) => + const update = (directory: string, providerID: ProviderV2.ID) => Effect.gen(function* () { yield* Reference.Service const catalog = yield* Catalog.Service - yield* catalog.transform((editor) => editor.provider.update(ProviderV2.ID.make("test"), () => {})) + yield* catalog.transform((editor) => editor.provider.update(providerID, () => {})) const registry = yield* ToolRegistry.Service // Tool plugins register during the forked PluginInternal boot; wait for // every expected tool rather than relying on batch ordering. @@ -103,8 +94,11 @@ describe("LocationServiceMap", () => { ), ) - const blockedState = yield* update(blocked.path) - expect(blockedState.providers.some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe(false) + const blockedID = ProviderV2.ID.make("blocked-location") + const allowedID = ProviderV2.ID.make("allowed-location") + const blockedState = yield* update(blocked.path, blockedID) + expect(blockedState.providers.some((provider) => provider.id === blockedID)).toBe(true) + expect(blockedState.providers.some((provider) => provider.id === allowedID)).toBe(false) expect(blockedState.tools.map((tool) => tool.name).sort()).toEqual([ "edit", "glob", @@ -119,8 +113,9 @@ describe("LocationServiceMap", () => { "websearch", "write", ]) - const allowedState = yield* update(allowed.path) - expect(allowedState.providers.some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe(true) + const allowedState = yield* update(allowed.path, allowedID) + expect(allowedState.providers.some((provider) => provider.id === allowedID)).toBe(true) + expect(allowedState.providers.some((provider) => provider.id === blockedID)).toBe(false) expect(allowedState.tools.map((tool) => tool.name).sort()).toEqual([ "edit", "glob", diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 27f1d04061..42f2a768ec 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -1,8 +1,11 @@ import { describe, expect } from "bun:test" -import { Effect, Exit, Fiber, Schema } from "effect" +import { Effect, Exit, Fiber, Schema, Stream } from "effect" import { define } from "@opencode-ai/plugin/v2/effect" +import { Config as ConfigSchema } from "@opencode-ai/schema/config" import { AgentV2 } from "@opencode-ai/core/agent" +import { EventV2 } from "@opencode-ai/core/event" import { PluginV2 } from "@opencode-ai/core/plugin" +import { PluginHost } from "@opencode-ai/core/plugin/host" import { SessionV2 } from "@opencode-ai/core/session" import { SessionMessage } from "@opencode-ai/core/session/message" import { Tool } from "@opencode-ai/core/tool/tool" @@ -14,6 +17,24 @@ import { PluginTestLayer } from "./plugin/fixture" const it = testEffect(PluginTestLayer) describe("PluginV2", () => { + it.live("exposes public events through the plugin context", () => + Effect.gen(function* () { + const plugins = yield* PluginV2.Service + const events = yield* EventV2.Service + const host = yield* PluginHost.make(plugins) + const received = yield* host.event.subscribe().pipe( + Stream.filter((event) => event.type === "config.updated"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ) + yield* Effect.sleep("10 millis") + + yield* events.publish(ConfigSchema.Event.Updated, {}) + + expect((yield* Fiber.join(received)).valueOrUndefined?.type).toBe("config.updated") + }), + ) + it.effect("waits for a plugin and returns immediately once active", () => Effect.gen(function* () { const plugins = yield* PluginV2.Service diff --git a/packages/core/test/plugin/host.ts b/packages/core/test/plugin/host.ts index c5f168f265..63ac18e31e 100644 --- a/packages/core/test/plugin/host.ts +++ b/packages/core/test/plugin/host.ts @@ -6,7 +6,7 @@ import { Integration } from "@opencode-ai/core/integration" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" import type { IntegrationEnvMethod, IntegrationKeyMethod, IntegrationOAuthMethod } from "@opencode-ai/sdk/v2/types" -import { Effect } from "effect" +import { Effect, Stream } from "effect" type Overrides = Partial> @@ -39,6 +39,9 @@ export function host(overrides: Overrides = {}): PluginContext { transform: () => Effect.die("unused command.transform"), reload: () => Effect.die("unused command.reload"), }, + event: overrides.event ?? { + subscribe: () => Stream.empty, + }, integration: overrides.integration ?? { list: () => Effect.die("unused integration.list"), get: () => Effect.die("unused integration.get"), diff --git a/packages/core/test/policy.test.ts b/packages/core/test/policy.test.ts deleted file mode 100644 index 1428c1b830..0000000000 --- a/packages/core/test/policy.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect } from "bun:test" -import { Effect, Layer } from "effect" -import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" -import { Location } from "@opencode-ai/core/location" -import { Policy } from "@opencode-ai/core/policy" -import { AbsolutePath } from "@opencode-ai/core/schema" -import { location } from "./fixture/location" -import { testEffect } from "./lib/effect" - -const it = testEffect( - AppNodeBuilder.build(Policy.node, [ - [ - Location.node, - Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make("test") }))), - ], - ]), -) - -describe("Policy", () => { - it.effect("returns the caller's fallback when no statement matches", () => - Effect.gen(function* () { - const policy = yield* Policy.Service - - expect(yield* policy.evaluate("provider.use", "anthropic", "allow")).toBe("allow") - expect(yield* policy.evaluate("provider.use", "anthropic", "deny")).toBe("deny") - }), - ) - - it.effect("evaluates wildcard provider rules in written order", () => - Effect.gen(function* () { - const policy = yield* Policy.Service - yield* policy.load([ - new Policy.Info({ - effect: "deny", - action: "provider.*", - resource: "*", - }), - new Policy.Info({ - effect: "allow", - action: "provider.use", - resource: "anthropic", - }), - ]) - - expect(yield* policy.evaluate("provider.use", "anthropic", "allow")).toBe("allow") - expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny") - }), - ) - - it.effect("matches action and resource independently", () => - Effect.gen(function* () { - const policy = yield* Policy.Service - yield* policy.load([ - new Policy.Info({ - effect: "deny", - action: "provider.*", - resource: "company-*", - }), - ]) - - expect(yield* policy.evaluate("provider.use", "company-stable", "allow")).toBe("deny") - expect(yield* policy.evaluate("plugin.load", "company-stable", "allow")).toBe("allow") - }), - ) - - it.effect("uses the last matching loaded statement", () => - Effect.gen(function* () { - const policy = yield* Policy.Service - yield* policy.load([ - new Policy.Info({ - effect: "allow", - action: "provider.use", - resource: "openai", - }), - new Policy.Info({ - effect: "deny", - action: "provider.use", - resource: "openai", - }), - ]) - - expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny") - }), - ) -}) diff --git a/packages/core/test/skill.test.ts b/packages/core/test/skill.test.ts index 38ca4cfb92..7e57610afa 100644 --- a/packages/core/test/skill.test.ts +++ b/packages/core/test/skill.test.ts @@ -10,7 +10,7 @@ import { FSUtil } from "@opencode-ai/core/fs-util" import { AbsolutePath } from "@opencode-ai/core/schema" import { SkillV2 } from "@opencode-ai/core/skill" import { SkillDiscovery } from "@opencode-ai/core/skill/discovery" -import { FileSystemWatcher } from "@opencode-ai/schema/filesystem-watcher" +import { FileSystem } from "@opencode-ai/schema/filesystem" import { tmpdir } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" @@ -206,7 +206,7 @@ metadata: waitForSkillUpdate(), ({ deferred }) => events - .publish(FileSystemWatcher.Event.Updated, { file, event: "change" }) + .publish(FileSystem.Event.Changed, { file, event: "change" }) .pipe(Effect.andThen(Deferred.await(deferred)), Effect.timeout("1 second")), ({ fiber }) => Fiber.interrupt(fiber), ) diff --git a/packages/opencode/src/tool/apply_patch.ts b/packages/opencode/src/tool/apply_patch.ts index f9201be8a7..312bef9f4f 100644 --- a/packages/opencode/src/tool/apply_patch.ts +++ b/packages/opencode/src/tool/apply_patch.ts @@ -12,6 +12,7 @@ import { LSP } from "@/lsp/lsp" import { FSUtil } from "@opencode-ai/core/fs-util" import DESCRIPTION from "./apply_patch.txt" import { FileSystem } from "@opencode-ai/core/filesystem" +import { FileSystemV1 } from "@opencode-ai/schema/filesystem-v1" import { Format } from "../format" import * as Bom from "@/util/bom" @@ -253,7 +254,7 @@ export const ApplyPatchTool = Tool.define( if (yield* format.file(edited)) { yield* Bom.syncFile(afs, edited, change.bom) } - yield* events.publish(FileSystem.Event.Edited, { file: edited }) + yield* events.publish(FileSystemV1.Event.Edited, { file: edited }) } } diff --git a/packages/opencode/src/tool/edit.ts b/packages/opencode/src/tool/edit.ts index a92e4720c0..7e13b85997 100644 --- a/packages/opencode/src/tool/edit.ts +++ b/packages/opencode/src/tool/edit.ts @@ -10,6 +10,7 @@ import { LSP } from "@/lsp/lsp" import { createTwoFilesPatch, diffLines } from "diff" import DESCRIPTION from "./edit.txt" import { FileSystem } from "@opencode-ai/core/filesystem" +import { FileSystemV1 } from "@opencode-ai/schema/filesystem-v1" import { Watcher } from "@opencode-ai/core/filesystem/watcher" import { EventV2Bridge } from "@/event-v2-bridge" import { Format } from "../format" @@ -112,7 +113,7 @@ export const EditTool = Tool.define( if (yield* format.file(filePath)) { contentNew = yield* Bom.syncFile(afs, filePath, desiredBom) } - yield* events.publish(FileSystem.Event.Edited, { file: filePath }) + yield* events.publish(FileSystemV1.Event.Edited, { file: filePath }) yield* events.publish(Watcher.Event.Updated, { file: filePath, event: "add", @@ -156,7 +157,7 @@ export const EditTool = Tool.define( if (yield* format.file(filePath)) { contentNew = yield* Bom.syncFile(afs, filePath, desiredBom) } - yield* events.publish(FileSystem.Event.Edited, { file: filePath }) + yield* events.publish(FileSystemV1.Event.Edited, { file: filePath }) yield* events.publish(Watcher.Event.Updated, { file: filePath, event: "change", diff --git a/packages/opencode/src/tool/write.ts b/packages/opencode/src/tool/write.ts index 37be6d8c47..7d9aa8326a 100644 --- a/packages/opencode/src/tool/write.ts +++ b/packages/opencode/src/tool/write.ts @@ -7,6 +7,7 @@ import { createTwoFilesPatch } from "diff" import DESCRIPTION from "./write.txt" import { EventV2Bridge } from "@/event-v2-bridge" import { FileSystem } from "@opencode-ai/core/filesystem" +import { FileSystemV1 } from "@opencode-ai/schema/filesystem-v1" import { Watcher } from "@opencode-ai/core/filesystem/watcher" import { Format } from "../format" import { FSUtil } from "@opencode-ai/core/fs-util" @@ -65,7 +66,7 @@ export const WriteTool = Tool.define( if (yield* format.file(filepath)) { yield* Bom.syncFile(fs, filepath, desiredBom) } - yield* events.publish(FileSystem.Event.Edited, { file: filepath }) + yield* events.publish(FileSystemV1.Event.Edited, { file: filepath }) yield* events.publish(Watcher.Event.Updated, { file: filepath, event: exists ? "change" : "add", diff --git a/packages/opencode/test/server/httpapi-v2-location.test.ts b/packages/opencode/test/server/httpapi-v2-location.test.ts index cf009812b8..1de6007b79 100644 --- a/packages/opencode/test/server/httpapi-v2-location.test.ts +++ b/packages/opencode/test/server/httpapi-v2-location.test.ts @@ -82,7 +82,7 @@ describe("v2 location HttpApi", () => { expect( Schema.decodeUnknownSync(Event)({ id: "evt_test", - type: "file.watcher.updated", + type: "filesystem.changed", location: { directory: "/tmp/project" }, data: {}, }), diff --git a/packages/plugin/src/v2/effect/context.ts b/packages/plugin/src/v2/effect/context.ts index db2f4c0ee6..219dc16581 100644 --- a/packages/plugin/src/v2/effect/context.ts +++ b/packages/plugin/src/v2/effect/context.ts @@ -3,6 +3,7 @@ import type { AgentHooks } from "./agent.js" import type { AISDKHooks } from "./aisdk.js" import type { CatalogHooks } from "./catalog.js" import type { CommandHooks } from "./command.js" +import type { EventHooks } from "./event.js" import type { IntegrationHooks } from "./integration.js" import type { PluginDomain } from "./plugin.js" import type { ReferenceHooks } from "./reference.js" @@ -16,6 +17,7 @@ export interface PluginContext { readonly aisdk: AISDKHooks readonly catalog: CatalogHooks readonly command: CommandHooks + readonly event: EventHooks readonly integration: IntegrationHooks readonly plugin: PluginDomain readonly reference: ReferenceHooks diff --git a/packages/plugin/src/v2/effect/event.ts b/packages/plugin/src/v2/effect/event.ts index e6ea7cf0ce..49ad375d67 100644 --- a/packages/plugin/src/v2/effect/event.ts +++ b/packages/plugin/src/v2/effect/event.ts @@ -1,10 +1,3 @@ -import type { Event as SDKEvent } from "@opencode-ai/sdk/v2/types" -import type { Stream } from "effect" +import type { EventApi } from "@opencode-ai/client/effect/api" -export type EventMap = { - [Item in SDKEvent as Item["type"]]: Item -} - -export interface Event { - subscribe(type: Type): Stream.Stream -} +export interface EventHooks extends Pick, "subscribe"> {} diff --git a/packages/plugin/src/v2/effect/index.ts b/packages/plugin/src/v2/effect/index.ts index 12b5971fef..2ebd0215b5 100644 --- a/packages/plugin/src/v2/effect/index.ts +++ b/packages/plugin/src/v2/effect/index.ts @@ -5,6 +5,7 @@ export type { AgentDraft, AgentHooks } from "./agent.js" export type { AISDKHooks } from "./aisdk.js" export type { CatalogDraft, CatalogHooks, CatalogProviderRecord } from "./catalog.js" export type { CommandDraft, CommandHooks } from "./command.js" +export type { EventHooks } from "./event.js" export type { IntegrationDraft, IntegrationHooks, IntegrationMethodRegistration } from "./integration.js" export type { ReferenceDraft, ReferenceHooks } from "./reference.js" export type { SkillDraft, SkillHooks } from "./skill.js" diff --git a/packages/plugin/src/v2/promise/context.ts b/packages/plugin/src/v2/promise/context.ts index 652deee9bb..5e67e44961 100644 --- a/packages/plugin/src/v2/promise/context.ts +++ b/packages/plugin/src/v2/promise/context.ts @@ -3,6 +3,7 @@ import type { AgentHooks } from "./agent.js" import type { AISDKHooks } from "./aisdk.js" import type { CatalogHooks } from "./catalog.js" import type { CommandHooks } from "./command.js" +import type { EventHooks } from "./event.js" import type { IntegrationHooks } from "./integration.js" import type { PluginDomain } from "./plugin.js" import type { ReferenceHooks } from "./reference.js" @@ -15,6 +16,7 @@ export interface PluginContext { readonly aisdk: AISDKHooks readonly catalog: CatalogHooks readonly command: CommandHooks + readonly event: EventHooks readonly integration: IntegrationHooks readonly plugin: PluginDomain readonly reference: ReferenceHooks diff --git a/packages/plugin/src/v2/promise/event.ts b/packages/plugin/src/v2/promise/event.ts new file mode 100644 index 0000000000..5330f70c7c --- /dev/null +++ b/packages/plugin/src/v2/promise/event.ts @@ -0,0 +1,3 @@ +import type { EventApi } from "@opencode-ai/client/promise/api" + +export interface EventHooks extends Pick {} diff --git a/packages/plugin/src/v2/promise/index.ts b/packages/plugin/src/v2/promise/index.ts index 1050463e70..594ff7da3c 100644 --- a/packages/plugin/src/v2/promise/index.ts +++ b/packages/plugin/src/v2/promise/index.ts @@ -6,6 +6,7 @@ export type { AgentDraft, AgentHooks } from "./agent.js" export type { AISDKHooks } from "./aisdk.js" export type { CatalogDraft, CatalogHooks, CatalogProviderRecord } from "./catalog.js" export type { CommandDraft, CommandHooks } from "./command.js" +export type { EventHooks } from "./event.js" export type { IntegrationDraft, IntegrationHooks, IntegrationMethodRegistration } from "./integration.js" export type { ReferenceDraft, ReferenceHooks } from "./reference.js" export type { SessionHooks } from "./runtime.js" diff --git a/packages/schema/src/config.ts b/packages/schema/src/config.ts new file mode 100644 index 0000000000..92b07b0e39 --- /dev/null +++ b/packages/schema/src/config.ts @@ -0,0 +1,10 @@ +export * as Config from "./config.js" + +import { ephemeral, inventory } from "./event.js" + +const Updated = ephemeral({ + type: "config.updated", + schema: {}, +}) + +export const Event = { Updated, Definitions: inventory(Updated) } diff --git a/packages/schema/src/event-manifest.ts b/packages/schema/src/event-manifest.ts index e17ff96bc9..6b2b806f81 100644 --- a/packages/schema/src/event-manifest.ts +++ b/packages/schema/src/event-manifest.ts @@ -3,10 +3,11 @@ export * as EventManifest from "./event-manifest.js" import { Agent } from "./agent.js" import { Catalog } from "./catalog.js" import { Command } from "./command.js" +import { Config } from "./config.js" import { Durable } from "./durable-event-manifest.js" import { Event } from "./event.js" import { FileSystem } from "./filesystem.js" -import { FileSystemWatcher } from "./filesystem-watcher.js" +import { FileSystemV1 } from "./filesystem-v1.js" import { Form } from "./form.js" import { InstallationEvent } from "./installation-event.js" import { Integration } from "./integration.js" @@ -60,8 +61,8 @@ const featureDefinitions = Event.inventory( ...Plugin.Event.Definitions, ...ProjectDirectories.Event.Definitions, ...Command.Event.Definitions, + ...Config.Event.Definitions, ...Skill.Event.Definitions, - ...FileSystemWatcher.Event.Definitions, ...Pty.Event.Definitions, ...Shell.Event.Definitions, ...Question.Event.Definitions, @@ -97,6 +98,7 @@ export const Definitions = Event.inventory( ...TuiEvent.Definitions, ...McpEvent.Definitions, ...LegacyEvent.Definitions, + ...FileSystemV1.Event.Definitions, ...Project.Event.Definitions, ...SessionStatusEvent.Definitions, ...QuestionV1.Event.Definitions, diff --git a/packages/schema/src/filesystem-v1.ts b/packages/schema/src/filesystem-v1.ts new file mode 100644 index 0000000000..60e1a91853 --- /dev/null +++ b/packages/schema/src/filesystem-v1.ts @@ -0,0 +1 @@ +export * from "./v1/filesystem.js" diff --git a/packages/schema/src/filesystem-watcher.ts b/packages/schema/src/filesystem-watcher.ts deleted file mode 100644 index debe0914d1..0000000000 --- a/packages/schema/src/filesystem-watcher.ts +++ /dev/null @@ -1,13 +0,0 @@ -export * as FileSystemWatcher from "./filesystem-watcher.js" - -import { Schema } from "effect" -import { ephemeral, inventory } from "./event.js" - -const Updated = ephemeral({ - type: "file.watcher.updated", - schema: { - file: Schema.String, - event: Schema.Literals(["add", "change", "unlink"]), - }, -}) -export const Event = { Updated, Definitions: inventory(Updated) } diff --git a/packages/schema/src/filesystem.ts b/packages/schema/src/filesystem.ts index 3599e48c7c..3f95e97a5b 100644 --- a/packages/schema/src/filesystem.ts +++ b/packages/schema/src/filesystem.ts @@ -5,11 +5,14 @@ import { optional } from "./schema.js" import { ephemeral, inventory } from "./event.js" import { NonNegativeInt, PositiveInt, RelativePath } from "./schema.js" -const Edited = ephemeral({ - type: "file.edited", - schema: { file: Schema.String }, +const Changed = ephemeral({ + type: "filesystem.changed", + schema: { + file: Schema.String, + event: Schema.Literals(["add", "change", "unlink"]), + }, }) -export const Event = { Edited, Definitions: inventory(Edited) } +export const Event = { Changed, Definitions: inventory(Changed) } export interface Entry extends Schema.Schema.Type {} export const Entry = Schema.Struct({ diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts index fb2ef17b96..1454fab1cf 100644 --- a/packages/schema/src/index.ts +++ b/packages/schema/src/index.ts @@ -1,5 +1,6 @@ export { Agent } from "./agent.js" export { Command } from "./command.js" +export { Config } from "./config.js" export { Connection } from "./connection.js" export { Credential } from "./credential.js" export { Event } from "./event.js" diff --git a/packages/schema/src/v1/filesystem.ts b/packages/schema/src/v1/filesystem.ts new file mode 100644 index 0000000000..a1756fefd3 --- /dev/null +++ b/packages/schema/src/v1/filesystem.ts @@ -0,0 +1,11 @@ +export * as FileSystemV1 from "./filesystem.js" + +import { Schema } from "effect" +import { ephemeral, inventory } from "../event.js" + +const Edited = ephemeral({ + type: "file.edited", + schema: { file: Schema.String }, +}) + +export const Event = { Edited, Definitions: inventory(Edited) } diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 873e415c61..487a942d9a 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test" import { Agent, + Config, FileSystem, Form, Integration, @@ -11,6 +12,7 @@ import { Workspace, } from "../src/index.js" import { EventManifest } from "../src/event-manifest.js" +import { FileSystemV1 } from "../src/filesystem-v1.js" import { IdeEvent } from "../src/ide-event.js" import { McpEvent } from "../src/mcp-event.js" import { SessionEvent } from "../src/session-event.js" @@ -59,7 +61,9 @@ describe("public event manifest", () => { expect(EventManifest.Latest.get("project.updated")).toBe(Project.Event.Updated) expect(Agent.Event.Definitions).toEqual([Agent.Event.Updated]) expect(Project.Event.Definitions).toEqual([Project.Event.Updated]) - expect(FileSystem.Event.Definitions).toEqual([FileSystem.Event.Edited]) + expect(Config.Event.Definitions).toEqual([Config.Event.Updated]) + expect(FileSystem.Event.Definitions).toEqual([FileSystem.Event.Changed]) + expect(FileSystemV1.Event.Definitions).toEqual([FileSystemV1.Event.Edited]) expect(Integration.Event.Definitions).toEqual([Integration.Event.Updated, Integration.Event.ConnectionUpdated]) expect(Permission.Event.Definitions).toEqual([Permission.Event.Asked, Permission.Event.Replied]) expect(Form.Event.Definitions).toEqual([Form.Event.Created, Form.Event.Replied, Form.Event.Cancelled]) diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index c693369281..524d7ea854 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -58,15 +58,15 @@ export type Event = | EventSessionError | EventInstallationUpdated | EventInstallationUpdateAvailable - | EventFileEdited + | EventFilesystemChanged | EventReferenceUpdated | EventPermissionV2Asked | EventPermissionV2Replied | EventPluginAdded | EventProjectDirectoriesUpdated | EventCommandUpdated + | EventConfigUpdated | EventSkillUpdated - | EventFileWatcherUpdated | EventPtyCreated | EventPtyUpdated | EventPtyExited @@ -91,6 +91,7 @@ export type Event = | EventMcpToolsChanged | EventMcpStatusChanged | EventCommandExecuted + | EventFileEdited | EventProjectUpdated | EventSessionStatus | EventSessionIdle @@ -1280,9 +1281,10 @@ export type GlobalEvent = { } | { id: string - type: "file.edited" + type: "filesystem.changed" properties: { file: string + event: "add" | "change" | "unlink" } } | { @@ -1339,17 +1341,16 @@ export type GlobalEvent = { } | { id: string - type: "skill.updated" + type: "config.updated" properties: { [key: string]: unknown } } | { id: string - type: "file.watcher.updated" + type: "skill.updated" properties: { - file: string - event: "add" | "change" | "unlink" + [key: string]: unknown } } | { @@ -1576,6 +1577,13 @@ export type GlobalEvent = { messageID: string } } + | { + id: string + type: "file.edited" + properties: { + file: string + } + } | { id: string type: "project.updated" @@ -2123,7 +2131,6 @@ export type Config = { primary_tools?: Array continue_loop_on_deny?: boolean mcp_timeout?: number - policies?: Array } } @@ -3059,15 +3066,15 @@ export type V2Event = | SessionError | InstallationUpdated | InstallationUpdateAvailable - | FileEdited + | FilesystemChanged | ReferenceUpdated | PermissionV2Asked | PermissionV2Replied | PluginAdded | ProjectDirectoriesUpdated | CommandUpdated + | ConfigUpdated | SkillUpdated - | FileWatcherUpdated | PtyCreated | PtyUpdated | PtyExited @@ -3092,6 +3099,7 @@ export type V2Event = | McpToolsChanged | McpStatusChanged | CommandExecuted + | FileEdited | ProjectUpdated | SessionStatus2 | SessionIdle @@ -4167,14 +4175,6 @@ export type ConfigV2ReferenceLocal = { hidden?: boolean } -export type PolicyEffect = "allow" | "deny" - -export type ConfigV2ExperimentalPolicy = { - action: "provider.use" - effect: PolicyEffect - resource: string -} - export type ProjectDirectory = { directory: string strategy?: string @@ -5880,16 +5880,17 @@ export type InstallationUpdateAvailable = { } } -export type FileEdited = { +export type FilesystemChanged = { id: string created: number metadata?: { [key: string]: unknown } - type: "file.edited" + type: "filesystem.changed" location?: LocationRef data: { file: string + event: "add" | "change" | "unlink" } } @@ -5981,6 +5982,19 @@ export type CommandUpdated = { } } +export type ConfigUpdated = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "config.updated" + location?: LocationRef + data: { + [key: string]: unknown + } +} + export type SkillUpdated = { id: string created: number @@ -5994,20 +6008,6 @@ export type SkillUpdated = { } } -export type FileWatcherUpdated = { - id: string - created: number - metadata?: { - [key: string]: unknown - } - type: "file.watcher.updated" - location?: LocationRef - data: { - file: string - event: "add" | "change" | "unlink" - } -} - export type PtyCreated = { id: string created: number @@ -6408,6 +6408,19 @@ export type CommandExecuted = { } } +export type FileEdited = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "file.edited" + location?: LocationRef + data: { + file: string + } +} + export type ProjectUpdated = { id: string created: number @@ -7209,11 +7222,12 @@ export type EventInstallationUpdateAvailable = { } } -export type EventFileEdited = { +export type EventFilesystemChanged = { id: string - type: "file.edited" + type: "filesystem.changed" properties: { file: string + event: "add" | "change" | "unlink" } } @@ -7275,20 +7289,19 @@ export type EventCommandUpdated = { } } -export type EventSkillUpdated = { +export type EventConfigUpdated = { id: string - type: "skill.updated" + type: "config.updated" properties: { [key: string]: unknown } } -export type EventFileWatcherUpdated = { +export type EventSkillUpdated = { id: string - type: "file.watcher.updated" + type: "skill.updated" properties: { - file: string - event: "add" | "change" | "unlink" + [key: string]: unknown } } @@ -7508,6 +7521,14 @@ export type EventCommandExecuted = { } } +export type EventFileEdited = { + id: string + type: "file.edited" + properties: { + file: string + } +} + export type EventProjectUpdated = { id: string type: "project.updated" @@ -10279,16 +10300,17 @@ export type SessionCompactionDelta2 = { } } -export type FileEdited2 = { +export type FilesystemChanged2 = { id: string created: number metadata?: { [key: string]: unknown } - type: "file.edited" + type: "filesystem.changed" location?: LocationRef2 data: { file: string + event: "add" | "change" | "unlink" } } @@ -10384,6 +10406,21 @@ export type CommandUpdated2 = { | Array } +export type ConfigUpdated2 = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "config.updated" + location?: LocationRef2 + data: + | { + [key: string]: unknown + } + | Array +} + export type SkillUpdated2 = { id: string created: number @@ -10399,20 +10436,6 @@ export type SkillUpdated2 = { | Array } -export type FileWatcherUpdated2 = { - id: string - created: number - metadata?: { - [key: string]: unknown - } - type: "file.watcher.updated" - location?: LocationRef2 - data: { - file: string - event: "add" | "change" | "unlink" - } -} - export type PtyV2 = { id: string title: string @@ -11162,15 +11185,15 @@ export type V2EventV2 = | SessionRevertStaged2 | SessionRevertCleared2 | SessionRevertCommitted2 - | FileEdited2 + | FilesystemChanged2 | ReferenceUpdated2 | PermissionV2Asked2 | PermissionV2Replied2 | PluginAdded2 | ProjectDirectoriesUpdated2 | CommandUpdated2 + | ConfigUpdated2 | SkillUpdated2 - | FileWatcherUpdated2 | PtyCreated2 | PtyUpdated2 | PtyExited2 From 9751615651e3e776ec8e57122160e3661f3393ba Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 20:41:33 -0400 Subject: [PATCH 37/82] fix(core): reload all config plugins --- packages/core/src/config/plugin/agent.ts | 53 +++++--- packages/core/src/config/plugin/external.ts | 39 ++++-- packages/core/src/config/plugin/provider.ts | 32 +++-- packages/core/src/config/plugin/reference.ts | 67 ++++++---- packages/core/src/config/plugin/skill.ts | 18 ++- packages/core/test/config/reload.test.ts | 125 +++++++++++++++++++ 6 files changed, 264 insertions(+), 70 deletions(-) create mode 100644 packages/core/test/config/reload.test.ts diff --git a/packages/core/src/config/plugin/agent.ts b/packages/core/src/config/plugin/agent.ts index 9c6c958025..3aebf88fbe 100644 --- a/packages/core/src/config/plugin/agent.ts +++ b/packages/core/src/config/plugin/agent.ts @@ -2,7 +2,7 @@ export * as ConfigAgentPlugin from "./agent" import { define } from "../../plugin/internal" import path from "path" -import { Effect, Option, Schema } from "effect" +import { Effect, Option, Schema, Stream } from "effect" import { AgentV2 } from "../../agent" import { Config } from "../../config" import { ConfigAgent } from "../agent" @@ -38,31 +38,34 @@ export const Plugin = define({ effect: Effect.fn(function* (ctx) { const config = yield* Config.Service const fs = yield* FSUtil.Service - const documents = yield* Effect.forEach(yield* config.entries(), (entry) => { - if (entry.type === "document") return Effect.succeed([entry]) - return Effect.gen(function* () { - const files = yield* discover(fs, entry.path) - return yield* Effect.forEach(files, (file) => - fs.readFileStringSafe(file.filepath).pipe( - Effect.map((content) => content && decode(file, content)), - Effect.catch(() => Effect.succeed(undefined)), - ), - ).pipe( - Effect.map((documents) => - documents.filter((document): document is Config.Document => document !== undefined), - ), - ) - }) - }).pipe(Effect.map((documents) => documents.flat())) - const global = documents.flatMap((document) => document.info.permissions ?? []) - const configuredDefault = Config.latest(documents, "default_agent") + const load = Effect.fn("ConfigAgentPlugin.load")(function* () { + return yield* Effect.forEach(yield* config.entries(), (entry) => { + if (entry.type === "document") return Effect.succeed([entry]) + return Effect.gen(function* () { + const files = yield* discover(fs, entry.path) + return yield* Effect.forEach(files, (file) => + fs.readFileStringSafe(file.filepath).pipe( + Effect.map((content) => content && decode(file, content)), + Effect.catch(() => Effect.succeed(undefined)), + ), + ).pipe( + Effect.map((documents) => + documents.filter((document): document is Config.Document => document !== undefined), + ), + ) + }) + }).pipe(Effect.map((documents) => documents.flat())) + }) + const loaded = { documents: yield* load() } yield* ctx.agent.transform((draft) => { + const global = loaded.documents.flatMap((document) => document.info.permissions ?? []) + const configuredDefault = Config.latest(loaded.documents, "default_agent") if (configuredDefault !== undefined) draft.default(AgentV2.ID.make(configuredDefault)) for (const current of draft.list()) { draft.update(current.id, (agent) => agent.permissions.push(...global)) } - for (const document of documents) { + for (const document of loaded.documents) { for (const [id, item] of Object.entries(document.info.agents ?? {})) { const agentID = AgentV2.ID.make(id) if (item.disabled) { @@ -95,6 +98,16 @@ export const Plugin = define({ } } }) + yield* ctx.event.subscribe().pipe( + Stream.filter((event) => event.type === "config.updated"), + Stream.runForEach(() => + load().pipe( + Effect.tap((documents) => Effect.sync(() => (loaded.documents = documents))), + Effect.andThen(ctx.agent.reload()), + ), + ), + Effect.forkScoped({ startImmediately: true }), + ) }), }) diff --git a/packages/core/src/config/plugin/external.ts b/packages/core/src/config/plugin/external.ts index 22f49bbf16..c67f67d481 100644 --- a/packages/core/src/config/plugin/external.ts +++ b/packages/core/src/config/plugin/external.ts @@ -2,7 +2,7 @@ export * as ConfigExternalPlugin from "./external" import type { Plugin as EffectPlugin } from "@opencode-ai/plugin/v2/effect" import type { Plugin as PromisePlugin } from "@opencode-ai/plugin/v2/promise" -import { Effect, Schema } from "effect" +import { Effect, Schema, Stream } from "effect" import path from "path" import { fileURLToPath, pathToFileURL } from "url" import { Config } from "../../config" @@ -42,8 +42,9 @@ export const Plugin = define({ const fs = yield* FSUtil.Service const location = yield* Location.Service const npm = yield* Npm.Service - yield* Effect.gen(function* () { - const configured: { package: string; options?: Record }[] = [] + const active = new Set() + const load = Effect.fn("ConfigExternalPlugin.load")(function* () { + const configured: { package: string; options?: Record }[] = [] for (const entry of yield* config.entries()) { if (entry.type === "document") { @@ -98,8 +99,8 @@ export const Plugin = define({ } } - for (const ref of configured) { - yield* Effect.gen(function* () { + return yield* Effect.forEach(configured, (ref) => + Effect.gen(function* () { const entrypoint = path.isAbsolute(ref.package) ? pathToFileURL(ref.package).href : (yield* npm.add(ref.package)).entrypoint @@ -108,13 +109,31 @@ export const Plugin = define({ const mod = yield* Effect.promise(() => import(entrypoint)) const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default const plugin = "effect" in value ? value : PluginPromise.fromPromise(value) - yield* ctx.plugin.add({ + return { id: plugin.id, - effect: (host) => plugin.effect({ ...host, options: ref.options ?? {} }), - }) - }).pipe(Effect.ignoreCause) - } + effect: (host: Parameters[0]) => + plugin.effect({ ...host, options: ref.options ?? {} }), + } + }).pipe(Effect.catchCause(() => Effect.succeed(undefined))), + ).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined))) }) + const reconcile = Effect.fn("ConfigExternalPlugin.reconcile")(function* () { + const plugins = yield* load() + const next = new Set(plugins.map((plugin) => plugin.id)) + for (const id of active) { + if (!next.has(id)) yield* ctx.plugin.remove(id) + } + for (const plugin of plugins) yield* ctx.plugin.add(plugin) + active.clear() + for (const id of next) active.add(id) + }) + + yield* reconcile() + yield* ctx.event.subscribe().pipe( + Stream.filter((event) => event.type === "config.updated"), + Stream.runForEach(() => reconcile()), + Effect.forkScoped({ startImmediately: true }), + ) }), }) diff --git a/packages/core/src/config/plugin/provider.ts b/packages/core/src/config/plugin/provider.ts index 4992233a1f..d2d6a26029 100644 --- a/packages/core/src/config/plugin/provider.ts +++ b/packages/core/src/config/plugin/provider.ts @@ -1,7 +1,7 @@ export * as ConfigProviderPlugin from "./provider" import { define } from "../../plugin/internal" -import { Effect } from "effect" +import { Effect, Stream } from "effect" import { Config } from "../../config" import { ModelV2 } from "../../model" @@ -9,14 +9,16 @@ export const Plugin = define({ id: "config-provider", effect: Effect.fn(function* (ctx) { const config = yield* Config.Service - const entries = yield* config.entries() - const files = entries.filter((entry): entry is Config.Document => entry.type === "document") - const configuredIntegrations = new Set( - files.flatMap((file) => - Object.entries(file.info.providers ?? {}).flatMap(([id, provider]) => (provider.env === undefined ? [] : [id])), - ), - ) + const loaded = { entries: yield* config.entries() } yield* ctx.integration.transform((integrations) => { + const files = loaded.entries.filter((entry): entry is Config.Document => entry.type === "document") + const configuredIntegrations = new Set( + files.flatMap((file) => + Object.entries(file.info.providers ?? {}).flatMap(([id, provider]) => + provider.env === undefined ? [] : [id], + ), + ), + ) for (const file of files) { for (const [id, item] of Object.entries(file.info.providers ?? {})) { const integrationID = id @@ -34,8 +36,9 @@ export const Plugin = define({ } }) - const configuredDefault = Config.latest(entries, "model") yield* ctx.catalog.transform((catalog) => { + const files = loaded.entries.filter((entry): entry is Config.Document => entry.type === "document") + const configuredDefault = Config.latest(loaded.entries, "model") if (configuredDefault !== undefined) { const model = ModelV2.parse(configuredDefault) catalog.model.default.set(model.providerID, model.modelID) @@ -105,5 +108,16 @@ export const Plugin = define({ } } }) + yield* ctx.event.subscribe().pipe( + Stream.filter((event) => event.type === "config.updated"), + Stream.runForEach(() => + config.entries().pipe( + Effect.tap((entries) => Effect.sync(() => (loaded.entries = entries))), + Effect.andThen(ctx.integration.reload()), + Effect.andThen(ctx.catalog.reload()), + ), + ), + Effect.forkScoped({ startImmediately: true }), + ) }), }) diff --git a/packages/core/src/config/plugin/reference.ts b/packages/core/src/config/plugin/reference.ts index 1c599dab7f..d33332f92d 100644 --- a/packages/core/src/config/plugin/reference.ts +++ b/packages/core/src/config/plugin/reference.ts @@ -2,7 +2,7 @@ export * as ConfigReferencePlugin from "./reference" import { define } from "../../plugin/internal" import path from "path" -import { Effect } from "effect" +import { Effect, Stream } from "effect" import { Config } from "../../config" import { ConfigReference } from "../reference" import { Reference } from "../../reference" @@ -16,35 +16,48 @@ export const Plugin = define({ const config = yield* Config.Service const location = yield* Location.Service const global = yield* Global.Service - const entries = new Map() - for (const doc of (yield* config.entries()).filter((entry): entry is Config.Document => entry.type === "document")) { - const directory = doc.path ? path.dirname(doc.path) : location.directory - for (const [name, entry] of Object.entries(doc.info.references ?? {})) { - if (!validAlias(name)) continue - const description = typeof entry === "string" ? undefined : entry.description - const hidden = typeof entry === "string" ? undefined : entry.hidden - entries.set( - name, - local(entry) - ? Reference.LocalSource.make({ - type: "local", - path: AbsolutePath.make(localPath(directory, global.home, typeof entry === "string" ? entry : entry.path)), - ...(description === undefined ? {} : { description }), - ...(hidden === undefined ? {} : { hidden }), - }) - : Reference.GitSource.make({ - type: "git", - repository: typeof entry === "string" ? entry : entry.repository, - ...(entry.branch === undefined ? {} : { branch: entry.branch }), - ...(description === undefined ? {} : { description }), - ...(hidden === undefined ? {} : { hidden }), - }), - ) - } - } + const loaded = { entries: yield* config.entries() } yield* ctx.reference.transform((draft) => { + const entries = new Map() + for (const doc of loaded.entries.filter((entry): entry is Config.Document => entry.type === "document")) { + const directory = doc.path ? path.dirname(doc.path) : location.directory + for (const [name, entry] of Object.entries(doc.info.references ?? {})) { + if (!validAlias(name)) continue + const description = typeof entry === "string" ? undefined : entry.description + const hidden = typeof entry === "string" ? undefined : entry.hidden + entries.set( + name, + local(entry) + ? Reference.LocalSource.make({ + type: "local", + path: AbsolutePath.make( + localPath(directory, global.home, typeof entry === "string" ? entry : entry.path), + ), + ...(description === undefined ? {} : { description }), + ...(hidden === undefined ? {} : { hidden }), + }) + : Reference.GitSource.make({ + type: "git", + repository: typeof entry === "string" ? entry : entry.repository, + ...(entry.branch === undefined ? {} : { branch: entry.branch }), + ...(description === undefined ? {} : { description }), + ...(hidden === undefined ? {} : { hidden }), + }), + ) + } + } for (const [name, source] of entries) draft.add(name, source) }) + yield* ctx.event.subscribe().pipe( + Stream.filter((event) => event.type === "config.updated"), + Stream.runForEach(() => + config.entries().pipe( + Effect.tap((entries) => Effect.sync(() => (loaded.entries = entries))), + Effect.andThen(ctx.reference.reload()), + ), + ), + Effect.forkScoped({ startImmediately: true }), + ) }), }) diff --git a/packages/core/src/config/plugin/skill.ts b/packages/core/src/config/plugin/skill.ts index c4b7ba95c1..ff83c53ff1 100644 --- a/packages/core/src/config/plugin/skill.ts +++ b/packages/core/src/config/plugin/skill.ts @@ -2,7 +2,7 @@ export * as ConfigSkillPlugin from "./skill" import { define } from "../../plugin/internal" import path from "path" -import { Effect } from "effect" +import { Effect, Stream } from "effect" import { Config } from "../../config" import { AbsolutePath } from "../../schema" import { SkillV2 } from "../../skill" @@ -15,10 +15,10 @@ export const Plugin = define({ const config = yield* Config.Service const global = yield* Global.Service const location = yield* Location.Service - const entries = yield* config.entries() - const directories = entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : [])) - const items = entries.flatMap((entry) => (entry.type === "document" ? (entry.info.skills ?? []) : [])) + const loaded = { entries: yield* config.entries() } yield* ctx.skill.transform((draft) => { + const directories = loaded.entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : [])) + const items = loaded.entries.flatMap((entry) => (entry.type === "document" ? (entry.info.skills ?? []) : [])) for (const directory of directories) { draft.source( SkillV2.DirectorySource.make({ type: "directory", path: AbsolutePath.make(path.join(directory, "skill")) }), @@ -44,5 +44,15 @@ export const Plugin = define({ ) } }) + yield* ctx.event.subscribe().pipe( + Stream.filter((event) => event.type === "config.updated"), + Stream.runForEach(() => + config.entries().pipe( + Effect.tap((entries) => Effect.sync(() => (loaded.entries = entries))), + Effect.andThen(ctx.skill.reload()), + ), + ), + Effect.forkScoped({ startImmediately: true }), + ) }), }) diff --git a/packages/core/test/config/reload.test.ts b/packages/core/test/config/reload.test.ts new file mode 100644 index 0000000000..0ee2f0467e --- /dev/null +++ b/packages/core/test/config/reload.test.ts @@ -0,0 +1,125 @@ +import path from "path" +import { describe, expect } from "bun:test" +import { Config as ConfigSchema } from "@opencode-ai/schema/config" +import { AgentV2 } from "@opencode-ai/core/agent" +import { Catalog } from "@opencode-ai/core/catalog" +import { CommandV2 } from "@opencode-ai/core/command" +import { Config } from "@opencode-ai/core/config" +import { ConfigAgentPlugin } from "@opencode-ai/core/config/plugin/agent" +import { ConfigCommandPlugin } from "@opencode-ai/core/config/plugin/command" +import { ConfigExternalPlugin } from "@opencode-ai/core/config/plugin/external" +import { ConfigProviderPlugin } from "@opencode-ai/core/config/plugin/provider" +import { ConfigReferencePlugin } from "@opencode-ai/core/config/plugin/reference" +import { ConfigSkillPlugin } from "@opencode-ai/core/config/plugin/skill" +import { EventV2 } from "@opencode-ai/core/event" +import { Global } from "@opencode-ai/core/global" +import { PluginV2 } from "@opencode-ai/core/plugin" +import { PluginHost } from "@opencode-ai/core/plugin/host" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { Reference } from "@opencode-ai/core/reference" +import { SkillV2 } from "@opencode-ai/core/skill" +import { Effect, Schema } from "effect" +import { testEffect } from "../lib/effect" +import { PluginTestLayer } from "../plugin/fixture" + +const it = testEffect(PluginTestLayer) +const decode = Schema.decodeUnknownSync(Config.Info) +const document = path.join(import.meta.dir, "opencode.json") + +describe("config plugin reloads", () => { + it.live("reloads every config-backed domain", () => + Effect.gen(function* () { + const agents = yield* AgentV2.Service + const catalog = yield* Catalog.Service + const commands = yield* CommandV2.Service + const events = yield* EventV2.Service + const plugins = yield* PluginV2.Service + const references = yield* Reference.Service + const skills = yield* SkillV2.Service + const host = yield* PluginHost.make(plugins) + let entries: Config.Entry[] = [config("first", "First plugin")] + const service = Config.Service.of({ entries: () => Effect.sync(() => entries) }) + const setup = (effect: Effect.Effect) => + effect.pipe(Effect.provideService(Config.Service, service)) + + yield* setup(ConfigAgentPlugin.Plugin.effect(host)) + yield* setup(ConfigCommandPlugin.Plugin.effect(host)) + yield* setup(ConfigSkillPlugin.Plugin.effect(host)) + yield* setup(ConfigReferencePlugin.Plugin.effect(host)) + yield* setup(ConfigProviderPlugin.Plugin.effect(host)) + yield* setup(ConfigExternalPlugin.Plugin.effect(host)) + + expect((yield* agents.get(AgentV2.ID.make("first")))?.description).toBe("First agent") + expect((yield* commands.get("first"))?.description).toBe("First command") + expect( + (yield* skills.sources()).some((source) => source.type === "directory" && source.path === "/skills/first"), + ).toBe(true) + expect((yield* references.list()).map((reference) => reference.name)).toEqual(["first"]) + expect(yield* catalog.provider.get(ProviderV2.ID.make("first"))).toBeDefined() + expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("First plugin") + + entries = [config("second", "Second plugin")] + yield* events.publish(ConfigSchema.Event.Updated, {}) + yield* waitUntil( + Effect.gen(function* () { + return ( + (yield* agents.get(AgentV2.ID.make("first"))) === undefined && + (yield* agents.get(AgentV2.ID.make("second")))?.description === "Second agent" && + (yield* commands.get("first")) === undefined && + (yield* commands.get("second"))?.description === "Second command" && + (yield* references.list()).some((reference) => reference.name === "second") && + (yield* catalog.provider.get(ProviderV2.ID.make("first"))) === undefined && + (yield* catalog.provider.get(ProviderV2.ID.make("second"))) !== undefined && + (yield* agents.get(AgentV2.ID.make("configured")))?.description === "Second plugin" + ) + }), + ) + + expect( + (yield* skills.sources()).some((source) => source.type === "directory" && source.path === "/skills/first"), + ).toBe(false) + expect( + (yield* skills.sources()).some((source) => source.type === "directory" && source.path === "/skills/second"), + ).toBe(true) + + entries = [config("second")] + yield* events.publish(ConfigSchema.Event.Updated, {}) + yield* waitUntil(agents.get(AgentV2.ID.make("configured")).pipe(Effect.map((agent) => agent === undefined))) + }).pipe(Effect.provideService(Global.Service, Global.Service.of(Global.make()))), + ) +}) + +function config(name: string, pluginDescription?: string) { + return new Config.Document({ + type: "document", + path: document, + info: decode({ + agents: { [name]: { description: `${title(name)} agent`, mode: "subagent" } }, + commands: { [name]: { template: `${title(name)} command`, description: `${title(name)} command` } }, + skills: [`/skills/${name}`], + references: { [name]: `/references/${name}` }, + providers: { [name]: { models: { chat: { name: `${title(name)} model` } } } }, + plugins: + pluginDescription === undefined + ? [] + : [ + { + package: "../plugin/fixtures/config-promise-plugin.ts", + options: { description: pluginDescription }, + }, + ], + }), + }) +} + +function title(value: string) { + return value.charAt(0).toUpperCase() + value.slice(1) +} + +const waitUntil = Effect.fnUntraced(function* (condition: Effect.Effect) { + for (let attempt = 0; attempt < 100; attempt++) { + if (yield* condition) return + yield* Effect.sleep("10 millis") + } + return yield* Effect.die("Timed out waiting for config plugin reloads") +}) From 35ed09ff37ec23c5b8dd62de41af76f8d6c0999b Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 22:26:54 -0400 Subject: [PATCH 38/82] fix(tui): improve MCP error details (#35263) --- packages/tui/src/app.tsx | 4 +- packages/tui/src/component/dialog-mcp.tsx | 132 +++++++++++++++++----- 2 files changed, 108 insertions(+), 28 deletions(-) diff --git a/packages/tui/src/app.tsx b/packages/tui/src/app.tsx index d5cf93c2c7..a3b2c31973 100644 --- a/packages/tui/src/app.tsx +++ b/packages/tui/src/app.tsx @@ -409,8 +409,8 @@ function App(props: { onSnapshot?: () => Promise; pluginHost: TuiPlugi else toast.show({ variant: "error", - title: "MCP server failed to connect", - message: `${server.name}: ${status.error}`, + title: `MCP server failed: ${server.name}`, + message: "Open MCPs to view details.", }) } }) diff --git a/packages/tui/src/component/dialog-mcp.tsx b/packages/tui/src/component/dialog-mcp.tsx index 004e4a6e15..003c207be0 100644 --- a/packages/tui/src/component/dialog-mcp.tsx +++ b/packages/tui/src/component/dialog-mcp.tsx @@ -1,12 +1,17 @@ import { createEffect, createMemo, createSignal, onMount, Show } from "solid-js" -import { createStore } from "solid-js/store" import { useData } from "../context/data" import { pipe, sortBy } from "remeda" -import { DialogSelect, type DialogSelectRef } from "../ui/dialog-select" +import { DialogSelect } from "../ui/dialog-select" import { useDialog } from "../ui/dialog" import { useTheme, type Theme } from "../context/theme" -import { TextAttributes } from "@opentui/core" +import { TextAttributes, type ScrollBoxRenderable } from "@opentui/core" import type { McpServer } from "@opencode-ai/sdk/v2" +import { useClipboard } from "../context/clipboard" +import { useToast } from "../ui/toast" +import { useKeyboard, useTerminalDimensions } from "@opentui/solid" +import { useTuiConfig } from "../config" +import { getScrollAcceleration } from "../util/scroll" +import { useBindings } from "../keymap" // Sort by how much attention a server needs: auth prompts first, then failures, // then healthy servers, and intentionally-off servers last. @@ -31,9 +36,8 @@ export function DialogMcp() { const data = useData() const dialog = useDialog() const { theme } = useTheme() - const [expanded, setExpanded] = createStore>({}) const [focused, setFocused] = createSignal() - const [, setRef] = createSignal>() + const [detail, setDetail] = createSignal() onMount(() => { dialog.setSize("large") @@ -66,9 +70,6 @@ export function DialogMcp() { {meta.icon} {meta.label} ), - details: meta.error && expanded[server.name] ? [meta.error] : undefined, - detailsColor: theme.error, - detailsWrap: true, } }), ) @@ -79,24 +80,103 @@ export function DialogMcp() { return server ? statusMeta(server.status, theme).error : undefined }) + const open = (name: string | undefined) => { + const server = servers().find((entry) => entry.name === name) + if (!server || !statusMeta(server.status, theme).error) return + setDetail(server) + } + return ( - setFocused(option.value as string)} - onSelect={(option) => { - const name = option.value as string - const server = servers().find((entry) => entry.name === name) - if (!server || !statusMeta(server.status, theme).error) return - setExpanded(name, (open) => !open) - }} - footer={ - - enter to {expanded[focused()!] ? "hide" : "view"} error - - } - /> + + setFocused(option.value as string)} + onSelect={(option) => open(option.value as string)} + footer={ + + enter to view error + + } + /> + } + > + {(server) => setDetail()} />} + + + ) +} + +function DialogMcpError(props: { server: McpServer; onBack: () => void }) { + const dialog = useDialog() + const clipboard = useClipboard() + const toast = useToast() + const { theme } = useTheme() + const dimensions = useTerminalDimensions() + const tuiConfig = useTuiConfig() + const [copied, setCopied] = createSignal(false) + const error = () => statusMeta(props.server.status, theme).error ?? "Unknown MCP connection error" + const height = createMemo(() => Math.max(3, Math.floor(dimensions().height / 2) - 5)) + let scroll: ScrollBoxRenderable | undefined + + onMount(() => dialog.setSize("large")) + + const copy = () => { + if (!clipboard.write) return + void clipboard + .write(error()) + .then(() => setCopied(true)) + .catch(toast.error) + } + + useBindings(() => ({ + bindings: [{ key: "escape", desc: "Back to MCP servers", group: "Dialog", cmd: props.onBack }], + })) + + useKeyboard((event) => { + if (event.name === "c") return copy() + if (event.name === "up") return scroll?.scrollBy(-1) + if (event.name === "down") return scroll?.scrollBy(1) + if (event.name === "pageup") return scroll?.scrollBy(-height()) + if (event.name === "pagedown") return scroll?.scrollBy(height()) + if (event.name === "home") return scroll?.scrollTo(0) + if (event.name === "end" && scroll) return scroll.scrollTo(scroll.scrollHeight) + }) + + return ( + + + + MCP / {props.server.name} + + + esc back + + + ✗ Failed + + (scroll = element)} + height={height()} + scrollbarOptions={{ visible: false }} + scrollAcceleration={getScrollAcceleration(tuiConfig)} + > + + {error()} + + + + + ↑↓ scroll + + {copied() ? "✓ copied" : "c copy details"} + + + ) } From e2faeb84e528514c4ff4c5848deff0541568f3c2 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 3 Jul 2026 22:37:42 -0400 Subject: [PATCH 39/82] fix(core): tolerate minimal FSWatcher typings (#35264) --- packages/core/src/filesystem/watcher.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/core/src/filesystem/watcher.ts b/packages/core/src/filesystem/watcher.ts index 2febe93b76..9a72903d84 100644 --- a/packages/core/src/filesystem/watcher.ts +++ b/packages/core/src/filesystem/watcher.ts @@ -89,9 +89,11 @@ const layer = Layer.effect( type: "update", } satisfies Update) }) - subscription.on("error", (error) => - Effect.runFork(Effect.logError("watcher callback failed", { path: target, error })), - ) + if ("on" in subscription && typeof subscription.on === "function") { + subscription.on("error", (error: unknown) => + Effect.runFork(Effect.logError("watcher callback failed", { path: target, error })), + ) + } return { unsubscribe: () => Promise.resolve(subscription.close()) } }) : subscribeDirectory(native, backend, directory, ignore, pubsub) From afe3ebbc35731131893b98893e8fadfbcf4562dd Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Fri, 3 Jul 2026 23:12:06 -0400 Subject: [PATCH 40/82] fix(core): bust external plugin import cache --- packages/core/src/config/plugin/external.ts | 19 +++++- packages/core/test/config/plugin.test.ts | 73 +++++++++++++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/packages/core/src/config/plugin/external.ts b/packages/core/src/config/plugin/external.ts index c67f67d481..29a63396a9 100644 --- a/packages/core/src/config/plugin/external.ts +++ b/packages/core/src/config/plugin/external.ts @@ -3,6 +3,7 @@ export * as ConfigExternalPlugin from "./external" import type { Plugin as EffectPlugin } from "@opencode-ai/plugin/v2/effect" import type { Plugin as PromisePlugin } from "@opencode-ai/plugin/v2/promise" import { Effect, Schema, Stream } from "effect" +import { createRequire } from "node:module" import path from "path" import { fileURLToPath, pathToFileURL } from "url" import { Config } from "../../config" @@ -35,6 +36,9 @@ const PluginPackage = Schema.Struct({ module: Schema.optional(Schema.String), }) +let importGeneration = 0 +const moduleCache = createRequire(import.meta.url).cache + export const Plugin = define({ id: "config-plugin", effect: Effect.fn(function* (ctx) { @@ -106,7 +110,7 @@ export const Plugin = define({ : (yield* npm.add(ref.package)).entrypoint if (!entrypoint) return yield* Effect.log({ msg: "loading plugin", id: ref.package, entrypoint }) - const mod = yield* Effect.promise(() => import(entrypoint)) + const mod = yield* Effect.promise(() => import(cacheBust(entrypoint))) const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default const plugin = "effect" in value ? value : PluginPromise.fromPromise(value) return { @@ -114,7 +118,11 @@ export const Plugin = define({ effect: (host: Parameters[0]) => plugin.effect({ ...host, options: ref.options ?? {} }), } - }).pipe(Effect.catchCause(() => Effect.succeed(undefined))), + }).pipe( + Effect.catchCause((cause) => + Effect.logError("failed to load plugin", { package: ref.package, cause }).pipe(Effect.as(undefined)), + ), + ), ).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined))) }) const reconcile = Effect.fn("ConfigExternalPlugin.reconcile")(function* () { @@ -137,6 +145,13 @@ export const Plugin = define({ }), }) +function cacheBust(entrypoint: string) { + const url = path.isAbsolute(entrypoint) ? pathToFileURL(entrypoint) : new URL(entrypoint) + if (url.protocol === "file:") delete moduleCache[fileURLToPath(url)] + url.searchParams.set("opencode-reload", String(++importGeneration)) + return url.href +} + const resolvePackageEntrypoint = Effect.fnUntraced(function* (fs: FSUtil.Interface, directory: string) { const pkg = yield* fs.readJson(path.join(directory, "package.json")).pipe( Effect.flatMap(Schema.decodeUnknownEffect(PluginPackage)), diff --git a/packages/core/test/config/plugin.test.ts b/packages/core/test/config/plugin.test.ts index b72a62df8a..8a28077c3e 100644 --- a/packages/core/test/config/plugin.test.ts +++ b/packages/core/test/config/plugin.test.ts @@ -1,15 +1,19 @@ +import fs from "fs/promises" import path from "path" import { describe, expect } from "bun:test" +import { Config as ConfigSchema } from "@opencode-ai/schema/config" import { Effect, Schema } from "effect" import { AgentV2 } from "@opencode-ai/core/agent" import { Config } from "@opencode-ai/core/config" import { ConfigExternalPlugin } from "@opencode-ai/core/config/plugin/external" +import { EventV2 } from "@opencode-ai/core/event" import { FSUtil } from "@opencode-ai/core/fs-util" import { Location } from "@opencode-ai/core/location" import { Npm } from "@opencode-ai/core/npm" import { PluginV2 } from "@opencode-ai/core/plugin" import { PluginHost } from "@opencode-ai/core/plugin/host" import { AbsolutePath } from "@opencode-ai/core/schema" +import { tmpdir } from "../fixture/tmpdir" import { testEffect } from "../lib/effect" import { PluginTestLayer } from "../plugin/fixture" @@ -240,6 +244,49 @@ describe("ConfigExternalPlugin", () => { }) }), ) + + it.live("reloads changed plugin source from the same entrypoint", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => + Effect.gen(function* () { + const plugins = yield* PluginV2.Service + const agents = yield* AgentV2.Service + const events = yield* EventV2.Service + const fsUtil = yield* FSUtil.Service + const location = yield* Location.Service + const npm = yield* Npm.Service + const host = yield* PluginHost.make(plugins) + const plugin = path.join(tmp.path, "plugin.ts") + const config = Config.Service.of({ + entries: () => + Effect.succeed([ + new Config.Document({ + type: "document", + info: decode({ plugins: [plugin] }), + }), + ]), + }) + + yield* Effect.promise(() => fs.writeFile(plugin, pluginSource("First source"))) + yield* ConfigExternalPlugin.Plugin.effect(host).pipe( + Effect.provideService(PluginV2.Service, plugins), + Effect.provideService(FSUtil.Service, fsUtil), + Effect.provideService(Location.Service, location), + Effect.provideService(Npm.Service, npm), + Effect.provideService(Config.Service, config), + ) + expect((yield* waitForAgent(agents, "hot-reload"))?.description).toBe("First source") + + yield* Effect.promise(() => fs.writeFile(plugin, pluginSource("Second source"))) + yield* events.publish(ConfigSchema.Event.Updated, {}) + expect(yield* waitForAgentDescription(agents, "hot-reload", "Second source")).toBe(true) + }), + ), + ), + ) }) const waitForAgent = Effect.fnUntraced(function* (agents: AgentV2.Interface, id: string) { @@ -250,3 +297,29 @@ const waitForAgent = Effect.fnUntraced(function* (agents: AgentV2.Interface, id: } return yield* Effect.die(`Timed out waiting for agent ${id}`) }) + +const waitForAgentDescription = Effect.fnUntraced(function* ( + agents: AgentV2.Interface, + id: string, + description: string, +) { + for (let attempt = 0; attempt < 100; attempt++) { + if ((yield* agents.get(AgentV2.ID.make(id)))?.description === description) return true + yield* Effect.sleep("10 millis") + } + return false +}) + +function pluginSource(description: string) { + return `export default { + id: "source-hot-reload", + setup: async (ctx) => { + await ctx.agent.transform((agents) => { + agents.update("hot-reload", (agent) => { + agent.description = ${JSON.stringify(description)} + agent.mode = "subagent" + }) + }) + }, +}` +} From 3baaabede864451a8152ead3654b87ccea28866f Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 3 Jul 2026 23:00:10 -0500 Subject: [PATCH 41/82] fix(core): resolve mcp header env placeholders (#35236) --- packages/core/src/config.ts | 4 +- packages/core/src/config/variable.ts | 85 ++++++++++++++++++++++++ packages/core/test/config/config.test.ts | 66 ++++++++++++++++++ 3 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/config/variable.ts diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 9e829fb740..48c380aef3 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -23,6 +23,7 @@ import { ConfigPlugin } from "./config/plugin" import { ConfigProvider } from "./config/provider" import { ConfigReference } from "./config/reference" import { ConfigToolOutput } from "./config/tool-output" +import { ConfigVariable } from "./config/variable" import { ConfigWatcher } from "./config/watcher" import { ConfigV1 } from "./v1/config/config" import { ConfigMigrateV1 } from "./v1/config/migrate" @@ -148,9 +149,10 @@ const layer = Layer.effect( const loadFile = Effect.fnUntraced(function* (filepath: string) { const text = yield* fs.readFileStringSafe(filepath) if (!text) return + const substituted = yield* ConfigVariable.substitute({ type: "path", path: filepath, text }) const errors: ParseError[] = [] - const input: unknown = parse(text, errors, { allowTrailingComma: true }) + const input: unknown = parse(substituted, errors, { allowTrailingComma: true }) if (errors.length) return const info = Option.getOrUndefined( diff --git a/packages/core/src/config/variable.ts b/packages/core/src/config/variable.ts new file mode 100644 index 0000000000..3bb1d22dd3 --- /dev/null +++ b/packages/core/src/config/variable.ts @@ -0,0 +1,85 @@ +export * as ConfigVariable from "./variable" + +import os from "os" +import path from "path" +import { Effect } from "effect" +import { FSUtil } from "../fs-util" +import { InvalidError } from "../v1/config/error" + +type ParseSource = + | { + type: "path" + path: string + } + | { + type: "virtual" + source: string + dir: string + } + +type SubstituteInput = ParseSource & { + text: string + missing?: "error" | "empty" + env?: Record +} + +/** Apply {env:VAR} and {file:path} substitutions to config text. */ +export const substitute = Effect.fn("ConfigVariable.substitute")(function* (input: SubstituteInput) { + const text = input.text.replace( + /\{env:([^}]+)\}/g, + (_, varName: string) => (input.env?.[varName] ?? process.env[varName]) || "", + ) + if (!text.includes("{file:")) return text + return yield* substituteFiles(input, text) +}) + +const substituteFiles = Effect.fnUntraced(function* (input: SubstituteInput, text: string) { + const fs = yield* FSUtil.Service + const configDir = input.type === "path" ? path.dirname(input.path) : input.dir + const configSource = input.type === "path" ? input.path : input.source + const matches = Array.from(text.matchAll(/\{file:[^}]+\}/g)) + let out = "" + let cursor = 0 + + for (const match of matches) { + const token = match[0] + const index = match.index + out += text.slice(cursor, index) + + const lineStart = text.lastIndexOf("\n", index - 1) + 1 + const prefix = text.slice(lineStart, index).trimStart() + if (prefix.startsWith("//")) { + out += token + cursor = index + token.length + continue + } + + const filePath = token.replace(/^\{file:/, "").replace(/\}$/, "") + const expandedPath = filePath.startsWith("~/") ? path.join(os.homedir(), filePath.slice(2)) : filePath + const resolvedPath = path.isAbsolute(expandedPath) ? expandedPath : path.resolve(configDir, expandedPath) + const fileContent = yield* fs.readFileString(resolvedPath).pipe( + Effect.catch((error) => { + if (input.missing === "empty") return Effect.succeed("") + + const message = `bad file reference: "${token}"` + return Effect.fail( + new InvalidError( + { + path: configSource, + message: + error._tag === "PlatformError" && error.reason._tag === "NotFound" + ? `${message} ${resolvedPath} does not exist` + : message, + }, + { cause: error }, + ), + ) + }), + ) + + out += JSON.stringify(fileContent.trim()).slice(1, -1) + cursor = index + token.length + } + + return out + text.slice(cursor) +}) diff --git a/packages/core/test/config/config.test.ts b/packages/core/test/config/config.test.ts index f3c7b20909..edf18d5add 100644 --- a/packages/core/test/config/config.test.ts +++ b/packages/core/test/config/config.test.ts @@ -292,6 +292,72 @@ describe("Config", () => { ), ) + it.live("substitutes environment variables and relative file contents", () => + Effect.acquireUseRelease( + Effect.sync(() => { + const previous = { + token: process.env.OPENCODE_TEST_MCP_TOKEN, + missing: process.env.OPENCODE_TEST_MISSING, + } + process.env.OPENCODE_TEST_MCP_TOKEN = "secret" + delete process.env.OPENCODE_TEST_MISSING + return previous + }), + () => + Effect.acquireUseRelease( + Effect.promise(() => tmpdir()), + (tmp) => + Effect.gen(function* () { + yield* Effect.promise(() => + Promise.all([ + fs.writeFile(path.join(tmp.path, "token.txt"), 'file\n"token"\n'), + fs.writeFile( + path.join(tmp.path, "opencode.jsonc"), + `{ + // Ignored reference: {file:missing.txt} + "username": "user-{env:OPENCODE_TEST_MISSING}", + "mcp": { + "servers": { + "remote": { + "type": "remote", + "url": "https://example.com/mcp", + "headers": { + "Authorization": "Bearer {env:OPENCODE_TEST_MCP_TOKEN}", + "X-Token": "{file:token.txt}" + } + } + } + } + }`, + ), + ]), + ) + + return yield* Effect.gen(function* () { + const config = yield* Config.Service + const document = (yield* config.entries()).find((entry) => entry.type === "document") + expect(document?.info.username).toBe("user-") + const remote = document?.info.mcp?.servers?.remote + expect(remote?.type).toBe("remote") + if (remote?.type !== "remote") return + expect(remote.headers).toEqual({ + Authorization: "Bearer secret", + "X-Token": 'file\n"token"', + }) + }).pipe(Effect.provide(testLayer(tmp.path))) + }), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ), + (previous) => + Effect.sync(() => { + if (previous.token === undefined) delete process.env.OPENCODE_TEST_MCP_TOKEN + else process.env.OPENCODE_TEST_MCP_TOKEN = previous.token + if (previous.missing === undefined) delete process.env.OPENCODE_TEST_MISSING + else process.env.OPENCODE_TEST_MISSING = previous.missing + }), + ), + ) + it.live("does not load legacy config.json files", () => Effect.acquireRelease( Effect.promise(() => tmpdir()), From f66c8292316184e536fc1b725469f026a0357594 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sat, 4 Jul 2026 01:54:30 -0400 Subject: [PATCH 42/82] Revert "fix(core): bust external plugin import cache" This reverts commit afe3ebbc35731131893b98893e8fadfbcf4562dd. --- packages/core/src/config/plugin/external.ts | 19 +----- packages/core/test/config/plugin.test.ts | 73 --------------------- 2 files changed, 2 insertions(+), 90 deletions(-) diff --git a/packages/core/src/config/plugin/external.ts b/packages/core/src/config/plugin/external.ts index 29a63396a9..c67f67d481 100644 --- a/packages/core/src/config/plugin/external.ts +++ b/packages/core/src/config/plugin/external.ts @@ -3,7 +3,6 @@ export * as ConfigExternalPlugin from "./external" import type { Plugin as EffectPlugin } from "@opencode-ai/plugin/v2/effect" import type { Plugin as PromisePlugin } from "@opencode-ai/plugin/v2/promise" import { Effect, Schema, Stream } from "effect" -import { createRequire } from "node:module" import path from "path" import { fileURLToPath, pathToFileURL } from "url" import { Config } from "../../config" @@ -36,9 +35,6 @@ const PluginPackage = Schema.Struct({ module: Schema.optional(Schema.String), }) -let importGeneration = 0 -const moduleCache = createRequire(import.meta.url).cache - export const Plugin = define({ id: "config-plugin", effect: Effect.fn(function* (ctx) { @@ -110,7 +106,7 @@ export const Plugin = define({ : (yield* npm.add(ref.package)).entrypoint if (!entrypoint) return yield* Effect.log({ msg: "loading plugin", id: ref.package, entrypoint }) - const mod = yield* Effect.promise(() => import(cacheBust(entrypoint))) + const mod = yield* Effect.promise(() => import(entrypoint)) const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default const plugin = "effect" in value ? value : PluginPromise.fromPromise(value) return { @@ -118,11 +114,7 @@ export const Plugin = define({ effect: (host: Parameters[0]) => plugin.effect({ ...host, options: ref.options ?? {} }), } - }).pipe( - Effect.catchCause((cause) => - Effect.logError("failed to load plugin", { package: ref.package, cause }).pipe(Effect.as(undefined)), - ), - ), + }).pipe(Effect.catchCause(() => Effect.succeed(undefined))), ).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined))) }) const reconcile = Effect.fn("ConfigExternalPlugin.reconcile")(function* () { @@ -145,13 +137,6 @@ export const Plugin = define({ }), }) -function cacheBust(entrypoint: string) { - const url = path.isAbsolute(entrypoint) ? pathToFileURL(entrypoint) : new URL(entrypoint) - if (url.protocol === "file:") delete moduleCache[fileURLToPath(url)] - url.searchParams.set("opencode-reload", String(++importGeneration)) - return url.href -} - const resolvePackageEntrypoint = Effect.fnUntraced(function* (fs: FSUtil.Interface, directory: string) { const pkg = yield* fs.readJson(path.join(directory, "package.json")).pipe( Effect.flatMap(Schema.decodeUnknownEffect(PluginPackage)), diff --git a/packages/core/test/config/plugin.test.ts b/packages/core/test/config/plugin.test.ts index 8a28077c3e..b72a62df8a 100644 --- a/packages/core/test/config/plugin.test.ts +++ b/packages/core/test/config/plugin.test.ts @@ -1,19 +1,15 @@ -import fs from "fs/promises" import path from "path" import { describe, expect } from "bun:test" -import { Config as ConfigSchema } from "@opencode-ai/schema/config" import { Effect, Schema } from "effect" import { AgentV2 } from "@opencode-ai/core/agent" import { Config } from "@opencode-ai/core/config" import { ConfigExternalPlugin } from "@opencode-ai/core/config/plugin/external" -import { EventV2 } from "@opencode-ai/core/event" import { FSUtil } from "@opencode-ai/core/fs-util" import { Location } from "@opencode-ai/core/location" import { Npm } from "@opencode-ai/core/npm" import { PluginV2 } from "@opencode-ai/core/plugin" import { PluginHost } from "@opencode-ai/core/plugin/host" import { AbsolutePath } from "@opencode-ai/core/schema" -import { tmpdir } from "../fixture/tmpdir" import { testEffect } from "../lib/effect" import { PluginTestLayer } from "../plugin/fixture" @@ -244,49 +240,6 @@ describe("ConfigExternalPlugin", () => { }) }), ) - - it.live("reloads changed plugin source from the same entrypoint", () => - Effect.acquireRelease( - Effect.promise(() => tmpdir()), - (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), - ).pipe( - Effect.flatMap((tmp) => - Effect.gen(function* () { - const plugins = yield* PluginV2.Service - const agents = yield* AgentV2.Service - const events = yield* EventV2.Service - const fsUtil = yield* FSUtil.Service - const location = yield* Location.Service - const npm = yield* Npm.Service - const host = yield* PluginHost.make(plugins) - const plugin = path.join(tmp.path, "plugin.ts") - const config = Config.Service.of({ - entries: () => - Effect.succeed([ - new Config.Document({ - type: "document", - info: decode({ plugins: [plugin] }), - }), - ]), - }) - - yield* Effect.promise(() => fs.writeFile(plugin, pluginSource("First source"))) - yield* ConfigExternalPlugin.Plugin.effect(host).pipe( - Effect.provideService(PluginV2.Service, plugins), - Effect.provideService(FSUtil.Service, fsUtil), - Effect.provideService(Location.Service, location), - Effect.provideService(Npm.Service, npm), - Effect.provideService(Config.Service, config), - ) - expect((yield* waitForAgent(agents, "hot-reload"))?.description).toBe("First source") - - yield* Effect.promise(() => fs.writeFile(plugin, pluginSource("Second source"))) - yield* events.publish(ConfigSchema.Event.Updated, {}) - expect(yield* waitForAgentDescription(agents, "hot-reload", "Second source")).toBe(true) - }), - ), - ), - ) }) const waitForAgent = Effect.fnUntraced(function* (agents: AgentV2.Interface, id: string) { @@ -297,29 +250,3 @@ const waitForAgent = Effect.fnUntraced(function* (agents: AgentV2.Interface, id: } return yield* Effect.die(`Timed out waiting for agent ${id}`) }) - -const waitForAgentDescription = Effect.fnUntraced(function* ( - agents: AgentV2.Interface, - id: string, - description: string, -) { - for (let attempt = 0; attempt < 100; attempt++) { - if ((yield* agents.get(AgentV2.ID.make(id)))?.description === description) return true - yield* Effect.sleep("10 millis") - } - return false -}) - -function pluginSource(description: string) { - return `export default { - id: "source-hot-reload", - setup: async (ctx) => { - await ctx.agent.transform((agents) => { - agents.update("hot-reload", (agent) => { - agent.description = ${JSON.stringify(description)} - agent.mode = "subagent" - }) - }) - }, -}` -} From 8e0856c43bf7143cc646cccd8e3c512f49e6c8bc Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sat, 4 Jul 2026 01:58:17 -0400 Subject: [PATCH 43/82] fix(core): disable external plugin hot reload --- packages/core/src/config/plugin/external.ts | 21 ++------------------- packages/core/test/config/reload.test.ts | 10 +++------- 2 files changed, 5 insertions(+), 26 deletions(-) diff --git a/packages/core/src/config/plugin/external.ts b/packages/core/src/config/plugin/external.ts index c67f67d481..70271dec23 100644 --- a/packages/core/src/config/plugin/external.ts +++ b/packages/core/src/config/plugin/external.ts @@ -2,7 +2,7 @@ export * as ConfigExternalPlugin from "./external" import type { Plugin as EffectPlugin } from "@opencode-ai/plugin/v2/effect" import type { Plugin as PromisePlugin } from "@opencode-ai/plugin/v2/promise" -import { Effect, Schema, Stream } from "effect" +import { Effect, Schema } from "effect" import path from "path" import { fileURLToPath, pathToFileURL } from "url" import { Config } from "../../config" @@ -42,7 +42,6 @@ export const Plugin = define({ const fs = yield* FSUtil.Service const location = yield* Location.Service const npm = yield* Npm.Service - const active = new Set() const load = Effect.fn("ConfigExternalPlugin.load")(function* () { const configured: { package: string; options?: Record }[] = [] @@ -117,23 +116,7 @@ export const Plugin = define({ }).pipe(Effect.catchCause(() => Effect.succeed(undefined))), ).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined))) }) - const reconcile = Effect.fn("ConfigExternalPlugin.reconcile")(function* () { - const plugins = yield* load() - const next = new Set(plugins.map((plugin) => plugin.id)) - for (const id of active) { - if (!next.has(id)) yield* ctx.plugin.remove(id) - } - for (const plugin of plugins) yield* ctx.plugin.add(plugin) - active.clear() - for (const id of next) active.add(id) - }) - - yield* reconcile() - yield* ctx.event.subscribe().pipe( - Stream.filter((event) => event.type === "config.updated"), - Stream.runForEach(() => reconcile()), - Effect.forkScoped({ startImmediately: true }), - ) + for (const plugin of yield* load()) yield* ctx.plugin.add(plugin) }), }) diff --git a/packages/core/test/config/reload.test.ts b/packages/core/test/config/reload.test.ts index 0ee2f0467e..3550bddb95 100644 --- a/packages/core/test/config/reload.test.ts +++ b/packages/core/test/config/reload.test.ts @@ -27,7 +27,7 @@ const decode = Schema.decodeUnknownSync(Config.Info) const document = path.join(import.meta.dir, "opencode.json") describe("config plugin reloads", () => { - it.live("reloads every config-backed domain", () => + it.live("reloads config-backed domains without reloading external plugins", () => Effect.gen(function* () { const agents = yield* AgentV2.Service const catalog = yield* Catalog.Service @@ -69,8 +69,7 @@ describe("config plugin reloads", () => { (yield* commands.get("second"))?.description === "Second command" && (yield* references.list()).some((reference) => reference.name === "second") && (yield* catalog.provider.get(ProviderV2.ID.make("first"))) === undefined && - (yield* catalog.provider.get(ProviderV2.ID.make("second"))) !== undefined && - (yield* agents.get(AgentV2.ID.make("configured")))?.description === "Second plugin" + (yield* catalog.provider.get(ProviderV2.ID.make("second"))) !== undefined ) }), ) @@ -81,10 +80,7 @@ describe("config plugin reloads", () => { expect( (yield* skills.sources()).some((source) => source.type === "directory" && source.path === "/skills/second"), ).toBe(true) - - entries = [config("second")] - yield* events.publish(ConfigSchema.Event.Updated, {}) - yield* waitUntil(agents.get(AgentV2.ID.make("configured")).pipe(Effect.map((agent) => agent === undefined))) + expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("First plugin") }).pipe(Effect.provideService(Global.Service, Global.Service.of(Global.make()))), ) }) From a15afbe8f21fb60ec9167e140c5619df86903b9a Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sat, 4 Jul 2026 02:04:58 -0400 Subject: [PATCH 44/82] bye bye orchestrator --- .opencode/plugins/orchestrator.ts | 36 ------------------------------- 1 file changed, 36 deletions(-) delete mode 100644 .opencode/plugins/orchestrator.ts diff --git a/.opencode/plugins/orchestrator.ts b/.opencode/plugins/orchestrator.ts deleted file mode 100644 index 10d4173ff5..0000000000 --- a/.opencode/plugins/orchestrator.ts +++ /dev/null @@ -1,36 +0,0 @@ -export default { - id: "Orchestrator", - setup: async (ctx) => { - await ctx.agent.transform((agents) => { - agents.update("orchestrator", (agent) => { - agent.description = "Coordinates work by delegating implementation tasks to the minion subagent." - agent.mode = "primary" - agent.system = [ - "You are Orchestrator, the primary coordinating agent for this repository. You do meta work only: you coordinate, brief, and synthesize — you do not perform the work itself.", - "Delegate ALL actual work to the minion subagent — implementation, exploration, discovery, searching the codebase, reading files to understand a problem, and even trivial one-line edits. Task size is never a reason to do it yourself, and there is no 'final integration' exception.", - "You are not hard-banned from tools, but direct tool use is reserved for coordination overhead: a quick peek to phrase a better brief, a fast read-only check to verify a minion's reported result, or answering a question about coordination state. If a tool call is producing the answer or the artifact the user asked for, that call belongs to a minion, not you.", - "Exploration is work. If the user asks how something works or where something lives, delegate the investigation to a minion rather than exploring yourself.", - "Always start minion subagents in the background. Even if you have nothing else to coordinate right now, the user may assign you new work while a Minion runs, and you must stay free to receive it. Never poll; you will be notified when they finish.", - "Give each minion a clear, self-contained brief: the goal, constraints, expected output, and any files or context already known from the user or previous minion reports.", - "Synthesize minion results, decide next steps, and report back concisely.", - ].join("\n") - }) - - agents.update("minion", (agent) => { - agent.description = "Subagent that executes focused tasks delegated by Orchestrator." - agent.mode = "subagent" - agent.model = { providerID: "opencode", id: "glm-5.2" } - agent.system = [ - "You are minion, a focused execution subagent for this repository.", - "Complete the specific task delegated to you by Orchestrator using the available tools.", - "Inspect the codebase before making assumptions, make targeted changes when requested, and verify your work when feasible.", - "Follow the repository's AGENTS.md conventions: respect the style guide, run `bun typecheck` from the affected package directory after code changes, never run tests from the repo root, and do not modify packages/opencode unless the task explicitly says V1 work.", - "If the task is ambiguous or you hit a blocker, stop and report your findings instead of guessing.", - "Keep your final response concise: summarize what you did, list important files changed or findings, and call out blockers or verification gaps.", - "Do not delegate to other subagents; execute the assigned work yourself.", - ].join("\n") - agent.permissions.push({ action: "subagent", resource: "*", effect: "deny" }) - }) - }) - }, -} From 5b44e5bf41ed3503b8d1633762e7fd42aa4a0f03 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 10:54:34 -0400 Subject: [PATCH 45/82] test(core): release shell test locations (#35271) --- packages/core/test/tool-shell.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 6fd43ee2a2..217414aa2c 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -171,9 +171,11 @@ const withSession = (directory: string, body: (registry: ToolRegistry.I }) const locations = yield* LocationServiceMap.Service const locationLayer = locations.get(location) - const registry = yield* ToolRegistry.Service.pipe(Effect.provide(locationLayer)) - yield* waitForTool(registry, ShellTool.name) - return yield* body(registry).pipe(Effect.provide(locationLayer)) + return yield* Effect.gen(function* () { + const registry = yield* ToolRegistry.Service + yield* waitForTool(registry, ShellTool.name) + return yield* body(registry) + }).pipe(Effect.provide(locationLayer), Effect.ensuring(locations.invalidate(location))) }) describe("ShellTool", () => { From 62af66a74fb9b01bbcea1fe5369ccd24c56085ff Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 10:58:56 -0400 Subject: [PATCH 46/82] fix(tui): distinguish variant switch notices (#35315) --- AGENTS.md | 1 + .../client/src/promise/generated/types.ts | 3 ++ packages/core/src/session.ts | 6 ++-- packages/core/src/session/message-updater.ts | 32 +++++++++++++------ packages/core/src/session/projector.ts | 14 +++++++- packages/core/test/session-create.test.ts | 6 ++-- packages/core/test/session-projector.test.ts | 3 ++ packages/schema/src/session-message.ts | 1 + packages/sdk/js/src/v2/gen/types.gen.ts | 2 ++ packages/tui/src/context/data.tsx | 11 +++++++ packages/tui/src/routes/session/index.tsx | 3 +- packages/tui/src/util/model.ts | 5 +-- packages/tui/test/cli/tui/data.test.tsx | 20 ++++++++++-- packages/tui/test/util/model.test.ts | 12 +++++++ 14 files changed, 98 insertions(+), 21 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8c72fe65a8..0ea4055ce2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -151,6 +151,7 @@ const table = sqliteTable("session", { ## V2 Session Core +- Keep durable events minimal: record irreducible new facts and do not repeat state derivable by folding the ordered aggregate history. Enrich projections and read models with previous or derived state when consumers need self-contained views. - Keep durable prompt admission separate from model execution. `SessionV2.prompt(...)` admits one durable `session_input` row before scheduling advisory `SessionExecution.wake(sessionID)` unless `resume: false` requests admit-only behavior. The serialized runner promotes admitted inputs into visible user messages at safe boundaries. - Reusing a Session ID adopts the existing Session. Reusing a prompt message ID reconciles an exact retry only when Session, prompt, and delivery mode match; conflicting reuse fails. Historical projected prompts lazily synthesize promoted inbox records during exact retry. - Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; idle or missing interruption is a no-op. diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index ff06963036..151f0ff03f 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -928,6 +928,7 @@ export type SessionContextOutput = { readonly time: { readonly created: number } readonly type: "model-switched" readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } + readonly previous?: { readonly id: string; readonly providerID: string; readonly variant?: string } } | { readonly id: string @@ -1621,6 +1622,7 @@ export type SessionMessageOutput = { readonly time: { readonly created: number } readonly type: "model-switched" readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } + readonly previous?: { readonly id: string; readonly providerID: string; readonly variant?: string } } | { readonly id: string @@ -1820,6 +1822,7 @@ export type MessageListOutput = { readonly time: { readonly created: number } readonly type: "model-switched" readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } + readonly previous?: { readonly id: string; readonly providerID: string; readonly variant?: string } } | { readonly id: string diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index e8928a7520..05d64c8efb 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -540,7 +540,8 @@ const layer = Layer.effect( const started = yield* Effect.gen(function* () { const shell = yield* Shell.Service return yield* shell.create({ command: input.command, cwd: session.location.directory }) - }).pipe(Effect.provide(locations.get(session.location))) + }) + .pipe(Effect.provide(locations.get(session.location))) yield* events.publish( SessionEvent.Shell.Started, { @@ -563,8 +564,7 @@ const layer = Layer.effect( .pipe(Effect.catchTag("Shell.NotFoundError", () => Effect.succeed(missingShellOutput()))) : missingShellOutput() return { shell: terminal.info, output } - }) - .pipe(Effect.provide(locations.get(session.location))) + }).pipe(Effect.provide(locations.get(session.location))) yield* events.publish(SessionEvent.Shell.Ended, { sessionID: input.sessionID, shell: completed.shell, diff --git a/packages/core/src/session/message-updater.ts b/packages/core/src/session/message-updater.ts index 3658e67c0f..2a8ade7b1a 100644 --- a/packages/core/src/session/message-updater.ts +++ b/packages/core/src/session/message-updater.ts @@ -8,6 +8,7 @@ export type MemoryState = { } export interface Adapter { + readonly getModel: () => Effect.Effect readonly getCurrentAssistant: () => Effect.Effect readonly getAssistant: ( messageID: SessionMessage.ID, @@ -29,6 +30,15 @@ export function memory(state: MemoryState): Adapter { const latestAssistantIndex = () => state.messages.findLastIndex((message) => message.type === "assistant") return { + getModel() { + return Effect.sync( + () => + state.messages.findLast( + (message): message is SessionMessage.ModelSelected | SessionMessage.Assistant => + message.type === "model-switched" || message.type === "assistant", + )?.model, + ) + }, getCurrentAssistant() { return Effect.sync(() => { const index = latestAssistantIndex() @@ -115,15 +125,19 @@ export function update(adapter: Adapter, event: SessionEvent.Event) { ) }, "session.model.selected": (event) => { - return adapter.appendMessage( - SessionMessage.ModelSelected.make({ - id: SessionMessage.ID.fromEvent(event.id), - type: "model-switched", - metadata: event.metadata, - model: event.data.model, - time: { created: event.created }, - }), - ) + return Effect.gen(function* () { + const previous = yield* adapter.getModel() + yield* adapter.appendMessage( + SessionMessage.ModelSelected.make({ + id: SessionMessage.ID.fromEvent(event.id), + type: "model-switched", + metadata: event.metadata, + model: event.data.model, + previous, + time: { created: event.created }, + }), + ) + }) }, "session.moved": () => Effect.void, "session.renamed": () => Effect.void, diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index 746e448a3b..f265aa6fc9 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -5,6 +5,7 @@ import { DateTime, Effect, Layer, Schema } from "effect" import { Database } from "../database/database" import { EventV2 } from "../event" import { makeGlobalNode } from "../effect/app-node" +import { ModelV2 } from "../model" import { SessionEvent } from "./event" import { SessionV1 } from "../v1/session" import { WorkspaceTable } from "../control-plane/workspace.sql" @@ -356,6 +357,17 @@ function run(db: DatabaseService, event: MessageEvent) { } const appendMessage = (message: SessionMessage.Message) => insertMessage(db, event, message) const adapter: SessionMessageUpdater.Adapter = { + getModel() { + return db + .select({ model: SessionTable.model }) + .from(SessionTable) + .where(eq(SessionTable.id, event.data.sessionID)) + .get() + .pipe( + Effect.orDie, + Effect.map((row) => (row?.model ? Schema.decodeUnknownSync(ModelV2.Ref)(row.model) : undefined)), + ) + }, getCurrentAssistant() { return Effect.gen(function* () { // A newer step supersedes stale incomplete rows; never resume an older assistant projection. @@ -570,13 +582,13 @@ const layer = Layer.effectDiscard( ) yield* events.project(SessionEvent.ModelSelected, (event) => Effect.gen(function* () { + yield* run(db, event) yield* db .update(SessionTable) .set({ model: event.data.model, time_updated: DateTime.toEpochMillis(event.created) }) .where(eq(SessionTable.id, event.data.sessionID)) .run() .pipe(Effect.orDie) - yield* run(db, event) }), ) yield* events.project(SessionEvent.Renamed, (event) => diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index d18c2c8e81..5408030c1a 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -562,9 +562,9 @@ describe("SessionV2.create", () => { yield* session.switchModel({ sessionID: created.id, model }) expect(yield* session.get(created.id)).toMatchObject({ model }) - expect( - Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)), - ).toMatchObject([{ type: "session.model.selected", data: { model } }]) + const events = Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)) + expect(events).toMatchObject([{ type: "session.model.selected" }]) + expect(events[0]?.data).toEqual({ sessionID: created.id, model }) }), ) diff --git a/packages/core/test/session-projector.test.ts b/packages/core/test/session-projector.test.ts index c17b979076..1d77303d43 100644 --- a/packages/core/test/session-projector.test.ts +++ b/packages/core/test/session-projector.test.ts @@ -34,6 +34,7 @@ const sessionsLayer = AppNodeBuilder.build(SessionV2.node, [[SessionExecution.no const sessionID = SessionV2.ID.make("ses_projector_test") const created = DateTime.makeUnsafe(0) const model = { id: ModelV2.ID.make("model"), providerID: ProviderV2.ID.make("provider") } +const previousModel = { ...model, variant: ModelV2.VariantID.make("medium") } const encodeMessage = Schema.encodeSync(SessionMessage.Message) const assistantRow = ( @@ -238,6 +239,7 @@ describe("SessionProjector", () => { directory: "/project", title: "test", version: "test", + model: previousModel, }) .run() .pipe(Effect.orDie) @@ -337,6 +339,7 @@ describe("SessionProjector", () => { text: "synthetic context", metadata: { source: "projector-test" }, }) + expect(messages.find((message) => message.type === "model-switched")).toMatchObject({ previous: previousModel }) expect(messages.find((message) => message.type === "shell")).toMatchObject({ shell: { command: "pwd", status: "exited", exit: 0 }, output: { output: "/project", truncated: false }, diff --git a/packages/schema/src/session-message.ts b/packages/schema/src/session-message.ts index e3d81a31d7..c9f39193a5 100644 --- a/packages/schema/src/session-message.ts +++ b/packages/schema/src/session-message.ts @@ -44,6 +44,7 @@ export const ModelSelected = Schema.Struct({ ...Base, type: Schema.Literal("model-switched"), model: Model.Ref, + previous: Model.Ref.pipe(optional), }).annotate({ identifier: "Session.Message.ModelSelected" }) export interface User extends Schema.Schema.Type {} diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 524d7ea854..2b6e1d031f 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -4310,6 +4310,7 @@ export type SessionMessageModelSelected = { } type: "model-switched" model: ModelRef + previous?: ModelRef } export type SessionMessageUser = { @@ -7985,6 +7986,7 @@ export type SessionMessageModelSelected2 = { } type: "model-switched" model: ModelRef2 + previous?: ModelRef2 } export type SessionMessageUser2 = { diff --git a/packages/tui/src/context/data.tsx b/packages/tui/src/context/data.tsx index 0ed464e561..5815bc2f20 100644 --- a/packages/tui/src/context/data.tsx +++ b/packages/tui/src/context/data.tsx @@ -235,6 +235,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ case "session.model.selected": if (store.session.info[event.data.sessionID]) setStore("session", "info", event.data.sessionID, "model", event.data.model) + if (!store.session.message[event.data.sessionID]) break message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { id: messageIDFromEvent(event.id), @@ -243,6 +244,16 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ time: { created: event.created }, }) }) + void sdk.api.session + .message({ sessionID: event.data.sessionID, messageID: messageIDFromEvent(event.id) }) + .then((item) => { + message.update(event.data.sessionID, (draft, index) => { + const position = index.get(item.id) + if (position === undefined) return message.append(draft, index, mutable(item)) + draft[position] = mutable(item) + }) + }) + .catch((error) => console.error("Failed to load projected model switch message", error)) break case "session.renamed": if (store.session.info[event.data.sessionID]) diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index b968f13cd3..604cd95e89 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -1231,7 +1231,8 @@ function SessionSwitchMessageV2(props: { message: SessionMessage }) { const { theme } = useTheme() const text = () => { if (props.message.type === "agent-switched") return `Switched agent to ${props.message.agent}` - if (props.message.type === "model-switched") return switchLabel(props.message.model, ctx.models()) + if (props.message.type === "model-switched") + return switchLabel(props.message.model, ctx.models(), props.message.previous) return "" } return {text()} diff --git a/packages/tui/src/util/model.ts b/packages/tui/src/util/model.ts index 64d8636406..275112d33d 100644 --- a/packages/tui/src/util/model.ts +++ b/packages/tui/src/util/model.ts @@ -34,11 +34,12 @@ export function formatRef(model: { providerID: string; id: string; variant?: str export function switchLabel( model: { providerID: string; id: string; variant?: string }, models?: readonly { providerID: string; id: string; name: string }[], + previous?: { providerID: string; id: string; variant?: string }, ) { + if (previous?.providerID === model.providerID && previous.id === model.id) + return `Switched variant to ${model.variant ?? "default"}` const display = models?.find((item) => item.providerID === model.providerID && item.id === model.id)?.name if (display === undefined) return `Switched model to ${formatRef(model)}` - // Variant-only switches publish the same model id; without the variant the - // notice would look like a redundant model switch. const variant = model.variant && model.variant !== "default" ? ` (${model.variant})` : "" return `Switched model to ${display}${variant}` } diff --git a/packages/tui/test/cli/tui/data.test.tsx b/packages/tui/test/cli/tui/data.test.tsx index 0587662dc3..1bc975b9bc 100644 --- a/packages/tui/test/cli/tui/data.test.tsx +++ b/packages/tui/test/cli/tui/data.test.tsx @@ -767,7 +767,18 @@ test("adds and dismisses question requests from live events", async () => { test("settles pending tools when a live failure arrives", async () => { const events = createEventStream() - const calls = createFetch(undefined, events) + const calls = createFetch((url) => { + if (url.pathname === "/api/session/session-1/message/msg_model_1") + return json({ + data: { + id: "msg_model_1", + type: "model-switched", + previous: { id: "model-1", providerID: "provider-1", variant: "medium" }, + model: { id: "model-1", providerID: "provider-1", variant: "high" }, + time: { created: 0 }, + }, + }) + }, events) let sync!: ReturnType let ready!: () => void const mounted = new Promise((resolve) => { @@ -808,7 +819,7 @@ test("settles pending tools when a live failure arrives", async () => { durable: durable("session-1", 1), data: { sessionID: "session-1", - model: { id: "model-1", providerID: "provider-1" }, + model: { id: "model-1", providerID: "provider-1", variant: "high" }, }, }) emitEvent(events, { @@ -895,6 +906,11 @@ test("settles pending tools when a live failure arrives", async () => { "model-switched", "assistant", ]) + expect(sync.session.message.get("session-1", "msg_model_1")).toMatchObject({ + type: "model-switched", + previous: { id: "model-1", providerID: "provider-1", variant: "medium" }, + model: { id: "model-1", providerID: "provider-1", variant: "high" }, + }) } finally { app.renderer.destroy() } diff --git a/packages/tui/test/util/model.test.ts b/packages/tui/test/util/model.test.ts index ad4ea87c88..888b102013 100644 --- a/packages/tui/test/util/model.test.ts +++ b/packages/tui/test/util/model.test.ts @@ -34,4 +34,16 @@ describe("util.model", () => { "Switched model to removed/gone/high", ) }) + + test("distinguishes variant-only switches from model switches", () => { + const previous = { providerID: "openai", id: "gpt-5.5", variant: "medium" } + + expect(switchLabel({ ...previous, variant: "high" }, undefined, previous)).toBe("Switched variant to high") + expect(switchLabel({ providerID: "openai", id: "gpt-5.5" }, undefined, previous)).toBe( + "Switched variant to default", + ) + expect(switchLabel({ providerID: "anthropic", id: "sonnet", variant: "high" }, undefined, previous)).toBe( + "Switched model to anthropic/sonnet/high", + ) + }) }) From 9daa4d85a427a67cd43917d5580dd837bca69e2d Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 11:05:41 -0400 Subject: [PATCH 47/82] fix(tui): reconcile session state after reconnect (#35262) --- .opencode/skills/debug-opencode/SKILL.md | 19 ++++ packages/tui/src/context/data.tsx | 68 +++++++++----- packages/tui/src/routes/session/rows.ts | 43 +++++++-- packages/tui/test/cli/tui/data.test.tsx | 111 ++++++++++++++++++++++- 4 files changed, 207 insertions(+), 34 deletions(-) diff --git a/.opencode/skills/debug-opencode/SKILL.md b/.opencode/skills/debug-opencode/SKILL.md index fd7cae09d2..01e0ca3523 100644 --- a/.opencode/skills/debug-opencode/SKILL.md +++ b/.opencode/skills/debug-opencode/SKILL.md @@ -104,6 +104,25 @@ bun dev api --param key=value - If no compatible background server is registered, `bun dev api` starts one through the daemon service. Use `bun dev service status`, `bun dev service restart`, and `bun dev service stop` when you need explicit lifecycle control. - Prefer raw method/path calls for quick server debugging and operation IDs when exercising documented OpenAPI routes with path or query parameters. +## Auditing installed `opencode2` sessions + +Installed next-channel sessions normally use `~/.local/share/opencode/opencode-next.db` and `~/.local/share/opencode/log/opencode.log`; `OPENCODE_DB` can override the database. Before calling `opencode2 api`, inspect `~/.local/state/opencode/service.json` because the command may start a daemon when none is healthy. + +For a supplied `ses_...` ID, compare three sources: + +- `opencode2 api get /api/session/active` and the Session/message endpoints for live server state. +- The database's ordered `event` rows for durable history. +- `packages/tui/src/context/data.tsx` and the relevant route for client projection and rendering. + +Locate an uncertain database without modifying it: + +```bash +SESSION=ses_... +for db in ~/.local/share/opencode/*.db; do + sqlite3 "file:$db?mode=ro" "select 1 from session where id='$SESSION' limit 1" 2>/dev/null | grep -q 1 && printf '%s\n' "$db" +done +``` + ## Logs - Log files live under `~/.local/share/opencode/log/`. In a local/dev checkout the active file is `opencode-local.log`; `opencode.log` is used for non-local (released) channel installs. Both are append-only, shared across every CLI and server process on the machine. diff --git a/packages/tui/src/context/data.tsx b/packages/tui/src/context/data.tsx index 5815bc2f20..82a7150c9e 100644 --- a/packages/tui/src/context/data.tsx +++ b/packages/tui/src/context/data.tsx @@ -20,7 +20,7 @@ import type { SkillV2Info, V2Event, } from "@opencode-ai/sdk/v2" -import { createStore, produce } from "solid-js/store" +import { createStore, produce, reconcile } from "solid-js/store" import { createSimpleContext } from "./helper" import { useSDK } from "./sdk" import { createSignal, onCleanup } from "solid-js" @@ -100,8 +100,15 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ directory: process.cwd(), }) const messageIndex = new Map>() + let connectionGeneration = 0 + let statusChanges: Set | undefined let bootstrapping: Promise | undefined + function setSessionStatus(sessionID: string, status: DataSessionStatus) { + statusChanges?.add(sessionID) + setStore("session", "status", sessionID, status) + } + const message = { update(sessionID: string, fn: (messages: SessionMessage[], index: Map) => void) { setStore( @@ -260,16 +267,19 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ setStore("session", "info", event.data.sessionID, "title", event.data.title) break case "session.prompt.promoted": { - setStore("session", "status", event.data.sessionID, "running") + setSessionStatus(event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { const position = index.get(event.data.inputID) - const existing = position === undefined ? undefined : draft[position] - if (existing?.type === "user") { + if (position === undefined) return + const existing = draft[position] + if (existing?.type === "user" && existing.metadata?.queued === true) { existing.time.created = event.created - if (existing.metadata?.queued === true) { - delete existing.metadata.queued - if (Object.keys(existing.metadata).length === 0) existing.metadata = undefined - } + delete existing.metadata.queued + if (Object.keys(existing.metadata).length === 0) existing.metadata = undefined + draft.splice(position, 1) + draft.push(existing) + index.clear() + draft.forEach((message, indexValue) => index.set(message.id, indexValue)) return } }) @@ -311,7 +321,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) break case "session.shell.started": - setStore("session", "status", event.data.sessionID, "running") + setSessionStatus(event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { message.append(draft, index, { id: messageIDFromEvent(event.id), @@ -322,7 +332,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) break case "session.shell.ended": - setStore("session", "status", event.data.sessionID, "idle") + setSessionStatus(event.data.sessionID, "idle") message.update(event.data.sessionID, (draft) => { const match = message.shell(draft, event.data.shell.id) if (!match) return @@ -332,7 +342,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) break case "session.step.started": - setStore("session", "status", event.data.sessionID, "running") + setSessionStatus(event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { if (index.has(event.data.assistantMessageID)) return const currentAssistant = message.activeAssistant(draft) @@ -349,7 +359,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ }) break case "session.step.ended": - setStore("session", "status", event.data.sessionID, "running") + setSessionStatus(event.data.sessionID, "running") message.update(event.data.sessionID, (draft, index) => { const currentAssistant = message.assistant(draft, index, event.data.assistantMessageID) if (!currentAssistant) return @@ -529,10 +539,10 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ break case "session.retried": case "session.compaction.started": - setStore("session", "status", event.data.sessionID, "running") + setSessionStatus(event.data.sessionID, "running") break case "session.execution.settled": - setStore("session", "status", event.data.sessionID, "idle") + setSessionStatus(event.data.sessionID, "idle") break case "session.revert.staged": if (store.session.info[event.data.sessionID]) @@ -869,15 +879,6 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ ) for (const session of response.data) registerSession(session.id) }), - sdk.api.session - .active() - .then((active) => - setStore( - "session", - "status", - Object.fromEntries(Object.keys(active.data).map((sessionID) => [sessionID, "running" as const])), - ), - ), result.location.refresh(), result.location.agent.refresh(), result.location.integration.refresh(), @@ -899,9 +900,30 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ return bootstrapping } + function refreshActive() { + const generation = ++connectionGeneration + const changed = new Set() + statusChanges = changed + void sdk.api.session + .active() + .then((active) => { + if (generation !== connectionGeneration) return + const status: Record = Object.fromEntries( + Object.keys(active.data).map((sessionID) => [sessionID, "running" as const]), + ) + for (const sessionID of changed) status[sessionID] = store.session.status[sessionID] + setStore("session", "status", reconcile(status)) + }) + .catch(() => undefined) + .finally(() => { + if (statusChanges === changed) statusChanges = undefined + }) + } + onCleanup( sdk.event.listen(({ details }) => { if (details.type === "server.connected") { + refreshActive() void bootstrap() return } diff --git a/packages/tui/src/routes/session/rows.ts b/packages/tui/src/routes/session/rows.ts index 783b2805f4..fc0b38b1ad 100644 --- a/packages/tui/src/routes/session/rows.ts +++ b/packages/tui/src/routes/session/rows.ts @@ -28,23 +28,24 @@ export function createSessionRows(sessionID: Accessor) { function reduce() { const messages = data.session.message.list(sessionID()) const boundary = revertBoundary() - return reduceSessionRows(boundary ? messages.filter((message) => message.id < boundary) : messages) + const rows = reduceSessionRows(boundary ? messages.filter((message) => message.id < boundary) : messages) + partitionPending(rows, pendingPermissions()) + return rows } - createEffect(() => { - const pending = new Set( + function pendingPermissions() { + return new Set( (data.session.permission.list(sessionID()) ?? []).flatMap((request) => request.source?.type === "tool" ? [request.source.callID] : [], ), ) + } + + createEffect(() => { + const pending = pendingPermissions() setRows( produce((draft) => { - draft.forEach((row) => { - if (row.type !== "group") return - const refs = [...row.refs, ...row.pending] - row.refs = refs.filter((ref) => !pending.has(ref.partID)) - row.pending = refs.filter((ref) => pending.has(ref.partID)) - }) + partitionPending(draft, pending) }), ) }) @@ -69,6 +70,20 @@ export function createSessionRows(sessionID: Accessor) { }), ) + createEffect( + on( + () => + data.session.message + .list(sessionID()) + .flatMap((message) => + message.type === "user" + ? [{ id: message.id, created: message.time.created, queued: message.metadata?.queued === true }] + : [], + ), + () => setRows(reconcile(reduce())), + ), + ) + const appendMessage = (messageID: string) => setRows( produce((draft) => { @@ -134,7 +149,6 @@ export function createSessionRows(sessionID: Accessor) { } const subscriptions = [ data.on("session.prompt.admitted", input), - data.on("session.prompt.promoted", input), data.on("session.context.updated", message), data.on("session.synthetic", (event) => { if (event.data.sessionID === sessionID() && event.data.description?.trim()) @@ -225,6 +239,15 @@ function completePrevious(rows: SessionRow[], index = rows.length) { if (previous?.type === "group") previous.completed = true } +function partitionPending(rows: SessionRow[], pending: Set) { + rows.forEach((row) => { + if (row.type !== "group") return + const refs = [...row.refs, ...row.pending] + row.refs = refs.filter((ref) => !pending.has(ref.partID)) + row.pending = refs.filter((ref) => pending.has(ref.partID)) + }) +} + function exploration(name: string) { return ["read", "glob", "grep"].includes(name.toLowerCase()) } diff --git a/packages/tui/test/cli/tui/data.test.tsx b/packages/tui/test/cli/tui/data.test.tsx index 1bc975b9bc..d9e82c2d3c 100644 --- a/packages/tui/test/cli/tui/data.test.tsx +++ b/packages/tui/test/cli/tui/data.test.tsx @@ -8,6 +8,7 @@ import { onMount } from "solid-js" import { ProjectProvider } from "../../../src/context/project" import { SDKProvider } from "../../../src/context/sdk" import { DataProvider, useData } from "../../../src/context/data" +import { createSessionRows } from "../../../src/routes/session/rows" import { createApi, createClient, createEventStream, createFetch, directory, json } from "../../fixture/tui-sdk" import { TestTuiContexts } from "../../fixture/tui-environment" @@ -109,12 +110,20 @@ test("refreshes resources into reactive getters", async () => { test("reconnects the event stream and bootstraps fresh data", async () => { const events = createEventStream() - const requests = { event: 0, model: 0 } + const requests = { active: 0, event: 0, model: 0 } + let resolveActive!: (response: Response) => void const calls = createFetch((url) => { if (url.pathname === "/api/event") { requests.event++ return events.v2() } + if (url.pathname === "/api/session/active") { + requests.active++ + if (requests.active === 1) return json({ data: { "session-stale": { type: "running" } }, watermarks: {} }) + return new Promise((resolve) => { + resolveActive = resolve + }) + } if (url.pathname !== "/api/model") return requests.model++ return json({ @@ -157,6 +166,7 @@ test("reconnects the event stream and bootstraps fresh data", async () => { try { await wait(() => data.location.model.list()?.[0]?.id === "model-1") + await wait(() => data.session.status("session-stale") === "running") expect(data.connection.status()).toBe("connected") expect(data.connection.attempt()).toBe(0) @@ -165,7 +175,25 @@ test("reconnects the event stream and bootstraps fresh data", async () => { expect(data.connection.attempt()).toBe(1) expect(data.connection.error()).toBe("Event stream disconnected") + await wait(() => requests.active === 2 && data.connection.status() === "connected", 4000) + emitEvent(events, { + id: "evt_step_started_after_reconnect", + created: 1, + type: "session.step.started", + durable: durable("session-new"), + data: { + sessionID: "session-new", + assistantMessageID: "message-new", + agent: "build", + model: { id: "model", providerID: "provider" }, + }, + }) + await wait(() => data.session.status("session-new") === "running") + resolveActive(json({ data: {}, watermarks: {} })) + await wait(() => data.location.model.list()?.[0]?.id === "model-2", 4000) + await wait(() => data.session.status("session-stale") === "idle") + expect(data.session.status("session-new")).toBe("running") expect(requests.event).toBe(2) expect(data.connection.status()).toBe("connected") expect(data.connection.attempt()).toBe(0) @@ -175,6 +203,87 @@ test("reconnects the event stream and bootstraps fresh data", async () => { } }) +test("completes exploration when a queued prompt is promoted", async () => { + const events = createEventStream() + const sessionID = "session-promotion" + const calls = createFetch((url) => { + if (url.pathname === `/api/session/${sessionID}/message`) return json({ data: [], cursor: {} }) + }, events) + let rows!: ReturnType + + function Probe() { + rows = createSessionRows(() => sessionID) + return + } + + const app = await testRender(() => ( + + + + + + + + + + )) + + try { + emitEvent(events, { + id: "evt_step_started", + created: 1, + type: "session.step.started", + durable: durable(sessionID), + data: { + sessionID, + assistantMessageID: "message-assistant", + agent: "build", + model: { id: "model", providerID: "provider" }, + }, + }) + emitEvent(events, { + id: "evt_tool_started", + created: 2, + type: "session.tool.input.started", + durable: durable(sessionID, 1), + data: { + sessionID, + assistantMessageID: "message-assistant", + callID: "call-read", + name: "read", + }, + }) + await wait(() => rows.some((row) => row.type === "group" && !row.completed)) + + emitEvent(events, { + id: "evt_prompt_admitted", + created: 3, + type: "session.prompt.admitted", + durable: durable(sessionID, 2), + data: { + sessionID, + inputID: "message-user", + prompt: { text: "Continue" }, + delivery: "steer", + }, + }) + await wait(() => rows.at(-1)?.type === "message") + expect(rows.find((row) => row.type === "group")?.completed).toBe(false) + + emitEvent(events, { + id: "evt_prompt_promoted", + created: 4, + type: "session.prompt.promoted", + durable: durable(sessionID, 3), + data: { sessionID, inputID: "message-user" }, + }) + await wait(() => rows.find((row) => row.type === "group")?.completed === true) + expect(rows.at(-1)).toEqual({ type: "message", messageID: "message-user" }) + } finally { + app.renderer.destroy() + } +}) + test("connectedOnce is false until first connect and persists across disconnect", async () => { const encoder = new TextEncoder() let stream: ReadableStreamDefaultController | undefined From 610e618bc5419b2d646adfeca185fd6fef0e803f Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 11:33:45 -0400 Subject: [PATCH 48/82] fix(tui): clear completed background shell status (#35320) --- packages/core/src/tool/shell.ts | 8 +++++--- packages/core/test/tool-shell.test.ts | 8 ++++++-- packages/tui/src/routes/session/index.tsx | 15 +++++++++++---- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/packages/core/src/tool/shell.ts b/packages/core/src/tool/shell.ts index cb7edb3113..c3644e4810 100644 --- a/packages/core/src/tool/shell.ts +++ b/packages/core/src/tool/shell.ts @@ -18,8 +18,9 @@ export const DEFAULT_TIMEOUT_MS = 2 * 60 * 1_000 export const MAX_TIMEOUT_MS = 10 * 60 * 1_000 export const MAX_CAPTURE_BYTES = 1024 * 1024 -const BACKGROUND_STARTED = - "The command has not completed; it is now running in the background." +const BACKGROUND_STARTED = "The command was moved to the background." +const BACKGROUND_INSTRUCTION = + "You will be notified automatically when the command finishes. DO NOT sleep, poll, or proactively check on its progress." export const Input = Schema.Struct({ command: Schema.String.annotate({ description: "Shell command string to execute" }), @@ -54,10 +55,11 @@ const Output = Schema.Struct({ type Output = typeof Output.Type const modelOutput = (output: Output): string | undefined => { - if (output.status === "running") return undefined const warnings = output.warnings?.length ? `\n\nWarnings:\n${output.warnings.map((warning) => `- ${warning}`).join("\n")}` : "" + if (output.status === "running") + return `${warnings.trimStart()}${warnings ? "\n\n" : ""}${BACKGROUND_INSTRUCTION}` if (output.timeout) return `${warnings.trimStart()}${warnings ? "\n\n" : ""}Command timed out before completion.` return `${warnings.trimStart()}${warnings ? "\n\n" : ""}Command exited with code ${output.exit}.` } diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 217414aa2c..117eba27f1 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -480,9 +480,13 @@ describe("ShellTool", () => { const structured = settled.output?.structured as Record | undefined const shellID = typeof structured?.shellID === "string" ? structured.shellID : undefined expect(settled.output?.structured).toMatchObject({ truncated: false }) - expect(settled.output?.content[0]).toMatchObject({ + expect(settled.output?.content[0]).toEqual({ type: "text", - text: expect.stringContaining("running in the background"), + text: "The command was moved to the background.", + }) + expect(settled.output?.content[1]).toMatchObject({ + type: "text", + text: expect.stringContaining("DO NOT sleep, poll"), }) expect(shellID).toStartWith("sh_") diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index 604cd95e89..dd9fd34d07 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -2080,14 +2080,16 @@ function Shell(props: ToolProps) { return request?.source?.type === "tool" && request.source.callID === props.part.id }) const color = createMemo(() => (permission() ? theme.warning : theme.text)) - const isRunning = createMemo(() => { - if (props.part.state.status === "running") return true - const shellID = stringValue(props.metadata.shellID) - return Boolean(shellID && data.shell.get(shellID)) + const shellID = createMemo(() => stringValue(props.metadata.shellID)) + const backgroundRunning = createMemo(() => { + const id = shellID() + return Boolean(id && data.shell.get(id)) }) + const isRunning = createMemo(() => props.part.state.status === "running" || backgroundRunning()) const command = createMemo(() => stringValue(props.input.command)) const output = createMemo(() => { if (props.part.state.status === "pending") return "" + if (shellID()) return "" const content = props.part.state.content[0] return stripAnsi(content?.type === "text" ? content.text.trim() : "") }) @@ -2130,6 +2132,11 @@ function Shell(props: ToolProps) { + + + Backgrounded + + {expanded() ? "Click to collapse" : "Click to expand"} From 945d1c8cb28b66732dfaefffc9631af78f83a8a0 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 11:55:05 -0400 Subject: [PATCH 49/82] fix(core): bound recursive file watching (#35323) --- packages/core/src/filesystem/ignore.ts | 2 +- packages/core/test/filesystem/ignore.test.ts | 29 ++++++++++++++++++ packages/core/test/filesystem/watcher.test.ts | 30 +++++++++++++++---- packages/web/src/content/docs/config.mdx | 4 +-- 4 files changed, 57 insertions(+), 8 deletions(-) diff --git a/packages/core/src/filesystem/ignore.ts b/packages/core/src/filesystem/ignore.ts index 2f5f52bf25..4d88eb5e87 100644 --- a/packages/core/src/filesystem/ignore.ts +++ b/packages/core/src/filesystem/ignore.ts @@ -45,7 +45,7 @@ const FILES = [ "**/.nyc_output/**", ] -export const PATTERNS = [...FILES, ...FOLDERS] +export const PATTERNS = [...FILES, ...FOLDERS, `**/{${Array.from(FOLDERS).join(",")}}/**`] export function match(filepath: string, opts?: { extra?: string[]; whitelist?: string[] }) { for (const pattern of opts?.whitelist || []) { diff --git a/packages/core/test/filesystem/ignore.test.ts b/packages/core/test/filesystem/ignore.test.ts index 87b07eacb9..d734ed16b2 100644 --- a/packages/core/test/filesystem/ignore.test.ts +++ b/packages/core/test/filesystem/ignore.test.ts @@ -1,5 +1,7 @@ import { expect, test } from "bun:test" import { Ignore } from "@opencode-ai/core/filesystem/ignore" +// @ts-ignore +import { createWrapper } from "@parcel/watcher/wrapper" test("match nested and non-nested", () => { expect(Ignore.match("node_modules/index.js")).toBe(true) @@ -8,3 +10,30 @@ test("match nested and non-nested", () => { expect(Ignore.match("node_modules/bar")).toBe(true) expect(Ignore.match("node_modules/bar/")).toBe(true) }) + +test("parcel patterns ignore built-in folders at any depth", async () => { + let ignoreGlobs: string[] = [] + const watcher = createWrapper({ + subscribe: async ( + _directory: string, + _callback: (...args: unknown[]) => unknown, + options: { ignoreGlobs?: string[] }, + ) => { + ignoreGlobs = options.ignoreGlobs ?? [] + }, + }) + await watcher.subscribe("/tmp/project", () => {}, { ignore: Ignore.PATTERNS }) + const patterns = ignoreGlobs.map((source) => new RegExp(source)) + + for (const path of [ + "nested/node_modules", + "nested/node_modules/package/index.js", + "nested/.git", + "nested/.git/HEAD", + "nested/dist", + "nested/dist/index.js", + ]) { + expect(patterns.some((pattern) => pattern.test(path))).toBe(true) + } + expect(patterns.some((pattern) => pattern.test("nested/src/index.ts"))).toBe(false) +}) diff --git a/packages/core/test/filesystem/watcher.test.ts b/packages/core/test/filesystem/watcher.test.ts index 323ba4c4ba..360c4c70db 100644 --- a/packages/core/test/filesystem/watcher.test.ts +++ b/packages/core/test/filesystem/watcher.test.ts @@ -2,7 +2,7 @@ import { $ } from "bun" import { describe, expect } from "bun:test" import fs from "fs/promises" import path from "path" -import { Deferred, Duration, Effect, Fiber, Layer, Option, Stream } from "effect" +import { Deferred, Duration, Effect, Fiber, Layer, Option, Schedule, Stream } from "effect" import { Config } from "@opencode-ai/core/config" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -149,12 +149,14 @@ describeWatcher("LocationWatcher", () => { const update = yield* watcher .subscribe({ path: target, type: "file" }) .pipe(Stream.take(1), Stream.runHead, Effect.forkScoped({ startImmediately: true })) - yield* Effect.yieldNow - yield* fs.writeFileString(sibling, "sibling") - yield* fs.writeFileString(target, "target") + const writes = yield* Effect.suspend(() => fs.writeFileString(target, `target-${Math.random()}`)).pipe( + Effect.repeat(Schedule.spaced("10 millis")), + Effect.forkScoped, + ) + const event = yield* Fiber.join(update).pipe(Effect.ensuring(Fiber.interrupt(writes))) - expect((yield* Fiber.join(update)).valueOrUndefined?.path).toBe(target) + expect(event.valueOrUndefined?.path).toBe(target) }).pipe(Effect.provide(AppNodeBuilder.build(Watcher.node))), ), ) @@ -197,6 +199,24 @@ describeWatcher("LocationWatcher", () => { ), ) + it.live("ignores dependency, VCS, and build directories at any depth", () => + withTmp((directory) => + Effect.gen(function* () { + const afs = yield* FSUtil.Service + yield* ready(directory) + const roots = ["node_modules", ".git", "dist"].map((name) => path.join(directory, "nested", name)) + const files = roots.map((root) => path.join(root, "package", "index.js")) + yield* noUpdate( + (event) => roots.some((root) => event.file === root || event.file.startsWith(`${root}${path.sep}`)), + Effect.forEach(files, (file) => afs.writeWithDirs(file, "ignored"), { + concurrency: "unbounded", + discard: true, + }), + ) + }), + ), + ) + it.live("cleanup stops publishing events", () => Effect.gen(function* () { const events = yield* EventV2.Service diff --git a/packages/web/src/content/docs/config.mdx b/packages/web/src/content/docs/config.mdx index c1a69f5a86..fbf41d4fe9 100644 --- a/packages/web/src/content/docs/config.mdx +++ b/packages/web/src/content/docs/config.mdx @@ -749,12 +749,12 @@ You can configure file watcher ignore patterns through the `watcher` option. { "$schema": "https://opencode.ai/config.json", "watcher": { - "ignore": ["node_modules/**", "dist/**", ".git/**"] + "ignore": ["**/generated/**"] } } ``` -Patterns follow glob syntax. Use this to exclude noisy directories from file watching. +Patterns follow glob syntax. Common dependency, VCS, build, and cache directories are ignored automatically at any depth. --- From 8f4b62eb49d52d6930f24895a2ccecac955a2125 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 12:12:56 -0400 Subject: [PATCH 50/82] fix(core): report missing search paths (#35337) --- packages/core/src/tool/glob.ts | 15 ++++- packages/core/src/tool/grep.ts | 16 ++++- packages/core/test/tool-search.test.ts | 87 ++++++++++++++++++++++++++ 3 files changed, 115 insertions(+), 3 deletions(-) create mode 100644 packages/core/test/tool-search.test.ts diff --git a/packages/core/src/tool/glob.ts b/packages/core/src/tool/glob.ts index d4412ae302..dcea52120f 100644 --- a/packages/core/src/tool/glob.ts +++ b/packages/core/src/tool/glob.ts @@ -5,6 +5,7 @@ import type { PluginContext } from "@opencode-ai/plugin/v2/effect" import { Effect, Schema } from "effect" import path from "path" import { FileSystem } from "../filesystem" +import { FSUtil } from "../fs-util" import { Location } from "../location" import { Ripgrep } from "../ripgrep" import { RelativePath } from "../schema" @@ -36,6 +37,7 @@ export const toModelOutput = (output: ModelOutput) => { export const Plugin = { id: "core-glob-tool", effect: Effect.fn("GlobTool.Plugin")(function* (ctx: PluginContext) { + const fs = yield* FSUtil.Service const ripgrep = yield* Ripgrep.Service const location = yield* Location.Service const permission = yield* PermissionV2.Service @@ -71,6 +73,13 @@ export const Plugin = { source: { type: "tool", messageID: context.assistantMessageID, callID: context.toolCallID }, }) const cwd = path.resolve(location.directory, input.path ?? ".") + yield* fs + .stat(cwd) + .pipe( + Effect.catchReason("PlatformError", "NotFound", () => + Effect.fail(new ToolFailure({ message: `Search path does not exist: ${input.path ?? "."}` })), + ), + ) return yield* ripgrep .glob({ cwd, @@ -88,7 +97,11 @@ export const Plugin = { ), ) }).pipe( - Effect.mapError(() => new ToolFailure({ message: `Unable to find files matching ${input.pattern}` })), + Effect.mapError((error) => + error instanceof ToolFailure + ? error + : new ToolFailure({ message: `Unable to find files matching ${input.pattern}` }), + ), ), }), }) diff --git a/packages/core/src/tool/grep.ts b/packages/core/src/tool/grep.ts index e525606609..35ac537c91 100644 --- a/packages/core/src/tool/grep.ts +++ b/packages/core/src/tool/grep.ts @@ -91,7 +91,13 @@ export const Plugin = { source: { type: "tool", messageID: context.assistantMessageID, callID: context.toolCallID }, }) const target = path.resolve(location.directory, input.path ?? ".") - const info = yield* fs.stat(target).pipe(Effect.catch(() => Effect.succeed(undefined))) + const info = yield* fs + .stat(target) + .pipe( + Effect.catchReason("PlatformError", "NotFound", () => + Effect.fail(new ToolFailure({ message: `Search path does not exist: ${input.path ?? "."}` })), + ), + ) return yield* ripgrep .grep({ cwd: info?.type === "Directory" ? target : path.dirname(target), @@ -121,7 +127,13 @@ export const Plugin = { ), ), ) - }).pipe(Effect.mapError(() => new ToolFailure({ message: `Unable to grep for ${input.pattern}` }))), + }).pipe( + Effect.mapError((error) => + error instanceof ToolFailure + ? error + : new ToolFailure({ message: `Unable to grep for ${input.pattern}` }), + ), + ), }), }) .pipe(Effect.orDie) diff --git a/packages/core/test/tool-search.test.ts b/packages/core/test/tool-search.test.ts new file mode 100644 index 0000000000..b1bad34102 --- /dev/null +++ b/packages/core/test/tool-search.test.ts @@ -0,0 +1,87 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" +import { makeLocationNode } from "@opencode-ai/core/effect/app-node" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Location } from "@opencode-ai/core/location" +import { PermissionV2 } from "@opencode-ai/core/permission" +import { Ripgrep } from "@opencode-ai/core/ripgrep" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { SessionV2 } from "@opencode-ai/core/session" +import { GlobTool } from "@opencode-ai/core/tool/glob" +import { GrepTool } from "@opencode-ai/core/tool/grep" +import { ToolRegistry } from "@opencode-ai/core/tool/registry" +import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" +import { location } from "./fixture/location" +import { tmpdir } from "./fixture/tmpdir" +import { testEffect } from "./lib/effect" +import { executeTool, registerToolPlugin, toolIdentity } from "./lib/tool" + +const globToolNode = makeLocationNode({ + name: "test/glob-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(GlobTool.Plugin)), + deps: [ToolRegistry.toolsNode, FSUtil.node, Ripgrep.node, Location.node, PermissionV2.node], +}) +const grepToolNode = makeLocationNode({ + name: "test/grep-tool-plugin", + layer: Layer.effectDiscard(registerToolPlugin(GrepTool.Plugin)), + deps: [ToolRegistry.toolsNode, FSUtil.node, Ripgrep.node, Location.node, PermissionV2.node], +}) +const permission = Layer.succeed( + PermissionV2.Service, + PermissionV2.Service.of({ + assert: () => Effect.void, + ask: () => Effect.die("unused"), + reply: () => Effect.die("unused"), + get: () => Effect.die("unused"), + forSession: () => Effect.die("unused"), + list: () => Effect.die("unused"), + }), +) +const sessionID = SessionV2.ID.make("ses_search_tool_test") + +const withTools = (directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect) => + Effect.gen(function* () { + return yield* body(yield* ToolRegistry.Service) + }).pipe( + Effect.provide( + AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, globToolNode, grepToolNode]), [ + [ + Location.node, + Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make(directory) }))), + ], + [PermissionV2.node, permission], + [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig], + ]), + ), + ) + +const call = (name: "glob" | "grep", input: unknown) => ({ + sessionID, + ...toolIdentity, + call: { type: "tool-call" as const, id: `call-${name}`, name, input }, +}) + +const it = testEffect(Layer.empty) + +describe("search tools", () => { + for (const name of ["glob", "grep"] as const) { + it.live(`${name} reports a missing search path`, () => + Effect.acquireUseRelease( + Effect.promise(() => tmpdir()), + (tmp) => + withTools(tmp.path, (registry) => + Effect.gen(function* () { + const result = yield* executeTool( + registry, + call(name, { path: "missing", pattern: name === "glob" ? "*" : "needle" }), + ) + expect(result).toEqual({ type: "error", value: "Search path does not exist: missing" }) + }), + ), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ), + ) + } +}) From c590e276398bfd3fbadbf2113144e0bece9bfaa8 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sat, 4 Jul 2026 11:49:24 -0500 Subject: [PATCH 51/82] feat(core): add grouped and deferred tool registration (#35232) --- packages/core/src/plugin/host.ts | 2 +- packages/core/src/tool/AGENTS.md | 3 +- packages/core/src/tool/mcp.ts | 111 +++++++++++++------------- packages/core/src/tool/registry.ts | 70 +++++++++++----- packages/core/src/tool/tools.ts | 3 + packages/core/test/mcp.test.ts | 5 ++ packages/core/test/plugin.test.ts | 32 ++++++++ packages/plugin/src/v2/effect/tool.ts | 23 +++++- 8 files changed, 170 insertions(+), 79 deletions(-) diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index d25555eb37..585c254a78 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -302,7 +302,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Int }), }, tool: { - register: (input) => tools.register(input), + register: (input, options) => tools.register(input, options), execute: { before: (callback) => toolHooks.hook.before((event) => { diff --git a/packages/core/src/tool/AGENTS.md b/packages/core/src/tool/AGENTS.md index 3719322fa1..4b427f9835 100644 --- a/packages/core/src/tool/AGENTS.md +++ b/packages/core/src/tool/AGENTS.md @@ -28,7 +28,8 @@ Leaves own resolution, permission, and side-effect ordering. Translate only expe ## Registration -Built-ins and plugin tools register through `Tools.Service.register({ [name]: tool })`. +Built-ins and plugin tools register through `Tools.Service.register({ [name]: tool })`. Registrations may provide a +group, which flattens direct model names to `_`, and may be deferred from direct model exposure. Registrations are scoped: diff --git a/packages/core/src/tool/mcp.ts b/packages/core/src/tool/mcp.ts index 571b747bab..7867fc6571 100644 --- a/packages/core/src/tool/mcp.ts +++ b/packages/core/src/tool/mcp.ts @@ -1,6 +1,5 @@ export * as McpTool from "./mcp" -import { createHash } from "node:crypto" import { ToolFailure } from "@opencode-ai/llm" import { McpEvent } from "@opencode-ai/schema/mcp-event" import { Effect, Exit, type JsonSchema, Layer, Scope, Semaphore, Stream } from "effect" @@ -11,35 +10,11 @@ import { Tool } from "./tool" import { Tools } from "./tools" import { ToolRegistry } from "./registry" -const MAX_NAME_LENGTH = 64 -const HASH_LENGTH = 8 - -const sanitize = (value: string) => value.replace(/[^A-Za-z0-9_-]/g, "_") - -// Deterministic short suffix used to keep overlong or colliding names unique and stable across restarts. -const hashSuffix = (raw: string) => "_" + createHash("sha1").update(raw).digest("hex").slice(0, HASH_LENGTH) - -const fit = (base: string, raw: string) => base.slice(0, MAX_NAME_LENGTH - HASH_LENGTH - 1) + hashSuffix(raw) - /** - * Registry/permission action name for an MCP tool: V1-compatible `_` so existing deny - * rules keep working. Sanitized to a valid tool name, prefixed when it would not start with a letter, - * and hashed down when it would exceed the 64-char limit. + * Registry and permission action name for an MCP tool. */ -export const name = (server: string, tool: string) => { - const joined = sanitize(server) + "_" + sanitize(tool) - const base = /^[A-Za-z]/.test(joined) ? joined : "mcp_" + joined - return base.length > MAX_NAME_LENGTH ? fit(base, `${server}\u0000${tool}`) : base -} - -const toContent = (part: MCP.ToolResultContent): Tool.Content => - part.type === "text" ? { type: "text", text: part.text } : { type: "file", data: part.data, mime: part.mimeType } - -const errorText = (content: ReadonlyArray) => - content - .flatMap((part) => (part.type === "text" ? [part.text] : [])) - .join("\n") - .trim() +export const name = (server: string, tool: string) => + `${server.replace(/[^a-zA-Z0-9_-]/g, "_")}_${tool.replace(/[^a-zA-Z0-9_-]/g, "_")}` export const layer = Layer.effectDiscard( Effect.gen(function* () { @@ -50,47 +25,71 @@ export const layer = Layer.effectDiscard( const lock = Semaphore.makeUnsafe(1) let current: Scope.Closeable | undefined - const make = (server: MCP.ServerName, tool: MCP.Tool) => - Tool.make({ - description: tool.description ?? "", - jsonSchema: (tool.inputSchema as JsonSchema.JsonSchema | undefined) ?? { type: "object", properties: {} }, - execute: (input) => - Effect.gen(function* () { - const result = yield* mcp.callTool({ server, name: tool.name, args: (input ?? {}) as Record }).pipe( - Effect.catchTags({ - "MCP.NotFoundError": (error) => new ToolFailure({ message: `MCP server "${error.server}" is not available` }), - "MCP.ToolCallError": (error) => new ToolFailure({ message: error.message }), - }), - ) - if (result.isError) - return yield* new ToolFailure({ message: errorText(result.content) || "MCP tool returned an error" }) - return { structured: result.structured ?? {}, content: result.content.map(toContent) } - }), - }) - // Register the current tool set under a fresh child scope, then close the previous one so the // registry never has a gap where MCP tools disappear mid-swap. const reconcile = lock.withPermit( Effect.gen(function* () { - const used = new Set() - const record: Record = {} + const groups = new Map>() for (const tool of yield* mcp.tools()) { - const initial = name(tool.server, tool.name) - const key = used.has(initial) ? fit(initial, `${tool.server}\u0000${tool.name}`) : initial - used.add(key) - record[key] = make(tool.server, tool) + const group = groups.get(tool.server) ?? {} + const schema = (tool.inputSchema ?? {}) as JsonSchema.JsonSchema + group[tool.name] = Tool.make({ + description: tool.description ?? "", + jsonSchema: { + ...schema, + type: "object", + properties: schema.properties ?? {}, + additionalProperties: false, + }, + execute: (input) => + Effect.gen(function* () { + const result = yield* mcp + .callTool({ + server: tool.server, + name: tool.name, + args: (input ?? {}) as Record, + }) + .pipe( + Effect.catchTags({ + "MCP.NotFoundError": (error) => + new ToolFailure({ message: `MCP server "${error.server}" is not available` }), + "MCP.ToolCallError": (error) => new ToolFailure({ message: error.message }), + }), + ) + if (result.isError) + return yield* new ToolFailure({ + message: + result.content + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join("\n") + .trim() || "MCP tool returned an error", + }) + return { + structured: result.structured ?? {}, + content: result.content.map((part) => + part.type === "text" + ? { type: "text" as const, text: part.text } + : { type: "file" as const, data: part.data, mime: part.mimeType }, + ), + } + }), + }) + groups.set(tool.server, group) } const next = yield* Scope.fork(scope) - yield* tools.register(record).pipe(Scope.provide(next), Effect.orDie) + yield* Effect.forEach(groups, ([group, record]) => tools.register(record, { group }), { + discard: true, + }).pipe(Scope.provide(next), Effect.orDie) if (current) yield* Scope.close(current, Exit.void) current = next }), ) yield* reconcile.pipe(Effect.forkScoped) - yield* events - .subscribe(McpEvent.ToolsChanged) - .pipe(Stream.runForEach(() => reconcile), Effect.forkScoped({ startImmediately: true })) + yield* events.subscribe(McpEvent.ToolsChanged).pipe( + Stream.runForEach(() => reconcile), + Effect.forkScoped({ startImmediately: true }), + ) }), ) diff --git a/packages/core/src/tool/registry.ts b/packages/core/src/tool/registry.ts index 1dc7478c11..dcdbb1c888 100644 --- a/packages/core/src/tool/registry.ts +++ b/packages/core/src/tool/registry.ts @@ -23,7 +23,10 @@ export type ExecuteInput = { export interface Interface { readonly materialize: (input: MaterializeInput) => Effect.Effect /** Internal registration capability exposed publicly only through Tools.Service. */ - readonly register: (tools: Readonly>) => Effect.Effect + readonly register: ( + tools: Readonly>, + options?: Tools.RegisterOptions, + ) => Effect.Effect } export interface MaterializeInput { @@ -49,7 +52,13 @@ const registryLayer = Layer.effect( Effect.gen(function* () { const resources = yield* ToolOutputStore.Service const toolHooks = yield* ToolHooks.Service - type Registration = { readonly identity: object; readonly tool: AnyTool } + type Registration = { + readonly identity: object + readonly tool: AnyTool + readonly name: string + readonly group?: string + readonly deferred: boolean + } const local = new Map>() const settleWith = Effect.fn("ToolRegistry.settle")(function* (input: ExecuteInput, advertised?: object) { @@ -73,12 +82,16 @@ const registryLayer = Layer.effect( input: input.call.input, } yield* toolHooks.runBefore(beforeEvent) - const pending = yield* settle(registration.tool, { ...input.call, input: beforeEvent.input }, { - sessionID: input.sessionID, - agent: input.agent, - assistantMessageID: input.assistantMessageID, - toolCallID: input.call.id, - }).pipe( + const pending = yield* settle( + registration.tool, + { ...input.call, input: beforeEvent.input }, + { + sessionID: input.sessionID, + agent: input.agent, + assistantMessageID: input.assistantMessageID, + toolCallID: input.call.id, + }, + ).pipe( Effect.map((output) => ({ output })), Effect.catchTag("LLM.ToolFailure", (failure) => Effect.succeed({ result: { type: "error" as const, value: failure.message } }), @@ -88,7 +101,11 @@ const registryLayer = Layer.effect( if ("result" in pending) { settlement = pending } else { - const bounded = yield* resources.bound({ sessionID: input.sessionID, toolCallID: input.call.id, output: pending.output }) + const bounded = yield* resources.bound({ + sessionID: input.sessionID, + toolCallID: input.call.id, + output: pending.output, + }) const result = ToolOutput.toResultValue(bounded.output) settlement = result.type === "error" @@ -119,20 +136,33 @@ const registryLayer = Layer.effect( }) return Service.of({ - register: Effect.fn("ToolRegistry.register")(function* (tools) { - const entries = registrationEntries(tools) + register: Effect.fn("ToolRegistry.register")(function* (tools, options) { + const entries = registrationEntries(tools, options?.group) if (entries.length === 0) return yield* Effect.uninterruptible( Effect.gen(function* () { const token = {} - for (const [name, tool] of entries) - local.set(name, [...(local.get(name) ?? []), { token, registration: { identity: {}, tool } }]) + for (const entry of entries) + local.set(entry.key, [ + ...(local.get(entry.key) ?? []), + { + token, + registration: { + identity: {}, + tool: entry.tool, + name: entry.name, + group: entry.group, + deferred: options?.deferred ?? false, + }, + }, + ]) yield* Effect.addFinalizer(() => Effect.sync(() => { - for (const [name] of entries) { - const registrations = local.get(name)?.filter((registration) => registration.token !== token) ?? [] - if (registrations.length > 0) local.set(name, registrations) - else local.delete(name) + for (const entry of entries) { + const registrations = + local.get(entry.key)?.filter((registration) => registration.token !== token) ?? [] + if (registrations.length > 0) local.set(entry.key, registrations) + else local.delete(entry.key) } }), ) @@ -149,7 +179,11 @@ const registryLayer = Layer.effect( const usePatch = input.model.provider.toLowerCase() === "openai" || input.model.id.toLowerCase().includes("gpt") for (const [name, registration] of registrations) { const wrongEditTool = name === "apply_patch" ? !usePatch : (name === "edit" || name === "write") && usePatch - if (wrongEditTool || whollyDisabled(permission(registration.tool, name), input.permissions ?? [])) + if ( + registration.deferred || + wrongEditTool || + whollyDisabled(permission(registration.tool, name), input.permissions ?? []) + ) registrations.delete(name) } return { diff --git a/packages/core/src/tool/tools.ts b/packages/core/src/tool/tools.ts index 0939ce957b..06b920a484 100644 --- a/packages/core/src/tool/tools.ts +++ b/packages/core/src/tool/tools.ts @@ -3,9 +3,12 @@ export * as Tools from "./tools" import { Context, Effect, Scope } from "effect" import { Tool } from "./tool" +export type RegisterOptions = Tool.RegisterOptions + export interface Interface { readonly register: ( tools: Readonly>, + options?: Tool.RegisterOptions, ) => Effect.Effect } diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index 15ff95a28f..7c62032784 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test" import { MCP } from "@opencode-ai/core/mcp/index" import { MCPClient } from "@opencode-ai/core/mcp/client" +import { McpTool } from "@opencode-ai/core/tool/mcp" describe("MCP errors", () => { test("expose useful messages", () => { @@ -12,3 +13,7 @@ describe("MCP errors", () => { expect(new MCPClient.ConnectError({ server: "demo", message: "offline" }).message).toBe("offline") }) }) + +test("MCP tool names match V1 sanitization", () => { + expect(McpTool.name("context 7", "resolve.library/id")).toBe("context_7_resolve_library_id") +}) diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 42f2a768ec..1a60decb0b 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -126,6 +126,38 @@ describe("PluginV2", () => { }), ) + it.effect("groups tool names and defers registrations from direct exposure", () => + Effect.gen(function* () { + const plugins = yield* PluginV2.Service + const registry = yield* ToolRegistry.Service + const tool = (description: string) => + Tool.make({ + description, + input: Schema.Struct({}), + output: Schema.Struct({ ok: Schema.Boolean }), + execute: () => Effect.succeed({ ok: true }), + }) + const plugin = define({ + id: "grouped-tools", + effect: (ctx) => + Effect.gen(function* () { + yield* ctx.tool.register({ plain: tool("Plain") }).pipe(Effect.orDie) + yield* ctx.tool.register({ "look/up": tool("Lookup") }, { group: "context 7" }).pipe(Effect.orDie) + yield* ctx.tool + .register({ search: tool("Search") }, { group: "context 7", deferred: true }) + .pipe(Effect.orDie) + }), + }) + + yield* plugins.add(PluginV2.ID.make(plugin.id), plugin.effect) + + expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toEqual([ + "plain", + "context_7_look_up", + ]) + }), + ) + it.effect("fires before/after tool hooks with mutable events around settlement", () => Effect.gen(function* () { const plugins = yield* PluginV2.Service diff --git a/packages/plugin/src/v2/effect/tool.ts b/packages/plugin/src/v2/effect/tool.ts index c25f79c58b..98efaa3ce2 100644 --- a/packages/plugin/src/v2/effect/tool.ts +++ b/packages/plugin/src/v2/effect/tool.ts @@ -186,8 +186,17 @@ export const validateName = (name: string) => ? Effect.void : Effect.fail(new RegistrationError({ name, message: `Invalid tool name: ${name}` })) -export const registrationEntries = (tools: Readonly>) => - Object.entries(tools).map(([name, tool]) => [name.replace(/[^a-zA-Z0-9_-]/g, "_"), tool] as const) +export const registrationEntries = (tools: Readonly>, group?: string) => + Object.entries(tools).map(([name, tool]) => { + const normalized = name.replace(/[^a-zA-Z0-9_-]/g, "_") + const parent = group?.replace(/[^a-zA-Z0-9_-]/g, "_") + return { + key: parent === undefined ? normalized : `${parent}_${normalized}`, + name: normalized, + group: parent, + tool, + } + }) export const withPermission = , Output extends SchemaType>( tool: Definition, @@ -235,7 +244,15 @@ export interface ToolExecuteAfterEvent { outputPaths?: ReadonlyArray } +export interface RegisterOptions { + readonly group?: string + readonly deferred?: boolean +} + export interface ToolDomain { - readonly register: (tools: Readonly>) => Effect.Effect + readonly register: ( + tools: Readonly>, + options?: RegisterOptions, + ) => Effect.Effect readonly execute: Hooks<{ before: ToolExecuteBeforeEvent; after: ToolExecuteAfterEvent }> } From b99759c7defbd7ade26ef220380888e2767995b0 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sat, 4 Jul 2026 13:03:40 -0500 Subject: [PATCH 52/82] fix(core): enforce mcp tool permissions (#35345) --- packages/core/src/tool/mcp.ts | 27 ++++++++- packages/core/test/mcp.test.ts | 108 +++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 3 deletions(-) diff --git a/packages/core/src/tool/mcp.ts b/packages/core/src/tool/mcp.ts index 7867fc6571..23d11d06a0 100644 --- a/packages/core/src/tool/mcp.ts +++ b/packages/core/src/tool/mcp.ts @@ -6,6 +6,7 @@ import { Effect, Exit, type JsonSchema, Layer, Scope, Semaphore, Stream } from " import { makeLocationNode } from "../effect/app-node" import { EventV2 } from "../event" import { MCP } from "../mcp" +import { PermissionV2 } from "../permission" import { Tool } from "./tool" import { Tools } from "./tools" import { ToolRegistry } from "./registry" @@ -21,6 +22,7 @@ export const layer = Layer.effectDiscard( const mcp = yield* MCP.Service const tools = yield* Tools.Service const events = yield* EventV2.Service + const permission = yield* PermissionV2.Service const scope = yield* Scope.Scope const lock = Semaphore.makeUnsafe(1) let current: Scope.Closeable | undefined @@ -41,8 +43,21 @@ export const layer = Layer.effectDiscard( properties: schema.properties ?? {}, additionalProperties: false, }, - execute: (input) => + execute: (input, context) => Effect.gen(function* () { + yield* permission.assert({ + action: name(tool.server, tool.name), + resources: ["*"], + save: ["*"], + metadata: {}, + sessionID: context.sessionID, + agent: context.agent, + source: { + type: "tool", + messageID: context.assistantMessageID, + callID: context.toolCallID, + }, + }) const result = yield* mcp .callTool({ server: tool.server, @@ -72,7 +87,13 @@ export const layer = Layer.effectDiscard( : { type: "file" as const, data: part.data, mime: part.mimeType }, ), } - }), + }).pipe( + Effect.mapError((error) => + error instanceof ToolFailure + ? error + : new ToolFailure({ message: `Unable to execute ${name(tool.server, tool.name)}` }), + ), + ), }) groups.set(tool.server, group) } @@ -96,5 +117,5 @@ export const layer = Layer.effectDiscard( export const node = makeLocationNode({ name: "mcp-tools", layer, - deps: [ToolRegistry.toolsNode, MCP.node, EventV2.node], + deps: [ToolRegistry.toolsNode, MCP.node, EventV2.node, PermissionV2.node], }) diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index 7c62032784..f52b223dce 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -1,7 +1,61 @@ import { describe, expect, test } from "bun:test" +import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { EventV2 } from "@opencode-ai/core/event" import { MCP } from "@opencode-ai/core/mcp/index" import { MCPClient } from "@opencode-ai/core/mcp/client" +import { PermissionV2 } from "@opencode-ai/core/permission" +import { SessionV2 } from "@opencode-ai/core/session" import { McpTool } from "@opencode-ai/core/tool/mcp" +import { ToolRegistry } from "@opencode-ai/core/tool/registry" +import { ToolOutputStore } from "@opencode-ai/core/tool-output-store" +import { Deferred, Effect, Fiber, Layer, Stream } from "effect" +import { testEffect } from "./lib/effect" +import { settleTool, toolIdentity, waitForTool } from "./lib/tool" + +let assertion: Deferred.Deferred | undefined +let decision: Effect.Effect = Effect.void +let calls = 0 + +const mcp = Layer.mock(MCP.Service, { + tools: () => + Effect.succeed([ + new MCP.Tool({ + server: MCP.ServerName.make("demo"), + name: "search", + description: "Search", + inputSchema: { type: "object", properties: {} }, + }), + ]), + callTool: (input) => + Effect.sync(() => { + calls += 1 + return new MCP.ToolResult({ + server: MCP.ServerName.make(input.server), + tool: input.name, + isError: false, + structured: { ok: true }, + content: [], + }) + }), +}) +const permissions = Layer.mock(PermissionV2.Service, { + assert: (input) => + Effect.gen(function* () { + if (!assertion) return yield* Effect.die("Permission test is not initialized") + yield* Deferred.succeed(assertion, input) + yield* decision + }), +}) +const events = Layer.mock(EventV2.Service, { subscribe: () => Stream.never }) +const it = testEffect( + AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, McpTool.node]), [ + [MCP.node, mcp], + [PermissionV2.node, permissions], + [EventV2.node, events], + [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig], + ]), +) describe("MCP errors", () => { test("expose useful messages", () => { @@ -17,3 +71,57 @@ describe("MCP errors", () => { test("MCP tool names match V1 sanitization", () => { expect(McpTool.name("context 7", "resolve.library/id")).toBe("context_7_resolve_library_id") }) + +it.effect("waits for permission before calling an MCP tool", () => + Effect.gen(function* () { + calls = 0 + assertion = yield* Deferred.make() + const permission = yield* Deferred.make() + decision = Deferred.await(permission) + const registry = yield* ToolRegistry.Service + yield* waitForTool(registry, "demo_search") + + const fiber = yield* settleTool(registry, { + sessionID: SessionV2.ID.make("ses_mcp_permission"), + ...toolIdentity, + call: { type: "tool-call", id: "call_mcp_permission", name: "demo_search", input: {} }, + }).pipe(Effect.forkScoped) + expect(yield* Deferred.await(assertion)).toEqual({ + action: "demo_search", + resources: ["*"], + save: ["*"], + metadata: {}, + sessionID: SessionV2.ID.make("ses_mcp_permission"), + agent: toolIdentity.agent, + source: { + type: "tool", + messageID: toolIdentity.assistantMessageID, + callID: "call_mcp_permission", + }, + }) + expect(calls).toBe(0) + + yield* Deferred.succeed(permission, undefined) + yield* Fiber.join(fiber) + expect(calls).toBe(1) + }), +) + +it.effect("does not call MCP when permission is rejected", () => + Effect.gen(function* () { + calls = 0 + assertion = yield* Deferred.make() + decision = Effect.fail(new PermissionV2.RejectedError()) + const registry = yield* ToolRegistry.Service + yield* waitForTool(registry, "demo_search") + + expect( + yield* settleTool(registry, { + sessionID: SessionV2.ID.make("ses_mcp_rejected"), + ...toolIdentity, + call: { type: "tool-call", id: "call_mcp_rejected", name: "demo_search", input: {} }, + }), + ).toEqual({ result: { type: "error", value: "Unable to execute demo_search" } }) + expect(calls).toBe(0) + }), +) From ba07481b59d012c9c708d092e169ec97f75309b0 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Sat, 4 Jul 2026 15:21:37 +0200 Subject: [PATCH 53/82] fix(run): restore subprocess output contracts --- .../server/routes/instance/httpapi/server.ts | 3 +- .../test/cli/run/session-data.test.ts | 93 ++++++++----------- packages/opencode/test/lib/llm-server.ts | 3 +- 3 files changed, 42 insertions(+), 57 deletions(-) diff --git a/packages/opencode/src/server/routes/instance/httpapi/server.ts b/packages/opencode/src/server/routes/instance/httpapi/server.ts index 7edefdacd4..108888d4f6 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/server.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/server.ts @@ -294,8 +294,6 @@ export function createRoutes( HttpServer.layerServices, ]), Layer.provide(Layer.succeed(CorsConfig)(corsOptions)), - Layer.provideMerge(Observability.layer), - Layer.provide(formLocationLayer), Layer.provide(sessionLocationLayer), Layer.provide(locationLayer), @@ -312,6 +310,7 @@ export function createRoutes( Layer.provide(locationServiceMapV2), Layer.provide(AppNodeBuilderV1.build(app)), + Layer.provideMerge(Observability.layer), ) } diff --git a/packages/opencode/test/cli/run/session-data.test.ts b/packages/opencode/test/cli/run/session-data.test.ts index 805bcd486f..1483356986 100644 --- a/packages/opencode/test/cli/run/session-data.test.ts +++ b/packages/opencode/test/cli/run/session-data.test.ts @@ -110,6 +110,39 @@ function tool(input: { id: string; messageID: string; tool: string; state: Recor } } +function shellInfo(id: string, status: "running" | "exited", completed?: number) { + return { + id, + status, + command: "pwd", + cwd: "/tmp/demo", + shell: "/bin/sh", + file: `/tmp/${id}.log`, + ...(status === "exited" ? { exit: 0 } : {}), + metadata: {}, + time: { started: 1, ...(completed === undefined ? {} : { completed }) }, + } +} + +function shellStarted(id = "call-1") { + return { + type: "session.shell.started", + properties: { sessionID: "session-1", shell: shellInfo(id, "running") }, + } +} + +function shellEnded(id = "call-1") { + const output = "/tmp/demo\n" + return { + type: "session.shell.ended", + properties: { + sessionID: "session-1", + shell: shellInfo(id, "exited", 2), + output: { output, cursor: Buffer.byteLength(output), size: Buffer.byteLength(output), truncated: false }, + }, + } +} + describe("run session data", () => { test("buffers delayed assistant text until the role is known", () => { let data = createSessionData() @@ -328,15 +361,7 @@ describe("run session data", () => { test("renders direct shell mode from first-class shell events", () => { let data = createSessionData() - const started = reduce(data, { - type: "session.shell.started", - properties: { - sessionID: "session-1", - timestamp: 1, - callID: "call-1", - command: "pwd", - }, - }) + const started = reduce(data, shellStarted()) expect(started.commits).toEqual([ expect.objectContaining({ @@ -352,15 +377,7 @@ describe("run session data", () => { ]) data = started.data - const ended = reduce(data, { - type: "session.shell.ended", - properties: { - sessionID: "session-1", - timestamp: 2, - callID: "call-1", - output: "/tmp/demo\n", - }, - }) + const ended = reduce(data, shellEnded()) expect(ended.commits).toEqual([ expect.objectContaining({ @@ -379,15 +396,7 @@ describe("run session data", () => { }) test("suppresses legacy bash part updates once shell events claim the call", () => { - let data = reduce(createSessionData(), { - type: "session.shell.started", - properties: { - sessionID: "session-1", - timestamp: 1, - callID: "call-1", - command: "pwd", - }, - }).data + let data = reduce(createSessionData(), shellStarted()).data expect( reduce( @@ -408,15 +417,7 @@ describe("run session data", () => { ).commits, ).toEqual([]) - data = reduce(data, { - type: "session.shell.ended", - properties: { - sessionID: "session-1", - timestamp: 2, - callID: "call-1", - output: "/tmp/demo\n", - }, - }).data + data = reduce(data, shellEnded()).data expect( reduce( @@ -462,15 +463,7 @@ describe("run session data", () => { ).data expect( - reduce(data, { - type: "session.shell.started", - properties: { - sessionID: "session-1", - timestamp: 1, - callID: "call-1", - command: "pwd", - }, - }).commits, + reduce(data, shellStarted()).commits, ).toEqual([]) data = reduce( @@ -496,15 +489,7 @@ describe("run session data", () => { ).data expect( - reduce(data, { - type: "session.shell.ended", - properties: { - sessionID: "session-1", - timestamp: 2, - callID: "call-1", - output: "/tmp/demo\n", - }, - }).commits, + reduce(data, shellEnded()).commits, ).toEqual([]) }) diff --git a/packages/opencode/test/lib/llm-server.ts b/packages/opencode/test/lib/llm-server.ts index 245acc7280..aa16fdb9a6 100644 --- a/packages/opencode/test/lib/llm-server.ts +++ b/packages/opencode/test/lib/llm-server.ts @@ -606,7 +606,8 @@ function hit(url: string, body: unknown) { function isTitleRequest(body: unknown): boolean { if (!body || typeof body !== "object") return false - return JSON.stringify(body).includes("Generate a title for this conversation") + const value = JSON.stringify(body) + return value.includes("Generate a title for this conversation") || value.includes("You are a title generator") } namespace TestLLMServer { From 57fb3e5cc585a4d26297db61635703a610abf99f Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Sat, 4 Jul 2026 21:14:01 +0200 Subject: [PATCH 54/82] fix(run): align mini with current session contracts (#35354) --- packages/core/src/session.ts | 14 +- packages/core/test/session-skill.test.ts | 70 +++ .../opencode/src/cli/cmd/run/runtime.boot.ts | 4 + packages/opencode/src/cli/cmd/run/runtime.ts | 116 ++-- .../src/cli/cmd/run/stream-v2.subagent.ts | 49 +- .../src/cli/cmd/run/stream-v2.transport.ts | 88 ++- packages/opencode/src/cli/cmd/run/tool.ts | 9 + .../opencode/test/cli/run/entry.body.test.ts | 17 + .../opencode/test/cli/run/runtime.test.ts | 187 +++++- .../test/cli/run/stream-v2.transport.test.ts | 589 +++++++++++++++++- 10 files changed, 1063 insertions(+), 80 deletions(-) create mode 100644 packages/core/test/session-skill.test.ts diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 05d64c8efb..57ae67ce34 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -585,11 +585,15 @@ const layer = Layer.effect( const skills = yield* SkillV2.Service.pipe(Effect.provide(locations.get(session.location))) const skill = (yield* skills.list()).find((item) => item.name === input.skill) if (!skill) return yield* new SkillNotFoundError({ skill: input.skill }) - yield* events.publish(SessionEvent.Skill.Activated, { - sessionID: input.sessionID, - name: skill.name, - text: skill.content, - }) + yield* events.publish( + SessionEvent.Skill.Activated, + { + sessionID: input.sessionID, + name: skill.name, + text: skill.content, + }, + { id: input.id ? EventV2.ID.make(input.id.replace(/^msg_/, "evt_")) : undefined }, + ) if (input.resume !== false) yield* execution .resume(input.sessionID) diff --git a/packages/core/test/session-skill.test.ts b/packages/core/test/session-skill.test.ts new file mode 100644 index 0000000000..8f9803ef4a --- /dev/null +++ b/packages/core/test/session-skill.test.ts @@ -0,0 +1,70 @@ +import path from "path" +import { describe, expect } from "bun:test" +import { Effect, Layer, LayerMap } from "effect" +import { Database } from "@opencode-ai/core/database/database" +import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { EventV2 } from "@opencode-ai/core/event" +import { Location } from "@opencode-ai/core/location" +import { LocationServiceMap } from "@opencode-ai/core/location-service-map" +import type { LocationServices } from "@opencode-ai/core/location-services" +import { ProjectV2 } from "@opencode-ai/core/project" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { SessionV2 } from "@opencode-ai/core/session" +import { SessionExecution } from "@opencode-ai/core/session/execution" +import { SessionMessage } from "@opencode-ai/core/session/message" +import { SessionProjector } from "@opencode-ai/core/session/projector" +import { SessionStore } from "@opencode-ai/core/session/store" +import { SkillV2 } from "@opencode-ai/core/skill" +import { testEffect } from "./lib/effect" + +const location = Location.Ref.make({ directory: AbsolutePath.make("/project") }) +const projects = Layer.mock(ProjectV2.Service, { + resolve: (directory) => Effect.succeed({ id: ProjectV2.ID.global, directory }), +}) +const skills = Layer.mock(SkillV2.Service, { + list: () => + Effect.succeed([ + SkillV2.Info.make({ + name: "effect", + description: "Effect guidance", + location: AbsolutePath.make(path.resolve("/skills/effect/SKILL.md")), + content: "Use Effect", + }), + ]), +}) +const locations = Layer.effect( + LocationServiceMap.Service, + LayerMap.make( + () => + // The skill endpoint only needs the location-scoped Skill service. + // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion + skills as unknown as Layer.Layer, + ), +) +const it = testEffect( + AppNodeBuilder.build( + LayerNode.group([Database.node, EventV2.node, SessionProjector.node, SessionStore.node, SessionV2.node]), + [ + [LocationServiceMap.node, locations], + [ProjectV2.node, projects], + [SessionExecution.node, SessionExecution.noopLayer], + ], + ), +) + +describe("SessionV2.skill", () => { + it.effect("projects the caller-supplied message ID", () => + Effect.gen(function* () { + const sessions = yield* SessionV2.Service + const session = yield* sessions.create({ location }) + const id = SessionMessage.ID.make("msg_caller_skill") + + yield* sessions.skill({ id, sessionID: session.id, skill: "effect", resume: false }) + + expect(yield* sessions.messages({ sessionID: session.id })).toContainEqual( + expect.objectContaining({ id, type: "skill", name: "effect", text: "Use Effect" }), + ) + }), + ) +}) diff --git a/packages/opencode/src/cli/cmd/run/runtime.boot.ts b/packages/opencode/src/cli/cmd/run/runtime.boot.ts index 4753adaae2..2933ce5fdd 100644 --- a/packages/opencode/src/cli/cmd/run/runtime.boot.ts +++ b/packages/opencode/src/cli/cmd/run/runtime.boot.ts @@ -174,6 +174,10 @@ export async function resolveModelInfo( 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"], diff --git a/packages/opencode/src/cli/cmd/run/runtime.ts b/packages/opencode/src/cli/cmd/run/runtime.ts index e340a89cc3..5c6ede1582 100644 --- a/packages/opencode/src/cli/cmd/run/runtime.ts +++ b/packages/opencode/src/cli/cmd/run/runtime.ts @@ -17,7 +17,7 @@ import { Flag } from "@opencode-ai/core/flag/flag" import { MessageID } from "@/session/schema" import { loadRunAgents, loadRunCommands, loadRunReferences } from "./catalog.shared" import { createRunDemo } from "./demo" -import { resolveModelInfo, resolveRunTuiConfig, resolveSessionInfo } from "./runtime.boot" +import { resolveModelInfo, resolveModelInfoStrict, resolveRunTuiConfig, resolveSessionInfo } from "./runtime.boot" import { createRuntimeLifecycle } from "./runtime.lifecycle" import { trace } from "./trace" import { cycleVariant, formatModelLabel, resolveSavedVariant, resolveVariant, saveVariant } from "./variant.shared" @@ -378,32 +378,89 @@ async function runInteractiveRuntime(input: RunRuntimeInput, deps: RunRuntimeDep state.localRows = [...state.localRows, { commit, after }].slice(-LOCAL_REPLAY_ROW_LIMIT) } - const loadCatalog = async (): Promise => { + const applyCatalog = (catalog: { + agents: Awaited> + references: Awaited> + commands: Awaited> + }) => { if (footer.isClosed) { return } - - const [agents, references, commands] = await Promise.all([ - loadRunAgents(ctx.sdk, ctx.directory).catch(() => []), - loadRunReferences(ctx.sdk, ctx.directory).catch(() => []), - loadRunCommands(ctx.sdk, ctx.directory).catch(() => []), - ]) - if (footer.isClosed) { - return - } - footer.event({ type: "catalog", - agents, - references, - commands, + agents: catalog.agents, + references: catalog.references, + commands: catalog.commands, }) } - void footer + const fetchCatalog = async () => { + const [agents, references, commands] = await Promise.all([ + loadRunAgents(ctx.sdk, ctx.directory), + loadRunReferences(ctx.sdk, ctx.directory), + loadRunCommands(ctx.sdk, ctx.directory), + ]) + return { agents, references, commands } + } + + const loadCatalog = async () => { + applyCatalog( + await Promise.all([ + loadRunAgents(ctx.sdk, ctx.directory).catch(() => []), + loadRunReferences(ctx.sdk, ctx.directory).catch(() => []), + loadRunCommands(ctx.sdk, ctx.directory).catch(() => []), + ]).then(([agents, references, commands]) => ({ agents, references, commands })), + ) + } + + const applyModelInfo = ( + info: Awaited>, + current: string | undefined, + boot = false, + ) => { + state.providers = info.providers + state.variants = variantsFor(state.providers, state.model) + state.limits = info.limits + state.activeVariant = boot + ? resolveVariant(ctx.variant, current, savedVariant, state.variants) + : current && !state.variants.includes(current) + ? undefined + : current + if (footer.isClosed) return + footer.event({ type: "models", providers: info.providers }) + footer.event({ type: "variants", variants: state.variants, current: state.activeVariant }) + if (state.model) + footer.event({ type: "model", model: formatModelLabel(state.model, state.activeVariant, state.providers) }) + } + + let catalogRefresh: Promise | undefined + let catalogRefreshQueued = false + const requestCatalogRefresh = () => { + catalogRefreshQueued = true + if (catalogRefresh || footer.isClosed) return + catalogRefresh = (async () => { + await Promise.all([modelTask, initialCatalog]) + while (catalogRefreshQueued && !footer.isClosed) { + catalogRefreshQueued = false + const [catalog, info] = await Promise.allSettled([ + fetchCatalog(), + resolveModelInfoStrict(ctx.sdk, ctx.directory, state.model), + ]) + if (catalog.status === "fulfilled") applyCatalog(catalog.value) + if (info.status === "fulfilled") applyModelInfo(info.value, state.activeVariant) + } + })().finally(() => { + catalogRefresh = undefined + if (catalogRefreshQueued) requestCatalogRefresh() + }) + void catalogRefresh.catch(() => {}) + } + + const initialCatalog = footer .idle() .then(loadCatalog) .catch(() => {}) + void initialCatalog if (Flag.OPENCODE_SHOW_TTFD) { footer.append({ @@ -428,31 +485,7 @@ async function runInteractiveRuntime(input: RunRuntimeInput, deps: RunRuntimeDep void Promise.resolve(input.afterPaint(ctx)).catch(() => {}) } - void modelTask.then((info) => { - state.providers = info.providers - state.variants = variantsFor(state.providers, state.model) - state.limits = info.limits - - const next = resolveVariant(ctx.variant, session.variant, savedVariant, state.variants) - if (next !== state.activeVariant) { - state.activeVariant = next - } - - if (footer.isClosed) { - return - } - - footer.event({ type: "models", providers: info.providers }) - footer.event({ type: "variants", variants: state.variants, current: state.activeVariant }) - if (!state.model) { - return - } - - footer.event({ - type: "model", - model: formatModelLabel(state.model, state.activeVariant, state.providers), - }) - }) + void modelTask.then((info) => applyModelInfo(info, session.variant, true)) const streamTask = deps.streamTransport ?? import("./stream-v2.transport") const ensureStream = () => { @@ -484,6 +517,7 @@ async function runInteractiveRuntime(input: RunRuntimeInput, deps: RunRuntimeDep providers: () => state.providers, footer, trace: log, + onCatalogRefresh: requestCatalogRefresh, }) if (footer.isClosed) { await handle.close() diff --git a/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts b/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts index 1e7b039fd8..00de6490c4 100644 --- a/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts +++ b/packages/opencode/src/cli/cmd/run/stream-v2.subagent.ts @@ -27,7 +27,7 @@ import type { FooterSubagentDetail, FooterSubagentState, FooterSubagentTab, Stre const CHILD_MESSAGE_LIMIT = 80 const CHILD_FRAME_LIMIT = 80 -const DISCOVERY_BUFFER_LIMIT = 64 +const CHILD_EVENT_BUFFER_LIMIT = 64 const FAMILY_LIST_LIMIT = 100 const FALLBACK_LABEL = "Subagent" @@ -160,6 +160,7 @@ type ChildState = { tools: Map finishedTools: Set messageIDs: Set + prompts: Map hydrated: boolean } @@ -223,6 +224,8 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac // 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() + const hydrationEvents = new Map() + const hydrationOverflow = new Set() const hydrations = new Map>() let selected: string | undefined @@ -244,6 +247,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac tools: new Map(), finishedTools: new Set(), messageIDs: new Set(), + prompts: new Map(), hydrated: false, } if (!existing) children.set(sessionID, child) @@ -332,6 +336,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac child.callIDs.clear() for (const message of messages) { if (message.type === "user") { + child.prompts.delete(message.id) userFrame(child, message.id, message.text) continue } @@ -382,16 +387,38 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac const hydrateChild = (child: ChildState): Promise => { 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.v2.session .messages({ sessionID: child.sessionID, limit: CHILD_MESSAGE_LIMIT, order: "desc" }, { throwOnError: true }) .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, response.data.data.toReversed()) + 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(() => {}) + .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 @@ -424,8 +451,14 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac } const reduce = (child: ChildState, event: V2Event) => { + if (event.type === "session.prompt.admitted") { + child.prompts.set(event.data.inputID, event.data.prompt.text) + return + } if (event.type === "session.prompt.promoted") { - if (userFrame(child, event.data.inputID, "")) { + const prompt = child.prompts.get(event.data.inputID) ?? "" + child.prompts.delete(event.data.inputID) + if (userFrame(child, event.data.inputID, prompt)) { touch(child, event.created) notifyDetail(child) } @@ -511,10 +544,12 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac 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: event.data.tool, @@ -640,12 +675,18 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac 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 < DISCOVERY_BUFFER_LIMIT) buffered.push(event) + if (buffered && buffered.length < CHILD_EVENT_BUFFER_LIMIT) buffered.push(event) }, async hydrate(next) { for (const message of next.messages) { diff --git a/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts b/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts index 42e2c7bd53..8b80b0b64e 100644 --- a/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts +++ b/packages/opencode/src/cli/cmd/run/stream-v2.transport.ts @@ -9,6 +9,7 @@ import type { SessionMessageAssistantTool, V2Event, } from "@opencode-ai/sdk/v2" +import { Event } from "@opencode-ai/schema/event" import { blockerStatus, pickBlockerView } from "./session-data" import { writeSessionOutput } from "./stream" import { createSubagentTracker, legacyTool, toolCommit } from "./stream-v2.subagent" @@ -41,6 +42,7 @@ type StreamInput = { footer: FooterApi trace?: Trace signal?: AbortSignal + onCatalogRefresh?: () => void } export type SessionTurnInput = { @@ -81,6 +83,8 @@ type Wait = { // callID correlates the live shell events once shell.started is observed, and // abort cancels the blocking request when the user interrupts the turn. type ShellWait = { + eventID: string + messageID: string callID?: string resolve: () => void abort: () => void @@ -232,7 +236,7 @@ function streamPartKey(messageID: string, partID: string) { function shellCommit( callID: string, command: string, - next: { text: string; phase: "start" | "progress"; toolState: "running" | "completed" }, + next: Pick, ): StreamCommit { return { kind: "tool", @@ -244,6 +248,41 @@ function shellCommit( } } +function shellTerminal( + callID: string, + command: string, + shell: { status: string; exit?: number | string }, + output: { output: string; cursor: number; size: number; truncated: boolean }, +) { + const incomplete = output.truncated || output.cursor < output.size + const text = `${output.output}${incomplete ? `${output.output.endsWith("\n") || !output.output ? "" : "\n"}[output truncated]` : ""}` + const error = + shell.status === "exited" && shell.exit === 0 + ? undefined + : shell.status === "exited" + ? `Shell exited with code ${shell.exit ?? "unknown"}` + : `Shell ${shell.status}` + if (!error) + return [shellCommit(callID, command, { text, phase: "progress", toolState: "completed" })] + return [ + ...(text ? [shellCommit(callID, command, { text, phase: "progress", toolState: "running" })] : []), + shellCommit(callID, command, { text: error, phase: "final", toolState: "error", toolError: error }), + ] +} + +function messageIDFromEvent(id: string) { + return id.replace(/^evt_/, "msg_") +} + +const catalogEvents = new Set([ + "catalog.updated", + "integration.updated", + "agent.updated", + "command.updated", + "skill.updated", + "reference.updated", +]) + // session.shell resolves after the command settled server-side; the matching // live shell.ended event usually lands within the same tick, but hold the turn // briefly so the output commit renders inside it. @@ -407,6 +446,7 @@ export async function createSessionTransport(input: StreamInput): Promise { + if (catalogEvents.has(event.type)) { + if (input.directory && event.location?.directory && event.location.directory !== input.directory) return + input.onCatalogRefresh?.() + return + } const source = sessionID(event) if (source !== input.sessionID) { if (source) subagents.foreign(source, event) @@ -540,8 +579,8 @@ export async function createSessionTransport(input: StreamInput): Promise {}) await hydrate({ render: state.initial ? input.replay === true : true, reuseVisibleWait: !state.initial }) + input.onCatalogRefresh?.() state.initial = false booting = false for (const event of buffered.splice(0)) apply(event) @@ -867,13 +899,19 @@ export async function createSessionTransport(input: StreamInput): Promise((resolve) => { rendered = resolve }) - const active: ShellWait = { resolve: rendered, abort: () => abort.abort() } + const eventID = Event.ID.create() + const active: ShellWait = { + eventID, + messageID: messageIDFromEvent(eventID), + resolve: rendered, + abort: () => abort.abort(), + } state.shellWait = active - input.trace?.write("send.shell", { sessionID: input.sessionID, command: next.prompt.text }) + input.trace?.write("send.shell", { sessionID: input.sessionID, id: eventID, command: next.prompt.text }) write([], { phase: "running", status: "running shell" }) try { await input.sdk.v2.session.shell( - { sessionID: input.sessionID, command: next.prompt.text }, + { sessionID: input.sessionID, id: eventID, command: next.prompt.text }, { throwOnError: true, signal: abort.signal }, ) await Promise.race([output, wait(SHELL_OUTPUT_GRACE_MS, abort.signal)]) diff --git a/packages/opencode/src/cli/cmd/run/tool.ts b/packages/opencode/src/cli/cmd/run/tool.ts index 9a717ba4e6..181ab7dc7c 100644 --- a/packages/opencode/src/cli/cmd/run/tool.ts +++ b/packages/opencode/src/cli/cmd/run/tool.ts @@ -671,6 +671,10 @@ function scrollBashProgress(p: ToolProps): string { } function scrollBashFinal(p: ToolProps): string { + if (p.frame.status === "error") { + return fail(p.frame) + } + const code = p.metadata.exit ?? num(p.frame.meta.exitCode) ?? num(p.frame.meta.exit_code) const time = span(p.frame.state) if (code === undefined) { @@ -1427,6 +1431,11 @@ export function toolEntryBody(commit: StreamCommit, raw: string): RunEntryBody | return textBody(shellOutput(commit.shell.command, raw) ?? "") } + if (commit.toolState === "error") { + const ctx = toolFrame(commit, raw) + return textBody(toolScroll("final", ctx)) + } + return undefined } diff --git a/packages/opencode/test/cli/run/entry.body.test.ts b/packages/opencode/test/cli/run/entry.body.test.ts index 17659113c5..f393350381 100644 --- a/packages/opencode/test/cli/run/entry.body.test.ts +++ b/packages/opencode/test/cli/run/entry.body.test.ts @@ -50,6 +50,23 @@ function structured(next: StreamCommit) { } describe("run entry body", () => { + test("renders a failed direct shell as an error instead of completed success", () => { + expect( + entryBody( + commit({ + kind: "tool", + text: "Shell exited with code 7", + phase: "final", + source: "tool", + tool: "bash", + toolState: "error", + toolError: "Shell exited with code 7", + shell: { callID: "sh_failed", command: "false" }, + }), + ), + ).toEqual({ type: "text", content: "✖ bash failed: Shell exited with code 7" }) + }) + test("renders assistant, reasoning, and user entries in their display formats", () => { expect( entryBody( diff --git a/packages/opencode/test/cli/run/runtime.test.ts b/packages/opencode/test/cli/run/runtime.test.ts index 9ad7e003b2..702d82d769 100644 --- a/packages/opencode/test/cli/run/runtime.test.ts +++ b/packages/opencode/test/cli/run/runtime.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, mock, spyOn, test } from "bun:test" import { OpencodeClient } from "@opencode-ai/sdk/v2" import { runInteractiveMode } from "@/cli/cmd/run/runtime" -import type { FooterApi, RunProvider } from "@/cli/cmd/run/types" +import type { FooterApi, FooterEvent, RunProvider } from "@/cli/cmd/run/types" const provider: RunProvider = { id: "openai", @@ -53,7 +53,7 @@ function ok(data: T) { }) } -function footer(): FooterApi { +function footer(events: FooterEvent[] = []): FooterApi { let closed = false const closes = new Set<() => void>() @@ -78,7 +78,9 @@ function footer(): FooterApi { closes.delete(fn) } }, - event() {}, + event(value) { + events.push(value) + }, append() {}, idle() { return Promise.resolve() @@ -296,4 +298,183 @@ describe("run interactive runtime", () => { expect(legacyAgents).not.toHaveBeenCalled() expect(legacyCommands).not.toHaveBeenCalled() }) + + test("retains last-known-good state across failed coalesced refreshes and retries later", async () => { + const sdk = new OpencodeClient() + const refreshGate = defer() + let providerCalls = 0 + let modelCalls = 0 + let agentCalls = 0 + let referenceCalls = 0 + const events: FooterEvent[] = [] + const api = footer(events) + spyOn(sdk.v2.provider, "list").mockImplementation(async () => { + providerCalls++ + if (providerCalls === 2) { + await refreshGate.promise + throw new Error("provider refresh failed") + } + return ok({ + location: { directory: "/tmp" }, + data: [ + { + id: "openai", + name: providerCalls >= 3 ? "OpenAI refreshed" : "OpenAI", + api: { type: "native", settings: {} }, + request: { headers: {}, body: {} }, + }, + ], + }) as never + }) + spyOn(sdk.v2.model, "list").mockImplementation(() => { + modelCalls++ + return ok({ + location: { directory: "/tmp" }, + data: [ + { + id: "gpt-5", + providerID: "openai", + name: "Little Frank", + api: { id: "openai", type: "native", settings: {} }, + capabilities: { tools: true, input: ["text"], output: ["text"] }, + request: { headers: {}, body: {} }, + variants: + modelCalls >= 4 + ? [] + : [{ id: modelCalls >= 3 ? "high" : "low", settings: {}, headers: {}, body: {} }], + time: { released: 1 }, + cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }], + status: "active", + enabled: true, + limit: { context: modelCalls >= 3 ? 256000 : 128000, output: 8192 }, + }, + ], + }) as never + }) + spyOn(sdk.v2.agent, "list").mockImplementation(async () => { + agentCalls++ + if (agentCalls === 2) throw new Error("agent refresh failed") + return ok({ + location: { directory: "/tmp" }, + data: [{ id: "build", description: agentCalls >= 3 ? "Refreshed agent" : "Agent", mode: "primary" }], + }) as never + }) + spyOn(sdk.v2.reference, "list").mockImplementation(() => { + referenceCalls++ + return ok({ + location: { directory: "/tmp" }, + data: [ + { name: "effect", path: "/effect", description: referenceCalls >= 3 ? "Refreshed reference" : "Reference" }, + ], + }) as never + }) + spyOn(sdk.v2.command, "list").mockImplementation(() => + ok({ location: { directory: "/tmp" }, data: [{ name: "check", description: "Check" }] }) as never, + ) + spyOn(sdk.v2.skill, "list").mockImplementation(() => + ok({ location: { directory: "/tmp" }, data: [] }) as never, + ) + let finalProviders: RunProvider[] = [] + let finalLimits: Record = {} + let retainedProviders: RunProvider[] = [] + let retainedLimits: Record = {} + let retainedCatalog: FooterEvent | undefined + let selectedDefault: unknown + let selectDefault: (() => unknown) | undefined + let selectVariant: ((variant: string | undefined) => unknown) | undefined + let defaultRefreshVariants: FooterEvent | undefined + + await runInteractiveMode( + { + sdk, + directory: "/tmp", + sessionID: "ses-1", + sessionTitle: "Session", + resume: false, + agent: "build", + model: { providerID: "openai", modelID: "gpt-5" }, + variant: "low", + files: [], + thinking: false, + backgroundSubagents: false, + }, + { + createRuntimeLifecycle: async (input) => { + selectDefault = () => input.onVariantSelect?.(undefined) + selectVariant = (variant) => input.onVariantSelect?.(variant) + return { + footer: api, + onResize: () => () => {}, + refreshTheme: () => {}, + resetForReplay: () => Promise.resolve(), + close: () => Promise.resolve(), + } + }, + streamTransport: Promise.resolve({ + createSessionTransport: async (input) => { + while ( + !events.some( + (event) => event.type === "variants" && event.variants.includes("low") && event.current === "low", + ) + ) + await Bun.sleep(0) + selectedDefault = await Promise.resolve(selectDefault?.()) + input.onCatalogRefresh?.() + input.onCatalogRefresh?.() + input.onCatalogRefresh?.() + while (providerCalls < 2) await Bun.sleep(0) + refreshGate.resolve() + await new Promise((resolve) => setTimeout(resolve, 0)) + retainedProviders = input.providers?.() ?? [] + retainedLimits = input.limits() + retainedCatalog = events.filter((event) => event.type === "catalog").at(-1) + input.onCatalogRefresh?.() + input.onCatalogRefresh?.() + while (providerCalls < 3 || modelCalls < 3 || agentCalls < 3) await Bun.sleep(0) + await new Promise((resolve) => setTimeout(resolve, 0)) + defaultRefreshVariants = events.filter((event) => event.type === "variants").at(-1) + await Promise.resolve(selectVariant?.("high")) + input.onCatalogRefresh?.() + while (providerCalls < 4 || modelCalls < 4) await Bun.sleep(0) + await new Promise((resolve) => setTimeout(resolve, 0)) + finalProviders = input.providers?.() ?? [] + finalLimits = input.limits() + setTimeout(() => input.footer.close(), 0) + return { + runPromptTurn: async () => {}, + interruptActiveTurn: async () => {}, + selectSubagent: () => {}, + replayOnResize: async () => false, + close: async () => {}, + } + }, + formatUnknownError: (error: unknown) => (error instanceof Error ? error.message : String(error)), + }), + }, + ) + + expect(providerCalls).toBe(4) + expect(modelCalls).toBe(4) + expect(retainedProviders[0]?.name).toBe("OpenAI") + expect(retainedProviders[0]?.models["gpt-5"]?.variants).toEqual({ low: {} }) + expect(retainedLimits["openai/gpt-5"]).toBe(128000) + expect(retainedCatalog).toMatchObject({ + agents: [{ name: "build", description: "Agent" }], + references: [{ name: "effect", description: "Reference" }], + }) + expect(selectedDefault).toMatchObject({ variant: undefined }) + expect(defaultRefreshVariants).toMatchObject({ variants: ["high"], current: undefined }) + expect(finalProviders[0]?.name).toBe("OpenAI refreshed") + expect(finalProviders[0]?.models["gpt-5"]?.variants).toEqual({}) + expect(finalLimits["openai/gpt-5"]).toBe(256000) + expect(events.filter((event) => event.type === "variants").at(-1)).toMatchObject({ + variants: [], + current: undefined, + }) + expect(events.filter((event) => event.type === "catalog").at(-1)).toMatchObject({ + agents: [{ name: "build", description: "Refreshed agent" }], + references: [{ name: "effect", description: "Refreshed reference" }], + commands: [{ name: "check", description: "Check" }], + }) + }) }) diff --git a/packages/opencode/test/cli/run/stream-v2.transport.test.ts b/packages/opencode/test/cli/run/stream-v2.transport.test.ts index cd2d131642..cd43fda2de 100644 --- a/packages/opencode/test/cli/run/stream-v2.transport.test.ts +++ b/packages/opencode/test/cli/run/stream-v2.transport.test.ts @@ -1019,7 +1019,7 @@ describe("V2 mini transport", () => { request = input queueMicrotask(() => { events.push({ - id: "evt_shell_start", + id: input.id ?? "evt_missing", created: 0, type: "session.shell.started", durable: durable("ses_1"), @@ -1071,7 +1071,7 @@ describe("V2 mini transport", () => { includeFiles: true, }) - expect(request).toMatchObject({ sessionID: "ses_1", command: "ls" }) + expect(request).toMatchObject({ sessionID: "ses_1", command: "ls", id: expect.stringMatching(/^evt_/) }) expect(ui.commits.filter((item) => item.shell)).toMatchObject([ { phase: "start", tool: "bash", toolState: "running", shell: { callID: "sh_shell", command: "ls" } }, { phase: "progress", text: "file.txt", toolState: "completed", shell: { callID: "sh_shell", command: "ls" } }, @@ -1123,6 +1123,133 @@ describe("V2 mini transport", () => { await transport.close() }) + test("does not resolve an owned shell output wait from an unrelated shell", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ streams: [events] }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + let request: Parameters[0] | undefined + let complete!: () => void + spyOn(client.v2.session, "shell").mockImplementation((input) => { + request = input + return new Promise((resolve) => { + complete = resolve + }) as never + }) + + let done = false + const turn = transport + .runPromptTurn({ + agent: undefined, + model: undefined, + variant: undefined, + prompt: { text: "pwd", parts: [], mode: "shell" }, + files: [], + includeFiles: true, + }) + .then(() => { + done = true + }) + while (!request) await Bun.sleep(0) + events.push({ + id: "evt_unrelated_shell", + created: 0, + type: "session.shell.started", + durable: durable("ses_1"), + data: { + sessionID: "ses_1", + shell: { + id: "sh_unrelated", + status: "running", + command: "other", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/unrelated", + metadata: {}, + time: { started: 0 }, + }, + }, + }) + events.push({ + id: "evt_unrelated_end", + created: 0, + type: "session.shell.ended", + durable: durable("ses_1", 1), + data: { + sessionID: "ses_1", + shell: { + id: "sh_unrelated", + status: "exited", + command: "other", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/unrelated", + exit: 0, + metadata: {}, + time: { started: 0, completed: 1 }, + }, + output: { output: "wrong", cursor: 5, size: 5, truncated: false }, + }, + }) + await Bun.sleep(0) + complete() + await Bun.sleep(0) + expect(done).toBe(false) + + events.push({ + id: request.id ?? "evt_missing", + created: 0, + type: "session.shell.started", + durable: durable("ses_1", 2), + data: { + sessionID: "ses_1", + shell: { + id: "sh_owned", + status: "running", + command: "pwd", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/owned", + metadata: {}, + time: { started: 0 }, + }, + }, + }) + events.push({ + id: "evt_owned_end", + created: 0, + type: "session.shell.ended", + durable: durable("ses_1", 3), + data: { + sessionID: "ses_1", + shell: { + id: "sh_owned", + status: "exited", + command: "pwd", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/owned", + exit: 0, + metadata: {}, + time: { started: 0, completed: 1 }, + }, + output: { output: "/tmp", cursor: 4, size: 4, truncated: false }, + }, + }) + await turn + + expect(request.id).toMatch(/^evt_/) + expect(ui.commits.some((item) => item.shell?.callID === "sh_owned" && item.text === "/tmp")).toBe(true) + await transport.close() + }) + test("hydrates projected shell transcripts once and dedupes live redelivery", async () => { const events = feed() events.push(connected()) @@ -1190,6 +1317,91 @@ describe("V2 mini transport", () => { await transport.close() }) + test("renders failed projected shells as errors and marks truncated live output", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ + streams: [events], + messages: { + ses_1: [ + { + id: "msg_failed_shell", + type: "shell" as const, + shell: { + id: "sh_failed", + status: "exited", + command: "false", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/failed", + exit: 7, + metadata: {}, + time: { started: 0, completed: 1 }, + }, + output: { output: "failure output", cursor: 14, size: 14, truncated: false }, + time: { created: 1, completed: 2 }, + }, + ], + }, + }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + events.push({ + id: "evt_truncated_start", + created: 0, + type: "session.shell.started", + durable: durable("ses_1"), + data: { + sessionID: "ses_1", + shell: { + id: "sh_truncated", + status: "running", + command: "long", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/truncated", + metadata: {}, + time: { started: 0 }, + }, + }, + }) + events.push({ + id: "evt_truncated_end", + created: 0, + type: "session.shell.ended", + durable: durable("ses_1", 1), + data: { + sessionID: "ses_1", + shell: { + id: "sh_truncated", + status: "exited", + command: "long", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/truncated", + exit: 0, + metadata: {}, + time: { started: 0, completed: 1 }, + }, + output: { output: "partial", cursor: 7, size: 20, truncated: false }, + }, + }) + await Bun.sleep(0) + + expect(ui.commits).toContainEqual( + expect.objectContaining({ toolState: "error", toolError: "Shell exited with code 7" }), + ) + expect(ui.commits).toContainEqual(expect.objectContaining({ text: "partial\n[output truncated]" })) + await transport.close() + }) + test("routes command prompts through v2.session.command", async () => { const events = feed() events.push(connected()) @@ -1363,6 +1575,17 @@ describe("V2 mini transport", () => { done = true }) while (!sent) await Bun.sleep(0) + events.push({ + id: "evt_other", + created: 0, + type: "session.skill.activated", + durable: durable("ses_1"), + data: { + sessionID: "ses_1", + name: "other", + text: "other instructions", + }, + }) events.push({ id: "evt_unrelated_settled", created: 0, @@ -1396,6 +1619,46 @@ describe("V2 mini transport", () => { await transport.close() }) + test("refreshes catalogs on connection and location-scoped invalidations", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ streams: [events] }) + const ui = footer() + let refreshes = 0 + const transport = await createSessionTransport({ + sdk: client, + directory: "/project", + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + onCatalogRefresh: () => refreshes++, + }) + expect(refreshes).toBe(1) + + for (const type of [ + "catalog.updated", + "integration.updated", + "agent.updated", + "command.updated", + "skill.updated", + "reference.updated", + ] as const) + events.push({ id: `evt_${type}`, created: 0, type, location: { directory: "/project" }, data: {} }) + events.push({ + id: "evt_foreign_catalog", + created: 0, + type: "catalog.updated", + location: { directory: "/other" }, + data: {}, + }) + while (refreshes < 7) await Bun.sleep(0) + await Bun.sleep(0) + + expect(refreshes).toBe(7) + await transport.close() + }) + test("hydrates skill activation messages once and dedupes live redelivery", async () => { const events = feed() events.push(connected()) @@ -1526,6 +1789,328 @@ describe("V2 mini transport", () => { await transport.close() }) + test("reveals an admitted child prompt only when it is promoted after hydration", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ + streams: [events], + messages: { ses_child: [] }, + sessions: [{ id: "ses_child", parentID: "ses_1", time: { updated: 1 } }], + }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + const states = () => ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) + transport.selectSubagent("ses_child") + while (!states().some((state) => state.details.ses_child)) await Bun.sleep(0) + + events.push({ + id: "evt_child_admitted", + created: 1, + type: "session.prompt.admitted", + durable: durable("ses_child"), + data: { + sessionID: "ses_child", + inputID: "msg_child_prompt", + prompt: { text: "actual child prompt" }, + delivery: "steer", + }, + }) + await Bun.sleep(0) + expect( + states().at(-1)?.details.ses_child?.commits.some((item) => item.messageID === "msg_child_prompt"), + ).toBe(false) + + events.push({ + id: "evt_child_promoted", + created: 2, + type: "session.prompt.promoted", + durable: durable("ses_child", 1), + data: { sessionID: "ses_child", inputID: "msg_child_prompt" }, + }) + while ( + !states() + .at(-1) + ?.details.ses_child?.commits.some( + (item) => item.messageID === "msg_child_prompt" && item.text === "actual child prompt", + ) + ) + await Bun.sleep(0) + + await transport.close() + }) + + test("preserves a pre-hydration admission promoted during stale hydration", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ + streams: [events], + sessions: [{ id: "ses_child", parentID: "ses_1", time: { updated: 1 } }], + }) + let childHydrating = false + let releaseHydration!: () => void + const hydration = new Promise((resolve) => { + releaseHydration = resolve + }) + spyOn(client.v2.session, "messages").mockImplementation(async (request) => { + if (request.sessionID === "ses_child") { + childHydrating = true + await hydration + } + return ok({ data: [], cursor: {} }) + }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + const states = () => ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) + events.push({ + id: "evt_child_admitted_race", + created: 1, + type: "session.prompt.admitted", + durable: durable("ses_child"), + data: { + sessionID: "ses_child", + inputID: "msg_child_race", + prompt: { text: "prompt admitted before hydration" }, + delivery: "steer", + }, + }) + await Bun.sleep(0) + transport.selectSubagent("ses_child") + while (!childHydrating) await Bun.sleep(0) + events.push({ + id: "evt_child_promoted_race", + created: 2, + type: "session.prompt.promoted", + durable: durable("ses_child", 1), + data: { sessionID: "ses_child", inputID: "msg_child_race" }, + }) + await Bun.sleep(0) + releaseHydration() + await Bun.sleep(0) + await Bun.sleep(0) + while ( + !states() + .at(-1) + ?.details.ses_child?.commits.some( + (item) => item.messageID === "msg_child_race" && item.text === "prompt admitted before hydration", + ) + ) + await Bun.sleep(0) + + await transport.close() + }) + + test("retries child hydration after a bounded live-event overflow", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ + streams: [events], + sessions: [{ id: "ses_child", parentID: "ses_1", time: { updated: 1 } }], + }) + let childRequests = 0 + let releaseStale!: () => void + let releaseRetry!: () => void + const stale = new Promise((resolve) => { + releaseStale = resolve + }) + const retry = new Promise((resolve) => { + releaseRetry = resolve + }) + spyOn(client.v2.session, "messages").mockImplementation(async (request) => { + if (request.sessionID !== "ses_child") return ok({ data: [], cursor: {} }) + childRequests++ + if (childRequests === 1) { + await stale + return ok({ data: [], cursor: {} }) + } + await retry + return ok({ + data: [ + { + id: "msg_overflow_assistant", + type: "assistant" as const, + agent: "explore", + model: { providerID: "test", id: "model" }, + content: [{ type: "text" as const, id: "txt_overflow_64", text: "live 64" }], + time: { created: 2, completed: 3 }, + }, + { + id: "msg_overflow_baseline", + type: "user" as const, + text: "baseline history", + files: [], + agents: [], + time: { created: 1 }, + }, + ], + cursor: {}, + }) + }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + const states = () => ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) + transport.selectSubagent("ses_child") + while (childRequests < 1) await Bun.sleep(0) + + for (let index = 0; index < 65; index++) + events.push({ + id: `evt_overflow_${index}`, + created: index, + type: "session.text.delta", + data: { + sessionID: "ses_child", + assistantMessageID: "msg_overflow_assistant", + textID: `txt_overflow_${index}`, + delta: `live ${index}`, + }, + }) + while (!states().at(-1)?.details.ses_child?.commits.some((item) => item.text === "live 64")) await Bun.sleep(0) + releaseStale() + while (childRequests < 2) await Bun.sleep(0) + expect(states().at(-1)?.details.ses_child?.commits.some((item) => item.text === "live 64")).toBe(true) + + releaseRetry() + while (!states().at(-1)?.details.ses_child?.commits.some((item) => item.text === "baseline history")) + await Bun.sleep(0) + expect(states().at(-1)?.details.ses_child?.commits.some((item) => item.text === "live 64")).toBe(true) + expect(childRequests).toBe(2) + await transport.close() + }) + + test("reconciles pre-hydration tool metadata without downgrading projected completion", async () => { + const events = feed() + events.push(connected()) + const client = sdk({ + streams: [events], + sessions: [{ id: "ses_child", parentID: "ses_1", time: { updated: 1 } }], + }) + let childHydrating = false + let releaseHydration!: () => void + const hydration = new Promise((resolve) => { + releaseHydration = resolve + }) + spyOn(client.v2.session, "messages").mockImplementation(async (request) => { + if (request.sessionID !== "ses_child") return ok({ data: [], cursor: {} }) + childHydrating = true + await hydration + return ok({ + data: [ + { + id: "msg_tool_projected", + type: "assistant" as const, + agent: "explore", + model: { providerID: "test", id: "model" }, + content: [ + { + type: "tool" as const, + id: "call_overlap", + name: "bash", + state: { + status: "completed" as const, + input: { command: "projected" }, + content: [{ type: "text" as const, text: "projected result" }], + structured: {}, + }, + time: { created: 1, ran: 1, completed: 2 }, + }, + ], + time: { created: 1, completed: 2 }, + }, + ], + cursor: {}, + }) + }) + const ui = footer() + const transport = await createSessionTransport({ + sdk: client, + sessionID: "ses_1", + thinking: false, + limits: () => ({}), + footer: ui.api, + }) + const states = () => ui.events.flatMap((event) => (event.type === "stream.subagent" ? [event.state] : [])) + const inputStarted = (callID: string, name: string, seq: number) => + events.push({ + id: `evt_started_${callID}`, + created: seq, + type: "session.tool.input.started", + durable: durable("ses_child", seq), + data: { sessionID: "ses_child", assistantMessageID: "msg_tool_projected", callID, name }, + }) + const called = (callID: string, tool: string, input: Record, seq: number) => + events.push({ + id: `evt_called_${callID}`, + created: seq, + type: "session.tool.called", + durable: durable("ses_child", seq), + data: { + sessionID: "ses_child", + assistantMessageID: "msg_tool_projected", + callID, + tool, + input, + provider: { executed: true }, + }, + }) + + inputStarted("call_terminal", "grep", 0) + called("call_terminal", "grep", { pattern: "needle" }, 1) + await Bun.sleep(0) + transport.selectSubagent("ses_child") + while (!childHydrating) await Bun.sleep(0) + events.push({ + id: "evt_success_terminal", + created: 2, + type: "session.tool.success", + durable: durable("ses_child", 2), + data: { + sessionID: "ses_child", + assistantMessageID: "msg_tool_projected", + callID: "call_terminal", + structured: {}, + content: [{ type: "text", text: "found" }], + provider: { executed: true }, + }, + }) + inputStarted("call_overlap", "bash", 3) + called("call_overlap", "bash", { command: "stale" }, 4) + await Bun.sleep(0) + const beforeHydration = states().length + releaseHydration() + while (states().length === beforeHydration) await Bun.sleep(0) + await Bun.sleep(0) + + const commits = states().at(-1)?.details.ses_child?.commits ?? [] + expect(commits.find((item) => item.partID === "prt_call_terminal")).toMatchObject({ + tool: "grep", + toolState: "completed", + part: { state: { input: { pattern: "needle" } } }, + }) + expect(commits.find((item) => item.partID === "prt_call_overlap")).toMatchObject({ + tool: "bash", + toolState: "completed", + part: { state: { input: { command: "projected" } } }, + }) + await transport.close() + }) + test("keeps child terminal state observed during discovery", async () => { const events = feed() events.push(connected()) From d65ecd4a90cf3927bd38f72987a6ac8b0d857545 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sat, 4 Jul 2026 16:20:56 -0500 Subject: [PATCH 55/82] feat(core): expose deferred tools through execute (#35361) --- bun.lock | 1 + packages/codemode/codemode.md | 6 + packages/core/package.json | 1 + packages/core/src/flag/flag.ts | 3 + packages/core/src/mcp/guidance.ts | 12 +- packages/core/src/tool/execute.ts | 211 +++++++++++++++++++++++++++++ packages/core/src/tool/mcp.ts | 130 ++++++++++-------- packages/core/src/tool/registry.ts | 58 +++++--- packages/core/test/mcp.test.ts | 33 +++-- packages/core/test/plugin.test.ts | 1 + 10 files changed, 367 insertions(+), 89 deletions(-) create mode 100644 packages/core/src/tool/execute.ts diff --git a/bun.lock b/bun.lock index 46382ce955..3ca6fd949d 100644 --- a/bun.lock +++ b/bun.lock @@ -321,6 +321,7 @@ "@modelcontextprotocol/sdk": "1.29.0", "@npmcli/arborist": "9.4.0", "@npmcli/config": "10.8.1", + "@opencode-ai/codemode": "workspace:*", "@opencode-ai/effect-drizzle-sqlite": "workspace:*", "@opencode-ai/effect-sqlite-node": "workspace:*", "@opencode-ai/llm": "workspace:*", diff --git a/packages/codemode/codemode.md b/packages/codemode/codemode.md index 41b801044d..14fe18b875 100644 --- a/packages/codemode/codemode.md +++ b/packages/codemode/codemode.md @@ -1132,6 +1132,12 @@ Post-MVP (logged, not blocking an experimental flag): - [ ] Reviewer observation worth keeping: MCP server instructions (`sys.mcp`, `session/system.ts:110-126`) still inject prose referencing server-native tool names that are no longer directly callable under code mode. +- [ ] Tool-tree path segments named `__proto__`, `constructor`, or `prototype` are included + in discovery but rejected by `ToolRuntime` resolution even when supplied as safe own + properties on null-prototype host records. Hosts should preserve registered names rather + than invent incompatible aliases. CodeMode should own a consistent policy: safely admit + these names as own tool-tree members, reject them before catalog generation with a clear + diagnostic, or define one canonical escaping contract. ### Backlog / loose ends (non-blocking, any order) diff --git a/packages/core/package.json b/packages/core/package.json index 56bcbb53ba..84a51e61d2 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -90,6 +90,7 @@ "@ff-labs/fff-bun": "0.9.4", "@npmcli/arborist": "9.4.0", "@npmcli/config": "10.8.1", + "@opencode-ai/codemode": "workspace:*", "@opencode-ai/effect-drizzle-sqlite": "workspace:*", "@opencode-ai/effect-sqlite-node": "workspace:*", "@opencode-ai/llm": "workspace:*", diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index 1c975040dc..b33c20c1ab 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -52,6 +52,9 @@ export const Flag = { get OPENCODE_EXPERIMENTAL_REFERENCES() { return enabledByExperimental("OPENCODE_EXPERIMENTAL_REFERENCES") }, + get CODEMODE_ENABLED() { + return process.env["CODEMODE_ENABLED"] === undefined || truthy("CODEMODE_ENABLED") + }, get OPENCODE_TUI_CONFIG() { return process.env["OPENCODE_TUI_CONFIG"] }, diff --git a/packages/core/src/mcp/guidance.ts b/packages/core/src/mcp/guidance.ts index eed26170b0..0963a69d23 100644 --- a/packages/core/src/mcp/guidance.ts +++ b/packages/core/src/mcp/guidance.ts @@ -1,6 +1,7 @@ export * as McpGuidance from "./guidance" import { makeLocationNode } from "../effect/app-node" +import { Flag } from "../flag/flag" import { Context, Effect, Layer, Schema } from "effect" import { AgentV2 } from "../agent" import { PermissionV2 } from "../permission" @@ -17,6 +18,11 @@ type Summary = typeof Summary.Type const entries = (servers: ReadonlyArray) => servers.flatMap((server) => [ ` `, + ...(Flag.CODEMODE_ENABLED + ? [ + ` Use tools from this server through \`execute\` under \`tools[${JSON.stringify(McpTool.group(server.server))}]\`.`, + ] + : []), ...server.instructions.split("\n").map((line) => ` ${line}`), " ", ]) @@ -64,15 +70,17 @@ export const layer = Layer.effect( load: Effect.fn("McpGuidance.load")(function* (selection) { const agent = selection.info if (!agent) return SystemContext.empty + if (Flag.CODEMODE_ENABLED && PermissionV2.evaluate("execute", "*", agent.permissions).effect === "deny") + return SystemContext.empty const [instructions, tools] = yield* Effect.all([mcp.instructions(), mcp.tools()], { concurrency: "unbounded", }) - // Hide a server only when every tool it contributes is wholly denied for this agent. + // Instructions are useful only when this agent can reach at least one server tool. const visible = instructions .filter((item) => { const owned = tools.filter((tool) => tool.server === item.server) return ( - owned.length === 0 || + (!Flag.CODEMODE_ENABLED && owned.length === 0) || owned.some( (tool) => PermissionV2.evaluate(McpTool.name(tool.server, tool.name), "*", agent.permissions).effect !== "deny", diff --git a/packages/core/src/tool/execute.ts b/packages/core/src/tool/execute.ts new file mode 100644 index 0000000000..67d1b21eaf --- /dev/null +++ b/packages/core/src/tool/execute.ts @@ -0,0 +1,211 @@ +export * as ExecuteTool from "./execute" + +import { + CodeMode, + ExecuteInputSchema, + Tool, + toolError, + type DataValue, + type ExecuteResult, + type ToolCallHooks, + type ToolDefinition, +} from "@opencode-ai/codemode" +import { ToolOutput } from "@opencode-ai/llm" +import { Effect, Ref, Schema } from "effect" +import { definition, make, settle, type AnyTool } from "./tool" + +const ExecuteFile = Schema.Struct({ + data: Schema.String, + mime: Schema.String, + name: Schema.optionalKey(Schema.String), +}) + +const ExecuteCall = Schema.Struct({ + tool: Schema.String, + status: Schema.Literals(["running", "completed", "error"]), + input: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)), +}) + +type ExecuteCall = typeof ExecuteCall.Type + +const ExecuteMetadata = Schema.Struct({ + toolCalls: Schema.Array(ExecuteCall), + error: Schema.optionalKey(Schema.Literal(true)), +}) + +const ExecuteOutput = Schema.Struct({ + output: Schema.String, + toolCalls: Schema.Array(ExecuteCall), + error: Schema.optionalKey(Schema.Literal(true)), + files: Schema.Array(ExecuteFile), +}) + +type CollectedFiles = { + readonly index: number + readonly files: Array +} + +export interface Registration { + readonly identity: object + readonly tool: AnyTool + readonly name: string + readonly group?: string +} + +export const create = (options: { + readonly registrations: ReadonlyMap + readonly current: (name: string) => Registration | undefined +}) => { + const runtime = ( + invoke: (name: string, registration: Registration, input: unknown) => Effect.Effect, + hooks?: ToolCallHooks, + ) => { + const tools: Record | Record>> = {} + for (const [name, registration] of options.registrations) { + const child = definition(name, registration.tool) + const value = Tool.make({ + description: child.description, + input: child.inputSchema, + output: child.outputSchema, + run: (input) => invoke(name, registration, input), + }) + if (registration.group === undefined) { + const path = registration.name + if (Object.hasOwn(tools, path)) throw new TypeError(`Deferred tool namespace conflict: ${path}`) + tools[path] = value + continue + } + const path = registration.name + const namespace = registration.group + const group = tools[namespace] + if (group && Tool.isDefinition(group)) throw new TypeError(`Deferred tool namespace conflict: ${namespace}`) + if (group) { + if (Object.hasOwn(group, path)) throw new TypeError(`Deferred tool namespace conflict: ${namespace}.${path}`) + group[path] = value + continue + } + const entries: Record> = {} + entries[path] = value + tools[namespace] = entries + } + return CodeMode.make({ tools, ...hooks }) + } + const discovery = runtime(() => Effect.fail(toolError("Execute context is unavailable"))) + return make({ + description: discovery.instructions(), + input: ExecuteInputSchema, + output: ExecuteOutput, + structured: ExecuteMetadata, + toStructuredOutput: ({ output }) => ({ + toolCalls: output.toolCalls, + ...(output.error ? { error: true as const } : {}), + }), + toModelOutput: ({ output }) => [ + { type: "text" as const, text: output.output }, + ...output.files.map((file) => ({ + type: "file" as const, + data: file.data, + mime: file.mime, + ...(file.name === undefined ? {} : { name: file.name }), + })), + ], + execute: ({ code }, context) => + Effect.gen(function* () { + const callIndex = yield* Ref.make(0) + const files = yield* Ref.make>([]) + const calls = yield* Ref.make>([]) + // TODO: Publish live call-list updates once V2 has a generic tool progress API. + const finalCalls = Ref.get(calls).pipe( + Effect.map((items) => + items.map((call) => (call.status === "running" ? { ...call, status: "error" as const } : call)), + ), + ) + const result = yield* runtime( + (name, registration, input) => + Effect.gen(function* () { + const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1) + const current = options.current(name) + if (!current || current.identity !== registration.identity) + return yield* Effect.fail(toolError(`Stale tool call: ${name}`)) + const output = yield* settle( + current.tool, + { type: "tool-call", id: context.toolCallID, name, input }, + { + sessionID: context.sessionID, + agent: context.agent, + assistantMessageID: context.assistantMessageID, + toolCallID: context.toolCallID, + }, + ).pipe(Effect.mapError((failure) => toolError(failure.message, failure))) + const outputFileParts = outputFiles(output) + if (outputFileParts.length > 0) + yield* Ref.update(files, (items) => [...items, { index, files: outputFileParts }]) + return output.structured + }), + { + onToolCallStart: ({ index, name, input }) => + Effect.gen(function* () { + const shown = displayInput(input) + yield* Ref.update(calls, (items) => { + const next = [...items] + next[index] = { tool: name, status: "running", ...(shown ? { input: shown } : {}) } + return next + }) + }), + onToolCallEnd: ({ index, outcome }) => + Ref.update(calls, (items) => { + const current = items[index] + if (!current) return items + const next = [...items] + next[index] = { ...current, status: outcome === "success" ? "completed" : "error" } + return next + }), + }, + ).execute(code) + const toolCalls = yield* finalCalls + const collected = (yield* Ref.get(files)) + .toSorted((left, right) => left.index - right.index) + .flatMap((item) => item.files) + const output = formatResult(result) + return { output, toolCalls, files: collected, ...(result.ok ? {} : { error: true as const }) } + }), + }) +} + +function displayInput(input: unknown): Record | undefined { + if (input === null || input === undefined) return + if (typeof input !== "object" || Array.isArray(input)) return { input } + if (Object.keys(input).length === 0) return + return input as Record +} + +function formatResult(result: ExecuteResult) { + const output = result.ok + ? formatValue(result.value) + : [result.error.message, ...(result.error.suggestions ?? []).filter((hint) => !result.error.message.includes(hint))] + .join("\n") + .trim() + if (!result.logs || result.logs.length === 0) return output + const logs = `Logs:\n${result.logs.join("\n")}` + return output === "" ? logs : `${output}\n\n${logs}` +} + +function formatValue(value: DataValue) { + if (typeof value === "string") return value + return JSON.stringify(value, null, 2) ?? String(value) +} + +function outputFiles(output: ToolOutput): Array { + return output.content.flatMap((part) => { + if (part.type !== "file") return [] + const prefix = `data:${part.mime};base64,` + if (!part.uri.startsWith(prefix)) return [] + return [ + { + data: part.uri.slice(prefix.length), + mime: part.mime, + ...(part.name === undefined ? {} : { name: part.name }), + }, + ] + }) +} diff --git a/packages/core/src/tool/mcp.ts b/packages/core/src/tool/mcp.ts index 23d11d06a0..8cb0117ebb 100644 --- a/packages/core/src/tool/mcp.ts +++ b/packages/core/src/tool/mcp.ts @@ -5,6 +5,7 @@ import { McpEvent } from "@opencode-ai/schema/mcp-event" import { Effect, Exit, type JsonSchema, Layer, Scope, Semaphore, Stream } from "effect" import { makeLocationNode } from "../effect/app-node" import { EventV2 } from "../event" +import { Flag } from "../flag/flag" import { MCP } from "../mcp" import { PermissionV2 } from "../permission" import { Tool } from "./tool" @@ -12,10 +13,10 @@ import { Tools } from "./tools" import { ToolRegistry } from "./registry" /** - * Registry and permission action name for an MCP tool. + * Registry group and permission action names for MCP tools. */ -export const name = (server: string, tool: string) => - `${server.replace(/[^a-zA-Z0-9_-]/g, "_")}_${tool.replace(/[^a-zA-Z0-9_-]/g, "_")}` +export const group = (server: string) => server.replace(/[^a-zA-Z0-9_-]/g, "_") +export const name = (server: string, tool: string) => `${group(server)}_${tool.replace(/[^a-zA-Z0-9_-]/g, "_")}` export const layer = Layer.effectDiscard( Effect.gen(function* () { @@ -35,72 +36,81 @@ export const layer = Layer.effectDiscard( for (const tool of yield* mcp.tools()) { const group = groups.get(tool.server) ?? {} const schema = (tool.inputSchema ?? {}) as JsonSchema.JsonSchema - group[tool.name] = Tool.make({ - description: tool.description ?? "", - jsonSchema: { - ...schema, - type: "object", - properties: schema.properties ?? {}, - additionalProperties: false, - }, - execute: (input, context) => - Effect.gen(function* () { - yield* permission.assert({ - action: name(tool.server, tool.name), - resources: ["*"], - save: ["*"], - metadata: {}, - sessionID: context.sessionID, - agent: context.agent, - source: { - type: "tool", - messageID: context.assistantMessageID, - callID: context.toolCallID, - }, - }) - const result = yield* mcp - .callTool({ - server: tool.server, - name: tool.name, - args: (input ?? {}) as Record, + group[tool.name] = Tool.withPermission( + Tool.make({ + description: tool.description ?? "", + jsonSchema: { + ...schema, + type: "object", + properties: schema.properties ?? {}, + additionalProperties: false, + }, + execute: (input, context) => + Effect.gen(function* () { + yield* permission.assert({ + action: name(tool.server, tool.name), + resources: ["*"], + save: ["*"], + metadata: {}, + sessionID: context.sessionID, + agent: context.agent, + source: { + type: "tool", + messageID: context.assistantMessageID, + callID: context.toolCallID, + }, }) - .pipe( - Effect.catchTags({ - "MCP.NotFoundError": (error) => - new ToolFailure({ message: `MCP server "${error.server}" is not available` }), - "MCP.ToolCallError": (error) => new ToolFailure({ message: error.message }), - }), - ) - if (result.isError) - return yield* new ToolFailure({ - message: - result.content - .flatMap((part) => (part.type === "text" ? [part.text] : [])) - .join("\n") - .trim() || "MCP tool returned an error", - }) - return { - structured: result.structured ?? {}, - content: result.content.map((part) => + const result = yield* mcp + .callTool({ + server: tool.server, + name: tool.name, + args: (input ?? {}) as Record, + }) + .pipe( + Effect.catchTags({ + "MCP.NotFoundError": (error) => + new ToolFailure({ message: `MCP server "${error.server}" is not available` }), + "MCP.ToolCallError": (error) => new ToolFailure({ message: error.message }), + }), + ) + if (result.isError) + return yield* new ToolFailure({ + message: + result.content + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join("\n") + .trim() || "MCP tool returned an error", + }) + const content = result.content.map((part) => part.type === "text" ? { type: "text" as const, text: part.text } : { type: "file" as const, data: part.data, mime: part.mimeType }, + ) + const text = content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") + return { + structured: result.structured ?? (text === "" ? null : text), + content, + } + }).pipe( + Effect.mapError((error) => + error instanceof ToolFailure + ? error + : new ToolFailure({ message: `Unable to execute ${name(tool.server, tool.name)}` }), ), - } - }).pipe( - Effect.mapError((error) => - error instanceof ToolFailure - ? error - : new ToolFailure({ message: `Unable to execute ${name(tool.server, tool.name)}` }), ), - ), - }) + }), + name(tool.server, tool.name), + ) groups.set(tool.server, group) } const next = yield* Scope.fork(scope) - yield* Effect.forEach(groups, ([group, record]) => tools.register(record, { group }), { - discard: true, - }).pipe(Scope.provide(next), Effect.orDie) + yield* Effect.forEach( + groups, + ([group, record]) => tools.register(record, { group, deferred: Flag.CODEMODE_ENABLED }), + { + discard: true, + }, + ).pipe(Scope.provide(next), Effect.orDie) if (current) yield* Scope.close(current, Exit.void) current = next }), diff --git a/packages/core/src/tool/registry.ts b/packages/core/src/tool/registry.ts index dcdbb1c888..de11c10e6f 100644 --- a/packages/core/src/tool/registry.ts +++ b/packages/core/src/tool/registry.ts @@ -3,12 +3,14 @@ export * as ToolRegistry from "./registry" import { ToolOutput, type ToolCall, type ToolDefinition, type ToolResultValue } from "@opencode-ai/llm" import { Context, Effect, Layer, Scope } from "effect" import type { AgentV2 } from "../agent" +import { Flag } from "../flag/flag" import { PermissionV2 } from "../permission" import { SessionMessage } from "../session/message" import { SessionSchema } from "../session/schema" import { ToolOutputStore } from "../tool-output-store" import { Wildcard } from "../util/wildcard" -import { definition, permission, registrationEntries, settle, type AnyTool, type RegistrationError } from "./tool" +import { ExecuteTool } from "./execute" +import { definition, permission, registrationEntries, RegistrationError, settle, type AnyTool } from "./tool" import { Tools } from "./tools" import { ToolHooks } from "./hooks" import { makeLocationNode } from "../effect/app-node" @@ -61,18 +63,8 @@ const registryLayer = Layer.effect( } const local = new Map>() - const settleWith = Effect.fn("ToolRegistry.settle")(function* (input: ExecuteInput, advertised?: object) { - const registration = local.get(input.call.name)?.at(-1)?.registration - if (!registration) - return { - result: { - type: "error" as const, - value: advertised ? `Stale tool call: ${input.call.name}` : `Unknown tool: ${input.call.name}`, - }, - } - if (advertised && registration.identity !== advertised) - return { result: { type: "error" as const, value: `Stale tool call: ${input.call.name}` } } - // Hooks fire only for hosted/local tools; provider-executed calls never reach settleWith. + const settleTool = Effect.fn("ToolRegistry.settleTool")(function* (input: ExecuteInput, tool: AnyTool) { + // Hooks fire only for hosted/local tools; provider-executed calls never reach settleTool. const beforeEvent: ToolHooks.BeforeEvent = { tool: input.call.name, sessionID: input.sessionID, @@ -83,7 +75,7 @@ const registryLayer = Layer.effect( } yield* toolHooks.runBefore(beforeEvent) const pending = yield* settle( - registration.tool, + tool, { ...input.call, input: beforeEvent.input }, { sessionID: input.sessionID, @@ -135,10 +127,29 @@ const registryLayer = Layer.effect( } }) + const settleWith = Effect.fn("ToolRegistry.settle")(function* (input: ExecuteInput, advertised: object) { + const registration = local.get(input.call.name)?.at(-1)?.registration + if (!registration) + return { + result: { + type: "error" as const, + value: `Stale tool call: ${input.call.name}`, + }, + } + if (registration.identity !== advertised) + return { result: { type: "error" as const, value: `Stale tool call: ${input.call.name}` } } + return yield* settleTool(input, registration.tool) + }) + return Service.of({ register: Effect.fn("ToolRegistry.register")(function* (tools, options) { const entries = registrationEntries(tools, options?.group) if (entries.length === 0) return + const reserved = options?.deferred ? undefined : entries.find((entry) => entry.key === "execute") + if (reserved) + return yield* Effect.fail( + new RegistrationError({ name: reserved.key, message: 'Tool name "execute" is reserved for CodeMode' }), + ) yield* Effect.uninterruptible( Effect.gen(function* () { const token = {} @@ -180,16 +191,29 @@ const registryLayer = Layer.effect( for (const [name, registration] of registrations) { const wrongEditTool = name === "apply_patch" ? !usePatch : (name === "edit" || name === "write") && usePatch if ( - registration.deferred || wrongEditTool || + (registration.deferred && !Flag.CODEMODE_ENABLED) || whollyDisabled(permission(registration.tool, name), input.permissions ?? []) ) registrations.delete(name) } + const direct = new Map(Array.from(registrations).filter(([, registration]) => !registration.deferred)) + const deferred = new Map(Array.from(registrations).filter(([, registration]) => registration.deferred)) + const execute = + deferred.size > 0 && !whollyDisabled("execute", input.permissions ?? []) + ? ExecuteTool.create({ + registrations: deferred, + current: (name) => local.get(name)?.at(-1)?.registration, + }) + : undefined return { - definitions: Array.from(registrations, ([name, registration]) => definition(name, registration.tool)), + definitions: [ + ...Array.from(direct, ([name, registration]) => definition(name, registration.tool)), + ...(execute ? [definition("execute", execute)] : []), + ], settle: (input) => { - const registration = registrations.get(input.call.name) + if (input.call.name === "execute" && execute) return settleTool(input, execute) + const registration = direct.get(input.call.name) if (registration) return settleWith(input, registration.identity) return Effect.succeed({ result: { type: "error", value: `Unknown tool: ${input.call.name}` } }) }, diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index f52b223dce..ffcc2d3b89 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -79,12 +79,17 @@ it.effect("waits for permission before calling an MCP tool", () => const permission = yield* Deferred.make() decision = Deferred.await(permission) const registry = yield* ToolRegistry.Service - yield* waitForTool(registry, "demo_search") + yield* waitForTool(registry, "execute") const fiber = yield* settleTool(registry, { sessionID: SessionV2.ID.make("ses_mcp_permission"), ...toolIdentity, - call: { type: "tool-call", id: "call_mcp_permission", name: "demo_search", input: {} }, + call: { + type: "tool-call", + id: "call_mcp_permission", + name: "execute", + input: { code: "return await tools.demo.search({})" }, + }, }).pipe(Effect.forkScoped) expect(yield* Deferred.await(assertion)).toEqual({ action: "demo_search", @@ -113,15 +118,23 @@ it.effect("does not call MCP when permission is rejected", () => assertion = yield* Deferred.make() decision = Effect.fail(new PermissionV2.RejectedError()) const registry = yield* ToolRegistry.Service - yield* waitForTool(registry, "demo_search") + yield* waitForTool(registry, "execute") - expect( - yield* settleTool(registry, { - sessionID: SessionV2.ID.make("ses_mcp_rejected"), - ...toolIdentity, - call: { type: "tool-call", id: "call_mcp_rejected", name: "demo_search", input: {} }, - }), - ).toEqual({ result: { type: "error", value: "Unable to execute demo_search" } }) + const settlement = yield* settleTool(registry, { + sessionID: SessionV2.ID.make("ses_mcp_rejected"), + ...toolIdentity, + call: { + type: "tool-call", + id: "call_mcp_rejected", + name: "execute", + input: { code: "return await tools.demo.search({})" }, + }, + }) + expect(settlement.result).toEqual({ type: "text", value: "Unable to execute demo_search" }) + expect(settlement.output?.structured).toEqual({ + toolCalls: [{ tool: "demo.search", status: "error" }], + error: true, + }) expect(calls).toBe(0) }), ) diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 1a60decb0b..266d487862 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -154,6 +154,7 @@ describe("PluginV2", () => { expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toEqual([ "plain", "context_7_look_up", + "execute", ]) }), ) From b8efb33cde6d35c6013d2682c2701ed789debd9d Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sat, 4 Jul 2026 16:28:11 -0500 Subject: [PATCH 56/82] feat(codemode): add OpenAPI tool adapter (#35362) --- packages/codemode/AGENTS.md | 8 + packages/codemode/README.md | 27 + packages/codemode/src/index.ts | 1 + packages/codemode/src/openapi/TODO.md | 19 + packages/codemode/src/openapi/index.ts | 130 + packages/codemode/src/openapi/runtime.ts | 324 + packages/codemode/src/openapi/spec.ts | 507 + packages/codemode/src/openapi/types.ts | 112 + packages/codemode/src/token.ts | 10 - packages/codemode/src/tool-runtime.ts | 80 +- packages/codemode/src/tool.ts | 72 +- .../test/fixtures/openapi-happy-path.json | 245 + .../test/fixtures/opencode-v2-openapi.json | 26962 ++++++++++++++++ packages/codemode/test/openapi.test.ts | 958 + packages/codemode/test/signature.test.ts | 67 +- packages/protocol/src/groups/pty.ts | 1 + 16 files changed, 29461 insertions(+), 62 deletions(-) create mode 100644 packages/codemode/src/openapi/TODO.md create mode 100644 packages/codemode/src/openapi/index.ts create mode 100644 packages/codemode/src/openapi/runtime.ts create mode 100644 packages/codemode/src/openapi/spec.ts create mode 100644 packages/codemode/src/openapi/types.ts delete mode 100644 packages/codemode/src/token.ts create mode 100644 packages/codemode/test/fixtures/openapi-happy-path.json create mode 100644 packages/codemode/test/fixtures/opencode-v2-openapi.json create mode 100644 packages/codemode/test/openapi.test.ts diff --git a/packages/codemode/AGENTS.md b/packages/codemode/AGENTS.md index 88dd9c81d9..df812c6d86 100644 --- a/packages/codemode/AGENTS.md +++ b/packages/codemode/AGENTS.md @@ -5,6 +5,14 @@ - Keep Code Mode unaware of host session, channel, and conversation models. The hosting application supplies trusted execution scope around it. - Tool schemas are the model-facing Interface. Keep arguments minimal and natural to the operation; never add unrelated IDs as ambient capability tokens. +## OpenAPI + +- Generate an operation only when its transport semantics are supported; otherwise return a precise `skipped` reason. +- Never guess parameter serialization or malformed security semantics. Unsupported serialization is skipped and malformed security fails closed. +- Render unresolved schema constructs as `unknown`, never as invented TypeScript names. +- Keep network reads bounded and map expected encoding, transport, and decoding failures to model-safe `ToolError` values. +- Test supported behavior directly; do not reproduce adapter algorithms in tests. + ## Future Design Notes - If a captured user-visible output channel returns (an earlier `output.text`/`output.file`/`output.image` API was removed from v1), keep `output` as its name, distinct from the program return value: `return` stays the structured result for the model, while `output.*` describes artifacts the host may render into a conversation or UI after execution. Keep this host-neutral and let applications decide how captured output is delivered. In v1, hosts collect media host-side (outside the sandbox) instead. diff --git a/packages/codemode/README.md b/packages/codemode/README.md index 3f1f641b3f..bd14a24fb0 100644 --- a/packages/codemode/README.md +++ b/packages/codemode/README.md @@ -152,6 +152,33 @@ interface ExecuteFailure { `onToolCallEnd` receives `{ index, name, input, durationMs, outcome, message? }` when an admitted call settles. `outcome` is `"success"` or `"failure"`; `message` is the model-safe failure message and is present only on failure. Interrupted calls (for example when the execution timeout fires) do not produce an end event. Both hooks are Effect-returning and must not fail. +### OpenAPI tools + +`OpenAPI.fromSpec` turns an OpenAPI 3.x document into a tool subtree - one tool per operation. Dotted `operationId` values form namespaces such as `v2.session.get`. Missing IDs receive a flat method/path fallback such as `getUsersById`; names are sanitized and deduplicated. The host places the subtree under a key in its `tools` tree; that key is the model-visible namespace. + +```ts +import { CodeMode, OpenAPI } from "@opencode-ai/codemode" +import { Effect } from "effect" +import { FetchHttpClient } from "effect/unstable/http" + +const api = OpenAPI.fromSpec({ + spec: await Bun.file("openapi.json").json(), // parsed document (no YAML) + auth: { + resolve: ({ name, scopes, operation }) => + name === "BearerAuth" + ? Effect.succeed({ type: "bearer", token }) + : Effect.succeed(undefined), + }, +}) + +const runtime = CodeMode.make({ tools: { opencode: api.tools } }) +const result = await Effect.runPromise(runtime.execute(code).pipe(Effect.provide(FetchHttpClient.layer))) +``` + +`fromSpec` is synchronous and returns `{ tools, skipped }`. The initial adapter supports query `form`/`deepObject`, path/header `simple`, JSON request bodies, JSON responses, and text responses; unsupported parameter encodings, non-JSON request bodies, binary responses, and streaming operations land in `skipped` instead of producing broken tools. Operation and path servers take precedence over document servers unless `baseUrl` explicitly overrides all of them. Tool inputs flatten path, query, header, and closed object-body fields into one model-facing object while retaining their HTTP locations internally. Cross-location name collisions receive a location prefix such as `path_id` and `query_id`; composed, nullable, dictionary, conditionally-required, and non-object JSON bodies remain under `body`. Auth is never model-visible. Responses are limited to 50 MiB, and non-2xx responses become safe tool failures carrying the status and a size-capped body summary. Deferred capabilities are tracked in `src/openapi/TODO.md`. + +Supported bearer, basic, header, and query authentication follows OpenAPI `security` semantics and is resolved host-side via `auth.resolve` - credential storage, OAuth flows, and token refresh never enter the compiler. Cookie authentication alternatives are discarded; an operation is skipped when it has no supported alternative. See the option docstrings in `src/openapi/types.ts` for the full semantics. Generated tools require `HttpClient.HttpClient` (from `effect/unstable/http`) in the Effect environment - provide `FetchHttpClient.layer` or a custom/test client layer at execution. The supplied client owns redirect policy; credentialed hosts should reject redirects or strip credentials when the origin changes. + ## Discovery The agent-tool instructions use a budgeted catalog. Every tool namespace is always listed with its tool count regardless of budget, and as many complete tool signatures (each with a one-line description) as fit an estimated-token budget are inlined. Selection is round-robin across namespaces for fairness: in each round (namespaces alphabetical), every namespace still holding un-inlined tools attempts to place its next-cheapest signature line against the shared budget, and a namespace whose next line does not fit drops out while the others keep going - so every namespace gets some representation before any namespace gets everything. The instructions state exactly how comprehensive the list is, both overall (`COMPLETE list` vs `PARTIAL - N of M shown`) and per namespace (`(3 tools)`, `(3 tools, 1 shown)`, `(3 tools, none shown)`). diff --git a/packages/codemode/src/index.ts b/packages/codemode/src/index.ts index 96629f486e..1aea6644da 100644 --- a/packages/codemode/src/index.ts +++ b/packages/codemode/src/index.ts @@ -1,5 +1,6 @@ export { ToolError, CodeMode, ExecuteInputSchema, ExecuteResultSchema, toolError } from "./codemode.js" export { Tool } from "./tool.js" +export * as OpenAPI from "./openapi/index.js" export type { Definition as ToolDefinition, JsonSchema, ToolSchema } from "./tool.js" export type { ToolCallEnded, ToolCallHooks } from "./tool-runtime.js" export type { diff --git a/packages/codemode/src/openapi/TODO.md b/packages/codemode/src/openapi/TODO.md new file mode 100644 index 0000000000..cbcfe81a68 --- /dev/null +++ b/packages/codemode/src/openapi/TODO.md @@ -0,0 +1,19 @@ +# OpenAPI Follow-ups + +The initial adapter intentionally skips operations it cannot execute correctly. Future work may add: + +- Cookie parameters, authentication, and cookie-header merging. +- Matrix, label, space-delimited, pipe-delimited, `allowReserved`, and parameter `content` serialization. +- External references and complete nested `$defs` support. +- Relative or templated server URLs and server variables. +- Base URLs containing query strings or fragments. +- Runtime response-schema validation and full content negotiation. +- Binary response values and explicit byte-oriented return types. +- Request/response projection for `readOnly` and `writeOnly` properties. +- SSE, WebSocket, and other streaming transports. +- Recovery of responses rejected by a status-filtering `HttpClient`. +- Configurable request and response size limits. +- Adapter-enforced redirect policy independent of the supplied `HttpClient`. +- Strict UTF-8 and empty-body validation for JSON responses. +- Compile-time rejection of parameter schemas with nested values unsupported by their serialization style; runtime rejects them before auth resolution. +- Complete malformed-security-scheme validation and broader auth-combination coverage. diff --git a/packages/codemode/src/openapi/index.ts b/packages/codemode/src/openapi/index.ts new file mode 100644 index 0000000000..4ceda5eef0 --- /dev/null +++ b/packages/codemode/src/openapi/index.ts @@ -0,0 +1,130 @@ +import { HttpClient } from "effect/unstable/http" +import { Tool, type Definition } from "../tool.js" +import { invoke } from "./runtime.js" +import { + componentDefinitions, + inputSchema, + isRecord, + methods, + nonEmptyString, + operationInput, + operationOutput, + operationPath, + operationSecurityRequirements, + securityRequirements, + securitySchemes, + specServerUrl, + validateBaseUrl, +} from "./spec.js" +import type { Operation, Options, Result, Skipped, Tools } from "./types.js" + +export type { + AuthResolver, + Credential, + Document, + Operation, + Options, + Result, + SecurityScheme, + Skipped, + Tools, +} from "./types.js" + +/** + * Builds a CodeMode tool subtree from an OpenAPI 3.x document, one tool per + * operation. Auth is resolved host-side via `auth.resolve` and never + * model-visible. Tools require `HttpClient.HttpClient`; unrepresentable + * operations land in `skipped`. + */ +export const fromSpec = (options: Options): Result => { + const document = options.spec + const schemes = securitySchemes(document) + const defaultSecurity = securityRequirements(document.security) + const definitions = componentDefinitions(document) + const paths = isRecord(document.paths) ? document.paths : {} + const used = new Set() + const namespaces = new Set() + const skipped: Array = [] + const tools = Object.create(null) as Tools + + for (const [path, pathValue] of Object.entries(paths)) { + if (!isRecord(pathValue)) continue + for (const [method, operationValue] of Object.entries(pathValue)) { + if (!methods.has(method) || !isRecord(operationValue)) continue + const segments = operationPath(method, path, operationValue, used, namespaces) + const operation: Operation = { + operationId: nonEmptyString(operationValue.operationId), + method: method.toUpperCase(), + path, + summary: nonEmptyString(operationValue.summary), + description: nonEmptyString(operationValue.description), + } + const output = operationOutput(document, operationValue, definitions) + if (!output.ok) { + skipped.push({ method: operation.method, path, reason: output.reason }) + continue + } + + const resolvedBaseUrl = (() => { + if (options.baseUrl !== undefined) return validateBaseUrl(options.baseUrl) + if (operationValue.servers !== undefined) return specServerUrl(operationValue) + if (pathValue.servers !== undefined) return specServerUrl(pathValue) + return specServerUrl(document) + })() + if (!resolvedBaseUrl.ok) { + skipped.push({ method: operation.method, path, reason: resolvedBaseUrl.reason }) + continue + } + const parsedInput = operationInput(document, pathValue, operationValue) + if (!parsedInput.ok) { + skipped.push({ method: operation.method, path, reason: parsedInput.reason }) + continue + } + const input = parsedInput.value + + const security = operationSecurityRequirements(operationValue.security, defaultSecurity, schemes) + if (!security.ok) { + skipped.push({ method: operation.method, path, reason: security.reason }) + continue + } + const plan = { + operation, + url: `${resolvedBaseUrl.value.replace(/\/+$/, "")}${path}`, + fields: input.fields, + body: input.body, + security: security.value, + schemes, + auth: options.auth, + headers: options.headers ?? {}, + } + used.add(segments.join(".")) + for (const index of segments.slice(0, -1).keys()) namespaces.add(segments.slice(0, index + 1).join(".")) + setTool( + tools, + segments, + Tool.make({ + description: operation.description ?? operation.summary ?? `${operation.method} ${path}`, + input: inputSchema(input.fields, definitions), + output: output.value, + run: (input) => invoke(plan, input), + }), + ) + } + } + + return { tools, skipped } +} + +const setTool = (tools: Tools, path: ReadonlyArray, definition: Definition): void => { + const [head, ...rest] = path + if (head === undefined) return + if (rest.length === 0) { + tools[head] = definition + return + } + const child = tools[head] + if (child === undefined || !isRecord(child) || child._tag === "CodeModeTool") { + tools[head] = Object.create(null) as Tools + } + setTool(tools[head] as Tools, rest, definition) +} diff --git a/packages/codemode/src/openapi/runtime.ts b/packages/codemode/src/openapi/runtime.ts new file mode 100644 index 0000000000..47312ae162 --- /dev/null +++ b/packages/codemode/src/openapi/runtime.ts @@ -0,0 +1,324 @@ +import { Effect, Option, Schema, Stream } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse, type HttpMethod } from "effect/unstable/http" +import { ToolError, toolError } from "../tool-error.js" +import { isRecord, own } from "./spec.js" +import type { AppliedAuth, Credential, Plan, SecurityScheme } from "./types.js" + +const decodeJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString) +const maxErrorBodyChars = 1_024 +const maxResponseBodyBytes = 50 * 1024 * 1024 + +export const invoke = (plan: Plan, input: unknown): Effect.Effect => + Effect.gen(function* () { + const value = isRecord(input) ? input : {} + + let request = yield* buildRequest(plan, value) + + const auth = yield* resolveAuth(plan) + for (const [name, item] of Object.entries(auth.query)) { + request = HttpClientRequest.setUrlParam(request, name, item) + } + request = HttpClientRequest.setHeaders(request, auth.headers) + + const client = yield* HttpClient.HttpClient + const response = yield* client + .execute(request) + .pipe( + Effect.catch((cause) => + Effect.fail(toolError(`${plan.operation.method} ${plan.operation.path} failed: transport error`, cause)), + ), + ) + const text = yield* readResponseBody(response, plan) + const mediaType = response.headers["content-type"]?.split(";")[0]?.trim().toLowerCase() + const json = mediaType === "application/json" || mediaType?.endsWith("+json") === true + const decoded = text === "" ? Option.some(null) : json ? decodeJson(text) : Option.none() + const parsed = json ? Option.getOrElse(decoded, () => text) : text === "" ? null : text + if (response.status < 200 || response.status >= 300) { + const rendered = typeof parsed === "string" ? parsed : (JSON.stringify(parsed) ?? "") + const summary = + rendered === "" || rendered === "null" + ? "no response body" + : rendered.length > maxErrorBodyChars + ? `${rendered.slice(0, maxErrorBodyChars)}...` + : rendered + return yield* Effect.fail( + toolError(`${plan.operation.method} ${plan.operation.path} failed with HTTP ${response.status}: ${summary}`), + ) + } + if (json && Option.isNone(decoded)) { + return yield* Effect.fail( + toolError(`${plan.operation.method} ${plan.operation.path} returned malformed JSON.`), + ) + } + return parsed + }) + +const buildRequest = ( + plan: Plan, + input: Readonly>, +): Effect.Effect => + Effect.gen(function* () { + // Validate every model-controlled value before auth resolution, which may refresh tokens. + const url = buildUrl(plan, input) + if (url instanceof ToolError) return yield* Effect.fail(url) + const missing = plan.fields.find( + (field) => field.required && field.location !== "path" && own(input, field.inputName) === undefined, + ) + if (missing !== undefined) { + const label = missing.location === "body" ? "body field" : `${missing.location} parameter` + return yield* Effect.fail(toolError(`Missing required ${label} '${missing.inputName}'.`)) + } + + let request = HttpClientRequest.make(plan.operation.method as HttpMethod.HttpMethod)(url) + for (const field of plan.fields) { + if (field.location !== "query") continue + const item = own(input, field.inputName) + if (item === undefined) continue + const serialized = serializeQuery(request, field, item) + if (serialized instanceof ToolError) return yield* Effect.fail(serialized) + request = serialized + } + + // Host headers first, then declared header parameters. + request = HttpClientRequest.setHeaders(request, plan.headers) + for (const field of plan.fields) { + if (field.location !== "header") continue + const item = own(input, field.inputName) + if (item === undefined) continue + const serialized = serializeSimple(field, item, String) + if (serialized instanceof ToolError) return yield* Effect.fail(serialized) + request = HttpClientRequest.setHeader(request, field.name, serialized) + } + + const setBody = (value: unknown, mediaType: string) => + HttpClientRequest.bodyJson(request, value).pipe( + Effect.map((next) => HttpClientRequest.setHeader(next, "content-type", mediaType)), + Effect.mapError((cause) => + toolError(`Invalid JSON body for ${plan.operation.method} ${plan.operation.path}.`, cause), + ), + ) + if (plan.body?.mode === "value") { + const field = plan.fields.find((field) => field.location === "body") + const body = field === undefined ? undefined : own(input, field.inputName) + if (body !== undefined) request = yield* setBody(body, plan.body.mediaType) + } + if (plan.body?.mode === "object") { + const entries = plan.fields.flatMap((field) => { + if (field.location !== "body") return [] + const item = own(input, field.inputName) + return item === undefined ? [] : [[field.name, item] as const] + }) + if (plan.body.required || entries.length > 0) { + request = yield* setBody(Object.fromEntries(entries), plan.body.mediaType) + } + } + return request + }) + +const resolveAuth = (plan: Plan): Effect.Effect => + Effect.gen(function* () { + const none: AppliedAuth = { headers: {}, query: {} } + if (plan.security.length === 0) return none + + const unavailable: Array = [] + alternatives: for (const requirement of plan.security) { + const names = Object.keys(requirement) + if (names.length === 0) return none + const credentials: Array = [] + for (const name of names) { + const scheme = own(plan.schemes, name) + if (scheme === undefined || plan.auth === undefined) { + unavailable.push(name) + continue alternatives + } + const credential = yield* plan.auth.resolve({ + name, + definition: scheme, + scopes: requirement[name] ?? [], + operation: plan.operation, + }) + if (credential === undefined) { + unavailable.push(name) + continue alternatives + } + credentials.push([name, scheme, credential]) + } + const applied = applyCredentials(credentials) + return applied instanceof ToolError ? yield* Effect.fail(applied) : applied + } + + return yield* Effect.fail( + toolError( + `${plan.operation.method} ${plan.operation.path} requires authentication; no credential available for: ${[...new Set(unavailable)].join(", ")}.`, + ), + ) + }) + +const applyCredentials = ( + credentials: ReadonlyArray, +): AppliedAuth | ToolError => { + const headers = new Map() + const query = new Map() + const add = (carrier: "header" | "query", name: string, value: string): ToolError | undefined => { + const target = carrier === "header" ? headers : query + if (target.has(name)) return toolError(`Authentication resolves multiple credentials for ${carrier} '${name}'.`) + target.set(name, value) + } + for (const [name, definition, credential] of credentials) { + if (credential.type === "bearer") { + const duplicate = add("header", "authorization", `Bearer ${credential.token}`) + if (duplicate !== undefined) return duplicate + continue + } + if (credential.type === "basic") { + // Buffer instead of btoa: btoa throws on non-Latin-1 credentials. + const duplicate = add( + "header", + "authorization", + `Basic ${Buffer.from(`${credential.username}:${credential.password}`, "utf8").toString("base64")}`, + ) + if (duplicate !== undefined) return duplicate + continue + } + if (credential.type === "header") { + const duplicate = add("header", credential.name.toLowerCase(), credential.value) + if (duplicate !== undefined) return duplicate + continue + } + // apiKey: the carrier comes from the scheme declaration. + if (definition.type !== "apiKey") { + return toolError( + `Security scheme '${name}' is not an apiKey scheme; resolve a bearer, basic, or header credential for it.`, + ) + } + if (definition.in === "cookie") return toolError(`Cookie authentication '${name}' is not supported.`) + const parameter = definition.in === "header" ? definition.name.toLowerCase() : definition.name + const duplicate = add(definition.in, parameter, credential.value) + if (duplicate !== undefined) return duplicate + } + return { headers: Object.fromEntries(headers), query: Object.fromEntries(query) } +} + +const buildUrl = (plan: Plan, input: Readonly>): string | ToolError => { + let url = plan.url + for (const field of plan.fields) { + if (field.location !== "path") continue + const item = own(input, field.inputName) + if (item === undefined) { + return toolError(`Missing required path parameter '${field.inputName}'.`) + } + const fieldValue = serializeSimple(field, item, (value) => + encodeURIComponent(value).replace(/[!'()*]/g, (character) => + `%${character.charCodeAt(0).toString(16).toUpperCase()}`, + ), + ) + if (fieldValue instanceof ToolError) return fieldValue + // '.'/'..' survive encoding and URL normalization collapses them, letting a + // model-supplied value retarget the request to a different endpoint. + if (fieldValue === "" || fieldValue === "." || fieldValue === "..") { + return toolError(`Invalid path parameter '${field.inputName}'.`) + } + url = url.replaceAll(`{${field.name}}`, fieldValue) + } + const unresolved = url.match(/\{[^{}]+\}/) + if (unresolved !== null) return toolError(`Unresolved path parameter ${unresolved[0]}.`) + return url +} + +const serializeSimple = ( + field: Plan["fields"][number], + value: unknown, + encode: (value: string) => string, +): string | ToolError => { + const scalar = (item: unknown): string | ToolError => + item !== null && typeof item !== "string" && typeof item !== "number" && typeof item !== "boolean" + ? toolError(`Parameter '${field.inputName}' contains an unsupported nested value.`) + : encode(String(item)) + if (Array.isArray(value)) { + const items = value.map(scalar) + const invalid = items.find((item): item is ToolError => item instanceof ToolError) + return invalid ?? items.join(",") + } + if (!isRecord(value)) return scalar(value) + const entries = Object.entries(value).flatMap(([name, item]) => { + const rendered = scalar(item) + if (rendered instanceof ToolError) return [rendered] + return field.explode ? [`${encode(name)}=${rendered}`] : [encode(name), rendered] + }) + const invalid = entries.find((item): item is ToolError => item instanceof ToolError) + return invalid ?? entries.join(",") +} + +const serializeQuery = ( + request: HttpClientRequest.HttpClientRequest, + field: Plan["fields"][number], + value: unknown, +): HttpClientRequest.HttpClientRequest | ToolError => { + if (field.style === "deepObject") { + if (!isRecord(value)) return toolError(`Deep-object parameter '${field.inputName}' must be an object.`) + return Object.entries(value).reduce((current, [name, item]) => { + if (current instanceof ToolError) return current + if (item === undefined || (item !== null && typeof item === "object")) { + return toolError(`Deep-object parameter '${field.inputName}' contains an unsupported nested value.`) + } + return HttpClientRequest.appendUrlParam(current, `${field.name}[${name}]`, String(item)) + }, request) + } + if (Array.isArray(value)) { + const rendered = serializeSimple(field, value, String) + if (rendered instanceof ToolError) return rendered + if (!field.explode) return HttpClientRequest.appendUrlParam(request, field.name, rendered) + if (value.some((item) => item === undefined || (item !== null && typeof item === "object"))) { + return toolError(`Query parameter '${field.inputName}' contains an unsupported nested value.`) + } + return value.reduce( + (current, item) => HttpClientRequest.appendUrlParam(current, field.name, String(item)), + request, + ) + } + if (isRecord(value) && field.explode) { + return Object.entries(value).reduce((current, [name, item]) => { + if (current instanceof ToolError) return current + if (item === undefined || (item !== null && typeof item === "object")) { + return toolError(`Query parameter '${field.inputName}' contains an unsupported nested value.`) + } + return HttpClientRequest.appendUrlParam(current, name, String(item)) + }, request) + } + const rendered = serializeSimple(field, value, String) + return rendered instanceof ToolError ? rendered : HttpClientRequest.appendUrlParam(request, field.name, rendered) +} + +const readResponseBody = (response: HttpClientResponse.HttpClientResponse, plan: Plan): Effect.Effect => + Effect.gen(function* () { + const contentLength = response.headers["content-length"] + const parsedSize = contentLength === undefined ? undefined : Number.parseInt(contentLength, 10) + const declaredSize = parsedSize !== undefined && Number.isSafeInteger(parsedSize) && parsedSize >= 0 ? parsedSize : undefined + if (declaredSize !== undefined && declaredSize > maxResponseBodyBytes) { + return yield* Effect.fail(toolError(`${plan.operation.method} ${plan.operation.path} response exceeds 50 MiB.`)) + } + let body = Buffer.allocUnsafe(Math.min(maxResponseBodyBytes, declaredSize ?? 64 * 1024)) + let size = 0 + yield* Stream.runForEach(response.stream, (chunk) => { + if (size + chunk.byteLength > maxResponseBodyBytes) { + return Effect.fail(toolError(`${plan.operation.method} ${plan.operation.path} response exceeds 50 MiB.`)) + } + if (size + chunk.byteLength > body.byteLength) { + const grown = Buffer.allocUnsafe(Math.min(maxResponseBodyBytes, Math.max(size + chunk.byteLength, body.byteLength * 2))) + body.copy(grown, 0, 0, size) + body = grown + } + body.set(chunk, size) + size += chunk.byteLength + return Effect.void + }).pipe( + Effect.catch((cause) => { + if (cause instanceof ToolError) return Effect.fail(cause) + if (cause.reason._tag === "EmptyBodyError") return Effect.void + return Effect.fail( + toolError(`${plan.operation.method} ${plan.operation.path} failed while reading the response body.`, cause), + ) + }), + ) + return new TextDecoder().decode(body.subarray(0, size)) + }) diff --git a/packages/codemode/src/openapi/spec.ts b/packages/codemode/src/openapi/spec.ts new file mode 100644 index 0000000000..22cf1535a8 --- /dev/null +++ b/packages/codemode/src/openapi/spec.ts @@ -0,0 +1,507 @@ +import { fromSchemaOpenApi3_0, fromSchemaOpenApi3_1 } from "effect/JsonSchema" +import type { JsonSchema } from "../tool.js" +import { isBlockedMember } from "../tool-runtime.js" +import type { + Body, + Document, + InputField, + OperationInput, + Parsed, + SecurityRequirement, + SecurityScheme, +} from "./types.js" + +export const methods = new Set(["get", "put", "post", "delete", "options", "head", "patch", "trace"]) +const parameterLocations = ["path", "query", "header"] as const +const ignoredHeaderParameters = new Set(["accept", "content-type", "authorization"]) + +export const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value) + +const asArray = (value: unknown): ReadonlyArray => (Array.isArray(value) ? value : []) + +export const nonEmptyString = (value: unknown): string | undefined => + typeof value === "string" && value !== "" ? value : undefined + +// Guards record lookups keyed by spec- or model-controlled names against +// prototype-inherited values (e.g. a parameter named `toString`). +export const own = (record: Readonly>, key: string): T | undefined => + Object.hasOwn(record, key) ? record[key] : undefined + +export const resolve = (document: Document, value: unknown): unknown => { + const next = (current: unknown, seen: ReadonlySet): unknown => { + if (!isRecord(current)) return current + const ref = nonEmptyString(current.$ref) + if (ref === undefined || !ref.startsWith("#/") || seen.has(ref)) return current + const target = ref + .slice(2) + .split("/") + .map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")) + .reduce((item, segment) => (isRecord(item) ? own(item, segment) : undefined), document) + return target === undefined ? current : next(target, new Set([...seen, ref])) + } + return next(value, new Set()) +} + +const projectSchema = (document: Document, value: unknown): JsonSchema => { + if (!isRecord(value)) return {} + const normalized = nonEmptyString(document.openapi)?.startsWith("3.0") + ? fromSchemaOpenApi3_0(value) + : fromSchemaOpenApi3_1(value) + return Object.keys(normalized.definitions).length === 0 + ? normalized.schema + : { ...normalized.schema, $defs: normalized.definitions } +} + +export const componentDefinitions = (document: Document): Readonly> => { + const components = isRecord(document.components) ? document.components : {} + const schemas = isRecord(components.schemas) ? components.schemas : {} + return Object.fromEntries(Object.entries(schemas).map(([name, value]) => [name, projectSchema(document, value)])) +} + +const withDefinitions = (schema: JsonSchema, definitions: Readonly>): JsonSchema => { + if (Object.keys(definitions).length === 0) return schema + const local = isRecord(schema.$defs) ? schema.$defs : {} + return { ...schema, $defs: { ...definitions, ...local } } +} + +const isJsonMediaType = (mediaType: string): boolean => { + const normalized = mediaType.split(";")[0]?.trim().toLowerCase() ?? "" + return normalized === "application/json" || normalized.endsWith("+json") +} + +const isBinaryMediaType = (document: Document, mediaType: string, value: unknown): boolean => { + const normalized = mediaType.split(";")[0]?.trim().toLowerCase() ?? "" + if (!isJsonMediaType(normalized) && !normalized.startsWith("text/")) return true + if (!isRecord(value)) return false + const schema = resolve(document, value.schema) + return isRecord(schema) && schema.format === "binary" +} + +const jsonContent = (content: Record): { readonly mediaType: string; readonly schema: unknown } | undefined => { + const entry = Object.entries(content).find(([mediaType]) => isJsonMediaType(mediaType)) + return entry !== undefined && isRecord(entry[1]) ? { mediaType: entry[0], schema: entry[1].schema } : undefined +} + +const isFlattenableObjectBody = ( + schema: unknown, + requestRequired: boolean, +): schema is Record & { readonly properties: Record } => + isRecord(schema) && + requestRequired && + schema.type === "object" && + isRecord(schema.properties) && + schema.additionalProperties === false && + schema.nullable !== true && + schema.allOf === undefined && + schema.anyOf === undefined && + schema.oneOf === undefined + +type PlannedField = Omit + +const operationParameters = ( + document: Document, + pathItem: Record, + operation: Record, +): Parsed> => { + // Operation-level parameters override path-level ones sharing (location, name). + const declared = new Map< + string, + { readonly name: string; readonly location: string; readonly parameter: Record } + >() + for (const raw of [...asArray(pathItem.parameters), ...asArray(operation.parameters)]) { + const resolved = resolve(document, raw) + if (!isRecord(resolved)) return { ok: false, reason: "parameter declaration is invalid or unresolved" } + const name = nonEmptyString(resolved.name) + const location = nonEmptyString(resolved.in) + if (name === undefined || location === undefined) + return { ok: false, reason: "parameter declaration is missing name or location" } + declared.set(`${location}:${name}`, { name, location, parameter: resolved }) + } + const unordered: Array = [] + for (const item of declared.values()) { + const name = item.name + const location = item.location + const resolved = item.parameter + if (location === "cookie") return { ok: false, reason: `cookie parameter '${name}' is not supported` } + if (location !== "path" && location !== "query" && location !== "header") { + return { ok: false, reason: `parameter '${name}' uses unsupported location '${location}'` } + } + if (location === "header" && ignoredHeaderParameters.has(name.toLowerCase())) continue + if (resolved.schema === undefined && resolved.content === undefined) { + return { ok: false, reason: `parameter '${name}' declares neither schema nor content` } + } + if (resolved.content !== undefined) + return { ok: false, reason: `parameter '${name}' uses unsupported content encoding` } + if (resolved.style !== undefined && nonEmptyString(resolved.style) === undefined) { + return { ok: false, reason: `parameter '${name}' has an invalid style` } + } + if (resolved.explode !== undefined && typeof resolved.explode !== "boolean") { + return { ok: false, reason: `parameter '${name}' has an invalid explode value` } + } + if (resolved.allowReserved !== undefined && typeof resolved.allowReserved !== "boolean") { + return { ok: false, reason: `parameter '${name}' has an invalid allowReserved value` } + } + if (resolved.allowReserved === true) + return { ok: false, reason: `parameter '${name}' uses unsupported allowReserved encoding` } + const declaredStyle = nonEmptyString(resolved.style) ?? (location === "query" ? "form" : "simple") + if (location === "query" && declaredStyle !== "form" && declaredStyle !== "deepObject") { + return { ok: false, reason: `query parameter '${name}' uses unsupported style '${declaredStyle}'` } + } + if (location !== "query" && declaredStyle !== "simple") { + return { ok: false, reason: `${location} parameter '${name}' uses unsupported style '${declaredStyle}'` } + } + const style = declaredStyle === "deepObject" ? "deepObject" : declaredStyle === "form" ? "form" : "simple" + const explode = typeof resolved.explode === "boolean" ? resolved.explode : style === "form" + if (style === "deepObject" && !explode) { + return { ok: false, reason: `query parameter '${name}' uses deepObject with explode=false` } + } + const base = projectSchema(document, resolved.schema) + const description = nonEmptyString(resolved.description) + unordered.push({ + name, + location, + required: resolved.required === true || location === "path", + style, + explode, + schema: { + ...base, + ...(base.description === undefined && description !== undefined ? { description } : {}), + }, + }) + } + return { + ok: true, + value: parameterLocations.flatMap((location) => unordered.filter((field) => field.location === location)), + } +} + +const operationBody = ( + document: Document, + operation: Record, +): Parsed<{ readonly fields: ReadonlyArray; readonly body: Body | undefined }> => { + const resolved = resolve(document, operation.requestBody) + if (!isRecord(resolved)) return { ok: true, value: { fields: [], body: undefined } } + const content = isRecord(resolved.content) ? resolved.content : {} + const selected = jsonContent(content) + if (selected === undefined) { + return { + ok: false, + reason: `request body has no JSON content (declared: ${Object.keys(content).join(", ") || "none"})`, + } + } + const schema = resolve(document, selected.schema) + const required = resolved.required === true + if (!isFlattenableObjectBody(schema, required)) { + return { + ok: true, + value: { + fields: [ + { + name: "body", + location: "body", + required, + schema: projectSchema(document, selected.schema), + style: undefined, + explode: undefined, + }, + ], + body: { required, mode: "value", mediaType: selected.mediaType }, + }, + } + } + const requiredProperties = new Set( + Array.isArray(schema.required) ? schema.required.filter((item): item is string => typeof item === "string") : [], + ) + return { + ok: true, + value: { + fields: Object.entries(schema.properties).map(([name, value]) => ({ + name, + location: "body" as const, + required: required && requiredProperties.has(name), + schema: projectSchema(document, value), + style: undefined, + explode: undefined, + })), + body: { required, mode: "object", mediaType: selected.mediaType }, + }, + } +} + +export const operationInput = ( + document: Document, + pathItem: Record, + operation: Record, +): Parsed => { + const parameters = operationParameters(document, pathItem, operation) + if (!parameters.ok) return parameters + const requestBody = operationBody(document, operation) + if (!requestBody.ok) return requestBody + const fields = [...parameters.value, ...requestBody.value.fields] + + const conflicts = new Set( + [...Map.groupBy(fields, (field) => field.name)] + .filter(([, matches]) => new Set(matches.map((field) => field.location)).size > 1) + .map(([name]) => name), + ) + const used = new Set() + return { + ok: true, + value: { + fields: fields.map((field) => { + const visibleName = isBlockedMember(field.name) ? `${field.name}_2` : field.name + const base = conflicts.has(field.name) ? `${field.location}_${visibleName}` : visibleName + const next = (index: number): string => { + const candidate = index === 1 ? base : `${base}_${index}` + return used.has(candidate) ? next(index + 1) : candidate + } + const inputName = next(1) + used.add(inputName) + return { ...field, inputName } + }), + body: requestBody.value.body, + }, + } +} + +export const inputSchema = ( + fields: ReadonlyArray, + definitions: Readonly>, +): JsonSchema => { + const required = fields.filter((field) => field.required).map((field) => field.inputName) + return withDefinitions( + { + type: "object", + properties: Object.fromEntries(fields.map((field) => [field.inputName, field.schema])), + ...(required.length === 0 ? {} : { required }), + }, + definitions, + ) +} + +const successfulResponses = ( + document: Document, + operation: Record, +): Parsed>> => { + if (!isRecord(operation.responses)) return { ok: true, value: [] } + const entries = Object.entries(operation.responses) + const selected = [ + ...entries.filter(([status]) => /^2\d\d$/.test(status)).sort(([a], [b]) => a.localeCompare(b)), + ...entries.filter(([status]) => status.toUpperCase() === "2XX"), + ] + const responses: Array> = [] + for (const [, value] of selected) { + const resolved = resolve(document, value) + if (!isRecord(resolved) || nonEmptyString(resolved.$ref) !== undefined) { + return { ok: false, reason: "successful response declaration is invalid or unresolved" } + } + responses.push(resolved) + } + return { ok: true, value: responses } +} + +export const operationOutput = ( + document: Document, + operation: Record, + definitions: Readonly>, +): Parsed => { + if (operation["x-websocket"] === true) return { ok: false, reason: "WebSocket operations are not supported" } + const responses = successfulResponses(document, operation) + if (!responses.ok) return responses + const streams = responses.value.some( + (response) => + isRecord(response.content) && + Object.keys(response.content).some( + (mediaType) => mediaType.split(";")[0]?.trim().toLowerCase() === "text/event-stream", + ), + ) + if (streams) return { ok: false, reason: "SSE operations are not supported" } + const binary = responses.value.some( + (response) => + isRecord(response.content) && + Object.entries(response.content).some(([mediaType, value]) => isBinaryMediaType(document, mediaType, value)), + ) + if (binary) return { ok: false, reason: "binary responses are not supported" } + + const outcomes: Array = [] + for (const response of responses.value) { + if (response.content !== undefined && !isRecord(response.content)) return { ok: true, value: undefined } + const content = isRecord(response.content) ? response.content : {} + if (Object.keys(content).length === 0) { + outcomes.push({ type: "null" }) + continue + } + for (const [mediaType, value] of Object.entries(content)) { + if (!isJsonMediaType(mediaType)) { + outcomes.push({ type: "string" }) + continue + } + if (!isRecord(value) || value.schema === undefined) return { ok: true, value: undefined } + outcomes.push(projectSchema(document, value.schema)) + } + } + if (outcomes.length === 0) return { ok: true, value: undefined } + return { + ok: true, + value: withDefinitions(outcomes.length === 1 ? outcomes[0] ?? {} : { anyOf: outcomes }, definitions), + } +} + +const sanitizeOperationSegment = (raw: string): string => { + const base = + raw + .replaceAll(/[^A-Za-z0-9_$]+/g, "_") + .replace(/^_+|_+$/g, "") + .replace(/^([0-9])/, "_$1") || "operation" + return isBlockedMember(base) ? `${base}_2` : base +} + +const fallbackOperationId = (method: string, path: string): string => + [ + method, + ...path + .split("/") + .filter((part) => part !== "") + .flatMap((part) => (part.startsWith("{") && part.endsWith("}") ? ["by", part.slice(1, -1)] : [part])) + .flatMap((part) => part.split(/[^A-Za-z0-9]+/).filter((word) => word !== "")), + ] + .map((word, index) => { + const lower = word.toLowerCase() + return index === 0 ? lower : `${lower.charAt(0).toUpperCase()}${lower.slice(1)}` + }) + .join("") + +export const operationPath = ( + method: string, + path: string, + operation: Record, + used: ReadonlySet, + namespaces: ReadonlySet, +): ReadonlyArray => { + const raw = nonEmptyString(operation.operationId) + const segments = (raw === undefined ? [fallbackOperationId(method, path)] : raw.split(".")).map(sanitizeOperationSegment) + if (isOperationPathAvailable(segments, used, namespaces)) return segments + const conflict = segments.slice(0, -1).findIndex((_, index) => used.has(segments.slice(0, index + 1).join("."))) + if (conflict >= 0 && conflict + 1 < segments.length) { + const collapsed = segments.flatMap((segment, index) => { + if (index === conflict) { + const next = segments[index + 1] ?? "" + return [`${segment}${next.charAt(0).toUpperCase()}${next.slice(1)}`] + } + return index === conflict + 1 ? [] : [segment] + }) + if (isOperationPathAvailable(collapsed, used, namespaces)) return collapsed + } + const fallback = segments.join("_") + const next = (index: number): string => { + const candidate = `${fallback}_${index}` + return isOperationPathAvailable([candidate], used, namespaces) ? candidate : next(index + 1) + } + return [next(2)] +} + +const isOperationPathAvailable = ( + segments: ReadonlyArray, + used: ReadonlySet, + namespaces: ReadonlySet, +): boolean => { + const key = segments.join(".") + if (used.has(key) || namespaces.has(key)) return false + return segments.slice(0, -1).every((_, index) => !used.has(segments.slice(0, index + 1).join("."))) +} + +export const specServerUrl = (source: Record): Parsed => { + const server = asArray(source.servers).find(isRecord) + const url = server === undefined ? undefined : nonEmptyString(server.url) + if (url === undefined) return { ok: false, reason: "spec declares no servers; pass baseUrl" } + if (/\{[^{}]+\}/.test(url)) { + return { ok: false, reason: `server URL '${url}' is not an absolute URL; pass baseUrl` } + } + return validateBaseUrl(url) +} + +export const validateBaseUrl = (value: string): Parsed => { + if (!/^https?:\/\//i.test(value)) return { ok: false, reason: `server URL '${value}' is not an absolute HTTP(S) URL` } + const url = URL.parse(value) + if (url === null || (url.protocol !== "http:" && url.protocol !== "https:")) { + return { ok: false, reason: `server URL '${value}' is not an absolute HTTP(S) URL` } + } + if (url.search !== "" || url.hash !== "") { + return { ok: false, reason: `server URL '${value}' contains an unsupported query string or fragment` } + } + return { ok: true, value } +} + +export const securityRequirements = (value: unknown): Parsed> => { + if (value === undefined) return { ok: true, value: [] } + if (!Array.isArray(value)) return { ok: false, reason: "security declaration is not an array" } + const requirements: Array = [] + for (const item of value) { + if (!isRecord(item)) return { ok: false, reason: "security requirement is not an object" } + const requirement = Object.create(null) as Record> + for (const [name, scopes] of Object.entries(item)) { + if (!Array.isArray(scopes)) return { ok: false, reason: "security requirement scopes are not string arrays" } + const parsed = scopes.filter((scope): scope is string => typeof scope === "string") + if (parsed.length !== scopes.length) { + return { ok: false, reason: "security requirement scopes are not string arrays" } + } + requirement[name] = parsed + } + requirements.push(requirement) + } + return { ok: true, value: requirements } +} + +export const operationSecurityRequirements = ( + value: unknown, + defaults: Parsed>, + schemes: Readonly>, +): Parsed> => { + const parsed = value === undefined ? defaults : securityRequirements(value) + if (!parsed.ok) return parsed + const supported = parsed.value.filter((requirement) => + Object.keys(requirement).every((name) => { + const scheme = own(schemes, name) + return scheme !== undefined && !(scheme.type === "apiKey" && scheme.in === "cookie") + }), + ) + if (parsed.value.length === 0 || supported.length > 0) return { ok: true, value: supported } + + const names = [...new Set(parsed.value.flatMap((requirement) => Object.keys(requirement)))] + const cookieScheme = names.find((name) => { + const definition = own(schemes, name) + return definition?.type === "apiKey" && definition.in === "cookie" + }) + return { + ok: false, + reason: + cookieScheme === undefined + ? `security requirement references missing or malformed scheme: ${names.join(", ")}` + : `cookie authentication '${cookieScheme}' is not supported`, + } +} + +export const securitySchemes = (document: Document): Readonly> => { + const components = isRecord(document.components) ? document.components : {} + const declared = isRecord(components.securitySchemes) ? components.securitySchemes : {} + return Object.fromEntries( + Object.entries(declared).flatMap(([name, value]) => { + const resolved = resolve(document, value) + if (!isRecord(resolved)) return [] + const type = nonEmptyString(resolved.type) + if (type === "apiKey") { + const carrier = nonEmptyString(resolved.in) + const parameter = nonEmptyString(resolved.name) + if (parameter === undefined || (carrier !== "header" && carrier !== "query" && carrier !== "cookie")) return [] + return [[name, { type, name: parameter, in: carrier }] as const] + } + if (type === "http") { + const scheme = nonEmptyString(resolved.scheme)?.toLowerCase() + return scheme === undefined ? [] : [[name, { type, scheme }] as const] + } + if (type === "oauth2" || type === "openIdConnect") return [[name, { type }] as const] + return [] + }), + ) +} diff --git a/packages/codemode/src/openapi/types.ts b/packages/codemode/src/openapi/types.ts new file mode 100644 index 0000000000..cab772e701 --- /dev/null +++ b/packages/codemode/src/openapi/types.ts @@ -0,0 +1,112 @@ +import { Effect } from "effect" +import { HttpClient } from "effect/unstable/http" +import type { Definition, JsonSchema } from "../tool.js" + +/** A parsed OpenAPI 3.x document. YAML must be parsed by the host. */ +export type Document = Record + +/** The operation identity handed to auth resolution and errors. */ +export type Operation = { + readonly operationId: string | undefined + readonly method: string + readonly path: string + readonly summary: string | undefined + readonly description: string | undefined +} + +/** A resolved OpenAPI security scheme from `components.securitySchemes`. */ +export type SecurityScheme = + | { readonly type: "apiKey"; readonly name: string; readonly in: "header" | "query" | "cookie" } + | { readonly type: "http"; readonly scheme: string } + | { readonly type: "oauth2" } + | { readonly type: "openIdConnect" } + +/** + * Credential material returned by a host auth resolver. The carrier for `apiKey` + * comes from the scheme definition, not the credential. `header` is the escape + * hatch for nonstandard schemes. + */ +export type Credential = + | { readonly type: "bearer"; readonly token: string } + | { readonly type: "basic"; readonly username: string; readonly password: string } + | { readonly type: "apiKey"; readonly value: string } + | { readonly type: "header"; readonly name: string; readonly value: string } + +/** + * Resolves credential material for one named security scheme at call time. + * `undefined` means unavailable, try the next OR alternative; a failure aborts + * the call rather than falling through. + */ +export type AuthResolver = (context: { + readonly name: string + readonly definition: SecurityScheme + readonly scopes: ReadonlyArray + readonly operation: Operation +}) => Effect.Effect + +export type Options = { + readonly spec: Document + /** Overrides all document, path, and operation `servers`. Required when no applicable absolute server URL exists. */ + readonly baseUrl?: string | undefined + /** Host credential resolution, keyed by security scheme name. */ + readonly auth?: { readonly resolve: AuthResolver } | undefined + /** Static headers on every request. Not model-visible; declared header params may override them, auth always wins. */ + readonly headers?: Readonly> | undefined +} + +/** An operation that could not be represented as a tool, and why. */ +export type Skipped = { + readonly method: string + readonly path: string + readonly reason: string +} + +export type Tools = { [name: string]: Definition | Tools } + +export type Result = { + /** Tool subtree; the host places it under a key in its `tools` tree. */ + readonly tools: Tools + readonly skipped: ReadonlyArray +} + +export type Parsed = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly reason: string } + +export type InputLocation = "path" | "query" | "header" | "body" + +export type InputField = { + /** Model-visible field name after cross-location collision handling. */ + readonly inputName: string + /** Original parameter or body-property name used on the wire. */ + readonly name: string + readonly location: InputLocation + readonly required: boolean + readonly schema: JsonSchema + readonly style: "simple" | "form" | "deepObject" | undefined + readonly explode: boolean | undefined +} + +export type Body = { readonly required: boolean; readonly mode: "object" | "value"; readonly mediaType: string } + +export type OperationInput = { + readonly fields: ReadonlyArray + readonly body: Body | undefined +} + +/** One OR alternative: scheme name -> required scopes. Empty object = unauthenticated is acceptable. */ +export type SecurityRequirement = Readonly>> + +export type Plan = { + readonly operation: Operation + readonly url: string + readonly fields: ReadonlyArray + readonly body: Body | undefined + readonly security: ReadonlyArray + readonly schemes: Readonly> + readonly auth: { readonly resolve: AuthResolver } | undefined + readonly headers: Readonly> +} + +export type AppliedAuth = { + readonly headers: Readonly> + readonly query: Readonly> +} diff --git a/packages/codemode/src/token.ts b/packages/codemode/src/token.ts deleted file mode 100644 index 1e06bec1e4..0000000000 --- a/packages/codemode/src/token.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Token estimation for budgeting model-facing text. Copied from - * `@opencode-ai/core/util/token` (chars / 4) so this package stays - * dependency-free; keep the two in sync if the heuristic ever changes. - */ -export * as Token from "./token.js" - -const CHARS_PER_TOKEN = 4 - -export const estimate = (input: string) => Math.max(0, Math.round(input.length / CHARS_PER_TOKEN)) diff --git a/packages/codemode/src/tool-runtime.ts b/packages/codemode/src/tool-runtime.ts index d79d0182b5..339737375c 100644 --- a/packages/codemode/src/tool-runtime.ts +++ b/packages/codemode/src/tool-runtime.ts @@ -10,27 +10,32 @@ import { outputTypeScript, type Definition, } from "./tool.js" -import { estimate } from "./token.js" import { SandboxDate, SandboxMap, SandboxPromise, SandboxRegExp, SandboxSet } from "./values.js" +const estimateTokens = (input: string) => Math.max(0, Math.round(input.length / 4)) + export type HostTool = (...args: Array) => Effect.Effect export type HostTools = { [name: string]: HostTool | Definition | HostTools } -export type Services = Tools extends (...args: Array) => Effect.Effect - ? R - : Tools extends { - readonly _tag: "CodeModeTool" - readonly run: (input: unknown) => Effect.Effect - } +export type Services = ServicesOf + +type ServicesOf> = Depth["length"] extends 8 + ? never + : Tools extends (...args: Array) => Effect.Effect ? R - : Tools extends object - ? string extends keyof Tools - ? never - : Services - : never + : Tools extends { + readonly _tag: "CodeModeTool" + readonly run: (input: unknown) => Effect.Effect + } + ? R + : Tools extends object + ? string extends keyof Tools + ? ServicesOf + : ServicesOf + : never /** Minimal audit record retained for each admitted tool call. */ export type ToolCall = { @@ -290,17 +295,16 @@ const definitions = ( return entries } -const describeDefinition = (path: string, definition: Definition): ToolDescription => ({ - path, - description: definition.description, - signature: `${toolExpression(path)}(input: ${inputTypeScript(definition)}): Promise<${outputTypeScript(definition)}>`, -}) - const visibleDefinitions = (tools: HostTools) => - definitions(tools).flatMap(({ path, definition }) => { - const description = describeDefinition(path, definition) - return [{ path, definition, description }] - }) + definitions(tools).map(({ path, definition }) => ({ + path, + definition, + description: { + path, + description: definition.description, + signature: `${toolExpression(path)}(input: ${inputTypeScript(definition)}): Promise<${outputTypeScript(definition)}>`, + }, + })) export const catalog = (tools: HostTools): ReadonlyArray => visibleDefinitions(tools).map(({ description }) => description) @@ -351,16 +355,10 @@ const termForms = (term: string): Array => { return forms } -const firstLine = (text: string) => text.split("\n", 1)[0]!.trim() - -/** One-line description used on inline catalog lines; the full text stays in search results. */ -const brief = (text: string, max = 120) => { - const line = firstLine(text) - return line.length > max ? line.slice(0, max - 1) + "..." : line -} - const catalogLine = (tool: ToolDescription) => { - const description = brief(tool.description) + // Inline catalog lines use only a compact first line; full text stays in search results. + const line = tool.description.split("\n", 1)[0]!.trim() + const description = line.length > 120 ? line.slice(0, 119) + "..." : line return description === "" ? ` - ${tool.signature}` : ` - ${tool.signature} // ${description}` } @@ -430,7 +428,7 @@ export const discoveryPlan = ( picked: new Set(), queue: [...group].sort( (left, right) => - estimate(catalogLine(left)) - estimate(catalogLine(right)) || left.path.localeCompare(right.path), + estimateTokens(catalogLine(left)) - estimateTokens(catalogLine(right)) || left.path.localeCompare(right.path), ), })) let used = 0 @@ -439,7 +437,7 @@ export const discoveryPlan = ( const stillActive: typeof active = [] for (const selection of active) { const tool = selection.queue[0]! - const cost = estimate(catalogLine(tool)) + const cost = estimateTokens(catalogLine(tool)) if (used + cost > maxInlineCatalogTokens) continue selection.queue.shift() selection.picked.add(tool) @@ -636,9 +634,6 @@ export type ToolRuntime = { readonly keys: (path: ReadonlyArray) => ReadonlyArray } -const failureMessage = (error: unknown): string => - error instanceof ToolError || error instanceof ToolRuntimeError ? error.message : "Tool execution failed" - export const make = ( tools: HostTools, /** Undefined means unlimited tool calls. */ @@ -657,9 +652,16 @@ export const make = ( const startedAt = Date.now() return effect.pipe( Effect.tap(() => onEnd({ ...call, durationMs: Date.now() - startedAt, outcome: "success" })), - Effect.tapError((error) => - onEnd({ ...call, durationMs: Date.now() - startedAt, outcome: "failure", message: failureMessage(error) }), - ), + Effect.tapError((error) => { + const message = + error instanceof ToolError || error instanceof ToolRuntimeError ? error.message : "Tool execution failed" + return onEnd({ + ...call, + durationMs: Date.now() - startedAt, + outcome: "failure", + message, + }) + }), ) } diff --git a/packages/codemode/src/tool.ts b/packages/codemode/src/tool.ts index 5a0d84ad52..e89f3d39d6 100644 --- a/packages/codemode/src/tool.ts +++ b/packages/codemode/src/tool.ts @@ -1,4 +1,4 @@ -import { Effect, Schema } from "effect" +import { Effect, JsonPointer, Schema } from "effect" /** * JSON Schema subset accepted for render-only tool schemas. @@ -13,6 +13,7 @@ export type JsonSchema = { readonly const?: unknown readonly anyOf?: ReadonlyArray readonly oneOf?: ReadonlyArray + readonly allOf?: ReadonlyArray readonly properties?: Readonly> readonly required?: ReadonlyArray readonly items?: JsonSchema @@ -76,6 +77,13 @@ const effectNumberSentinel = (schema: JsonSchema) => schema.enum.length === 1 && (schema.enum[0] === "NaN" || schema.enum[0] === "Infinity" || schema.enum[0] === "-Infinity") +const intersection = (members: ReadonlyArray): string => { + const concrete = members.filter((member) => member !== "unknown") + if (concrete.length === 0) return "unknown" + if (concrete.length === 1) return concrete[0] ?? "unknown" + return concrete.map((member) => (member.includes(" | ") ? `(${member})` : member)).join(" & ") +} + /** * Recursion ceiling for schema rendering. Object, array, and union recursion all increment * depth, so this bounds every recursion path - pathological or structurally cyclic schemas @@ -89,6 +97,30 @@ type RenderContext = { readonly pretty: boolean } +const hasUnresolvedRef = ( + schema: JsonSchema, + definitions: Readonly>, + seen: ReadonlySet = new Set(), + visited: ReadonlySet = new Set(), +): boolean => { + if (visited.has(schema)) return false + const nextVisited = new Set([...visited, schema]) + if (schema.$ref !== undefined) { + const segment = schema.$ref.match(/^#\/(?:\$defs|definitions)\/([^/]+)$/)?.[1] + const name = segment === undefined ? undefined : JsonPointer.unescapeToken(segment) + if (name === undefined || definitions[name] === undefined || seen.has(name)) return true + if (hasUnresolvedRef(definitions[name], definitions, new Set([...seen, name]), nextVisited)) return true + } + return [ + ...(schema.anyOf ?? []), + ...(schema.oneOf ?? []), + ...(schema.allOf ?? []), + ...Object.values(schema.properties ?? {}), + ...(schema.items === undefined ? [] : [schema.items]), + ...(typeof schema.additionalProperties === "object" ? [schema.additionalProperties] : []), + ].some((item) => hasUnresolvedRef(item, definitions, seen, nextVisited)) +} + /** * Schema constraints a TypeScript type cannot express natively but a model benefits from, * surfaced as JSDoc tags (`@deprecated`, `@default`, `@format`, `@minItems`, `@maxItems`). @@ -136,11 +168,18 @@ const renderSchema = ( seen: ReadonlySet = new Set(), ): string => { if (depth > MAX_RENDER_DEPTH) return "unknown" + const nested = + schema.definitions === undefined && schema.$defs === undefined + ? ctx + : { ...ctx, definitions: { ...ctx.definitions, ...(schema.definitions ?? {}), ...(schema.$defs ?? {}) } } if (schema.$ref) { - const name = schema.$ref.split("/").pop() - if (!name || !ctx.definitions[name]) return name ?? "unknown" - if (seen.has(name)) return name // recursive type: reference by name rather than loop - return renderSchema(ctx.definitions[name], ctx, depth, new Set([...seen, name])) + const segment = schema.$ref.match(/^#\/(?:\$defs|definitions)\/([^/]+)$/)?.[1] + const name = segment === undefined ? undefined : JsonPointer.unescapeToken(segment) + if (!name || !nested.definitions[name] || seen.has(name)) return "unknown" + return intersection([ + renderSchema(nested.definitions[name], nested, depth, new Set([...seen, name])), + renderSchema({ ...schema, $ref: undefined }, nested, depth + 1, seen), + ]) } if (schema.const !== undefined) return renderLiteral(schema.const) if (schema.enum) return schema.enum.map(renderLiteral).join(" | ") @@ -166,24 +205,34 @@ const renderSchema = ( ) { return "{}" } - return alternatives.map((item) => renderSchema(item, ctx, depth + 1, seen)).join(" | ") + const members = alternatives.map((item) => renderSchema(item, nested, depth + 1, seen)) + if (members.some((member) => member === "unknown")) return "unknown" + return intersection([ + members.join(" | "), + renderSchema({ ...schema, anyOf: undefined, oneOf: undefined }, nested, depth + 1, seen), + ]) + } + if (schema.allOf) { + const members = schema.allOf.map((item) => renderSchema(item, nested, depth + 1, seen)) + if (schema.allOf.some((item) => hasUnresolvedRef(item, nested.definitions))) return "unknown" + return intersection([renderSchema({ ...schema, allOf: undefined }, nested, depth + 1, seen), ...members]) } if (Array.isArray(schema.type)) { - return schema.type.map((item) => renderSchema({ type: item }, ctx, depth + 1, seen)).join(" | ") + return schema.type.map((item) => renderSchema({ ...schema, type: item }, nested, depth + 1, seen)).join(" | ") } if (schema.type === "string") return "string" if (schema.type === "number" || schema.type === "integer") return "number" if (schema.type === "boolean") return "boolean" if (schema.type === "null") return "null" - if (schema.type === "array") return `Array<${renderSchema(schema.items ?? {}, ctx, depth + 1, seen)}>` + if (schema.type === "array") return `Array<${renderSchema(schema.items ?? {}, nested, depth + 1, seen)}>` if (schema.type === "object" || schema.properties) { const required = new Set(schema.required ?? []) const properties = Object.entries(schema.properties ?? {}) const additional = schema.additionalProperties const indexType = - additional && typeof additional === "object" ? renderSchema(additional, ctx, depth + 1, seen) : undefined + additional && typeof additional === "object" ? renderSchema(additional, nested, depth + 1, seen) : undefined const field = ([name, value]: readonly [string, JsonSchema]) => - `${renderKey(name)}${required.has(name) ? "" : "?"}: ${renderSchema(value, ctx, depth + 1, seen)}` + `${renderKey(name)}${required.has(name) ? "" : "?"}: ${renderSchema(value, nested, depth + 1, seen)}` if (!ctx.pretty) { const fields = properties.map(field) @@ -253,7 +302,8 @@ export const inputProperties = (definition: Definition): Array" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Switch the agent used by subsequent provider turns.", + "summary": "Switch session agent", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agent": { + "type": "string" + } + }, + "required": [ + "agent" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/model": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.switchModel", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Switch the model used by subsequent provider turns.", + "summary": "Switch session model", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "model": { + "$ref": "#/components/schemas/Model.Ref" + } + }, + "required": [ + "model" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/rename": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.rename", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Update the session title.", + "summary": "Rename session", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "title": { + "type": "string" + } + }, + "required": [ + "title" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/prompt": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.prompt", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/SessionInput.Admitted" + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "ConflictError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConflictError" + } + } + } + } + }, + "description": "Durably admit one session input and schedule agent-loop execution unless resume is false.", + "summary": "Send message", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "anyOf": [ + { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + { + "type": "null" + } + ] + }, + "prompt": { + "$ref": "#/components/schemas/PromptInput" + }, + "delivery": { + "anyOf": [ + { + "type": "string", + "enum": [ + "steer", + "queue" + ] + }, + { + "type": "null" + } + ] + }, + "resume": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "prompt" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/command": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.command", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/SessionInput.Admitted" + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | CommandNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/CommandNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "ConflictError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConflictError" + } + } + } + }, + "500": { + "description": "CommandEvaluationError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CommandEvaluationError" + } + } + } + } + }, + "description": "Resolve a slash command into prompt input, admit it durably, and schedule execution unless resume is false.", + "summary": "Run command", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "anyOf": [ + { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + { + "type": "null" + } + ] + }, + "command": { + "type": "string" + }, + "arguments": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "agent": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "model": { + "anyOf": [ + { + "$ref": "#/components/schemas/Model.Ref" + }, + { + "type": "null" + } + ] + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PromptInput.FileAttachment" + } + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Prompt.AgentAttachment" + } + }, + "delivery": { + "anyOf": [ + { + "type": "string", + "enum": [ + "steer", + "queue" + ] + }, + { + "type": "null" + } + ] + }, + "resume": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "command" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/skill": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.skill", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | SkillNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SkillNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Activate a skill for a session by appending a skill message and resuming execution.", + "summary": "Activate skill", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "anyOf": [ + { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + { + "type": "null" + } + ] + }, + "skill": { + "type": "string" + }, + "resume": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "skill" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/synthetic": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.synthetic", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Append a synthetic message to a session and resume execution.", + "summary": "Add synthetic message", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "text": { + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "metadata": { + "type": "object" + } + }, + "required": [ + "text" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/compact": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.compact", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "SessionBusyError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionBusyError" + } + } + } + }, + "500": { + "description": "UnknownError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownError" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + } + } + }, + "description": "Compact a session conversation.", + "summary": "Compact session" + } + }, + "/api/session/{sessionID}/wait": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.wait", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + } + } + }, + "description": "Wait for a session agent loop to become idle.", + "summary": "Wait for session" + } + }, + "/api/session/{sessionID}/revert/stage": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.revert.stage", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Revert.State" + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "MessageNotFoundError | SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/MessageNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "SessionBusyError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionBusyError" + } + } + } + }, + "500": { + "description": "UnknownError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownError" + } + } + } + } + }, + "description": "Stage or move a reversible session boundary and optionally apply its file changes.", + "summary": "Stage session revert", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "files": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "messageID" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/revert/clear": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.revert.clear", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "SessionBusyError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionBusyError" + } + } + } + }, + "500": { + "description": "UnknownError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownError" + } + } + } + } + }, + "summary": "Clear staged revert" + } + }, + "/api/session/{sessionID}/revert/commit": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.revert.commit", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "SessionBusyError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionBusyError" + } + } + } + } + }, + "summary": "Commit staged revert" + } + }, + "/api/session/{sessionID}/context": { + "get": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.context", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Session.Message" + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "500": { + "description": "UnknownError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownError" + } + } + } + } + }, + "description": "Retrieve the active context messages for a session (all messages after the last compaction).", + "summary": "Get session context" + } + }, + "/api/session/{sessionID}/context-entry": { + "get": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.context.entry.list", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SessionContextEntry.Info" + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "List API-managed context entries attached to the session's system context.", + "summary": "List context entries" + } + }, + "/api/session/{sessionID}/context-entry/{key}": { + "put": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.context.entry.put", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "key", + "in": "path", + "schema": { + "$ref": "#/components/schemas/SessionContextEntry.Key" + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Attach or replace one durable context entry. The value is rendered into the session's system context; changes announce as updates at the next turn boundary.", + "summary": "Put context entry", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": {} + }, + "required": [ + "value" + ], + "additionalProperties": false + } + } + }, + "required": true + } + }, + "delete": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.context.entry.remove", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "key", + "in": "path", + "schema": { + "$ref": "#/components/schemas/SessionContextEntry.Key" + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Remove one context entry; the removal is announced to the model at the next turn boundary.", + "summary": "Remove context entry" + } + }, + "/api/session/{sessionID}/log": { + "get": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.log", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "after", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "required": false + }, + { + "name": "follow", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "true", + "false" + ] + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "text/event-stream": { + "schema": { + "type": "object", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "event": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/SessionLogItemStream" + } + }, + "required": [ + "id", + "event", + "data" + ], + "additionalProperties": false + }, + "x-effect-stream": { + "encoding": "sse", + "causeSchema": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Fail" + ] + }, + "error": { + "not": {} + } + }, + "required": [ + "_tag", + "error" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Die" + ] + }, + "defect": {} + }, + "required": [ + "_tag", + "defect" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Interrupt" + ] + }, + "fiberId": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "_tag", + "fiberId" + ], + "additionalProperties": false + } + ] + } + }, + "errorSchema": { + "not": {} + }, + "failureEvent": "effect/httpapi/stream/failure" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Durable, ordered, gap-free read of public session events after an exclusive aggregate sequence. Emits a synced marker once replay reaches the captured watermark, then completes; with follow=true it continues with live events instead. The only event API that promises reliability: attach after a snapshot watermark to compose fetch and stream without a race window.", + "summary": "Read the session log" + } + }, + "/api/session/{sessionID}/interrupt": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.interrupt", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Interrupt active execution owned by this OpenCode process. Idle interruption is a no-op.", + "summary": "Interrupt session execution" + } + }, + "/api/session/{sessionID}/background": { + "post": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.background", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Move active foreground backgroundable tools for this session into background observation. Idle requests are a no-op.", + "summary": "Background blocking session tools" + } + }, + "/api/session/{sessionID}/message/{messageID}": { + "get": { + "tags": [ + "sessions" + ], + "operationId": "v2.session.message", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "messageID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Session.Message" + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | MessageNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/MessageNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Retrieve one projected message owned by the Session.", + "summary": "Get session message" + } + }, + "/api/session/{sessionID}/message": { + "get": { + "tags": [ + "messages" + ], + "operationId": "v2.session.messages", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "limit", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Maximum number of messages to return. When omitted, the endpoint returns its default page size." + }, + "required": false + }, + { + "name": "order", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "asc", + "desc" + ] + }, + { + "type": "null" + } + ], + "description": "Message order for the first page. Use desc for newest first or asc for oldest first." + }, + "required": false + }, + { + "name": "cursor", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "description": "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order." + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "SessionMessagesResponse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionMessagesResponse" + } + } + } + }, + "400": { + "description": "InvalidCursorError | InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidCursorError" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "500": { + "description": "UnknownError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownError" + } + } + } + } + }, + "description": "Retrieve projected messages for a session. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline.", + "summary": "Get session messages" + } + }, + "/api/model": { + "get": { + "tags": [ + "models" + ], + "operationId": "v2.model.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ModelV2.Info" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + } + } + }, + "description": "Retrieve available models ordered by release date.", + "summary": "List models" + } + }, + "/api/model/default": { + "get": { + "tags": [ + "models" + ], + "operationId": "v2.model.default", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModelV2.Info" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + } + } + }, + "description": "Retrieve the model used when a session has no explicit model selection.", + "summary": "Get default model" + } + }, + "/api/generate": { + "post": { + "tags": [ + "generate" + ], + "operationId": "v2.generate.text", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "GenerateTextResponse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenerateTextResponse" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidRequestError1" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + } + } + }, + "description": "Run one stateless model generation at the requested location and return the assistant text. Uses the location's default model when none is specified.", + "summary": "Generate text", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "prompt": { + "type": "string" + }, + "model": { + "anyOf": [ + { + "$ref": "#/components/schemas/Model.Ref" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "prompt" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/provider": { + "get": { + "tags": [ + "providers" + ], + "operationId": "v2.provider.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProviderV2.Info" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + } + } + }, + "description": "Retrieve active AI providers so clients can show provider availability and configuration.", + "summary": "List providers" + } + }, + "/api/provider/{providerID}": { + "get": { + "tags": [ + "providers" + ], + "operationId": "v2.provider.get", + "parameters": [ + { + "name": "providerID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/ProviderV2.Info" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "ProviderNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProviderNotFoundError" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + } + } + }, + "description": "Retrieve a single AI provider so clients can inspect its availability and endpoint settings.", + "summary": "Get provider" + } + }, + "/api/integration": { + "get": { + "tags": [ + "integrations" + ], + "operationId": "v2.integration.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Integration.Info" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve available integrations and their authentication methods.", + "summary": "List integrations" + } + }, + "/api/integration/{integrationID}": { + "get": { + "tags": [ + "integrations" + ], + "operationId": "v2.integration.get", + "parameters": [ + { + "name": "integrationID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "anyOf": [ + { + "$ref": "#/components/schemas/Integration.Info" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve one integration and its authentication methods.", + "summary": "Get integration" + } + }, + "/api/integration/{integrationID}/connect/key": { + "post": { + "tags": [ + "integrations" + ], + "operationId": "v2.integration.connect.key", + "parameters": [ + { + "name": "integrationID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidRequestError1" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Run a key authentication method and store the resulting credential.", + "summary": "Connect with key", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "label": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "key" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/integration/{integrationID}/connect/oauth": { + "post": { + "tags": [ + "integrations" + ], + "operationId": "v2.integration.connect.oauth", + "parameters": [ + { + "name": "integrationID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/Integration.Attempt" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidRequestError1" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Start an OAuth attempt and return the authorization details.", + "summary": "Begin OAuth connection", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "methodID": { + "type": "string" + }, + "inputs": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "label": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "methodID", + "inputs" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/integration/attempt/{attemptID}": { + "get": { + "tags": [ + "integrations" + ], + "operationId": "v2.integration.attempt.status", + "parameters": [ + { + "name": "attemptID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/Integration.AttemptStatus" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Poll the current status of an OAuth attempt.", + "summary": "Get OAuth attempt status" + }, + "delete": { + "tags": [ + "integrations" + ], + "operationId": "v2.integration.attempt.cancel", + "parameters": [ + { + "name": "attemptID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Cancel an OAuth attempt and release its resources.", + "summary": "Cancel OAuth connection" + } + }, + "/api/integration/attempt/{attemptID}/complete": { + "post": { + "tags": [ + "integrations" + ], + "operationId": "v2.integration.attempt.complete", + "parameters": [ + { + "name": "attemptID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidRequestError1" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Complete a code-based OAuth attempt and store the resulting credential.", + "summary": "Complete OAuth connection", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "code": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/mcp": { + "get": { + "tags": [ + "mcp" + ], + "operationId": "v2.mcp.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Mcp.Server" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve configured MCP servers and their connection status.", + "summary": "List MCP servers" + } + }, + "/api/credential/{credentialID}": { + "patch": { + "tags": [ + "server.credential" + ], + "operationId": "v2.credential.update", + "parameters": [ + { + "name": "credentialID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Update a stored credential label.", + "summary": "Update credential", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "label": { + "type": "string" + } + }, + "required": [ + "label" + ], + "additionalProperties": false + } + } + }, + "required": true + } + }, + "delete": { + "tags": [ + "server.credential" + ], + "operationId": "v2.credential.remove", + "parameters": [ + { + "name": "credentialID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Remove a stored integration credential.", + "summary": "Remove credential" + } + }, + "/api/project/current": { + "get": { + "tags": [ + "projects" + ], + "operationId": "v2.project.current", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Project.Current", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Project.Current" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Resolve the project for the requested location.", + "summary": "Get current project" + } + }, + "/api/project/{projectID}/directories": { + "get": { + "tags": [ + "projects" + ], + "operationId": "v2.project.directories", + "parameters": [ + { + "name": "projectID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Project.Directories", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Project.Directories" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "List known local absolute directories for a project.", + "summary": "List project directories" + } + }, + "/api/form/request": { + "get": { + "tags": [ + "forms" + ], + "operationId": "v2.form.request.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/Form.FormInfo" + }, + { + "$ref": "#/components/schemas/Form.UrlInfo" + } + ] + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve pending forms for a location.", + "summary": "List pending form requests" + } + }, + "/api/session/{sessionID}/form": { + "get": { + "tags": [ + "forms" + ], + "operationId": "v2.session.form.list", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/Form.FormInfo" + }, + { + "$ref": "#/components/schemas/Form.UrlInfo" + } + ] + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Retrieve pending forms for a session.", + "summary": "List session forms" + }, + "post": { + "tags": [ + "forms" + ], + "operationId": "v2.session.form.create", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "anyOf": [ + { + "$ref": "#/components/schemas/Form.FormInfo" + }, + { + "$ref": "#/components/schemas/Form.UrlInfo" + } + ] + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidRequestError1" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "ConflictError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConflictError" + } + } + } + } + }, + "description": "Create a form for a session.", + "summary": "Create session form", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Form.CreatePayload" + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/form/{formID}": { + "get": { + "tags": [ + "forms" + ], + "operationId": "v2.session.form.get", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "formID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "anyOf": [ + { + "$ref": "#/components/schemas/Form.FormInfo" + }, + { + "$ref": "#/components/schemas/Form.UrlInfo" + } + ] + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | FormNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/FormNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Retrieve a form for a session.", + "summary": "Get session form" + } + }, + "/api/session/{sessionID}/form/{formID}/state": { + "get": { + "tags": [ + "forms" + ], + "operationId": "v2.session.form.state", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "formID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Form.State" + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | FormNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/FormNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Retrieve the current state for a form.", + "summary": "Get form state" + } + }, + "/api/session/{sessionID}/form/{formID}/reply": { + "post": { + "tags": [ + "forms" + ], + "operationId": "v2.session.form.reply", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "formID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "FormInvalidAnswerError | InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/FormInvalidAnswerError" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | FormNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/FormNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "FormAlreadySettledError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FormAlreadySettledError" + } + } + } + } + }, + "description": "Submit an answer to a pending form.", + "summary": "Reply to form", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Form.Reply" + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/form/{formID}/cancel": { + "post": { + "tags": [ + "forms" + ], + "operationId": "v2.session.form.cancel", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "formID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | FormNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/FormNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + }, + "409": { + "description": "FormAlreadySettledError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FormAlreadySettledError" + } + } + } + } + }, + "description": "Cancel a pending form.", + "summary": "Cancel form" + } + }, + "/api/permission/request": { + "get": { + "tags": [ + "permissions" + ], + "operationId": "v2.permission.request.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionV2.Request" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve pending permission requests for a location.", + "summary": "List pending permission requests" + } + }, + "/api/permission/saved": { + "get": { + "tags": [ + "permissions" + ], + "operationId": "v2.permission.saved.list", + "parameters": [ + { + "name": "projectID", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionSaved.Info" + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve saved permissions, optionally filtered by project.", + "summary": "List saved permissions" + } + }, + "/api/permission/saved/{id}": { + "delete": { + "tags": [ + "permissions" + ], + "operationId": "v2.permission.saved.remove", + "parameters": [ + { + "name": "id", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Remove a saved permission by ID.", + "summary": "Remove saved permission" + } + }, + "/api/session/{sessionID}/permission": { + "post": { + "tags": [ + "permissions" + ], + "operationId": "v2.session.permission.create", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + "effect": { + "$ref": "#/components/schemas/PermissionV2.Effect" + } + }, + "required": [ + "id", + "effect" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Evaluate and, when approval is required, create a permission request for a session.", + "summary": "Create permission request", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "anyOf": [ + { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + { + "type": "null" + } + ] + }, + "action": { + "type": "string" + }, + "resources": { + "type": "array", + "items": { + "type": "string" + } + }, + "save": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { + "type": "object" + }, + "source": { + "$ref": "#/components/schemas/PermissionV2.Source" + }, + "agent": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "action", + "resources" + ], + "additionalProperties": false + } + } + }, + "required": true + } + }, + "get": { + "tags": [ + "permissions" + ], + "operationId": "v2.session.permission.list", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionV2.Request" + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Retrieve pending permission requests owned by a session.", + "summary": "List session permission requests" + } + }, + "/api/session/{sessionID}/permission/{requestID}": { + "get": { + "tags": [ + "permissions" + ], + "operationId": "v2.session.permission.get", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "requestID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/PermissionV2.Request" + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | PermissionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/PermissionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Retrieve a pending permission request owned by a session.", + "summary": "Get permission request" + } + }, + "/api/session/{sessionID}/permission/{requestID}/reply": { + "post": { + "tags": [ + "permissions" + ], + "operationId": "v2.session.permission.reply", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "requestID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | PermissionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/PermissionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Respond to a pending permission request owned by a session.", + "summary": "Reply to pending permission request", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "reply": { + "$ref": "#/components/schemas/PermissionV2.Reply" + }, + "message": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "reply" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/fs/read/*": { + "get": { + "tags": [ + "filesystem" + ], + "operationId": "v2.fs.read", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Serve one file relative to the requested location.", + "summary": "Read file" + } + }, + "/api/fs/list": { + "get": { + "tags": [ + "filesystem" + ], + "operationId": "v2.fs.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + }, + { + "name": "path", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FileSystem.Entry" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "List direct children of one directory relative to the requested location.", + "summary": "List directory" + } + }, + "/api/fs/find": { + "get": { + "tags": [ + "filesystem" + ], + "operationId": "v2.fs.find", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + }, + { + "name": "query", + "in": "query", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "type", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "file", + "directory" + ] + }, + "required": false + }, + { + "name": "limit", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FileSystem.Entry" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Find recursively ranked filesystem entries relative to the requested location.", + "summary": "Find files" + } + }, + "/api/command": { + "get": { + "tags": [ + "commands" + ], + "operationId": "v2.command.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CommandV2.Info" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve currently registered commands.", + "summary": "List commands" + } + }, + "/api/skill": { + "get": { + "tags": [ + "skills" + ], + "operationId": "v2.skill.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SkillV2.Info" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve currently registered skills.", + "summary": "List skills" + } + }, + "/api/event": { + "get": { + "tags": [ + "events" + ], + "operationId": "v2.event.subscribe", + "parameters": [], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "text/event-stream": { + "schema": { + "type": "object", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "event": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/V2EventStream" + } + }, + "required": [ + "id", + "event", + "data" + ], + "additionalProperties": false + }, + "x-effect-stream": { + "encoding": "sse", + "causeSchema": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Fail" + ] + }, + "error": { + "not": {} + } + }, + "required": [ + "_tag", + "error" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Die" + ] + }, + "defect": {} + }, + "required": [ + "_tag", + "defect" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Interrupt" + ] + }, + "fiberId": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "_tag", + "fiberId" + ], + "additionalProperties": false + } + ] + } + }, + "errorSchema": { + "not": {} + }, + "failureEvent": "effect/httpapi/stream/failure" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Subscribe to native event payloads for the server. Volatile by contract: a slow consumer overflows and fails the stream, and events during disconnection are missed. Consumers that need reliability should combine the changes feed with durable session log reads.", + "summary": "Subscribe to events" + } + }, + "/api/event/changes": { + "get": { + "tags": [ + "events" + ], + "operationId": "v2.event.changes", + "parameters": [], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "text/event-stream": { + "schema": { + "type": "object", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "event": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/EventLog.ChangeStream" + } + }, + "required": [ + "id", + "event", + "data" + ], + "additionalProperties": false + }, + "x-effect-stream": { + "encoding": "sse", + "causeSchema": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Fail" + ] + }, + "error": { + "not": {} + } + }, + "required": [ + "_tag", + "error" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Die" + ] + }, + "defect": {} + }, + "required": [ + "_tag", + "defect" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "Interrupt" + ] + }, + "fiberId": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "_tag", + "fiberId" + ], + "additionalProperties": false + } + ] + } + }, + "errorSchema": { + "not": {} + }, + "failureEvent": "effect/httpapi/stream/failure" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Payload-free hint channel: after an event commits, a subscriber eventually receives a hint for that aggregate with seq at or beyond the event, or a sweep-required marker. Hints coalesce to the latest seq per aggregate under backpressure and the stream never fails from overflow. No consumer may derive correctness from receiving a hint; correctness always comes from durable log reads plus the consumer's own checkpoint. A sweep-required marker is emitted first on every (re)subscribe and whenever hint retention is exceeded: treat every aggregate as potentially dirty and recover via bounded sweep plus log reads.", + "summary": "Subscribe to change hints" + } + }, + "/api/pty": { + "get": { + "tags": [ + "pty" + ], + "operationId": "v2.pty.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Pty" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "List PTY sessions for a location, including exited sessions retained until removal.", + "summary": "List PTY sessions" + }, + "post": { + "tags": [ + "pty" + ], + "operationId": "v2.pty.create", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Create a pseudo-terminal session for a location.", + "summary": "Create PTY session", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "command": { + "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } + }, + "cwd": { + "type": "string" + }, + "title": { + "type": "string" + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/pty/{ptyID}": { + "get": { + "tags": [ + "pty" + ], + "operationId": "v2.pty.get", + "parameters": [ + { + "name": "ptyID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^pty" + } + ] + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "PtyNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PtyNotFoundError" + } + } + } + } + }, + "description": "Get one PTY session, including its exit code once exited.", + "summary": "Get PTY session" + }, + "put": { + "tags": [ + "pty" + ], + "operationId": "v2.pty.update", + "parameters": [ + { + "name": "ptyID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^pty" + } + ] + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "PtyNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PtyNotFoundError" + } + } + } + } + }, + "description": "Update the title or viewport size of one PTY session.", + "summary": "Update PTY session", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "size": { + "type": "object", + "properties": { + "rows": { + "type": "integer", + "allOf": [ + { + "exclusiveMinimum": 0 + } + ] + }, + "cols": { + "type": "integer", + "allOf": [ + { + "exclusiveMinimum": 0 + } + ] + } + }, + "required": [ + "rows", + "cols" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + } + } + }, + "required": true + } + }, + "delete": { + "tags": [ + "pty" + ], + "operationId": "v2.pty.remove", + "parameters": [ + { + "name": "ptyID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^pty" + } + ] + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "PtyNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PtyNotFoundError" + } + } + } + } + }, + "description": "Terminate and remove one PTY session.", + "summary": "Remove PTY session" + } + }, + "/api/pty/{ptyID}/connect-token": { + "post": { + "tags": [ + "pty" + ], + "operationId": "v2.pty.connectToken", + "parameters": [ + { + "name": "ptyID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^pty" + } + ] + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/PtyTicket.ConnectToken" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenError" + } + } + } + }, + "404": { + "description": "PtyNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PtyNotFoundError" + } + } + } + } + }, + "description": "Create a short-lived single-use ticket for opening a PTY WebSocket connection.", + "summary": "Create PTY WebSocket token" + } + }, + "/api/pty/{ptyID}/connect": { + "get": { + "tags": [ + "pty" + ], + "operationId": "v2.pty.connect", + "x-websocket": true, + "parameters": [ + { + "name": "ptyID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^pty" + } + ] + }, + "required": true + }, + { + "in": "query", + "name": "location[directory]", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "location[workspace]", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "cursor", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "ticket", + "schema": { + "type": "string" + } + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "boolean" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenError" + } + } + } + }, + "404": { + "description": "PtyNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PtyNotFoundError" + } + } + } + } + }, + "description": "Establish a WebSocket connection streaming PTY output and accepting terminal input.", + "summary": "Connect to PTY session" + } + }, + "/api/shell": { + "get": { + "tags": [ + "shell" + ], + "operationId": "v2.shell.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Shell1" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "List currently running shell commands for a location. Exited commands are not included.", + "summary": "List running shell commands" + }, + "post": { + "tags": [ + "shell" + ], + "operationId": "v2.shell.create", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/Shell1" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Spawn one non-interactive shell command for a location. Combined stdout/stderr is captured to a file pageable via output.", + "summary": "Run shell command", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "command": { + "type": "string" + }, + "cwd": { + "type": "string" + }, + "timeout": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "metadata": { + "type": "object" + } + }, + "required": [ + "command" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/shell/{id}": { + "get": { + "tags": [ + "shell" + ], + "operationId": "v2.shell.get", + "parameters": [ + { + "name": "id", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^sh_" + } + ] + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "$ref": "#/components/schemas/Shell1" + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "ShellNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShellNotFoundError" + } + } + } + } + }, + "description": "Get one shell command, including its status and exit code once exited.", + "summary": "Get shell command" + }, + "delete": { + "tags": [ + "shell" + ], + "operationId": "v2.shell.remove", + "parameters": [ + { + "name": "id", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^sh_" + } + ] + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "ShellNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShellNotFoundError" + } + } + } + } + }, + "description": "Terminate and remove one shell command and its retained output.", + "summary": "Remove shell command" + } + }, + "/api/shell/{id}/output": { + "get": { + "tags": [ + "shell" + ], + "operationId": "v2.shell.output", + "parameters": [ + { + "name": "id", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^sh_" + } + ] + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + }, + { + "name": "cursor", + "in": "query", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?$" + } + ] + }, + "required": false + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?$" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "object", + "properties": { + "output": { + "type": "string" + }, + "cursor": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "size": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "truncated": { + "type": "boolean" + } + }, + "required": [ + "output", + "cursor", + "size", + "truncated" + ], + "additionalProperties": false + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "ShellNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShellNotFoundError" + } + } + } + } + }, + "description": "Page through captured combined output by absolute byte cursor.", + "summary": "Read shell output" + } + }, + "/api/question/request": { + "get": { + "tags": [ + "session questions" + ], + "operationId": "v2.question.request.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionV2.Request" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Retrieve pending question requests for a location.", + "summary": "List pending question requests" + } + }, + "/api/session/{sessionID}/question": { + "get": { + "tags": [ + "session questions" + ], + "operationId": "v2.session.question.list", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionV2.Request" + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Retrieve pending question requests owned by a session.", + "summary": "List session question requests" + } + }, + "/api/session/{sessionID}/question/{requestID}/reply": { + "post": { + "tags": [ + "session questions" + ], + "operationId": "v2.session.question.reply", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "requestID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | QuestionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/QuestionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Answer a pending question request owned by a session.", + "summary": "Reply to pending question request", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/QuestionV2.Reply" + } + } + }, + "required": true + } + } + }, + "/api/session/{sessionID}/question/{requestID}/reject": { + "post": { + "tags": [ + "session questions" + ], + "operationId": "v2.session.question.reject", + "parameters": [ + { + "name": "sessionID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "required": true + }, + { + "name": "requestID", + "in": "path", + "schema": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | QuestionNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/QuestionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + }, + { + "$ref": "#/components/schemas/SessionNotFoundError" + } + ] + } + } + } + } + }, + "description": "Reject a pending question request owned by a session.", + "summary": "Reject pending question request" + } + }, + "/api/reference": { + "get": { + "tags": [ + "reference" + ], + "operationId": "v2.reference.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Reference.Info" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "List references available in the requested location.", + "summary": "List references" + } + }, + "/experimental/project/{projectID}/copy": { + "post": { + "tags": [ + "projectCopy" + ], + "operationId": "v2.projectCopy.create", + "parameters": [ + { + "name": "projectID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "ProjectCopy.Copy", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectCopy.Copy" + } + } + } + }, + "400": { + "description": "ProjectCopyError | InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ProjectCopyError" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "strategy": { + "type": "string" + }, + "directory": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "strategy", + "directory" + ], + "additionalProperties": false + } + } + }, + "required": true + } + }, + "delete": { + "tags": [ + "projectCopy" + ], + "operationId": "v2.projectCopy.remove", + "parameters": [ + { + "name": "projectID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "ProjectCopyError | InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ProjectCopyError" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "directory": { + "type": "string" + }, + "force": { + "type": "boolean" + } + }, + "required": [ + "directory", + "force" + ], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/experimental/project/{projectID}/copy/refresh": { + "post": { + "tags": [ + "projectCopy" + ], + "operationId": "v2.projectCopy.refresh", + "parameters": [ + { + "name": "projectID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "ProjectCopyError | InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ProjectCopyError" + }, + { + "$ref": "#/components/schemas/InvalidRequestError" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + } + } + }, + "/api/vcs/status": { + "get": { + "tags": [ + "vcs" + ], + "operationId": "v2.vcs.status", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Vcs.FileStatus" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "List uncommitted working-copy changes relative to the requested location.", + "summary": "VCS status" + } + }, + "/api/vcs/diff": { + "get": { + "tags": [ + "vcs" + ], + "operationId": "v2.vcs.diff", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + }, + { + "name": "mode", + "in": "query", + "schema": { + "$ref": "#/components/schemas/Vcs.Mode" + }, + "required": true + }, + { + "name": "context", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.Info" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SnapshotFileDiff" + } + } + }, + "required": [ + "location", + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestError" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedError" + } + } + } + } + }, + "description": "Diff the working copy against HEAD (mode git) or the default-branch merge base (mode branch) for the requested location.", + "summary": "VCS diff" + } + } + }, + "components": { + "schemas": { + "UnauthorizedError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "UnauthorizedError" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "additionalProperties": false + }, + "InvalidRequestError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "InvalidRequestError" + ] + }, + "message": { + "type": "string" + }, + "kind": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "field": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "_tag", + "message" + ], + "additionalProperties": false + }, + "Location.Info": { + "type": "object", + "properties": { + "directory": { + "type": "string" + }, + "workspaceID": { + "type": "string", + "allOf": [ + { + "pattern": "^wrk" + } + ] + }, + "project": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "directory": { + "type": "string" + } + }, + "required": [ + "id", + "directory" + ], + "additionalProperties": false + } + }, + "required": [ + "directory", + "project" + ], + "additionalProperties": false + }, + "Model.Ref": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { + "type": "string" + } + }, + "required": [ + "id", + "providerID" + ], + "additionalProperties": false + }, + "Provider.Settings": { + "type": "object" + }, + "Provider.Request": { + "type": "object", + "properties": { + "settings": { + "$ref": "#/components/schemas/Provider.Settings" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + } + }, + "required": [ + "settings", + "headers", + "body" + ], + "additionalProperties": false + }, + "Agent.Color": { + "anyOf": [ + { + "type": "string", + "allOf": [ + { + "pattern": "^#[0-9a-fA-F]{6}$" + } + ] + }, + { + "type": "string", + "enum": [ + "primary", + "secondary", + "accent", + "success", + "warning", + "error", + "info" + ] + } + ] + }, + "PermissionV2.Effect": { + "type": "string", + "enum": [ + "allow", + "deny", + "ask" + ] + }, + "PermissionV2.Rule": { + "type": "object", + "properties": { + "action": { + "type": "string" + }, + "resource": { + "type": "string" + }, + "effect": { + "$ref": "#/components/schemas/PermissionV2.Effect" + } + }, + "required": [ + "action", + "resource", + "effect" + ], + "additionalProperties": false + }, + "PermissionV2.Ruleset": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionV2.Rule" + } + }, + "AgentV2.Info": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "model": { + "$ref": "#/components/schemas/Model.Ref" + }, + "request": { + "$ref": "#/components/schemas/Provider.Request" + }, + "system": { + "type": "string" + }, + "description": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "subagent", + "primary", + "all" + ] + }, + "hidden": { + "type": "boolean" + }, + "color": { + "$ref": "#/components/schemas/Agent.Color" + }, + "steps": { + "type": "integer", + "allOf": [ + { + "exclusiveMinimum": 0 + } + ] + }, + "permissions": { + "$ref": "#/components/schemas/PermissionV2.Ruleset" + } + }, + "required": [ + "id", + "request", + "mode", + "hidden", + "permissions" + ], + "additionalProperties": false + }, + "Plugin.Info": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "required": [ + "id" + ], + "additionalProperties": false + }, + "Location.Ref": { + "type": "object", + "properties": { + "directory": { + "type": "string" + }, + "workspaceID": { + "type": "string", + "allOf": [ + { + "pattern": "^wrk" + } + ] + } + }, + "required": [ + "directory" + ], + "additionalProperties": false + }, + "File.Diff": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "added", + "modified", + "deleted" + ] + }, + "additions": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "deletions": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "patch": { + "type": "string" + } + }, + "required": [ + "path", + "status", + "additions", + "deletions", + "patch" + ], + "additionalProperties": false + }, + "Revert.State": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "partID": { + "type": "string" + }, + "snapshot": { + "type": "string" + }, + "diff": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/File.Diff" + } + } + }, + "required": [ + "messageID" + ], + "additionalProperties": false + }, + "SessionV2.Info": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "parentID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "projectID": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "model": { + "$ref": "#/components/schemas/Model.Ref" + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": [ + "read", + "write" + ], + "additionalProperties": false + } + }, + "required": [ + "input", + "output", + "reasoning", + "cache" + ], + "additionalProperties": false + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + }, + "updated": { + "type": "number" + }, + "archived": { + "type": "number" + } + }, + "required": [ + "created", + "updated" + ], + "additionalProperties": false + }, + "title": { + "type": "string" + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "subpath": { + "type": "string" + }, + "revert": { + "$ref": "#/components/schemas/Revert.State" + } + }, + "required": [ + "id", + "projectID", + "cost", + "tokens", + "time", + "title", + "location" + ], + "additionalProperties": false + }, + "SessionWatermarks": { + "type": "object", + "patternProperties": { + "^ses": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "description": "Durable log seq each session's snapshot was computed at. Attach a live log read after the watermark to compose fetch and stream gap-free; apply a snapshot only where its watermark is at or beyond already-applied events. Sessions without durable events are absent." + }, + "SessionsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SessionV2.Info" + } + }, + "watermarks": { + "$ref": "#/components/schemas/SessionWatermarks" + }, + "cursor": { + "type": "object", + "properties": { + "previous": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "next": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + }, + "required": [ + "data", + "watermarks", + "cursor" + ], + "additionalProperties": false + }, + "InvalidCursorError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "InvalidCursorError" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "additionalProperties": false + }, + "InvalidRequestError1": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "InvalidRequestError" + ] + }, + "message": { + "type": "string" + }, + "kind": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "field": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "_tag", + "message" + ], + "additionalProperties": false + }, + "SessionActive": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "running" + ] + } + }, + "required": [ + "type" + ], + "additionalProperties": false + }, + "SessionNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "SessionNotFoundError" + ] + }, + "sessionID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "sessionID", + "message" + ], + "additionalProperties": false + }, + "MessageNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "MessageNotFoundError" + ] + }, + "sessionID": { + "type": "string" + }, + "messageID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "sessionID", + "messageID", + "message" + ], + "additionalProperties": false + }, + "Prompt.Source": { + "type": "object", + "properties": { + "start": { + "type": "number" + }, + "end": { + "type": "number" + }, + "text": { + "type": "string" + } + }, + "required": [ + "start", + "end", + "text" + ], + "additionalProperties": false + }, + "PromptInput.FileAttachment": { + "type": "object", + "properties": { + "uri": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "source": { + "$ref": "#/components/schemas/Prompt.Source" + } + }, + "required": [ + "uri" + ], + "additionalProperties": false + }, + "Prompt.AgentAttachment": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "source": { + "$ref": "#/components/schemas/Prompt.Source" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "PromptInput": { + "type": "object", + "properties": { + "text": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PromptInput.FileAttachment" + } + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Prompt.AgentAttachment" + } + } + }, + "required": [ + "text" + ], + "additionalProperties": false + }, + "Prompt.FileAttachment": { + "type": "object", + "properties": { + "uri": { + "type": "string" + }, + "mime": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "source": { + "$ref": "#/components/schemas/Prompt.Source" + } + }, + "required": [ + "uri", + "mime" + ], + "additionalProperties": false + }, + "Prompt": { + "type": "object", + "properties": { + "text": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Prompt.FileAttachment" + } + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Prompt.AgentAttachment" + } + } + }, + "required": [ + "text" + ], + "additionalProperties": false + }, + "SessionInput.Admitted": { + "type": "object", + "properties": { + "admittedSeq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "prompt": { + "$ref": "#/components/schemas/Prompt" + }, + "delivery": { + "type": "string", + "enum": [ + "steer", + "queue" + ] + }, + "timeCreated": { + "type": "number" + }, + "promotedSeq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "admittedSeq", + "id", + "sessionID", + "prompt", + "delivery", + "timeCreated" + ], + "additionalProperties": false + }, + "ConflictError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "ConflictError" + ] + }, + "message": { + "type": "string" + }, + "resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "_tag", + "message" + ], + "additionalProperties": false + }, + "CommandNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "CommandNotFoundError" + ] + }, + "command": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "command", + "message" + ], + "additionalProperties": false + }, + "CommandEvaluationError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "CommandEvaluationError" + ] + }, + "command": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "command", + "message" + ], + "additionalProperties": false + }, + "SkillNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "SkillNotFoundError" + ] + }, + "skill": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "skill", + "message" + ], + "additionalProperties": false + }, + "SessionBusyError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "SessionBusyError" + ] + }, + "sessionID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "sessionID", + "message" + ], + "additionalProperties": false + }, + "ServiceUnavailableError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "ServiceUnavailableError" + ] + }, + "message": { + "type": "string" + }, + "service": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "_tag", + "message" + ], + "additionalProperties": false + }, + "UnknownError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "UnknownError" + ] + }, + "message": { + "type": "string" + }, + "ref": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "_tag", + "message" + ], + "additionalProperties": false + }, + "Session.Message.AgentSwitched": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "type": { + "type": "string", + "enum": [ + "agent-switched" + ] + }, + "agent": { + "type": "string" + } + }, + "required": [ + "id", + "time", + "type", + "agent" + ], + "additionalProperties": false + }, + "Session.Message.ModelSwitched": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "type": { + "type": "string", + "enum": [ + "model-switched" + ] + }, + "model": { + "$ref": "#/components/schemas/Model.Ref" + } + }, + "required": [ + "id", + "time", + "type", + "model" + ], + "additionalProperties": false + }, + "Session.Message.User": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "text": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Prompt.FileAttachment" + } + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Prompt.AgentAttachment" + } + }, + "type": { + "type": "string", + "enum": [ + "user" + ] + } + }, + "required": [ + "id", + "time", + "text", + "type" + ], + "additionalProperties": false + }, + "Session.Message.Synthetic": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "text": { + "type": "string" + }, + "description": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "synthetic" + ] + } + }, + "required": [ + "id", + "time", + "sessionID", + "text", + "type" + ], + "additionalProperties": false + }, + "Session.Message.System": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "type": { + "type": "string", + "enum": [ + "system" + ] + }, + "text": { + "type": "string" + } + }, + "required": [ + "id", + "time", + "type", + "text" + ], + "additionalProperties": false + }, + "Session.Message.Skill": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "type": { + "type": "string", + "enum": [ + "skill" + ] + }, + "name": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "id", + "time", + "type", + "name", + "text" + ], + "additionalProperties": false + }, + "Session.Message.Shell": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + }, + "completed": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "type": { + "type": "string", + "enum": [ + "shell" + ] + }, + "callID": { + "type": "string" + }, + "command": { + "type": "string" + }, + "output": { + "type": "string" + } + }, + "required": [ + "id", + "time", + "type", + "callID", + "command", + "output" + ], + "additionalProperties": false + }, + "Session.Message.Assistant.Text": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ] + }, + "id": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "id", + "text" + ], + "additionalProperties": false + }, + "LLM.ProviderMetadata": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "Session.Message.Assistant.Reasoning": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "reasoning" + ] + }, + "id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "providerMetadata": { + "$ref": "#/components/schemas/LLM.ProviderMetadata" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + }, + "completed": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + } + }, + "required": [ + "type", + "id", + "text" + ], + "additionalProperties": false + }, + "Session.Message.ToolState.Pending": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "pending" + ] + }, + "input": { + "type": "string" + } + }, + "required": [ + "status", + "input" + ], + "additionalProperties": false + }, + "Tool.TextContent": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ] + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ], + "additionalProperties": false + }, + "Tool.FileContent": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "file" + ] + }, + "uri": { + "type": "string" + }, + "mime": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "type", + "uri", + "mime" + ], + "additionalProperties": false + }, + "LLM.ToolContent": { + "anyOf": [ + { + "$ref": "#/components/schemas/Tool.TextContent" + }, + { + "$ref": "#/components/schemas/Tool.FileContent" + } + ] + }, + "Session.Message.ToolState.Running": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "running" + ] + }, + "input": { + "type": "object" + }, + "structured": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LLM.ToolContent" + } + } + }, + "required": [ + "status", + "input", + "structured", + "content" + ], + "additionalProperties": false + }, + "Session.Message.ToolState.Completed": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "completed" + ] + }, + "input": { + "type": "object" + }, + "attachments": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Prompt.FileAttachment" + } + }, + "content": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LLM.ToolContent" + } + }, + "outputPaths": { + "type": "array", + "items": { + "type": "string" + } + }, + "structured": { + "type": "object" + }, + "result": {} + }, + "required": [ + "status", + "input", + "content", + "structured" + ], + "additionalProperties": false + }, + "Session.Error.Unknown": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "unknown" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "type", + "message" + ], + "additionalProperties": false + }, + "Session.Message.ToolState.Error": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "error" + ] + }, + "input": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LLM.ToolContent" + } + }, + "structured": { + "type": "object" + }, + "error": { + "$ref": "#/components/schemas/Session.Error.Unknown" + }, + "result": {} + }, + "required": [ + "status", + "input", + "content", + "structured", + "error" + ], + "additionalProperties": false + }, + "Session.Message.Assistant.Tool": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "tool" + ] + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "$ref": "#/components/schemas/LLM.ProviderMetadata" + }, + "resultMetadata": { + "$ref": "#/components/schemas/LLM.ProviderMetadata" + } + }, + "required": [ + "executed" + ], + "additionalProperties": false + }, + "state": { + "anyOf": [ + { + "$ref": "#/components/schemas/Session.Message.ToolState.Pending" + }, + { + "$ref": "#/components/schemas/Session.Message.ToolState.Running" + }, + { + "$ref": "#/components/schemas/Session.Message.ToolState.Completed" + }, + { + "$ref": "#/components/schemas/Session.Message.ToolState.Error" + } + ] + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + }, + "ran": { + "type": "number" + }, + "completed": { + "type": "number" + }, + "pruned": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + } + }, + "required": [ + "type", + "id", + "name", + "state", + "time" + ], + "additionalProperties": false + }, + "Session.Message.Assistant": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + }, + "completed": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "type": { + "type": "string", + "enum": [ + "assistant" + ] + }, + "agent": { + "type": "string" + }, + "model": { + "$ref": "#/components/schemas/Model.Ref" + }, + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/Session.Message.Assistant.Text" + }, + { + "$ref": "#/components/schemas/Session.Message.Assistant.Reasoning" + }, + { + "$ref": "#/components/schemas/Session.Message.Assistant.Tool" + } + ] + } + }, + "snapshot": { + "type": "object", + "properties": { + "start": { + "type": "string" + }, + "end": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "finish": { + "type": "string" + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": [ + "read", + "write" + ], + "additionalProperties": false + } + }, + "required": [ + "input", + "output", + "reasoning", + "cache" + ], + "additionalProperties": false + }, + "error": { + "$ref": "#/components/schemas/Session.Error.Unknown" + } + }, + "required": [ + "id", + "time", + "type", + "agent", + "model", + "content" + ], + "additionalProperties": false + }, + "Session.Message.Compaction": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "compaction" + ] + }, + "reason": { + "type": "string", + "enum": [ + "auto", + "manual" + ] + }, + "summary": { + "type": "string" + }, + "recent": { + "type": "string" + }, + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": [ + "created" + ], + "additionalProperties": false + } + }, + "required": [ + "type", + "reason", + "summary", + "recent", + "id", + "time" + ], + "additionalProperties": false + }, + "Session.Message": { + "anyOf": [ + { + "$ref": "#/components/schemas/Session.Message.AgentSwitched" + }, + { + "$ref": "#/components/schemas/Session.Message.ModelSwitched" + }, + { + "$ref": "#/components/schemas/Session.Message.User" + }, + { + "$ref": "#/components/schemas/Session.Message.Synthetic" + }, + { + "$ref": "#/components/schemas/Session.Message.System" + }, + { + "$ref": "#/components/schemas/Session.Message.Skill" + }, + { + "$ref": "#/components/schemas/Session.Message.Shell" + }, + { + "$ref": "#/components/schemas/Session.Message.Assistant" + }, + { + "$ref": "#/components/schemas/Session.Message.Compaction" + } + ] + }, + "SessionContextEntry.Key": { + "type": "string", + "allOf": [ + { + "pattern": "^[a-z0-9][a-z0-9._-]*$", + "description": "Context entry key (lowercase alphanumerics plus . _ -)" + } + ] + }, + "SessionContextEntry.Info": { + "type": "object", + "properties": { + "key": { + "$ref": "#/components/schemas/SessionContextEntry.Key" + }, + "value": {} + }, + "required": [ + "key", + "value" + ], + "additionalProperties": false + }, + "session.next.agent.switched": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.agent.switched" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "agent": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "agent" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.model.switched": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.model.switched" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "model": { + "$ref": "#/components/schemas/Model.Ref" + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "model" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.moved": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.moved" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "subdirectory": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "location" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.renamed": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.renamed" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "title": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "title" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.forked": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.forked" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "parentID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + } + }, + "required": [ + "timestamp", + "sessionID", + "parentID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.prompted": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.prompted" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "prompt": { + "$ref": "#/components/schemas/Prompt" + }, + "delivery": { + "type": "string", + "enum": [ + "steer", + "queue" + ] + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "prompt", + "delivery" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.prompt.admitted": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.prompt.admitted" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "prompt": { + "$ref": "#/components/schemas/Prompt" + }, + "delivery": { + "type": "string", + "enum": [ + "steer", + "queue" + ] + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "prompt", + "delivery" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.context.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.context.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "text": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.synthetic": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.synthetic" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "text": { + "type": "string" + }, + "description": { + "type": "string" + }, + "metadata": { + "type": "object" + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.skill.activated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.skill.activated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "name": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "name", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.shell.started": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.shell.started" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "callID": { + "type": "string" + }, + "command": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "callID", + "command" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.shell.ended": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.shell.ended" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "callID": { + "type": "string" + }, + "output": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "callID", + "output" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.step.started": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.step.started" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "agent": { + "type": "string" + }, + "model": { + "$ref": "#/components/schemas/Model.Ref" + }, + "snapshot": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "agent", + "model" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.step.ended": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.step.ended" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "finish": { + "type": "string" + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": [ + "read", + "write" + ], + "additionalProperties": false + } + }, + "required": [ + "input", + "output", + "reasoning", + "cache" + ], + "additionalProperties": false + }, + "snapshot": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "finish", + "cost", + "tokens" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.step.failed": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.step.failed" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "error": { + "$ref": "#/components/schemas/Session.Error.Unknown" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "error" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.text.started": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.text.started" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "textID": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "textID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.text.ended": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.text.ended" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "textID": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "textID", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.tool.input.started": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.tool.input.started" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "callID": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "callID", + "name" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.tool.input.ended": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.tool.input.ended" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "callID": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "callID", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "LLM.ProviderMetadata3": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "session.next.tool.called": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.tool.called" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "callID": { + "type": "string" + }, + "tool": { + "type": "string" + }, + "input": { + "type": "object" + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "$ref": "#/components/schemas/LLM.ProviderMetadata3" + } + }, + "required": [ + "executed" + ], + "additionalProperties": false + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "callID", + "tool", + "input", + "provider" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.tool.progress": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.tool.progress" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "callID": { + "type": "string" + }, + "structured": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LLM.ToolContent" + } + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "callID", + "structured", + "content" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "LLM.ProviderMetadata4": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "session.next.tool.success": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.tool.success" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "callID": { + "type": "string" + }, + "structured": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LLM.ToolContent" + } + }, + "outputPaths": { + "type": "array", + "items": { + "type": "string" + } + }, + "result": {}, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "$ref": "#/components/schemas/LLM.ProviderMetadata4" + } + }, + "required": [ + "executed" + ], + "additionalProperties": false + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "callID", + "structured", + "content", + "provider" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "LLM.ProviderMetadata5": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "session.next.tool.failed": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.tool.failed" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "callID": { + "type": "string" + }, + "error": { + "$ref": "#/components/schemas/Session.Error.Unknown" + }, + "result": {}, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "$ref": "#/components/schemas/LLM.ProviderMetadata5" + } + }, + "required": [ + "executed" + ], + "additionalProperties": false + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "callID", + "error", + "provider" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "LLM.ProviderMetadata6": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "session.next.reasoning.started": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.reasoning.started" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "reasoningID": { + "type": "string" + }, + "providerMetadata": { + "$ref": "#/components/schemas/LLM.ProviderMetadata6" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "reasoningID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "LLM.ProviderMetadata7": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "session.next.reasoning.ended": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.reasoning.ended" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "reasoningID": { + "type": "string" + }, + "text": { + "type": "string" + }, + "providerMetadata": { + "$ref": "#/components/schemas/LLM.ProviderMetadata7" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "reasoningID", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.retry_error": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "statusCode": { + "type": "number" + }, + "isRetryable": { + "type": "boolean" + }, + "responseHeaders": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "responseBody": { + "type": "string" + }, + "metadata": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "message", + "isRetryable" + ], + "additionalProperties": false + }, + "session.next.retried": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.retried" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "attempt": { + "type": "number" + }, + "error": { + "$ref": "#/components/schemas/session.next.retry_error" + } + }, + "required": [ + "timestamp", + "sessionID", + "attempt", + "error" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.compaction.started": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.compaction.started" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "reason": { + "type": "string", + "enum": [ + "auto", + "manual" + ] + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "reason" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.compaction.ended": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.compaction.ended" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "reason": { + "type": "string", + "enum": [ + "auto", + "manual" + ] + }, + "text": { + "type": "string" + }, + "recent": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "reason", + "text", + "recent" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.revert.staged": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.revert.staged" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "revert": { + "$ref": "#/components/schemas/Revert.State" + } + }, + "required": [ + "timestamp", + "sessionID", + "revert" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.revert.cleared": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.revert.cleared" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + } + }, + "required": [ + "timestamp", + "sessionID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.revert.committed": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.revert.committed" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "SessionDurableEvent": { + "oneOf": [ + { + "$ref": "#/components/schemas/session.next.agent.switched" + }, + { + "$ref": "#/components/schemas/session.next.model.switched" + }, + { + "$ref": "#/components/schemas/session.next.moved" + }, + { + "$ref": "#/components/schemas/session.next.renamed" + }, + { + "$ref": "#/components/schemas/session.next.forked" + }, + { + "$ref": "#/components/schemas/session.next.prompted" + }, + { + "$ref": "#/components/schemas/session.next.prompt.admitted" + }, + { + "$ref": "#/components/schemas/session.next.context.updated" + }, + { + "$ref": "#/components/schemas/session.next.synthetic" + }, + { + "$ref": "#/components/schemas/session.next.skill.activated" + }, + { + "$ref": "#/components/schemas/session.next.shell.started" + }, + { + "$ref": "#/components/schemas/session.next.shell.ended" + }, + { + "$ref": "#/components/schemas/session.next.step.started" + }, + { + "$ref": "#/components/schemas/session.next.step.ended" + }, + { + "$ref": "#/components/schemas/session.next.step.failed" + }, + { + "$ref": "#/components/schemas/session.next.text.started" + }, + { + "$ref": "#/components/schemas/session.next.text.ended" + }, + { + "$ref": "#/components/schemas/session.next.tool.input.started" + }, + { + "$ref": "#/components/schemas/session.next.tool.input.ended" + }, + { + "$ref": "#/components/schemas/session.next.tool.called" + }, + { + "$ref": "#/components/schemas/session.next.tool.progress" + }, + { + "$ref": "#/components/schemas/session.next.tool.success" + }, + { + "$ref": "#/components/schemas/session.next.tool.failed" + }, + { + "$ref": "#/components/schemas/session.next.reasoning.started" + }, + { + "$ref": "#/components/schemas/session.next.reasoning.ended" + }, + { + "$ref": "#/components/schemas/session.next.retried" + }, + { + "$ref": "#/components/schemas/session.next.compaction.started" + }, + { + "$ref": "#/components/schemas/session.next.compaction.ended" + }, + { + "$ref": "#/components/schemas/session.next.revert.staged" + }, + { + "$ref": "#/components/schemas/session.next.revert.cleared" + }, + { + "$ref": "#/components/schemas/session.next.revert.committed" + } + ] + }, + "EventLog.Synced": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "log.synced" + ] + }, + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "type", + "aggregateID" + ], + "additionalProperties": false, + "description": "Marker emitted once when a log read reaches its captured watermark. The reader holds every event committed at or below seq." + }, + "SessionLogItem": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionDurableEvent" + }, + { + "$ref": "#/components/schemas/EventLog.Synced" + } + ] + }, + "SessionLogItemStream": { + "type": "string", + "contentSchema": { + "$ref": "#/components/schemas/SessionLogItem" + }, + "contentMediaType": "application/json" + }, + "SessionMessagesResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Session.Message" + } + }, + "watermark": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "cursor": { + "type": "object", + "properties": { + "previous": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "next": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + }, + "required": [ + "data", + "cursor" + ], + "additionalProperties": false + }, + "Model.Api": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "aisdk" + ] + }, + "package": { + "type": "string" + }, + "url": { + "type": "string" + }, + "settings": { + "type": "object" + } + }, + "required": [ + "id", + "type", + "package" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "native" + ] + }, + "url": { + "type": "string" + }, + "settings": { + "type": "object" + } + }, + "required": [ + "id", + "type", + "settings" + ], + "additionalProperties": false + } + ] + }, + "Model.Capabilities": { + "type": "object", + "properties": { + "tools": { + "type": "boolean" + }, + "input": { + "type": "array", + "items": { + "type": "string" + } + }, + "output": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "tools", + "input", + "output" + ], + "additionalProperties": false + }, + "Model.Cost": { + "type": "object", + "properties": { + "tier": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "context" + ] + }, + "size": { + "type": "integer" + } + }, + "required": [ + "type", + "size" + ], + "additionalProperties": false + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": [ + "read", + "write" + ], + "additionalProperties": false + } + }, + "required": [ + "input", + "output", + "cache" + ], + "additionalProperties": false + }, + "ModelV2.Info": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "family": { + "type": "string" + }, + "name": { + "type": "string" + }, + "api": { + "$ref": "#/components/schemas/Model.Api" + }, + "capabilities": { + "$ref": "#/components/schemas/Model.Capabilities" + }, + "request": { + "type": "object", + "properties": { + "settings": { + "$ref": "#/components/schemas/Provider.Settings" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + }, + "variant": { + "type": "string" + } + }, + "required": [ + "settings", + "headers", + "body" + ], + "additionalProperties": false + }, + "variants": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "settings": { + "$ref": "#/components/schemas/Provider.Settings" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + } + }, + "required": [ + "id", + "settings", + "headers", + "body" + ], + "additionalProperties": false + } + }, + "time": { + "type": "object", + "properties": { + "released": { + "type": "number" + } + }, + "required": [ + "released" + ], + "additionalProperties": false + }, + "cost": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Model.Cost" + } + }, + "status": { + "type": "string", + "enum": [ + "alpha", + "beta", + "deprecated", + "active" + ] + }, + "enabled": { + "type": "boolean" + }, + "limit": { + "type": "object", + "properties": { + "context": { + "type": "integer" + }, + "input": { + "type": "integer" + }, + "output": { + "type": "integer" + } + }, + "required": [ + "context", + "output" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "providerID", + "name", + "api", + "capabilities", + "request", + "variants", + "time", + "cost", + "status", + "enabled", + "limit" + ], + "additionalProperties": false + }, + "GenerateTextResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "text": { + "type": "string" + } + }, + "required": [ + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + }, + "Provider.AISDK": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "aisdk" + ] + }, + "package": { + "type": "string" + }, + "url": { + "type": "string" + }, + "settings": { + "type": "object" + } + }, + "required": [ + "type", + "package" + ], + "additionalProperties": false + }, + "Provider.Native": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "native" + ] + }, + "url": { + "type": "string" + }, + "settings": { + "type": "object" + } + }, + "required": [ + "type", + "settings" + ], + "additionalProperties": false + }, + "Provider.Api": { + "anyOf": [ + { + "$ref": "#/components/schemas/Provider.AISDK" + }, + { + "$ref": "#/components/schemas/Provider.Native" + } + ] + }, + "ProviderV2.Info": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "integrationID": { + "type": "string" + }, + "name": { + "type": "string" + }, + "disabled": { + "type": "boolean" + }, + "api": { + "$ref": "#/components/schemas/Provider.Api" + }, + "request": { + "$ref": "#/components/schemas/Provider.Request" + } + }, + "required": [ + "id", + "name", + "api", + "request" + ], + "additionalProperties": false + }, + "ProviderNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "ProviderNotFoundError" + ] + }, + "providerID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "providerID", + "message" + ], + "additionalProperties": false + }, + "Integration.When": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "op": { + "type": "string", + "enum": [ + "eq", + "neq" + ] + }, + "value": { + "type": "string" + } + }, + "required": [ + "key", + "op", + "value" + ], + "additionalProperties": false + }, + "Integration.TextPrompt": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ] + }, + "key": { + "type": "string" + }, + "message": { + "type": "string" + }, + "placeholder": { + "type": "string" + }, + "when": { + "$ref": "#/components/schemas/Integration.When" + } + }, + "required": [ + "type", + "key", + "message" + ], + "additionalProperties": false + }, + "Integration.SelectPrompt": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "select" + ] + }, + "key": { + "type": "string" + }, + "message": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string" + }, + "value": { + "type": "string" + }, + "hint": { + "type": "string" + } + }, + "required": [ + "label", + "value" + ], + "additionalProperties": false + } + }, + "when": { + "$ref": "#/components/schemas/Integration.When" + } + }, + "required": [ + "type", + "key", + "message", + "options" + ], + "additionalProperties": false + }, + "Integration.OAuthMethod": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "oauth" + ] + }, + "label": { + "type": "string" + }, + "prompts": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/Integration.TextPrompt" + }, + { + "$ref": "#/components/schemas/Integration.SelectPrompt" + } + ] + } + } + }, + "required": [ + "id", + "type", + "label" + ], + "additionalProperties": false + }, + "Integration.KeyMethod": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "key" + ] + }, + "label": { + "type": "string" + } + }, + "required": [ + "type" + ], + "additionalProperties": false + }, + "Integration.EnvMethod": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "env" + ] + }, + "names": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "type", + "names" + ], + "additionalProperties": false + }, + "Integration.Method": { + "anyOf": [ + { + "$ref": "#/components/schemas/Integration.OAuthMethod" + }, + { + "$ref": "#/components/schemas/Integration.KeyMethod" + }, + { + "$ref": "#/components/schemas/Integration.EnvMethod" + } + ] + }, + "Connection.CredentialInfo": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "credential" + ] + }, + "id": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "type", + "id", + "label" + ], + "additionalProperties": false + }, + "Connection.EnvInfo": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "env" + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "type", + "name" + ], + "additionalProperties": false + }, + "Connection.Info": { + "anyOf": [ + { + "$ref": "#/components/schemas/Connection.CredentialInfo" + }, + { + "$ref": "#/components/schemas/Connection.EnvInfo" + } + ] + }, + "Integration.Info": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "methods": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Integration.Method" + } + }, + "connections": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Connection.Info" + } + } + }, + "required": [ + "id", + "name", + "methods", + "connections" + ], + "additionalProperties": false + }, + "Integration.Attempt": { + "type": "object", + "properties": { + "attemptID": { + "type": "string" + }, + "url": { + "type": "string" + }, + "instructions": { + "type": "string" + }, + "mode": { + "type": "string", + "enum": [ + "auto", + "code" + ] + }, + "time": { + "type": "object", + "properties": { + "created": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "expires": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + } + }, + "required": [ + "created", + "expires" + ], + "additionalProperties": false + } + }, + "required": [ + "attemptID", + "url", + "instructions", + "mode", + "time" + ], + "additionalProperties": false + }, + "Integration.AttemptStatus": { + "anyOf": [ + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "pending" + ] + }, + "time": { + "type": "object", + "properties": { + "created": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "expires": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + } + }, + "required": [ + "created", + "expires" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "time" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "complete" + ] + }, + "time": { + "type": "object", + "properties": { + "created": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "expires": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + } + }, + "required": [ + "created", + "expires" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "time" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "failed" + ] + }, + "message": { + "type": "string" + }, + "time": { + "type": "object", + "properties": { + "created": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "expires": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + } + }, + "required": [ + "created", + "expires" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "message", + "time" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "expired" + ] + }, + "time": { + "type": "object", + "properties": { + "created": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "expires": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + } + }, + "required": [ + "created", + "expires" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "time" + ], + "additionalProperties": false + } + ] + }, + "Mcp.Status.Connected": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "connected" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + }, + "Mcp.Status.Disconnected": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "disconnected" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + }, + "Mcp.Status.Disabled": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "disabled" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + }, + "Mcp.Status.Failed": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "failed" + ] + }, + "error": { + "type": "string" + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + }, + "Mcp.Status.NeedsAuth": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "needs_auth" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + }, + "Mcp.Status.NeedsClientRegistration": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "needs_client_registration" + ] + }, + "error": { + "type": "string" + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + }, + "Mcp.Server": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "status": { + "anyOf": [ + { + "$ref": "#/components/schemas/Mcp.Status.Connected" + }, + { + "$ref": "#/components/schemas/Mcp.Status.Disconnected" + }, + { + "$ref": "#/components/schemas/Mcp.Status.Disabled" + }, + { + "$ref": "#/components/schemas/Mcp.Status.Failed" + }, + { + "$ref": "#/components/schemas/Mcp.Status.NeedsAuth" + }, + { + "$ref": "#/components/schemas/Mcp.Status.NeedsClientRegistration" + } + ] + }, + "integrationID": { + "type": "string" + } + }, + "required": [ + "name", + "status" + ], + "additionalProperties": false + }, + "Project.Current": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "directory": { + "type": "string" + } + }, + "required": [ + "id", + "directory" + ], + "additionalProperties": false + }, + "Project.Directory": { + "type": "object", + "properties": { + "directory": { + "type": "string" + }, + "strategy": { + "type": "string" + } + }, + "required": [ + "directory" + ], + "additionalProperties": false + }, + "Project.Directories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Project.Directory" + } + }, + "Form.Metadata": { + "type": "object" + }, + "Form.When": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "op": { + "type": "string", + "enum": [ + "eq", + "neq" + ] + }, + "value": { + "anyOf": [ + { + "type": "string" + }, + { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + { + "type": "boolean" + } + ] + } + }, + "required": [ + "key", + "op", + "value" + ], + "additionalProperties": false + }, + "Form.Option": { + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "label": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "value", + "label" + ], + "additionalProperties": false + }, + "Form.StringField": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When" + } + }, + "type": { + "type": "string", + "enum": [ + "string" + ] + }, + "format": { + "type": "string", + "enum": [ + "email", + "uri", + "date", + "date-time" + ] + }, + "minLength": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "maxLength": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "pattern": { + "type": "string" + }, + "placeholder": { + "type": "string" + }, + "default": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.Option" + } + }, + "custom": { + "type": "boolean" + } + }, + "required": [ + "key", + "type" + ], + "additionalProperties": false + }, + "Form.NumberField": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When" + } + }, + "type": { + "type": "string", + "enum": [ + "number" + ] + }, + "minimum": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "maximum": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "default": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + } + }, + "required": [ + "key", + "type" + ], + "additionalProperties": false + }, + "Form.IntegerField": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When" + } + }, + "type": { + "type": "string", + "enum": [ + "integer" + ] + }, + "minimum": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "maximum": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "default": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + } + }, + "required": [ + "key", + "type" + ], + "additionalProperties": false + }, + "Form.BooleanField": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When" + } + }, + "type": { + "type": "string", + "enum": [ + "boolean" + ] + }, + "default": { + "type": "boolean" + } + }, + "required": [ + "key", + "type" + ], + "additionalProperties": false + }, + "Form.MultiselectField": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When" + } + }, + "type": { + "type": "string", + "enum": [ + "multiselect" + ] + }, + "options": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.Option" + } + }, + "minItems": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "maxItems": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "custom": { + "type": "boolean" + }, + "default": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "key", + "type", + "options" + ], + "additionalProperties": false + }, + "Form.FormInfo": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "sessionID": { + "type": "string" + }, + "title": { + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Form.Metadata" + }, + "mode": { + "type": "string", + "enum": [ + "form" + ] + }, + "fields": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/Form.StringField" + }, + { + "$ref": "#/components/schemas/Form.NumberField" + }, + { + "$ref": "#/components/schemas/Form.IntegerField" + }, + { + "$ref": "#/components/schemas/Form.BooleanField" + }, + { + "$ref": "#/components/schemas/Form.MultiselectField" + } + ] + } + } + }, + "required": [ + "id", + "sessionID", + "mode", + "fields" + ], + "additionalProperties": false + }, + "Form.UrlInfo": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "sessionID": { + "type": "string" + }, + "title": { + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Form.Metadata" + }, + "mode": { + "type": "string", + "enum": [ + "url" + ] + }, + "url": { + "type": "string" + } + }, + "required": [ + "id", + "sessionID", + "mode", + "url" + ], + "additionalProperties": false + }, + "Form.CreatePayload": { + "type": "object", + "properties": { + "id": { + "anyOf": [ + { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + { + "type": "null" + } + ] + }, + "title": { + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Form.Metadata" + }, + "mode": { + "type": "string", + "enum": [ + "form", + "url" + ] + }, + "fields": { + "anyOf": [ + { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/Form.StringField" + }, + { + "$ref": "#/components/schemas/Form.NumberField" + }, + { + "$ref": "#/components/schemas/Form.IntegerField" + }, + { + "$ref": "#/components/schemas/Form.BooleanField" + }, + { + "$ref": "#/components/schemas/Form.MultiselectField" + } + ] + } + }, + { + "type": "null" + } + ] + }, + "url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "mode" + ], + "additionalProperties": false + }, + "FormNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "FormNotFoundError" + ] + }, + "id": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "id", + "message" + ], + "additionalProperties": false + }, + "Form.Value": { + "anyOf": [ + { + "type": "string" + }, + { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + { + "type": "boolean" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "Form.Answer": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Form.Value" + } + }, + "Form.State": { + "anyOf": [ + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "pending" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "answered" + ] + }, + "answer": { + "$ref": "#/components/schemas/Form.Answer" + } + }, + "required": [ + "status", + "answer" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "cancelled" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + } + ] + }, + "Form.Reply": { + "type": "object", + "properties": { + "answer": { + "$ref": "#/components/schemas/Form.Answer" + } + }, + "required": [ + "answer" + ], + "additionalProperties": false + }, + "FormAlreadySettledError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "FormAlreadySettledError" + ] + }, + "id": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "id", + "message" + ], + "additionalProperties": false + }, + "FormInvalidAnswerError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "FormInvalidAnswerError" + ] + }, + "id": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "id", + "message" + ], + "additionalProperties": false + }, + "PermissionV2.Source": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "tool" + ] + }, + "messageID": { + "type": "string" + }, + "callID": { + "type": "string" + } + }, + "required": [ + "type", + "messageID", + "callID" + ], + "additionalProperties": false + } + ] + }, + "PermissionV2.Request": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "action": { + "type": "string" + }, + "resources": { + "type": "array", + "items": { + "type": "string" + } + }, + "save": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { + "type": "object" + }, + "source": { + "$ref": "#/components/schemas/PermissionV2.Source" + } + }, + "required": [ + "id", + "sessionID", + "action", + "resources" + ], + "additionalProperties": false + }, + "PermissionSaved.Info": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "projectID": { + "type": "string" + }, + "action": { + "type": "string" + }, + "resource": { + "type": "string" + } + }, + "required": [ + "id", + "projectID", + "action", + "resource" + ], + "additionalProperties": false + }, + "PermissionNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "PermissionNotFoundError" + ] + }, + "requestID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "requestID", + "message" + ], + "additionalProperties": false + }, + "PermissionV2.Reply": { + "type": "string", + "enum": [ + "once", + "always", + "reject" + ] + }, + "FileSystem.Entry": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "file", + "directory" + ] + } + }, + "required": [ + "path", + "type" + ], + "additionalProperties": false + }, + "CommandV2.Info": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "template": { + "type": "string" + }, + "description": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "model": { + "$ref": "#/components/schemas/Model.Ref" + }, + "subtask": { + "type": "boolean" + } + }, + "required": [ + "name", + "template" + ], + "additionalProperties": false + }, + "SkillV2.Info": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "slash": { + "type": "boolean" + }, + "autoinvoke": { + "type": "boolean" + }, + "location": { + "type": "string" + }, + "content": { + "type": "string" + } + }, + "required": [ + "name", + "location", + "content" + ], + "additionalProperties": false + }, + "models-dev.refreshed": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "models-dev.refreshed" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "integration.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "integration.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "integration.connection.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "integration.connection.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "integrationID": { + "type": "string" + } + }, + "required": [ + "integrationID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "catalog.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "catalog.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "agent.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "agent.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "SnapshotFileDiff": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "patch": { + "type": "string" + }, + "additions": { + "type": "number" + }, + "deletions": { + "type": "number" + }, + "status": { + "type": "string", + "enum": [ + "added", + "deleted", + "modified" + ] + } + }, + "required": [ + "additions", + "deletions" + ], + "additionalProperties": false + }, + "PermissionAction": { + "type": "string", + "enum": [ + "allow", + "deny", + "ask" + ] + }, + "PermissionRule": { + "type": "object", + "properties": { + "permission": { + "type": "string" + }, + "pattern": { + "type": "string" + }, + "action": { + "$ref": "#/components/schemas/PermissionAction" + } + }, + "required": [ + "permission", + "pattern", + "action" + ], + "additionalProperties": false + }, + "PermissionRuleset": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionRule" + } + }, + "Session": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "slug": { + "type": "string" + }, + "projectID": { + "type": "string" + }, + "workspaceID": { + "type": "string", + "allOf": [ + { + "pattern": "^wrk" + } + ] + }, + "directory": { + "type": "string" + }, + "path": { + "type": "string" + }, + "parentID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "summary": { + "type": "object", + "properties": { + "additions": { + "type": "number" + }, + "deletions": { + "type": "number" + }, + "files": { + "type": "number" + }, + "diffs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SnapshotFileDiff" + } + } + }, + "required": [ + "additions", + "deletions", + "files" + ], + "additionalProperties": false + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": [ + "read", + "write" + ], + "additionalProperties": false + } + }, + "required": [ + "input", + "output", + "reasoning", + "cache" + ], + "additionalProperties": false + }, + "share": { + "type": "object", + "properties": { + "url": { + "type": "string" + } + }, + "required": [ + "url" + ], + "additionalProperties": false + }, + "title": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "model": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { + "type": "string" + } + }, + "required": [ + "id", + "providerID" + ], + "additionalProperties": false + }, + "version": { + "type": "string" + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "updated": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "compacting": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "archived": { + "type": "number" + } + }, + "required": [ + "created", + "updated" + ], + "additionalProperties": false + }, + "permission": { + "$ref": "#/components/schemas/PermissionRuleset" + }, + "revert": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "partID": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "snapshot": { + "type": "string" + }, + "diff": { + "type": "string" + } + }, + "required": [ + "messageID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "slug", + "projectID", + "directory", + "title", + "version", + "time" + ], + "additionalProperties": false + }, + "session.created": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.created" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": [ + "sessionID", + "info" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": [ + "sessionID", + "info" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.deleted": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.deleted" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": [ + "sessionID", + "info" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "JSONSchema": { + "type": "object" + }, + "OutputFormat": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ] + } + }, + "required": [ + "type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "json_schema" + ] + }, + "schema": { + "$ref": "#/components/schemas/JSONSchema" + }, + "retryCount": { + "anyOf": [ + { + "anyOf": [ + { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "type", + "schema" + ], + "additionalProperties": false + } + ] + }, + "UserMessage": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "role": { + "type": "string", + "enum": [ + "user" + ] + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "format": { + "anyOf": [ + { + "$ref": "#/components/schemas/OutputFormat" + }, + { + "type": "null" + } + ] + }, + "summary": { + "anyOf": [ + { + "type": "object", + "properties": { + "title": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "body": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "diffs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SnapshotFileDiff" + } + } + }, + "required": [ + "diffs" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "agent": { + "type": "string" + }, + "model": { + "type": "object", + "properties": { + "providerID": { + "type": "string" + }, + "modelID": { + "type": "string" + }, + "variant": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "providerID", + "modelID" + ], + "additionalProperties": false + }, + "system": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "tools": { + "anyOf": [ + { + "type": "object", + "additionalProperties": { + "type": "boolean" + } + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "role", + "time", + "agent", + "model" + ], + "additionalProperties": false + }, + "ProviderAuthError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "ProviderAuthError" + ] + }, + "data": { + "type": "object", + "properties": { + "providerID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "providerID", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "UnknownError1": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "UnknownError" + ] + }, + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "ref": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "MessageOutputLengthError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "MessageOutputLengthError" + ] + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "MessageAbortedError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "MessageAbortedError" + ] + }, + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "StructuredOutputError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "StructuredOutputError" + ] + }, + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "retries": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "message", + "retries" + ], + "additionalProperties": false + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "ContextOverflowError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "ContextOverflowError" + ] + }, + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "responseBody": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "ContentFilterError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "ContentFilterError" + ] + }, + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "APIError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "APIError" + ] + }, + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "statusCode": { + "anyOf": [ + { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + { + "type": "null" + } + ] + }, + "isRetryable": { + "type": "boolean" + }, + "responseHeaders": { + "anyOf": [ + { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + { + "type": "null" + } + ] + }, + "responseBody": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "metadata": { + "anyOf": [ + { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "message", + "isRetryable" + ], + "additionalProperties": false + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "AssistantMessage": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "role": { + "type": "string", + "enum": [ + "assistant" + ] + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "completed": { + "anyOf": [ + { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "created" + ], + "additionalProperties": false + }, + "error": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/components/schemas/ProviderAuthError" + }, + { + "$ref": "#/components/schemas/UnknownError1" + }, + { + "$ref": "#/components/schemas/MessageOutputLengthError" + }, + { + "$ref": "#/components/schemas/MessageAbortedError" + }, + { + "$ref": "#/components/schemas/StructuredOutputError" + }, + { + "$ref": "#/components/schemas/ContextOverflowError" + }, + { + "$ref": "#/components/schemas/ContentFilterError" + }, + { + "$ref": "#/components/schemas/APIError" + } + ] + }, + { + "type": "null" + } + ] + }, + "parentID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "modelID": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "mode": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "path": { + "type": "object", + "properties": { + "cwd": { + "type": "string" + }, + "root": { + "type": "string" + } + }, + "required": [ + "cwd", + "root" + ], + "additionalProperties": false + }, + "summary": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "total": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": [ + "read", + "write" + ], + "additionalProperties": false + } + }, + "required": [ + "input", + "output", + "reasoning", + "cache" + ], + "additionalProperties": false + }, + "structured": { + "anyOf": [ + {}, + { + "type": "null" + } + ] + }, + "variant": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "finish": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "role", + "time", + "parentID", + "modelID", + "providerID", + "mode", + "agent", + "path", + "cost", + "tokens" + ], + "additionalProperties": false + }, + "Message": { + "anyOf": [ + { + "$ref": "#/components/schemas/UserMessage" + }, + { + "$ref": "#/components/schemas/AssistantMessage" + } + ] + }, + "message.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "message.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "info": { + "$ref": "#/components/schemas/Message" + } + }, + "required": [ + "sessionID", + "info" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "message.removed": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "message.removed" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + } + }, + "required": [ + "sessionID", + "messageID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "TextPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "text" + ] + }, + "text": { + "type": "string" + }, + "synthetic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + "ignored": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + "time": { + "anyOf": [ + { + "type": "object", + "properties": { + "start": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "end": { + "anyOf": [ + { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "start" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "metadata": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "text" + ], + "additionalProperties": false + }, + "SubtaskPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "subtask" + ] + }, + "prompt": { + "type": "string" + }, + "description": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "model": { + "anyOf": [ + { + "type": "object", + "properties": { + "providerID": { + "type": "string" + }, + "modelID": { + "type": "string" + } + }, + "required": [ + "providerID", + "modelID" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "command": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "prompt", + "description", + "agent" + ], + "additionalProperties": false + }, + "ReasoningPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "reasoning" + ] + }, + "text": { + "type": "string" + }, + "metadata": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "null" + } + ] + }, + "time": { + "type": "object", + "properties": { + "start": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "end": { + "anyOf": [ + { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "start" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "text", + "time" + ], + "additionalProperties": false + }, + "FilePartSourceText": { + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "start": { + "type": "number" + }, + "end": { + "type": "number" + } + }, + "required": [ + "value", + "start", + "end" + ], + "additionalProperties": false + }, + "FileSource": { + "type": "object", + "properties": { + "text": { + "$ref": "#/components/schemas/FilePartSourceText" + }, + "type": { + "type": "string", + "enum": [ + "file" + ] + }, + "path": { + "type": "string" + } + }, + "required": [ + "text", + "type", + "path" + ], + "additionalProperties": false + }, + "Range": { + "type": "object", + "properties": { + "start": { + "type": "object", + "properties": { + "line": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "character": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "line", + "character" + ], + "additionalProperties": false + }, + "end": { + "type": "object", + "properties": { + "line": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "character": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "line", + "character" + ], + "additionalProperties": false + } + }, + "required": [ + "start", + "end" + ], + "additionalProperties": false + }, + "SymbolSource": { + "type": "object", + "properties": { + "text": { + "$ref": "#/components/schemas/FilePartSourceText" + }, + "type": { + "type": "string", + "enum": [ + "symbol" + ] + }, + "path": { + "type": "string" + }, + "range": { + "$ref": "#/components/schemas/Range" + }, + "name": { + "type": "string" + }, + "kind": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "text", + "type", + "path", + "range", + "name", + "kind" + ], + "additionalProperties": false + }, + "ResourceSource": { + "type": "object", + "properties": { + "text": { + "$ref": "#/components/schemas/FilePartSourceText" + }, + "type": { + "type": "string", + "enum": [ + "resource" + ] + }, + "clientName": { + "type": "string" + }, + "uri": { + "type": "string" + } + }, + "required": [ + "text", + "type", + "clientName", + "uri" + ], + "additionalProperties": false + }, + "FilePartSource": { + "anyOf": [ + { + "$ref": "#/components/schemas/FileSource" + }, + { + "$ref": "#/components/schemas/SymbolSource" + }, + { + "$ref": "#/components/schemas/ResourceSource" + } + ] + }, + "FilePart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "file" + ] + }, + "mime": { + "type": "string" + }, + "filename": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "url": { + "type": "string" + }, + "source": { + "anyOf": [ + { + "$ref": "#/components/schemas/FilePartSource" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "mime", + "url" + ], + "additionalProperties": false + }, + "ToolStatePending": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "pending" + ] + }, + "input": { + "type": "object" + }, + "raw": { + "type": "string" + } + }, + "required": [ + "status", + "input", + "raw" + ], + "additionalProperties": false + }, + "ToolStateRunning": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "running" + ] + }, + "input": { + "type": "object" + }, + "title": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "metadata": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "null" + } + ] + }, + "time": { + "type": "object", + "properties": { + "start": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "start" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "input", + "time" + ], + "additionalProperties": false + }, + "ToolStateCompleted": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "completed" + ] + }, + "input": { + "type": "object" + }, + "output": { + "type": "string" + }, + "title": { + "type": "string" + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "start": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "end": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "compacted": { + "anyOf": [ + { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "start", + "end" + ], + "additionalProperties": false + }, + "attachments": { + "anyOf": [ + { + "type": "array", + "items": { + "$ref": "#/components/schemas/FilePart" + } + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "status", + "input", + "output", + "title", + "metadata", + "time" + ], + "additionalProperties": false + }, + "ToolStateError": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "error" + ] + }, + "input": { + "type": "object" + }, + "error": { + "type": "string" + }, + "metadata": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "null" + } + ] + }, + "time": { + "type": "object", + "properties": { + "start": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "end": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "start", + "end" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "input", + "error", + "time" + ], + "additionalProperties": false + }, + "ToolState": { + "anyOf": [ + { + "$ref": "#/components/schemas/ToolStatePending" + }, + { + "$ref": "#/components/schemas/ToolStateRunning" + }, + { + "$ref": "#/components/schemas/ToolStateCompleted" + }, + { + "$ref": "#/components/schemas/ToolStateError" + } + ] + }, + "ToolPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "tool" + ] + }, + "callID": { + "type": "string" + }, + "tool": { + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/ToolState" + }, + "metadata": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "callID", + "tool", + "state" + ], + "additionalProperties": false + }, + "StepStartPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "step-start" + ] + }, + "snapshot": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type" + ], + "additionalProperties": false + }, + "StepFinishPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "step-finish" + ] + }, + "reason": { + "type": "string" + }, + "snapshot": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "total": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": [ + "read", + "write" + ], + "additionalProperties": false + } + }, + "required": [ + "input", + "output", + "reasoning", + "cache" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "reason", + "cost", + "tokens" + ], + "additionalProperties": false + }, + "SnapshotPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "snapshot" + ] + }, + "snapshot": { + "type": "string" + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "snapshot" + ], + "additionalProperties": false + }, + "PatchPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "patch" + ] + }, + "hash": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "hash", + "files" + ], + "additionalProperties": false + }, + "AgentPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "agent" + ] + }, + "name": { + "type": "string" + }, + "source": { + "anyOf": [ + { + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "start": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "end": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "value", + "start", + "end" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "name" + ], + "additionalProperties": false + }, + "RetryPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "retry" + ] + }, + "attempt": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "error": { + "$ref": "#/components/schemas/APIError" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "created" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "attempt", + "error", + "time" + ], + "additionalProperties": false + }, + "CompactionPart": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "compaction" + ] + }, + "auto": { + "type": "boolean" + }, + "overflow": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + "tail_start_id": { + "anyOf": [ + { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "messageID", + "type", + "auto" + ], + "additionalProperties": false + }, + "Part": { + "anyOf": [ + { + "$ref": "#/components/schemas/TextPart" + }, + { + "$ref": "#/components/schemas/SubtaskPart" + }, + { + "$ref": "#/components/schemas/ReasoningPart" + }, + { + "$ref": "#/components/schemas/FilePart" + }, + { + "$ref": "#/components/schemas/ToolPart" + }, + { + "$ref": "#/components/schemas/StepStartPart" + }, + { + "$ref": "#/components/schemas/StepFinishPart" + }, + { + "$ref": "#/components/schemas/SnapshotPart" + }, + { + "$ref": "#/components/schemas/PatchPart" + }, + { + "$ref": "#/components/schemas/AgentPart" + }, + { + "$ref": "#/components/schemas/RetryPart" + }, + { + "$ref": "#/components/schemas/CompactionPart" + } + ] + }, + "message.part.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "message.part.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "part": { + "$ref": "#/components/schemas/Part" + }, + "time": { + "type": "number" + } + }, + "required": [ + "sessionID", + "part", + "time" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "message.part.removed": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "message.part.removed" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "partID": { + "type": "string", + "allOf": [ + { + "pattern": "^prt" + } + ] + } + }, + "required": [ + "sessionID", + "messageID", + "partID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.execution.settled": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.execution.settled" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "outcome": { + "type": "string", + "enum": [ + "success", + "failure", + "interrupted" + ] + }, + "error": { + "$ref": "#/components/schemas/Session.Error.Unknown" + } + }, + "required": [ + "timestamp", + "sessionID", + "outcome" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.text.delta": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.text.delta" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "textID": { + "type": "string" + }, + "delta": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "textID", + "delta" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.reasoning.delta": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.reasoning.delta" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "reasoningID": { + "type": "string" + }, + "delta": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "reasoningID", + "delta" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.tool.input.delta": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.tool.input.delta" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "assistantMessageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "callID": { + "type": "string" + }, + "delta": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "assistantMessageID", + "callID", + "delta" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.next.compaction.delta": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.next.compaction.delta" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg_" + } + ] + }, + "text": { + "type": "string" + } + }, + "required": [ + "timestamp", + "sessionID", + "messageID", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "file.edited": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "file.edited" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "file": { + "type": "string" + } + }, + "required": [ + "file" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "reference.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "reference.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "permission.v2.asked": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "permission.v2.asked" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "action": { + "type": "string" + }, + "resources": { + "type": "array", + "items": { + "type": "string" + } + }, + "save": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { + "type": "object" + }, + "source": { + "$ref": "#/components/schemas/PermissionV2.Source" + } + }, + "required": [ + "id", + "sessionID", + "action", + "resources" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "permission.v2.replied": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "permission.v2.replied" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "requestID": { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + "reply": { + "$ref": "#/components/schemas/PermissionV2.Reply" + } + }, + "required": [ + "sessionID", + "requestID", + "reply" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "plugin.added": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "plugin.added" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "required": [ + "id" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "project.directories.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "project.directories.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "projectID": { + "type": "string" + } + }, + "required": [ + "projectID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "command.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "command.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "skill.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "skill.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "file.watcher.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "file.watcher.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "event": { + "type": "string", + "enum": [ + "add", + "change", + "unlink" + ] + } + }, + "required": [ + "file", + "event" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "Pty": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^pty" + } + ] + }, + "title": { + "type": "string" + }, + "command": { + "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } + }, + "cwd": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "running", + "exited" + ] + }, + "pid": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "exitCode": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "id", + "title", + "command", + "args", + "cwd", + "status", + "pid" + ], + "additionalProperties": false + }, + "pty.created": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "pty.created" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "info": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": [ + "info" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "pty.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "pty.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "info": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": [ + "info" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "pty.exited": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "pty.exited" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^pty" + } + ] + }, + "exitCode": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "id", + "exitCode" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "pty.deleted": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "pty.deleted" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^pty" + } + ] + } + }, + "required": [ + "id" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "Shell": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^sh_" + } + ] + }, + "status": { + "type": "string", + "enum": [ + "running", + "exited", + "timeout", + "killed" + ] + }, + "command": { + "type": "string" + }, + "cwd": { + "type": "string" + }, + "shell": { + "type": "string" + }, + "file": { + "type": "string" + }, + "pid": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "exit": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "started": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + "completed": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + } + }, + "required": [ + "started" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "status", + "command", + "cwd", + "shell", + "file", + "metadata", + "time" + ], + "additionalProperties": false + }, + "shell.created": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "shell.created" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "info": { + "$ref": "#/components/schemas/Shell" + } + }, + "required": [ + "info" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "shell.exited": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "shell.exited" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^sh_" + } + ] + }, + "exit": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + "status": { + "type": "string", + "enum": [ + "running", + "exited", + "timeout", + "killed" + ] + } + }, + "required": [ + "id", + "status" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "shell.deleted": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "shell.deleted" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^sh_" + } + ] + } + }, + "required": [ + "id" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "QuestionV2.Option": { + "type": "object", + "properties": { + "label": { + "type": "string", + "description": "Display text (1-5 words, concise)" + }, + "description": { + "type": "string", + "description": "Explanation of choice" + } + }, + "required": [ + "label", + "description" + ], + "additionalProperties": false + }, + "QuestionV2.Info": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "Complete question" + }, + "header": { + "type": "string", + "description": "Very short label (max 30 chars)" + }, + "options": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionV2.Option" + }, + "description": "Available choices" + }, + "multiple": { + "type": "boolean" + }, + "custom": { + "type": "boolean" + } + }, + "required": [ + "question", + "header", + "options" + ], + "additionalProperties": false + }, + "QuestionV2.Tool": { + "type": "object", + "properties": { + "messageID": { + "type": "string" + }, + "callID": { + "type": "string" + } + }, + "required": [ + "messageID", + "callID" + ], + "additionalProperties": false + }, + "question.v2.asked": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "question.v2.asked" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "questions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionV2.Info" + }, + "description": "Questions to ask" + }, + "tool": { + "$ref": "#/components/schemas/QuestionV2.Tool" + } + }, + "required": [ + "id", + "sessionID", + "questions" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "QuestionV2.Answer": { + "type": "array", + "items": { + "type": "string" + } + }, + "question.v2.replied": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "question.v2.replied" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "requestID": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + }, + "answers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionV2.Answer" + } + } + }, + "required": [ + "sessionID", + "requestID", + "answers" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "question.v2.rejected": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "question.v2.rejected" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "requestID": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + } + }, + "required": [ + "sessionID", + "requestID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "Form.Metadata1": { + "type": "object" + }, + "Form.When1": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "op": { + "type": "string", + "enum": [ + "eq", + "neq" + ] + }, + "value": { + "anyOf": [ + { + "type": "string" + }, + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "boolean" + } + ] + } + }, + "required": [ + "key", + "op", + "value" + ], + "additionalProperties": false + }, + "Form.StringField1": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When1" + } + }, + "type": { + "type": "string", + "enum": [ + "string" + ] + }, + "format": { + "type": "string", + "enum": [ + "email", + "uri", + "date", + "date-time" + ] + }, + "minLength": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "maxLength": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "pattern": { + "type": "string" + }, + "placeholder": { + "type": "string" + }, + "default": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.Option" + } + }, + "custom": { + "type": "boolean" + } + }, + "required": [ + "key", + "type" + ], + "additionalProperties": false + }, + "Form.NumberField1": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When1" + } + }, + "type": { + "type": "string", + "enum": [ + "number" + ] + }, + "minimum": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + "maximum": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + "default": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + } + }, + "required": [ + "key", + "type" + ], + "additionalProperties": false + }, + "Form.IntegerField1": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When1" + } + }, + "type": { + "type": "string", + "enum": [ + "integer" + ] + }, + "minimum": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + "maximum": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + "default": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + } + }, + "required": [ + "key", + "type" + ], + "additionalProperties": false + }, + "Form.BooleanField1": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When1" + } + }, + "type": { + "type": "string", + "enum": [ + "boolean" + ] + }, + "default": { + "type": "boolean" + } + }, + "required": [ + "key", + "type" + ], + "additionalProperties": false + }, + "Form.MultiselectField1": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "when": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.When1" + } + }, + "type": { + "type": "string", + "enum": [ + "multiselect" + ] + }, + "options": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Form.Option" + } + }, + "minItems": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "maxItems": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "custom": { + "type": "boolean" + }, + "default": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "key", + "type", + "options" + ], + "additionalProperties": false + }, + "Form.FormInfo1": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "sessionID": { + "type": "string" + }, + "title": { + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Form.Metadata1" + }, + "mode": { + "type": "string", + "enum": [ + "form" + ] + }, + "fields": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/Form.StringField1" + }, + { + "$ref": "#/components/schemas/Form.NumberField1" + }, + { + "$ref": "#/components/schemas/Form.IntegerField1" + }, + { + "$ref": "#/components/schemas/Form.BooleanField1" + }, + { + "$ref": "#/components/schemas/Form.MultiselectField1" + } + ] + } + } + }, + "required": [ + "id", + "sessionID", + "mode", + "fields" + ], + "additionalProperties": false + }, + "Form.UrlInfo1": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "sessionID": { + "type": "string" + }, + "title": { + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/Form.Metadata1" + }, + "mode": { + "type": "string", + "enum": [ + "url" + ] + }, + "url": { + "type": "string" + } + }, + "required": [ + "id", + "sessionID", + "mode", + "url" + ], + "additionalProperties": false + }, + "form.created": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "form.created" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "form": { + "anyOf": [ + { + "$ref": "#/components/schemas/Form.FormInfo1" + }, + { + "$ref": "#/components/schemas/Form.UrlInfo1" + } + ] + } + }, + "required": [ + "form" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "Form.Value1": { + "anyOf": [ + { + "type": "string" + }, + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "boolean" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "Form.Answer1": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Form.Value1" + } + }, + "form.replied": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "form.replied" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "sessionID": { + "type": "string" + }, + "answer": { + "$ref": "#/components/schemas/Form.Answer1" + } + }, + "required": [ + "id", + "sessionID", + "answer" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "form.cancelled": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "form.cancelled" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^frm_" + } + ] + }, + "sessionID": { + "type": "string" + } + }, + "required": [ + "id", + "sessionID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "Todo": { + "type": "object", + "properties": { + "content": { + "type": "string", + "description": "Brief description of the task" + }, + "status": { + "type": "string", + "description": "Current status of the task: pending, in_progress, completed, cancelled" + }, + "priority": { + "type": "string", + "description": "Priority level of the task: high, medium, low" + } + }, + "required": [ + "content", + "status", + "priority" + ], + "additionalProperties": false + }, + "todo.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "todo.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "todos": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Todo" + } + } + }, + "required": [ + "sessionID", + "todos" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "SessionStatus": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "idle" + ] + } + }, + "required": [ + "type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "retry" + ] + }, + "attempt": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "message": { + "type": "string" + }, + "action": { + "type": "object", + "properties": { + "reason": { + "type": "string" + }, + "provider": { + "type": "string" + }, + "title": { + "type": "string" + }, + "message": { + "type": "string" + }, + "label": { + "type": "string" + }, + "link": { + "type": "string" + } + }, + "required": [ + "reason", + "provider", + "title", + "message", + "label" + ], + "additionalProperties": false + }, + "next": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "type", + "attempt", + "message", + "next" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "busy" + ] + } + }, + "required": [ + "type" + ], + "additionalProperties": false + } + ] + }, + "session.status": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.status" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "status": { + "$ref": "#/components/schemas/SessionStatus" + } + }, + "required": [ + "sessionID", + "status" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.idle": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.idle" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + } + }, + "required": [ + "sessionID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "tui.prompt.append": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "tui.prompt.append" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "text": { + "type": "string" + } + }, + "required": [ + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "tui.command.execute": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "tui.command.execute" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "command": { + "anyOf": [ + { + "type": "string", + "enum": [ + "session.list", + "session.new", + "session.share", + "session.interrupt", + "session.background", + "session.compact", + "session.page.up", + "session.page.down", + "session.line.up", + "session.line.down", + "session.half.page.up", + "session.half.page.down", + "session.first", + "session.last", + "prompt.clear", + "prompt.submit", + "agent.cycle" + ] + }, + { + "type": "string" + } + ] + } + }, + "required": [ + "command" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "tui.toast.show": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "tui.toast.show" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "message": { + "type": "string" + }, + "variant": { + "type": "string", + "enum": [ + "info", + "success", + "warning", + "error" + ] + }, + "duration": { + "anyOf": [ + { + "type": "integer", + "allOf": [ + { + "exclusiveMinimum": 0 + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "message", + "variant" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "tui.session.select": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "tui.session.select" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses", + "description": "Session ID to navigate to" + } + ] + } + }, + "required": [ + "sessionID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "installation.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "installation.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "version": { + "type": "string" + } + }, + "required": [ + "version" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "installation.update-available": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "installation.update-available" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "version": { + "type": "string" + } + }, + "required": [ + "version" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "vcs.branch.updated": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "vcs.branch.updated" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "branch": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "mcp.status.changed": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "mcp.status.changed" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "server": { + "type": "string" + } + }, + "required": [ + "server" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "permission.asked": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "permission.asked" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "permission": { + "type": "string" + }, + "patterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { + "type": "object" + }, + "always": { + "type": "array", + "items": { + "type": "string" + } + }, + "tool": { + "anyOf": [ + { + "type": "object", + "properties": { + "messageID": { + "type": "string" + }, + "callID": { + "type": "string" + } + }, + "required": [ + "messageID", + "callID" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "permission", + "patterns", + "metadata", + "always" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "permission.replied": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "permission.replied" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "requestID": { + "type": "string", + "allOf": [ + { + "pattern": "^per" + } + ] + }, + "reply": { + "type": "string", + "enum": [ + "once", + "always", + "reject" + ] + } + }, + "required": [ + "sessionID", + "requestID", + "reply" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "QuestionOption": { + "type": "object", + "properties": { + "label": { + "type": "string", + "description": "Display text (1-5 words, concise)" + }, + "description": { + "type": "string", + "description": "Explanation of choice" + } + }, + "required": [ + "label", + "description" + ], + "additionalProperties": false + }, + "QuestionInfo": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "Complete question" + }, + "header": { + "type": "string", + "description": "Very short label (max 30 chars)" + }, + "options": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionOption" + }, + "description": "Available choices" + }, + "multiple": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "Allow selecting multiple choices" + }, + "custom": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "Allow typing a custom answer (default: true)" + } + }, + "required": [ + "question", + "header", + "options" + ], + "additionalProperties": false + }, + "QuestionTool": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "allOf": [ + { + "pattern": "^msg" + } + ] + }, + "callID": { + "type": "string" + } + }, + "required": [ + "messageID", + "callID" + ], + "additionalProperties": false + }, + "question.asked": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "question.asked" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "questions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionInfo" + }, + "description": "Questions to ask" + }, + "tool": { + "anyOf": [ + { + "$ref": "#/components/schemas/QuestionTool" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "sessionID", + "questions" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "QuestionAnswer": { + "type": "array", + "items": { + "type": "string" + } + }, + "question.replied": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "question.replied" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "requestID": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + }, + "answers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionAnswer" + } + } + }, + "required": [ + "sessionID", + "requestID", + "answers" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "question.rejected": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "question.rejected" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "requestID": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + } + }, + "required": [ + "sessionID", + "requestID" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "session.error": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": [ + "session.error" + ] + }, + "durable": { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "sessionID": { + "anyOf": [ + { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + { + "type": "null" + } + ] + }, + "error": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/components/schemas/ProviderAuthError" + }, + { + "$ref": "#/components/schemas/UnknownError1" + }, + { + "$ref": "#/components/schemas/MessageOutputLengthError" + }, + { + "$ref": "#/components/schemas/MessageAbortedError" + }, + { + "$ref": "#/components/schemas/StructuredOutputError" + }, + { + "$ref": "#/components/schemas/ContextOverflowError" + }, + { + "$ref": "#/components/schemas/ContentFilterError" + }, + { + "$ref": "#/components/schemas/APIError" + } + ] + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "V2Event.server.connected": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^evt_" + } + ] + }, + "metadata": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "null" + } + ] + }, + "durable": { + "anyOf": [ + { + "type": "object", + "properties": { + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "version": { + "type": "integer", + "allOf": [ + { + "minimum": 1 + } + ] + } + }, + "required": [ + "aggregateID", + "seq", + "version" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "location": { + "anyOf": [ + { + "$ref": "#/components/schemas/Location.Ref" + }, + { + "type": "null" + } + ] + }, + "type": { + "type": "string", + "enum": [ + "server.connected" + ] + }, + "data": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "array" + } + ] + } + }, + "required": [ + "id", + "type", + "data" + ], + "additionalProperties": false + }, + "V2Event": { + "anyOf": [ + { + "$ref": "#/components/schemas/models-dev.refreshed" + }, + { + "$ref": "#/components/schemas/integration.updated" + }, + { + "$ref": "#/components/schemas/integration.connection.updated" + }, + { + "$ref": "#/components/schemas/catalog.updated" + }, + { + "$ref": "#/components/schemas/agent.updated" + }, + { + "$ref": "#/components/schemas/session.created" + }, + { + "$ref": "#/components/schemas/session.updated" + }, + { + "$ref": "#/components/schemas/session.deleted" + }, + { + "$ref": "#/components/schemas/message.updated" + }, + { + "$ref": "#/components/schemas/message.removed" + }, + { + "$ref": "#/components/schemas/message.part.updated" + }, + { + "$ref": "#/components/schemas/message.part.removed" + }, + { + "$ref": "#/components/schemas/session.next.agent.switched" + }, + { + "$ref": "#/components/schemas/session.next.model.switched" + }, + { + "$ref": "#/components/schemas/session.next.moved" + }, + { + "$ref": "#/components/schemas/session.next.renamed" + }, + { + "$ref": "#/components/schemas/session.next.forked" + }, + { + "$ref": "#/components/schemas/session.next.prompted" + }, + { + "$ref": "#/components/schemas/session.next.prompt.admitted" + }, + { + "$ref": "#/components/schemas/session.next.execution.settled" + }, + { + "$ref": "#/components/schemas/session.next.context.updated" + }, + { + "$ref": "#/components/schemas/session.next.synthetic" + }, + { + "$ref": "#/components/schemas/session.next.skill.activated" + }, + { + "$ref": "#/components/schemas/session.next.shell.started" + }, + { + "$ref": "#/components/schemas/session.next.shell.ended" + }, + { + "$ref": "#/components/schemas/session.next.step.started" + }, + { + "$ref": "#/components/schemas/session.next.step.ended" + }, + { + "$ref": "#/components/schemas/session.next.step.failed" + }, + { + "$ref": "#/components/schemas/session.next.text.started" + }, + { + "$ref": "#/components/schemas/session.next.text.delta" + }, + { + "$ref": "#/components/schemas/session.next.text.ended" + }, + { + "$ref": "#/components/schemas/session.next.reasoning.started" + }, + { + "$ref": "#/components/schemas/session.next.reasoning.delta" + }, + { + "$ref": "#/components/schemas/session.next.reasoning.ended" + }, + { + "$ref": "#/components/schemas/session.next.tool.input.started" + }, + { + "$ref": "#/components/schemas/session.next.tool.input.delta" + }, + { + "$ref": "#/components/schemas/session.next.tool.input.ended" + }, + { + "$ref": "#/components/schemas/session.next.tool.called" + }, + { + "$ref": "#/components/schemas/session.next.tool.progress" + }, + { + "$ref": "#/components/schemas/session.next.tool.success" + }, + { + "$ref": "#/components/schemas/session.next.tool.failed" + }, + { + "$ref": "#/components/schemas/session.next.retried" + }, + { + "$ref": "#/components/schemas/session.next.compaction.started" + }, + { + "$ref": "#/components/schemas/session.next.compaction.delta" + }, + { + "$ref": "#/components/schemas/session.next.compaction.ended" + }, + { + "$ref": "#/components/schemas/session.next.revert.staged" + }, + { + "$ref": "#/components/schemas/session.next.revert.cleared" + }, + { + "$ref": "#/components/schemas/session.next.revert.committed" + }, + { + "$ref": "#/components/schemas/file.edited" + }, + { + "$ref": "#/components/schemas/reference.updated" + }, + { + "$ref": "#/components/schemas/permission.v2.asked" + }, + { + "$ref": "#/components/schemas/permission.v2.replied" + }, + { + "$ref": "#/components/schemas/plugin.added" + }, + { + "$ref": "#/components/schemas/project.directories.updated" + }, + { + "$ref": "#/components/schemas/command.updated" + }, + { + "$ref": "#/components/schemas/skill.updated" + }, + { + "$ref": "#/components/schemas/file.watcher.updated" + }, + { + "$ref": "#/components/schemas/pty.created" + }, + { + "$ref": "#/components/schemas/pty.updated" + }, + { + "$ref": "#/components/schemas/pty.exited" + }, + { + "$ref": "#/components/schemas/pty.deleted" + }, + { + "$ref": "#/components/schemas/shell.created" + }, + { + "$ref": "#/components/schemas/shell.exited" + }, + { + "$ref": "#/components/schemas/shell.deleted" + }, + { + "$ref": "#/components/schemas/question.v2.asked" + }, + { + "$ref": "#/components/schemas/question.v2.replied" + }, + { + "$ref": "#/components/schemas/question.v2.rejected" + }, + { + "$ref": "#/components/schemas/form.created" + }, + { + "$ref": "#/components/schemas/form.replied" + }, + { + "$ref": "#/components/schemas/form.cancelled" + }, + { + "$ref": "#/components/schemas/todo.updated" + }, + { + "$ref": "#/components/schemas/session.status" + }, + { + "$ref": "#/components/schemas/session.idle" + }, + { + "$ref": "#/components/schemas/tui.prompt.append" + }, + { + "$ref": "#/components/schemas/tui.command.execute" + }, + { + "$ref": "#/components/schemas/tui.toast.show" + }, + { + "$ref": "#/components/schemas/tui.session.select" + }, + { + "$ref": "#/components/schemas/installation.updated" + }, + { + "$ref": "#/components/schemas/installation.update-available" + }, + { + "$ref": "#/components/schemas/vcs.branch.updated" + }, + { + "$ref": "#/components/schemas/mcp.status.changed" + }, + { + "$ref": "#/components/schemas/permission.asked" + }, + { + "$ref": "#/components/schemas/permission.replied" + }, + { + "$ref": "#/components/schemas/question.asked" + }, + { + "$ref": "#/components/schemas/question.replied" + }, + { + "$ref": "#/components/schemas/question.rejected" + }, + { + "$ref": "#/components/schemas/session.error" + }, + { + "$ref": "#/components/schemas/V2Event.server.connected" + } + ] + }, + "V2EventStream": { + "type": "string", + "contentSchema": { + "$ref": "#/components/schemas/V2Event" + }, + "contentMediaType": "application/json" + }, + "EventLog.Hint": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "log.hint" + ] + }, + "aggregateID": { + "type": "string" + }, + "seq": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + } + }, + "required": [ + "type", + "aggregateID", + "seq" + ], + "additionalProperties": false, + "description": "Payload-free change hint: the aggregate's durable log advanced to at least seq. Hints coalesce under backpressure (latest per aggregate) and are never a delivery guarantee." + }, + "EventLog.SweepRequired": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "log.sweep_required" + ] + } + }, + "required": [ + "type" + ], + "additionalProperties": false, + "description": "Hints may have been lost; treat every aggregate as potentially dirty and recover via bounded sweep plus durable log reads. Emitted first on every (re)subscribe." + }, + "EventLog.Change": { + "anyOf": [ + { + "$ref": "#/components/schemas/EventLog.Hint" + }, + { + "$ref": "#/components/schemas/EventLog.SweepRequired" + } + ] + }, + "EventLog.ChangeStream": { + "type": "string", + "contentSchema": { + "$ref": "#/components/schemas/EventLog.Change" + }, + "contentMediaType": "application/json" + }, + "PtyNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "PtyNotFoundError" + ] + }, + "ptyID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "ptyID", + "message" + ], + "additionalProperties": false + }, + "PtyTicket.ConnectToken": { + "type": "object", + "properties": { + "ticket": { + "type": "string" + }, + "expires_in": { + "type": "integer", + "allOf": [ + { + "exclusiveMinimum": 0 + } + ] + } + }, + "required": [ + "ticket", + "expires_in" + ], + "additionalProperties": false + }, + "ForbiddenError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "ForbiddenError" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "additionalProperties": false + }, + "Shell1": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^sh_" + } + ] + }, + "status": { + "type": "string", + "enum": [ + "running", + "exited", + "timeout", + "killed" + ] + }, + "command": { + "type": "string" + }, + "cwd": { + "type": "string" + }, + "shell": { + "type": "string" + }, + "file": { + "type": "string" + }, + "pid": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "exit": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "started": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + }, + "completed": { + "anyOf": [ + { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": [ + "NaN" + ] + }, + { + "type": "string", + "enum": [ + "Infinity" + ] + }, + { + "type": "string", + "enum": [ + "-Infinity" + ] + } + ] + }, + { + "type": "string", + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ] + } + ] + } + }, + "required": [ + "started" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "status", + "command", + "cwd", + "shell", + "file", + "metadata", + "time" + ], + "additionalProperties": false + }, + "ShellNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "ShellNotFoundError" + ] + }, + "id": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "id", + "message" + ], + "additionalProperties": false + }, + "QuestionV2.Request": { + "type": "object", + "properties": { + "id": { + "type": "string", + "allOf": [ + { + "pattern": "^que" + } + ] + }, + "sessionID": { + "type": "string", + "allOf": [ + { + "pattern": "^ses" + } + ] + }, + "questions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionV2.Info" + }, + "description": "Questions to ask" + }, + "tool": { + "$ref": "#/components/schemas/QuestionV2.Tool" + } + }, + "required": [ + "id", + "sessionID", + "questions" + ], + "additionalProperties": false + }, + "QuestionV2.Reply": { + "type": "object", + "properties": { + "answers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionV2.Answer" + }, + "description": "User answers in order of questions (each answer is an array of selected labels)" + } + }, + "required": [ + "answers" + ], + "additionalProperties": false + }, + "QuestionNotFoundError": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": [ + "QuestionNotFoundError" + ] + }, + "requestID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "_tag", + "requestID", + "message" + ], + "additionalProperties": false + }, + "Reference.LocalSource": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "local" + ] + }, + "path": { + "type": "string" + }, + "description": { + "type": "string" + }, + "hidden": { + "type": "boolean" + } + }, + "required": [ + "type", + "path" + ], + "additionalProperties": false + }, + "Reference.GitSource": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "git" + ] + }, + "repository": { + "type": "string" + }, + "branch": { + "type": "string" + }, + "description": { + "type": "string" + }, + "hidden": { + "type": "boolean" + } + }, + "required": [ + "type", + "repository" + ], + "additionalProperties": false + }, + "Reference.Source": { + "anyOf": [ + { + "$ref": "#/components/schemas/Reference.LocalSource" + }, + { + "$ref": "#/components/schemas/Reference.GitSource" + } + ] + }, + "Reference.Info": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "description": { + "type": "string" + }, + "hidden": { + "type": "boolean" + }, + "source": { + "$ref": "#/components/schemas/Reference.Source" + } + }, + "required": [ + "name", + "path", + "source" + ], + "additionalProperties": false + }, + "ProjectCopy.Copy": { + "type": "object", + "properties": { + "directory": { + "type": "string" + } + }, + "required": [ + "directory" + ], + "additionalProperties": false + }, + "ProjectCopyError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "ProjectCopyError" + ] + }, + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "forceRequired": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "name", + "data" + ], + "additionalProperties": false + }, + "Vcs.FileStatus": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "additions": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "deletions": { + "type": "integer", + "allOf": [ + { + "minimum": 0 + } + ] + }, + "status": { + "type": "string", + "enum": [ + "added", + "deleted", + "modified" + ] + } + }, + "required": [ + "file", + "additions", + "deletions", + "status" + ], + "additionalProperties": false + }, + "Vcs.Mode": { + "type": "string", + "enum": [ + "working", + "branch" + ] + } + }, + "securitySchemes": {} + }, + "security": [], + "tags": [ + { + "name": "server.health" + }, + { + "name": "server.location" + }, + { + "name": "server.agent" + }, + { + "name": "plugins", + "description": "Experimental plugin routes." + }, + { + "name": "sessions", + "description": "Experimental session routes." + }, + { + "name": "messages", + "description": "Experimental message routes." + }, + { + "name": "models", + "description": "Experimental model routes." + }, + { + "name": "generate", + "description": "Experimental one-shot generation routes." + }, + { + "name": "providers", + "description": "Experimental provider routes." + }, + { + "name": "integrations", + "description": "Integration discovery and authentication routes." + }, + { + "name": "mcp", + "description": "MCP server status routes." + }, + { + "name": "server.credential" + }, + { + "name": "projects", + "description": "Location-scoped project routes." + }, + { + "name": "forms", + "description": "Session form routes." + }, + { + "name": "permissions", + "description": "Experimental permission routes." + }, + { + "name": "filesystem", + "description": "Experimental location-scoped filesystem routes." + }, + { + "name": "commands", + "description": "Experimental command routes." + }, + { + "name": "skills", + "description": "Experimental skill routes." + }, + { + "name": "events", + "description": "Experimental event stream routes." + }, + { + "name": "pty", + "description": "Experimental location-scoped PTY routes." + }, + { + "name": "shell", + "description": "Experimental location-scoped shell command routes." + }, + { + "name": "session questions", + "description": "Experimental session question routes." + }, + { + "name": "reference", + "description": "Location-scoped project references." + }, + { + "name": "projectCopy", + "description": "Project copy management routes." + }, + { + "name": "vcs", + "description": "Location-scoped version control routes." + } + ] +} diff --git a/packages/codemode/test/openapi.test.ts b/packages/codemode/test/openapi.test.ts new file mode 100644 index 0000000000..99a0890091 --- /dev/null +++ b/packages/codemode/test/openapi.test.ts @@ -0,0 +1,958 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Layer, Option } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" +import { CodeMode, OpenAPI } from "../src/index.js" +import { inputTypeScript, outputTypeScript, Tool } from "../src/tool.js" + +const baseUrl = "http://localhost:4096" +type Document = OpenAPI.Document + +type Recorded = { + readonly method: string + readonly url: string + readonly headers: Record + readonly body: unknown +} + +const opencodeSpec = async (): Promise => { + return Bun.file(new URL("./fixtures/opencode-v2-openapi.json", import.meta.url)).json() as Promise +} + +const happyPathSpec = async (): Promise => { + return Bun.file(new URL("./fixtures/openapi-happy-path.json", import.meta.url)).json() as Promise +} + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value) + +const toolAt = (tools: unknown, name: string) => + name.split(".").reduce((current, segment) => (isRecord(current) ? current[segment] : undefined), tools) + +const recordingClient = (respond: (request: HttpClientRequest.HttpClientRequest) => Response) => { + const requests: Array = [] + const layer = Layer.succeed(HttpClient.HttpClient)( + HttpClient.make((request) => + Effect.gen(function* () { + const body = + request.body._tag === "Uint8Array" ? JSON.parse(new TextDecoder().decode(request.body.body)) : undefined + const url = Option.map(HttpClientRequest.toUrl(request), (resolved) => resolved.toString()) + requests.push({ + method: request.method, + url: Option.getOrElse(url, () => request.url), + headers: { ...request.headers }, + body, + }) + return HttpClientResponse.fromWeb(request, respond(request)) + }), + ), + ) + return { requests, layer } +} + +const json = (value: unknown, status = 200) => + new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json" } }) + +const singleOperation = (operation: Record, method = "get"): Document => ({ + openapi: "3.1.0", + paths: { "/test": { [method]: { operationId: "test", responses: { 200: { description: "Success" } }, ...operation } } }, +}) + +describe("OpenAPI.fromSpec", () => { + test("covers a representative API from generation through execution", async () => { + const resolutions: Array = [] + const client = recordingClient((request) => { + const url = Option.getOrElse(HttpClientRequest.toUrl(request), () => new URL(request.url)) + if (request.method === "POST") { + return new Response( + JSON.stringify({ id: "user-2", name: "Grace", email: "grace@example.test", role: "admin" }), + { status: 201, headers: { "content-type": "application/vnd.example+json" } }, + ) + } + if (request.method === "DELETE") return new Response(null, { status: 204 }) + if (url.pathname === "/search") { + return new Response("2 matches", { headers: { "content-type": "text/plain" } }) + } + return json({ id: "user-1", name: "Ada", email: "ada@example.test", role: "member" }) + }) + const api = OpenAPI.fromSpec({ + spec: await happyPathSpec(), + baseUrl, + auth: { + resolve: ({ name }) => { + resolutions.push(name) + return Effect.succeed( + name === "BearerAuth" + ? { type: "bearer", token: "bearer-secret" } + : { type: "apiKey", value: "api-secret" }, + ) + }, + }, + }) + const get = toolAt(api.tools, "users.get") + const create = toolAt(api.tools, "users.create") + const search = toolAt(api.tools, "search.run") + const remove = toolAt(api.tools, "users.remove") + + expect(api.skipped).toEqual([]) + if (!Tool.isDefinition(get) || !Tool.isDefinition(create) || !Tool.isDefinition(search) || !Tool.isDefinition(remove)) { + throw new Error("happy-path fixture did not generate every operation") + } + expect(inputTypeScript(get)).toBe( + '{ userId: string; include?: Array; verbose?: boolean; "X-Trace-ID"?: string }', + ) + expect(inputTypeScript(create)).toBe('{ name: string; email: string; role?: "admin" | "member" }') + expect(inputTypeScript(search)).toBe("{ filter?: { query: string; page?: number }; tags?: Array }") + expect(inputTypeScript(remove)).toBe("{ userId: string }") + expect(outputTypeScript(get)).toContain("id: string") + expect(outputTypeScript(create)).toContain('role?: "admin" | "member"') + expect(outputTypeScript(search)).toBe("string") + expect(outputTypeScript(remove)).toBe("null") + + const result = await Effect.runPromise( + CodeMode.make({ tools: { api: api.tools } }) + .execute(` + const user = await tools.api.users.get({ + userId: "user-1", + include: ["profile", "permissions"], + verbose: true, + "X-Trace-ID": "trace-1", + }) + const created = await tools.api.users.create({ + name: "Grace", + email: "grace@example.test", + role: "admin", + }) + const summary = await tools.api.search.run({ + filter: { query: "effect", page: 2 }, + tags: ["typescript", "runtime"], + }) + const removed = await tools.api.users.remove({ userId: "user-1" }) + return { user, created, summary, removed } + `) + .pipe(Effect.provide(client.layer)), + ) + + expect(result).toMatchObject({ + ok: true, + value: { + user: { id: "user-1", name: "Ada" }, + created: { id: "user-2", name: "Grace" }, + summary: "2 matches", + removed: null, + }, + }) + expect(resolutions).toEqual(["BearerAuth", "ApiKey", "BearerAuth"]) + expect(client.requests).toHaveLength(4) + + const getUrl = new URL(client.requests[0]!.url) + expect(getUrl.pathname).toBe("/users/user-1") + expect(getUrl.searchParams.get("include")).toBe("profile,permissions") + expect(getUrl.searchParams.get("verbose")).toBe("true") + expect(client.requests[0]!.headers["x-trace-id"]).toBe("trace-1") + expect(client.requests[0]!.headers.authorization).toBe("Bearer bearer-secret") + + const createUrl = new URL(client.requests[1]!.url) + expect(createUrl.searchParams.get("api_key")).toBe("api-secret") + expect(client.requests[1]!.body).toEqual({ name: "Grace", email: "grace@example.test", role: "admin" }) + + const searchUrl = new URL(client.requests[2]!.url) + expect(searchUrl.searchParams.get("filter[query]")).toBe("effect") + expect(searchUrl.searchParams.get("filter[page]")).toBe("2") + expect(searchUrl.searchParams.getAll("tags")).toEqual(["typescript", "runtime"]) + expect(client.requests[2]!.headers.authorization).toBeUndefined() + expect(new URL(client.requests[3]!.url).pathname).toBe("/users/user-1") + expect(client.requests[3]!.headers.authorization).toBe("Bearer bearer-secret") + }) + + test("converts representative opencode operations into the expected tool shape", async () => { + const spec = await opencodeSpec() + const result = OpenAPI.fromSpec({ spec, baseUrl }) + + expect(result.skipped).toHaveLength(5) + expect(result.skipped).toContainEqual({ + method: "GET", + path: "/api/pty/{ptyID}/connect", + reason: "WebSocket operations are not supported", + }) + expect(result.skipped.filter((item) => item.reason === "SSE operations are not supported")).toHaveLength(3) + expect(result.skipped).toContainEqual({ + method: "GET", + path: "/api/fs/read/*", + reason: "binary responses are not supported", + }) + expect(toolAt(result.tools, "v2.health.get")).not.toBeUndefined() + expect(toolAt(result.tools, "v2.session.get")).not.toBeUndefined() + expect(toolAt(result.tools, "v2.session.create")).not.toBeUndefined() + + const sessionGet = toolAt(result.tools, "v2.session.get") + expect(Tool.isDefinition(sessionGet)).toBe(true) + if (!Tool.isDefinition(sessionGet)) throw new Error("v2.session.get was not generated") + expect(inputTypeScript(sessionGet)).toBe("{ sessionID: string }") + expect(outputTypeScript(sessionGet)).toContain("id: string") + expect(outputTypeScript(sessionGet)).toContain("additions: number") + + const switchAgent = toolAt(result.tools, "v2.session.switchAgent") + expect(Tool.isDefinition(switchAgent)).toBe(true) + if (!Tool.isDefinition(switchAgent)) throw new Error("v2.session.switchAgent was not generated") + expect(inputTypeScript(switchAgent)).toBe("{ sessionID: string; agent: string }") + + const contextEntryPut = toolAt(result.tools, "v2.session.contextEntry.put") + expect(Tool.isDefinition(contextEntryPut)).toBe(true) + if (!Tool.isDefinition(contextEntryPut)) throw new Error("v2.session.contextEntry.put was not generated") + expect(inputTypeScript(contextEntryPut)).toBe("{ sessionID: string; key: string; value: unknown }") + expect(toolAt(result.tools, "v2_session_context_entry_put_2")).toBeUndefined() + expect(toolAt(result.tools, "v2.pty.connect")).toBeUndefined() + expect(toolAt(result.tools, "v2.session.log")).toBeUndefined() + expect(toolAt(result.tools, "v2.event.subscribe")).toBeUndefined() + expect(toolAt(result.tools, "v2.event.changes")).toBeUndefined() + expect(toolAt(result.tools, "v2.fs.read")).toBeUndefined() + expect(toolAt(result.tools, "v2.pty.connectToken")).not.toBeUndefined() + }) + + test("preserves operation path sanitization and collision handling", () => { + const response = { responses: { 200: { description: "Success" } } } + const result = OpenAPI.fromSpec({ + baseUrl, + spec: { + openapi: "3.1.0", + paths: { + "/first": { get: { ...response, operationId: "group.item" } }, + "/second": { get: { ...response, operationId: "group.item" } }, + "/third": { get: { ...response, operationId: "group..other" } }, + }, + }, + }) + + expect(Tool.isDefinition(toolAt(result.tools, "group.item"))).toBe(true) + expect(Tool.isDefinition(toolAt(result.tools, "group_item_2"))).toBe(true) + expect(Tool.isDefinition(toolAt(result.tools, "group.operation.other"))).toBe(true) + }) + + test("synthesizes flat operation IDs from methods and paths", () => { + const response = { responses: { 200: { description: "Success" } } } + const tools = OpenAPI.fromSpec({ + baseUrl, + spec: { + openapi: "3.1.0", + paths: { + "/users": { get: response, post: response }, + "/users/{id}": { get: response, patch: response, delete: response }, + "/organizations/{organizationId}/users/{id}": { get: response }, + }, + }, + }).tools + + for (const path of [ + "getUsers", + "postUsers", + "getUsersById", + "patchUsersById", + "deleteUsersById", + "getOrganizationsByOrganizationidUsersById", + ]) { + expect(Tool.isDefinition(toolAt(tools, path))).toBe(true) + } + }) + + test("lets operation parameters override matching path parameters", () => { + const tool = toolAt( + OpenAPI.fromSpec({ + baseUrl, + spec: { + openapi: "3.1.0", + paths: { + "/test": { + parameters: [{ name: "limit", in: "query", schema: { type: "string" } }], + get: { + operationId: "test", + parameters: [{ name: "limit", in: "query", required: true, schema: { type: "number" } }], + responses: { 200: { description: "Success" } }, + }, + }, + }, + }, + }).tools, + "test", + ) + + if (!Tool.isDefinition(tool)) throw new Error("test was not generated") + expect(inputTypeScript(tool)).toBe("{ limit: number }") + }) + + test("normalizes OpenAPI 3.0 schemas with Effect", () => { + const result = OpenAPI.fromSpec({ + baseUrl, + spec: { + openapi: "3.0.3", + paths: { + "/search": { + get: { + operationId: "search", + parameters: [ + { + in: "query", + name: "value", + schema: { type: "string", nullable: true, minLength: 2 }, + }, + ], + responses: { 200: { description: "Success" } }, + }, + }, + }, + }, + }) + const search = toolAt(result.tools, "search") + + expect(Tool.isDefinition(search)).toBe(true) + if (!Tool.isDefinition(search)) throw new Error("search was not generated") + expect(inputTypeScript(search)).toBe("{ value?: string | null }") + const schema: unknown = search.input + const input = isRecord(schema) ? schema : {} + const properties = isRecord(input.properties) ? input.properties : {} + const value = isRecord(properties.value) ? properties.value : {} + expect(value.minLength).toBe(2) + }) + + test("preserves schema-local definitions alongside component definitions", () => { + const tool = toolAt( + OpenAPI.fromSpec({ + baseUrl, + spec: { + openapi: "3.1.0", + paths: { + "/test": { + get: { + operationId: "test", + responses: { + 200: { + description: "Success", + content: { + "application/json": { + schema: { $ref: "#/$defs/Local", $defs: { Local: { type: "string" } } }, + }, + }, + }, + }, + }, + }, + }, + components: { schemas: { Global: { type: "number" } } }, + }, + }).tools, + "test", + ) + + if (!Tool.isDefinition(tool) || !isRecord(tool.output)) throw new Error("test output was not generated") + expect(tool.output.$defs).toMatchObject({ Local: { type: "string" }, Global: { type: "number" } }) + }) + + test("documents that the opencode fixture is unauthenticated", async () => { + const spec = await opencodeSpec() + const components = isRecord(spec.components) ? spec.components : {} + const result = OpenAPI.fromSpec({ spec, baseUrl }) + + expect(spec.security).toStrictEqual([]) + expect(isRecord(components.securitySchemes) ? Object.keys(components.securitySchemes) : []).toStrictEqual([]) + const health = toolAt(result.tools, "v2.health.get") + const healthInput = isRecord(health) ? health.input : undefined + expect(healthInput).toMatchObject({ type: "object", properties: {} }) + const input = isRecord(healthInput) ? healthInput : {} + expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual([]) + }) + + test("exposes real opencode operations through CodeMode discovery", async () => { + const { layer } = recordingClient(() => json({})) + const runtime = CodeMode.make({ + tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools }, + }) + const result = await Effect.runPromise( + runtime + .execute( + ` + return await tools.$codemode.search({ query: "global health", namespace: "opencode", limit: 1 }) + `, + ) + .pipe(Effect.provide(layer)), + ) + + expect(result).toMatchObject({ ok: true }) + if (!result.ok) return + expect(result.value).toMatchObject({ + items: [ + { + path: "tools.opencode.v2.health.get", + description: "Check whether the API server is ready to accept requests.", + }, + ], + }) + expect(JSON.stringify(result.value)).toContain("healthy: true") + }) + + test("invokes real opencode path parameters and JSON request bodies", async () => { + const { requests, layer } = recordingClient((request) => { + if (request.method === "GET") return json({ id: "ses_123" }) + return json({ id: "ses_456" }) + }) + const runtime = CodeMode.make({ + tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools }, + }) + + const result = await Effect.runPromise( + runtime + .execute( + ` + const existing = await tools.opencode.v2.session.get({ sessionID: "ses_123" }) + const created = await tools.opencode.v2.session.create({ id: "ses_456" }) + return { existing, created } + `, + ) + .pipe(Effect.provide(layer)), + ) + + expect(result).toMatchObject({ ok: true }) + expect(requests).toHaveLength(2) + expect(requests[0]).toMatchObject({ method: "GET", body: undefined }) + expect(new URL(requests[0]!.url).pathname).toBe("/api/session/ses_123") + expect(requests[1]).toMatchObject({ + method: "POST", + url: "http://localhost:4096/api/session", + body: { id: "ses_456" }, + }) + }) + + test("serializes deep-object query parameters from the opencode fixture", async () => { + const client = recordingClient(() => json({ directory: "/tmp" })) + const location = toolAt(OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools, "v2.location.get") + if (!Tool.isDefinition(location)) throw new Error("v2.location.get was not generated") + + await Effect.runPromise( + location.run({ location: { directory: "/tmp", workspace: "workspace-1" } }).pipe(Effect.provide(client.layer)), + ) + + const url = new URL(client.requests[0]!.url) + expect(url.searchParams.get("location[directory]")).toBe("/tmp") + expect(url.searchParams.get("location[workspace]")).toBe("workspace-1") + }) + + test("serializes supported simple and form parameter shapes", async () => { + const client = recordingClient(() => json({ ok: true })) + const result = OpenAPI.fromSpec({ + baseUrl, + spec: { + openapi: "3.1.0", + paths: { + "/items/{keys}": { + get: { + operationId: "items", + parameters: [ + { name: "keys", in: "path", required: true, schema: { type: "array", items: { type: "string" } } }, + { name: "tags", in: "query", style: "form", explode: false, schema: { type: "array" } }, + { name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } }, + { name: "nullable", in: "query", required: true, schema: { type: ["string", "null"] } }, + { name: "constructor", in: "query", schema: { type: "string" } }, + { name: "meta", in: "header", style: "simple", explode: true, schema: { type: "object" } }, + ], + responses: { 200: { description: "Success" } }, + }, + }, + }, + }, + }) + const tool = toolAt(result.tools, "items") + if (!Tool.isDefinition(tool)) throw new Error("items was not generated") + + await Effect.runPromise( + tool + .run({ + keys: ["a!", "b*"], + tags: ["x", "y"], + filter: { state: "open", page: 2 }, + nullable: null, + constructor_2: "safe", + meta: { a: "b", c: "d" }, + }) + .pipe(Effect.provide(client.layer)), + ) + + const url = new URL(client.requests[0]!.url) + expect(url.pathname).toBe("/items/a%21,b%2A") + expect(url.searchParams.get("tags")).toBe("x,y") + expect(url.searchParams.get("state")).toBe("open") + expect(url.searchParams.get("page")).toBe("2") + expect(url.searchParams.get("nullable")).toBe("null") + expect(url.searchParams.get("constructor")).toBe("safe") + expect(client.requests[0]!.headers.meta).toBe("a=b,c=d") + await expect( + Effect.runPromise(tool.run({ keys: [undefined] }).pipe(Effect.provide(client.layer))), + ).rejects.toThrow("unsupported nested value") + }) + + test("skips unsupported parameter encodings and malformed security", () => { + const result = OpenAPI.fromSpec({ + baseUrl, + spec: { + openapi: "3.1.0", + security: [{ bearer: [] }], + paths: { + "/cookie": { + get: { + operationId: "cookie", + parameters: [{ name: "session", in: "cookie", schema: { type: "string" } }], + responses: { 200: { description: "Success" } }, + }, + }, + "/reserved": { + get: { + operationId: "reserved", + parameters: [{ name: "query", in: "query", allowReserved: true, schema: { type: "string" } }], + responses: { 200: { description: "Success" } }, + }, + }, + "/invalid-style": { + get: { + operationId: "invalidStyle", + parameters: [{ name: "query", in: "query", style: 42, schema: { type: "string" } }], + responses: { 200: { description: "Success" } }, + }, + }, + "/security": { + get: { operationId: "security", security: null, responses: { 200: { description: "Success" } } }, + }, + }, + }, + }) + + expect(result.tools).toEqual({}) + expect(result.skipped.map((item) => item.reason)).toEqual([ + "cookie parameter 'session' is not supported", + "parameter 'query' uses unsupported allowReserved encoding", + "parameter 'query' has an invalid style", + "security declaration is not an array", + ]) + }) + + test("fails closed on prototype-named missing security schemes", () => { + const result = OpenAPI.fromSpec({ + baseUrl, + spec: singleOperation({ security: [JSON.parse('{"__proto__":[]}')] }), + }) + + expect(result.tools).toEqual({}) + expect(result.skipped[0]?.reason).toBe("security requirement references missing or malformed scheme: __proto__") + }) + + test("resolves bearer authentication without exposing it as input", async () => { + const contexts: Array[0]> = [] + const client = recordingClient(() => json({ ok: true })) + const spec = { + ...singleOperation({ operationId: undefined }), + security: [{ bearer: [] }], + components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } } }, + } satisfies Document + const tool = toolAt( + OpenAPI.fromSpec({ + baseUrl, + spec, + auth: { + resolve: (context) => { + contexts.push(context) + return Effect.succeed({ type: "bearer", token: "secret" }) + }, + }, + }).tools, + "getTest", + ) + if (!Tool.isDefinition(tool)) throw new Error("test was not generated") + + await Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer))) + + expect(inputTypeScript(tool)).toBe("{}") + expect(client.requests[0]!.headers.authorization).toBe("Bearer secret") + expect(contexts).toEqual([ + { + name: "bearer", + definition: { type: "http", scheme: "bearer" }, + scopes: [], + operation: { + operationId: undefined, + method: "GET", + path: "/test", + summary: undefined, + description: undefined, + }, + }, + ]) + }) + + test("applies authentication carriers without prototype or collision loss", async () => { + const client = recordingClient(() => json({ ok: true })) + const authenticated = (security: ReadonlyArray>>, schemes: Record) => + OpenAPI.fromSpec({ + baseUrl, + spec: { ...singleOperation({}), security, components: { securitySchemes: schemes } }, + auth: { resolve: () => Effect.succeed({ type: "apiKey", value: "secret" }) }, + }) + const prototype = toolAt( + authenticated([{ key: [] }], { key: { type: "apiKey", in: "query", name: "__proto__" } }).tools, + "test", + ) + if (!Tool.isDefinition(prototype)) throw new Error("prototype auth tool was not generated") + + await Effect.runPromise(prototype.run({}).pipe(Effect.provide(client.layer))) + expect(new URL(client.requests[0]!.url).searchParams.get("__proto__")).toBe("secret") + + const duplicate = toolAt( + authenticated( + [{ first: [], second: [] }], + { + first: { type: "apiKey", in: "header", name: "x-key" }, + second: { type: "apiKey", in: "header", name: "x-key" }, + }, + ).tools, + "test", + ) + if (!Tool.isDefinition(duplicate)) throw new Error("duplicate auth tool was not generated") + await expect(Effect.runPromise(duplicate.run({}).pipe(Effect.provide(client.layer)))).rejects.toThrow( + "multiple credentials", + ) + + const cookie = authenticated([{ key: [] }], { key: { type: "apiKey", in: "cookie", name: "session" } }) + expect(cookie.tools).toEqual({}) + expect(cookie.skipped[0]?.reason).toBe("cookie authentication 'key' is not supported") + + const alternative = OpenAPI.fromSpec({ + baseUrl, + spec: { + ...singleOperation({}), + security: [{ cookie: [] }, { bearer: [] }], + components: { + securitySchemes: { + cookie: { type: "apiKey", in: "cookie", name: "session" }, + bearer: { type: "http", scheme: "bearer" }, + }, + }, + }, + auth: { + resolve: ({ name }) => + Effect.succeed(name === "bearer" ? { type: "bearer", token: "secret" } : undefined), + }, + }) + const alternativeTool = toolAt(alternative.tools, "test") + if (!Tool.isDefinition(alternativeTool)) throw new Error("supported auth alternative was not generated") + await Effect.runPromise(alternativeTool.run({}).pipe(Effect.provide(client.layer))) + expect(client.requests.at(-1)?.headers.authorization).toBe("Bearer secret") + }) + + test("honors server precedence and rejects ambiguous base URLs", async () => { + const client = recordingClient(() => json({ ok: true })) + const spec = { + ...singleOperation({ servers: [{ url: "https://operation.example/v1" }] }), + servers: [{ url: "https://document.example" }], + } satisfies Document + const tool = toolAt(OpenAPI.fromSpec({ spec }).tools, "test") + if (!Tool.isDefinition(tool)) throw new Error("test was not generated") + + await Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer))) + expect(client.requests[0]?.url).toBe("https://operation.example/v1/test") + + const invalid = OpenAPI.fromSpec({ spec, baseUrl: "https://example.com/api?tenant=one" }) + expect(invalid.tools).toEqual({}) + expect(invalid.skipped[0]?.reason).toContain("unsupported query string or fragment") + + const malformed = OpenAPI.fromSpec({ spec, baseUrl: "https:/example.com" }) + expect(malformed.tools).toEqual({}) + expect(malformed.skipped[0]?.reason).toContain("not an absolute HTTP(S) URL") + }) + + test("resolves chained response refs before detecting unsupported transports", () => { + const result = OpenAPI.fromSpec({ + baseUrl, + spec: { + ...singleOperation({ responses: { 200: { $ref: "#/components/responses/First" } } }), + components: { + responses: { + First: { $ref: "#/components/responses/Stream" }, + Stream: { content: { "text/event-stream": { schema: { type: "string" } } } }, + }, + }, + }, + }) + + expect(result.tools).toEqual({}) + expect(result.skipped[0]?.reason).toBe("SSE operations are not supported") + }) + + test("resolves response schemas before detecting binary output", () => { + const result = OpenAPI.fromSpec({ + baseUrl, + spec: { + ...singleOperation({ + responses: { + 200: { + content: { "text/plain": { schema: { $ref: "#/components/schemas/File" } } }, + }, + }, + }), + components: { schemas: { File: { type: "string", format: "binary" } } }, + }, + }) + + expect(result.tools).toEqual({}) + expect(result.skipped[0]?.reason).toBe("binary responses are not supported") + }) + + test("validates composite parameters before resolving auth", async () => { + const resolutions: Array = [] + const client = recordingClient(() => json({ ok: true })) + const tool = toolAt( + OpenAPI.fromSpec({ + baseUrl, + spec: { + ...singleOperation({ + parameters: [{ name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } }], + }), + security: [{ bearer: [] }], + components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } } }, + }, + auth: { + resolve: ({ name }) => { + resolutions.push(name) + return Effect.succeed({ type: "bearer", token: "secret" }) + }, + }, + }).tools, + "test", + ) + if (!Tool.isDefinition(tool)) throw new Error("test was not generated") + + await expect( + Effect.runPromise(tool.run({ filter: { value: undefined } }).pipe(Effect.provide(client.layer))), + ).rejects.toThrow("unsupported nested value") + expect(resolutions).toEqual([]) + expect(client.requests).toEqual([]) + }) + + test("preserves JSON media types and rejects unencodable bodies", async () => { + const client = recordingClient(() => json({ ok: true })) + const tool = toolAt( + OpenAPI.fromSpec({ + baseUrl, + spec: singleOperation( + { + requestBody: { + required: true, + content: { "application/merge-patch+json": { schema: { type: "object" } } }, + }, + }, + "post", + ), + }).tools, + "test", + ) + if (!Tool.isDefinition(tool)) throw new Error("test was not generated") + + await Effect.runPromise(tool.run({ body: { name: "updated" } }).pipe(Effect.provide(client.layer))) + expect(client.requests[0]!.headers["content-type"]).toBe("application/merge-patch+json") + const cyclic: Record = {} + cyclic.self = cyclic + await expect(Effect.runPromise(tool.run({ body: cyclic }).pipe(Effect.provide(client.layer)))).rejects.toThrow( + "Invalid JSON body", + ) + }) + + test("rejects oversized and malformed JSON responses", async () => { + const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec: singleOperation({}) }).tools, "test") + if (!Tool.isDefinition(tool)) throw new Error("test was not generated") + const oversized = recordingClient( + () => new Response(null, { headers: { "content-length": String(50 * 1024 * 1024 + 1) } }), + ) + const malformed = recordingClient( + () => new Response("{", { headers: { "content-type": "application/json" } }), + ) + const chunked = recordingClient(() => new Response(new Uint8Array(50 * 1024 * 1024 + 1))) + + await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(oversized.layer)))).rejects.toThrow( + "response exceeds 50 MiB", + ) + await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(malformed.layer)))).rejects.toThrow( + "returned malformed JSON", + ) + await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(chunked.layer)))).rejects.toThrow( + "response exceeds 50 MiB", + ) + }) + + test("keeps non-JSON responses raw and unions every success output", async () => { + const spec = singleOperation({ + responses: { + 200: { description: "Text", content: { "text/plain": { schema: { type: "string" } } } }, + 204: { description: "Empty" }, + }, + }) + const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec }).tools, "test") + if (!Tool.isDefinition(tool)) throw new Error("test was not generated") + const client = recordingClient(() => new Response("123", { headers: { "content-type": "text/plain" } })) + + expect(outputTypeScript(tool)).toBe("string | null") + await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer)))).resolves.toBe("123") + }) + + test("fails missing required parameters before auth and network", async () => { + const { requests, layer } = recordingClient(() => json({})) + const runtime = CodeMode.make({ + tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools }, + }) + + const result = await Effect.runPromise( + runtime.execute("return await tools.opencode.v2.session.get({})").pipe(Effect.provide(layer)), + ) + + expect(result).toMatchObject({ ok: false }) + expect(JSON.stringify(result)).toContain("Missing required path parameter 'sessionID'") + expect(requests).toHaveLength(0) + }) + + test("prefixes cross-location collisions and reconstructs the HTTP request", async () => { + const spec = { + openapi: "3.1.0", + info: { title: "collision", version: "1.0.0" }, + paths: { + "/echo": { + post: { + operationId: "echo", + requestBody: { + required: true, + content: { "application/json": { schema: { type: "string" } } }, + }, + responses: { "204": { description: "Echoed" } }, + }, + }, + "/things/{id}": { + post: { + operationId: "things.update", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + { name: "id", in: "query", required: true, schema: { type: "string" } }, + { name: "path_id", in: "query", schema: { type: "string" } }, + { name: "id", in: "header", required: true, schema: { type: "string" } }, + ], + requestBody: { + required: true, + content: { + "application/json": { + schema: { + type: "object", + properties: { id: { type: "string" } }, + required: ["id"], + additionalProperties: false, + }, + }, + }, + }, + responses: { "204": { description: "Updated" } }, + }, + }, + }, + } satisfies Document + const { requests, layer } = recordingClient(() => new Response(null, { status: 204 })) + const tools = OpenAPI.fromSpec({ spec, baseUrl }).tools + const update = toolAt(tools, "things.update") + const echo = toolAt(tools, "echo") + + expect(Tool.isDefinition(update)).toBe(true) + if (!Tool.isDefinition(update)) throw new Error("things.update was not generated") + expect(inputTypeScript(update)).toBe( + "{ path_id: string; query_id: string; path_id_2?: string; header_id: string; body_id: string }", + ) + expect(Tool.isDefinition(echo)).toBe(true) + if (!Tool.isDefinition(echo)) throw new Error("echo was not generated") + expect(inputTypeScript(echo)).toBe("{ body: string }") + + const runtime = CodeMode.make({ tools }) + const result = await Effect.runPromise( + runtime + .execute( + ` + const updated = await tools.things.update({ path_id: "path", query_id: "query", path_id_2: "literal", header_id: "header", body_id: "body" }) + const echoed = await tools.echo({ body: "hello" }) + return { updated, echoed } + `, + ) + .pipe(Effect.provide(layer)), + ) + + expect(result).toMatchObject({ ok: true }) + expect(requests).toHaveLength(2) + expect(new URL(requests[0]!.url).pathname).toBe("/things/path") + expect(new URL(requests[0]!.url).searchParams.get("id")).toBe("query") + expect(new URL(requests[0]!.url).searchParams.get("path_id")).toBe("literal") + expect(requests[0]!.headers.id).toBe("header") + expect(requests[0]!.body).toStrictEqual({ id: "body" }) + expect(requests[1]!.body).toBe("hello") + }) + + test("keeps bodies nested when flattening would lose schema semantics", () => { + const body = (schema: Record, required = true) => ({ + required, + content: { "application/json": { schema } }, + }) + const spec = { + openapi: "3.1.0", + info: { title: "bodies", version: "1.0.0" }, + paths: Object.fromEntries( + [ + [ + "optional", + body( + { + type: "object", + properties: { name: { type: "string" } }, + required: ["name"], + additionalProperties: false, + }, + false, + ), + ], + ["dictionary", body({ type: "object", additionalProperties: { type: "string" } })], + [ + "composed", + body({ + type: "object", + allOf: [{ type: "object", properties: { name: { type: "string" } }, required: ["name"] }], + additionalProperties: false, + }), + ], + [ + "nullable", + body({ + type: ["object", "null"], + properties: { name: { type: "string" } }, + additionalProperties: false, + }), + ], + ].map(([name, requestBody]) => [ + `/body/${name}`, + { + post: { + operationId: `body.${name}`, + requestBody, + responses: { "204": { description: "Accepted" } }, + }, + }, + ]), + ), + } satisfies Document + const tools = OpenAPI.fromSpec({ spec, baseUrl }).tools + + for (const name of ["optional", "dictionary", "composed", "nullable"]) { + const tool = toolAt(tools, `body.${name}`) + expect(Tool.isDefinition(tool)).toBe(true) + if (!Tool.isDefinition(tool)) throw new Error(`body.${name} was not generated`) + const input = isRecord(tool.input) ? tool.input : {} + expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual(["body"]) + } + const optional = toolAt(tools, "body.optional") + if (!Tool.isDefinition(optional)) throw new Error("body.optional was not generated") + expect(inputTypeScript(optional)).toBe("{ body?: { name: string } }") + }) +}) diff --git a/packages/codemode/test/signature.test.ts b/packages/codemode/test/signature.test.ts index edf4c442c4..55b8ac020a 100644 --- a/packages/codemode/test/signature.test.ts +++ b/packages/codemode/test/signature.test.ts @@ -159,8 +159,8 @@ describe("pretty signature rendering", () => { $ref: "#/$defs/Node", $defs: { Node: { type: "object", properties: { child: { $ref: "#/$defs/Node" }, name: { type: "string" } } } }, } as const - expect(jsonSchemaToTypeScript(cyclic)).toBe("{ child?: Node; name?: string }") - expect(jsonSchemaToTypeScript(cyclic, true)).toContain("child?: Node") + expect(jsonSchemaToTypeScript(cyclic)).toBe("{ child?: unknown; name?: string }") + expect(jsonSchemaToTypeScript(cyclic, true)).toContain("child?: unknown") let deep: Record = { type: "string" } for (let level = 0; level < 12; level += 1) deep = { type: "object", properties: { next: deep } } @@ -170,6 +170,43 @@ describe("pretty signature rendering", () => { expect(rendered).toContain("next?:") } }) + + test("intersects ref and union siblings instead of discarding them", () => { + expect( + jsonSchemaToTypeScript({ + $ref: "#/$defs/User", + properties: { active: { type: "boolean" } }, + required: ["active"], + $defs: { + User: { type: "object", properties: { id: { type: "string" } }, required: ["id"] }, + }, + }), + ).toBe("{ id: string } & { active: boolean }") + expect( + jsonSchemaToTypeScript({ + type: "object", + properties: { common: { type: "boolean" } }, + required: ["common"], + anyOf: [ + { type: "object", properties: { name: { type: "string" } }, required: ["name"] }, + { type: "object", properties: { count: { type: "number" } }, required: ["count"] }, + ], + }), + ).toBe("({ name: string } | { count: number }) & { common: boolean }") + expect(jsonSchemaToTypeScript({ $ref: "https://example.com/schema.json" })).toBe("unknown") + expect( + jsonSchemaToTypeScript({ + $ref: "#/$defs/User/properties/id", + $defs: { User: { type: "object" }, id: { type: "string" } }, + }), + ).toBe("unknown") + expect( + jsonSchemaToTypeScript({ + type: ["object", "null"], + properties: { name: { type: "string" } }, + }), + ).toBe("{ name?: string } | null") + }) }) describe("non-identifier property names render as quoted keys", () => { @@ -268,6 +305,32 @@ describe("union schemas render every alternative", () => { expect(inputTypeScript(tool)).toBe("{ value?: string | number }") expect(outputTypeScript(tool)).toBe("number | boolean") }) + + test("allOf renders intersections with parenthesized union members", () => { + const schema = { + allOf: [ + { type: "object", properties: { id: { type: "string" } } }, + { type: ["string", "null"] }, + ], + } as const + expect(jsonSchemaToTypeScript(schema)).toBe("{ id?: string } & (string | null)") + }) + + test("allOf does not discard an unresolved constraint", () => { + expect(jsonSchemaToTypeScript({ allOf: [{ type: "string" }, { $ref: "https://example.com/external.json" }] })).toBe( + "unknown", + ) + expect( + jsonSchemaToTypeScript({ allOf: [{ type: "string" }, { allOf: [{ $ref: "https://example.com/external.json" }] }] }), + ).toBe("unknown") + expect( + jsonSchemaToTypeScript({ + type: "string", + allOf: [{ $ref: "#/$defs/Constraint" }], + $defs: { Constraint: { description: "TypeScript-neutral constraint" } }, + }), + ).toBe("string") + }) }) describe("pretty signatures in search results", () => { diff --git a/packages/protocol/src/groups/pty.ts b/packages/protocol/src/groups/pty.ts index 4ac3c5519f..309868189f 100644 --- a/packages/protocol/src/groups/pty.ts +++ b/packages/protocol/src/groups/pty.ts @@ -127,6 +127,7 @@ export const PtyGroup = HttpApiGroup.make("server.pty") description: "Establish a WebSocket connection streaming PTY output and accepting terminal input.", transform: (operation) => ({ ...operation, + "x-websocket": true, parameters: [ ...(operation.parameters ?? []), ...["location[directory]", "location[workspace]", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({ From bb3b6a2f65a3c95015fb2461e436288a316d7930 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 20:47:33 -0400 Subject: [PATCH 57/82] fix(protocol): expose MCP tool change events (#35373) --- .../client/src/promise/generated/types.ts | 8 +++++++ packages/protocol/test/event.test.ts | 23 +++++++++++++++++++ packages/schema/src/event-manifest.ts | 2 +- packages/schema/test/event-manifest.test.ts | 1 + 4 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 packages/protocol/test/event.test.ts diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 151f0ff03f..ba3c1a563b 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -5402,6 +5402,14 @@ export type EventSubscribeOutput = readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly branch?: string } } + | { + readonly id: string + readonly created: number + readonly metadata?: { readonly [x: string]: unknown } + readonly type: "mcp.tools.changed" + readonly location?: { readonly directory: string; readonly workspaceID?: string } + readonly data: { readonly server: string } + } | { readonly id: string readonly created: number diff --git a/packages/protocol/test/event.test.ts b/packages/protocol/test/event.test.ts new file mode 100644 index 0000000000..52757ad30e --- /dev/null +++ b/packages/protocol/test/event.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from "bun:test" +import { Event } from "@opencode-ai/schema/event" +import { AbsolutePath } from "@opencode-ai/schema/schema" +import { DateTime, Schema } from "effect" +import { OpenCodeEvent } from "../src/groups/event.js" + +test("encodes MCP tool changes emitted by the server", () => { + expect( + Schema.encodeSync(OpenCodeEvent)({ + id: Event.ID.make("evt_test"), + created: DateTime.makeUnsafe(0), + type: "mcp.tools.changed", + location: { directory: AbsolutePath.make("/tmp") }, + data: { server: "example" }, + }), + ).toEqual({ + id: "evt_test", + created: 0, + type: "mcp.tools.changed", + location: { directory: "/tmp" }, + data: { server: "example" }, + }) +}) diff --git a/packages/schema/src/event-manifest.ts b/packages/schema/src/event-manifest.ts index 6b2b806f81..09a5db8da4 100644 --- a/packages/schema/src/event-manifest.ts +++ b/packages/schema/src/event-manifest.ts @@ -78,7 +78,7 @@ export const ServerDefinitions = Event.inventory( ...TuiEvent.Definitions, ...InstallationEvent.Definitions, ...VcsEvent.Definitions, - McpEvent.StatusChanged, + ...McpEvent.Definitions, // Shared transitional: V1 contracts the current TUI still consumes during // the migration (permission.asked/replied, question.asked, session.error). // Remove when the TUI moves to the current permission/question surfaces. diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 487a942d9a..22003313ba 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -27,6 +27,7 @@ describe("public event manifest", () => { Agent.Event.Updated, ]) expect(EventManifest.Definitions).toContain(Agent.Event.Updated) + expect(EventManifest.ServerDefinitions).toContain(McpEvent.ToolsChanged) expect(EventManifest.Definitions.filter((definition) => definition.type === "agent.updated")).toEqual([ Agent.Event.Updated, ]) From 905123b9c0716b20c09a03991ff314dd57d08795 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 21:12:45 -0400 Subject: [PATCH 58/82] fix(protocol): keep internal events off SSE (#35378) --- .../client/src/promise/generated/types.ts | 8 ------ packages/core/src/event.ts | 21 ++++++++++------ packages/core/src/plugin/host.ts | 4 +-- packages/core/test/event.test.ts | 20 +++++++++++++-- packages/protocol/src/groups/event.ts | 2 ++ packages/protocol/test/event.test.ts | 25 ++++--------------- packages/schema/src/event-manifest.ts | 6 ++++- packages/schema/test/event-manifest.test.ts | 3 ++- packages/server/src/handlers/event.ts | 7 ++++-- 9 files changed, 52 insertions(+), 44 deletions(-) diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index ba3c1a563b..151f0ff03f 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -5402,14 +5402,6 @@ export type EventSubscribeOutput = readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly branch?: string } } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "mcp.tools.changed" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly server: string } - } | { readonly id: string readonly created: number diff --git a/packages/core/src/event.ts b/packages/core/src/event.ts index 587688d814..3e352c6e6b 100644 --- a/packages/core/src/event.ts +++ b/packages/core/src/event.ts @@ -160,15 +160,22 @@ export interface Interface { export class Service extends Context.Service()("@opencode/Event") {} -export const liveBounded = (events: Interface, capacity: number) => +export const liveBounded = ( + events: Interface, + options: { readonly capacity: number; readonly accept?: (event: Payload) => boolean }, +) => Effect.gen(function* () { - const queue = yield* Queue.dropping(capacity) + const queue = yield* Queue.dropping(options.capacity) const unsubscribe = yield* events.listen((event) => - Queue.offer(queue, event).pipe( - Effect.flatMap((accepted) => - accepted ? Effect.void : Queue.fail(queue, new SubscriberOverflowError({ capacity })).pipe(Effect.asVoid), - ), - ), + options.accept && !options.accept(event) + ? Effect.void + : Queue.offer(queue, event).pipe( + Effect.flatMap((accepted) => + accepted + ? Effect.void + : Queue.fail(queue, new SubscriberOverflowError({ capacity: options.capacity })).pipe(Effect.asVoid), + ), + ), ) yield* Effect.addFinalizer(() => unsubscribe.pipe(Effect.andThen(Queue.shutdown(queue)), Effect.asVoid)) return Stream.fromQueue(queue) diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index 585c254a78..4c7bb8538c 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -23,8 +23,6 @@ import { ToolHooks } from "../tool/hooks" import { WorkspaceV2 } from "../workspace" const mutable = (value: T) => value as DeepMutable -const isEvent = Schema.is(Schema.Union(EventManifest.ServerDefinitions)) - export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Interface) { const agents = yield* AgentV2.Service const aisdk = yield* AISDK.Service @@ -160,7 +158,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Int }), }, event: { - subscribe: () => events.live().pipe(Stream.filter(isEvent)), + subscribe: () => events.live().pipe(Stream.filter(EventManifest.isServer)), }, integration: { list: () => response(integration.list()), diff --git a/packages/core/test/event.test.ts b/packages/core/test/event.test.ts index 65c370f1eb..70a8083d16 100644 --- a/packages/core/test/event.test.ts +++ b/packages/core/test/event.test.ts @@ -2,6 +2,8 @@ import { describe, expect } from "bun:test" import { Cause, DateTime, Deferred, Effect, Exit, Fiber, Layer, Option, Ref, Schema, Stream } from "effect" import { EventV2 } from "@opencode-ai/core/event" import { Event } from "@opencode-ai/schema/event" +import { EventManifest } from "@opencode-ai/schema/event-manifest" +import { McpEvent } from "@opencode-ai/schema/mcp-event" import { Session } from "@opencode-ai/schema/session" import { SessionEvent } from "@opencode-ai/schema/session-event" import { SessionV1 } from "@opencode-ai/schema/session-v1" @@ -329,8 +331,8 @@ describe("EventV2", () => { const events = yield* EventV2.Service const consuming = yield* Deferred.make() const release = yield* Deferred.make() - const slowStream = yield* EventV2.liveBounded(events, 1) - const fastStream = yield* EventV2.liveBounded(events, 8) + const slowStream = yield* EventV2.liveBounded(events, { capacity: 1 }) + const fastStream = yield* EventV2.liveBounded(events, { capacity: 8 }) const slow = yield* slowStream.pipe( Stream.runForEach(() => Deferred.succeed(consuming, undefined).pipe(Effect.andThen(Deferred.await(release)))), Effect.forkScoped, @@ -355,6 +357,20 @@ describe("EventV2", () => { }), ) + it.effect("filters internal events before they enter a bounded server stream", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const stream = yield* EventV2.liveBounded(events, { capacity: 1, accept: EventManifest.isServer }) + const received = yield* stream.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) + + yield* events.publish(McpEvent.ToolsChanged, { server: "one" }) + yield* events.publish(McpEvent.ToolsChanged, { server: "two" }) + const published = yield* events.publish(McpEvent.StatusChanged, { server: "example" }) + + expect(Array.from(yield* Fiber.join(received))).toEqual([published]) + }), + ) + it.effect("preserves observer interruption", () => Effect.gen(function* () { const events = yield* EventV2.Service diff --git a/packages/protocol/src/groups/event.ts b/packages/protocol/src/groups/event.ts index 9860aa0cad..94cedd1a57 100644 --- a/packages/protocol/src/groups/event.ts +++ b/packages/protocol/src/groups/event.ts @@ -67,3 +67,5 @@ export const EventGroup = event.group export const OpenCodeEvent = event.schema export type OpenCodeEvent = typeof OpenCodeEvent.Type export type OpenCodeEventEncoded = typeof OpenCodeEvent.Encoded +export const isOpenCodeEvent = (event: { readonly type: string }): event is OpenCodeEvent => + event.type === "server.connected" || EventManifest.isServer(event) diff --git a/packages/protocol/test/event.test.ts b/packages/protocol/test/event.test.ts index 52757ad30e..33ece777c4 100644 --- a/packages/protocol/test/event.test.ts +++ b/packages/protocol/test/event.test.ts @@ -1,23 +1,8 @@ import { expect, test } from "bun:test" -import { Event } from "@opencode-ai/schema/event" -import { AbsolutePath } from "@opencode-ai/schema/schema" -import { DateTime, Schema } from "effect" -import { OpenCodeEvent } from "../src/groups/event.js" +import { isOpenCodeEvent } from "../src/groups/event.js" -test("encodes MCP tool changes emitted by the server", () => { - expect( - Schema.encodeSync(OpenCodeEvent)({ - id: Event.ID.make("evt_test"), - created: DateTime.makeUnsafe(0), - type: "mcp.tools.changed", - location: { directory: AbsolutePath.make("/tmp") }, - data: { server: "example" }, - }), - ).toEqual({ - id: "evt_test", - created: 0, - type: "mcp.tools.changed", - location: { directory: "/tmp" }, - data: { server: "example" }, - }) +test("classifies public events by type", () => { + expect(isOpenCodeEvent({ type: "server.connected" })).toBe(true) + expect(isOpenCodeEvent({ type: "mcp.status.changed" })).toBe(true) + expect(isOpenCodeEvent({ type: "mcp.tools.changed" })).toBe(false) }) diff --git a/packages/schema/src/event-manifest.ts b/packages/schema/src/event-manifest.ts index 09a5db8da4..23ed3fd044 100644 --- a/packages/schema/src/event-manifest.ts +++ b/packages/schema/src/event-manifest.ts @@ -1,5 +1,6 @@ export * as EventManifest from "./event-manifest.js" +import { Schema } from "effect" import { Agent } from "./agent.js" import { Catalog } from "./catalog.js" import { Command } from "./command.js" @@ -78,7 +79,7 @@ export const ServerDefinitions = Event.inventory( ...TuiEvent.Definitions, ...InstallationEvent.Definitions, ...VcsEvent.Definitions, - ...McpEvent.Definitions, + McpEvent.StatusChanged, // Shared transitional: V1 contracts the current TUI still consumes during // the migration (permission.asked/replied, question.asked, session.error). // Remove when the TUI moves to the current permission/question surfaces. @@ -86,6 +87,9 @@ export const ServerDefinitions = Event.inventory( ...QuestionV1.Event.Definitions, SessionV1.Error, ) +export const Server = Event.latest(ServerDefinitions) +export type ServerEvent = Schema.Schema.Type<(typeof ServerDefinitions)[number]> +export const isServer = (event: { readonly type: string }): event is ServerEvent => Server.has(event.type) export const Definitions = Event.inventory( ...foundationDefinitions, diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 22003313ba..0147c7469b 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -27,7 +27,6 @@ describe("public event manifest", () => { Agent.Event.Updated, ]) expect(EventManifest.Definitions).toContain(Agent.Event.Updated) - expect(EventManifest.ServerDefinitions).toContain(McpEvent.ToolsChanged) expect(EventManifest.Definitions.filter((definition) => definition.type === "agent.updated")).toEqual([ Agent.Event.Updated, ]) @@ -47,6 +46,8 @@ describe("public event manifest", () => { EventManifest.Definitions.map((definition) => definition.type), ) expect(EventManifest.Latest.get("agent.updated")).toBe(Agent.Event.Updated) + expect(EventManifest.Server.get("mcp.status.changed")).toBe(McpEvent.StatusChanged) + expect(EventManifest.Server.has("mcp.tools.changed")).toBe(false) expect(Agent.Event.Updated.durable).toBeUndefined() expect(EventManifest.Durable.has("agent.updated")).toBe(false) }) diff --git a/packages/server/src/handlers/event.ts b/packages/server/src/handlers/event.ts index ca9c02620d..1c8b94d124 100644 --- a/packages/server/src/handlers/event.ts +++ b/packages/server/src/handlers/event.ts @@ -1,5 +1,5 @@ import { EventV2 } from "@opencode-ai/core/event" -import { OpenCodeEvent } from "@opencode-ai/protocol/groups/event" +import { isOpenCodeEvent, OpenCodeEvent } from "@opencode-ai/protocol/groups/event" import { Effect, Schema, Stream } from "effect" import { Sse } from "effect/unstable/encoding" import { HttpServerResponse } from "effect/unstable/http" @@ -35,7 +35,10 @@ export const EventHandler = HttpApiBuilder.group(Api, "server.event", (handlers) const output = Stream.unwrap( Effect.gen(function* () { // Acquiring the bounded stream installs its listener before readiness is observable. - const live = yield* EventV2.liveBounded(events, subscriberCapacity) + const live = yield* EventV2.liveBounded(events, { + capacity: subscriberCapacity, + accept: isOpenCodeEvent, + }) return Stream.make(connected).pipe(Stream.concat(live)) }), ).pipe(Stream.map(eventData), Stream.pipeThroughChannel(Sse.encode())) From 44b182fe23f12bc802f02625cb5e485405c6b3e8 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sat, 4 Jul 2026 21:43:08 -0400 Subject: [PATCH 59/82] fix(core): validate scalar newtypes (#35381) --- packages/core/src/schema.ts | 56 ++++++++++++++++++------------ packages/core/test/newtype.test.ts | 47 +++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 23 deletions(-) create mode 100644 packages/core/test/newtype.test.ts diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index 9c25bee19b..338255309f 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -43,37 +43,47 @@ export type DeepMutable = T extends string | number | boolean | bigint | symb * Nominal wrapper for scalar types. The class itself is a valid schema — * pass it directly to `Schema.decode`, `Schema.decodeEffect`, etc. * - * Overrides `~type.make` on the derived `Schema.Opaque` so `Schema.Schema.Type` - * of a field using this newtype resolves to `Self` rather than the underlying - * branded phantom. Without that override, passing a class instance to code - * typed against `Schema.Schema.Type` would require a cast even - * though the values are structurally equivalent at runtime. + * The runtime value remains an unwrapped primitive. `Schema.brand` supplies + * the primitive schema behavior and constructor validation, while the class + * supplies the nominal TypeScript identity. + * Apply checks and annotations to the underlying schema before wrapping it; + * schema rebuild operations intentionally return the underlying schema shape. * * @example - * class QuestionID extends Newtype()("QuestionID", Schema.String) { - * static make(id: string): QuestionID { - * return this.make(id) - * } - * } + * class QuestionID extends Newtype()("QuestionID", Schema.String) {} * - * Schema.decodeEffect(QuestionID)(input) + * const id = QuestionID.make("question-1") + * Schema.decodeUnknownEffect(QuestionID)(input) */ +type NewtypeSchema = (abstract new (_: never) => { + readonly _newtype: Tag +}) & + Schema.Bottom< + Self, + S["Encoded"], + S["DecodingServices"], + S["EncodingServices"], + S["ast"], + S["Rebuild"], + S["~type.make.in"], + Self, + S["~type.parameters"], + Self, + S["~type.mutability"], + S["~type.optionality"], + S["~type.constructor.default"], + S["~encoded.mutability"], + S["~encoded.optionality"] + > & + Omit + export function Newtype() { - return (tag: Tag, schema: S) => { + return (tag: Tag, schema: S): NewtypeSchema => { abstract class Base { declare readonly _newtype: Tag - - static make(value: Schema.Schema.Type): Self { - return value as unknown as Self - } } - Object.setPrototypeOf(Base, schema) - - return Base as unknown as (abstract new (_: never) => { readonly _newtype: Tag }) & { - readonly make: (value: Schema.Schema.Type) => Self - } & Omit, "make" | "~type.make"> & { - readonly "~type.make": Self - } + Object.setPrototypeOf(Base, schema.pipe(Schema.brand(tag))) + return Base as unknown as NewtypeSchema } } diff --git a/packages/core/test/newtype.test.ts b/packages/core/test/newtype.test.ts new file mode 100644 index 0000000000..1bcba5709d --- /dev/null +++ b/packages/core/test/newtype.test.ts @@ -0,0 +1,47 @@ +import { expect, test } from "bun:test" +import { Effect, Schema } from "effect" +import { Newtype } from "../src/schema" + +class UserID extends Newtype()("Test.UserID", Schema.NonEmptyString) {} +class ProjectID extends Newtype()("Test.ProjectID", Schema.NonEmptyString) {} +class Port extends Newtype()("Test.Port", Schema.FiniteFromString) {} + +const User = Schema.Struct({ id: UserID }) + +test("constructs nominal values from the underlying type", () => { + const id = UserID.make("user-1") + const acceptUserID = (_id: UserID) => undefined + + expect(String(id)).toBe("user-1") + acceptUserID(id) + + if (false) { + // @ts-expect-error distinct newtypes are not interchangeable + acceptUserID(ProjectID.make("project-1")) + } +}) + +test("preserves constructor validation", () => { + expect(() => UserID.make("")).toThrow() +}) + +test("decodes and encodes as a schema", async () => { + const decoded = await Effect.runPromise(Schema.decodeUnknownEffect(User)({ id: "user-1" })) + const encoded = await Effect.runPromise(Schema.encodeEffect(User)(decoded)) + + expect(String(decoded.id)).toBe("user-1") + expect(encoded).toEqual({ id: "user-1" }) +}) + +test("preserves the underlying schema validation", async () => { + const result = await Effect.runPromise(Schema.decodeUnknownEffect(UserID)("").pipe(Effect.result)) + expect(result._tag).toBe("Failure") +}) + +test("preserves transformed encoded and decoded representations", async () => { + const decoded = await Effect.runPromise(Schema.decodeUnknownEffect(Port)("8080")) + const encoded = await Effect.runPromise(Schema.encodeEffect(Port)(decoded)) + + expect(Number(decoded)).toBe(8080) + expect(encoded).toBe("8080") +}) From 29e8502bb0dc6b38764e38fa41c8e1b8873ee87d Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sun, 5 Jul 2026 09:08:09 -0500 Subject: [PATCH 60/82] fix(tui): align integration empty state (#35414) --- packages/tui/src/component/dialog-integration.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/tui/src/component/dialog-integration.tsx b/packages/tui/src/component/dialog-integration.tsx index cd8780ddfb..52aba6d0e3 100644 --- a/packages/tui/src/component/dialog-integration.tsx +++ b/packages/tui/src/component/dialog-integration.tsx @@ -81,7 +81,11 @@ export function DialogIntegration(props: { onConnected?: OnIntegrationConnected No integrations available} + emptyView={ + + No integrations available + + } /> ) } From 391aa382810e2eb9d408e92c7e9ffc16d33248fd Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sun, 5 Jul 2026 10:40:55 -0500 Subject: [PATCH 61/82] test(core): serve skill fixtures locally (#35429) --- packages/core/test/skill-discovery.test.ts | 143 +++++++++++---------- 1 file changed, 77 insertions(+), 66 deletions(-) diff --git a/packages/core/test/skill-discovery.test.ts b/packages/core/test/skill-discovery.test.ts index e875beb931..28071c926f 100644 --- a/packages/core/test/skill-discovery.test.ts +++ b/packages/core/test/skill-discovery.test.ts @@ -1,36 +1,42 @@ import fs from "fs/promises" import path from "path" import { describe, expect, test } from "bun:test" -import { Effect, Layer } from "effect" -import { HttpClient, HttpClientResponse } from "effect/unstable/http" +import { Effect } from "effect" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" -import { LayerNodePlatform } from "@opencode-ai/core/effect/app-node-platform" -import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Global } from "@opencode-ai/core/global" import { SkillDiscovery } from "@opencode-ai/core/skill/discovery" import { tmpdir } from "./fixture/tmpdir" -const base = "https://skills.example.test/catalog/" +type Fixture = { + tmp: Awaited> + server: Bun.Server + state: { + skills: unknown[] + files: Record + requests: string[] + } + base: string +} -async function pull(skills: unknown[], files: Record = {}, cache?: Awaited>) { - const tmp = cache ?? (await tmpdir()) - const requests: string[] = [] - const http = Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request) => - Effect.sync(() => requests.push(request.url)).pipe( - Effect.map(() => { - const body = request.url === `${base}index.json` ? JSON.stringify({ skills }) : files[request.url] - return HttpClientResponse.fromWeb( - request, - new Response(body ?? "Not Found", { status: body === undefined ? 404 : 200 }), - ) - }), - ), - ), - ) +async function pull(skills: unknown[], files: Record = {}, fixture?: Fixture) { + const state = fixture?.state ?? { skills, files, requests: [] } + state.skills = skills + state.files = files + state.requests = [] + const server = + fixture?.server ?? + Bun.serve({ + port: 0, + fetch(request) { + state.requests.push(request.url) + const pathname = new URL(request.url).pathname + const body = pathname === "/catalog/index.json" ? JSON.stringify({ skills: state.skills }) : state.files[pathname] + return new Response(body ?? "Not Found", { status: body === undefined ? 404 : 200 }) + }, + }) + const tmp = fixture?.tmp ?? (await tmpdir()) + const base = fixture?.base ?? new URL("/catalog/", server.url).href const skillDiscoveryLayer = AppNodeBuilder.build(SkillDiscovery.node, [ - [LayerNodePlatform.httpClient, http], [Global.node, Global.layerWith({ cache: tmp.path })], ]) const directories = await Effect.runPromise( @@ -38,7 +44,12 @@ async function pull(skills: unknown[], files: Record = {}, cache return yield* (yield* SkillDiscovery.Service).pull(base) }).pipe(Effect.provide(skillDiscoveryLayer)), ) - return { tmp, requests, directories } + return { tmp, server, state, base, requests: state.requests, directories } +} + +async function dispose(fixture: Fixture) { + await fixture.server.stop(true) + await fixture.tmp[Symbol.asyncDispose]() } describe("SkillDiscovery.pull", () => { @@ -46,10 +57,10 @@ describe("SkillDiscovery.pull", () => { const result = await pull([{ name: "../outside", files: ["SKILL.md"] }]) try { expect(result.directories).toEqual([]) - expect(result.requests).toEqual([`${base}index.json`]) + expect(result.requests).toEqual([`${result.base}index.json`]) expect(await fs.readdir(result.tmp.path)).toEqual([]) } finally { - await result.tmp[Symbol.asyncDispose]() + await dispose(result) } }) @@ -57,10 +68,10 @@ describe("SkillDiscovery.pull", () => { const result = await pull([{ name: "deploy", files: ["SKILL.md", "../outside.md"] }]) try { expect(result.directories).toEqual([]) - expect(result.requests).toEqual([`${base}index.json`]) + expect(result.requests).toEqual([`${result.base}index.json`]) expect(await fs.readdir(result.tmp.path)).toEqual([]) } finally { - await result.tmp[Symbol.asyncDispose]() + await dispose(result) } }) @@ -68,10 +79,10 @@ describe("SkillDiscovery.pull", () => { const result = await pull([{ name: "deploy", files: ["SKILL.md", "/tmp/outside.md"] }]) try { expect(result.directories).toEqual([]) - expect(result.requests).toEqual([`${base}index.json`]) + expect(result.requests).toEqual([`${result.base}index.json`]) expect(await fs.readdir(result.tmp.path)).toEqual([]) } finally { - await result.tmp[Symbol.asyncDispose]() + await dispose(result) } }) @@ -79,87 +90,87 @@ describe("SkillDiscovery.pull", () => { const result = await pull([{ name: "deploy", files: ["SKILL.md", "https://evil.example.test/outside.md"] }]) try { expect(result.directories).toEqual([]) - expect(result.requests).toEqual([`${base}index.json`]) + expect(result.requests).toEqual([`${result.base}index.json`]) expect(await fs.readdir(result.tmp.path)).toEqual([]) } finally { - await result.tmp[Symbol.asyncDispose]() + await dispose(result) } }) test("downloads safe nested files under the skill root", async () => { const result = await pull([{ name: "deploy", files: ["SKILL.md", "references/guide.md"] }], { - [`${base}deploy/SKILL.md`]: "# Deploy", - [`${base}deploy/references/guide.md`]: "# Guide", + "/catalog/deploy/SKILL.md": "# Deploy", + "/catalog/deploy/references/guide.md": "# Guide", }) try { expect(result.directories).toHaveLength(1) expect(result.requests.toSorted()).toEqual( - [`${base}index.json`, `${base}deploy/SKILL.md`, `${base}deploy/references/guide.md`].toSorted(), + [ + `${result.base}index.json`, + `${result.base}deploy/SKILL.md`, + `${result.base}deploy/references/guide.md`, + ].toSorted(), ) expect(await fs.readFile(path.join(result.directories[0], "SKILL.md"), "utf8")).toBe("# Deploy") expect(await fs.readFile(path.join(result.directories[0], "references", "guide.md"), "utf8")).toBe("# Guide") } finally { - await result.tmp[Symbol.asyncDispose]() + await dispose(result) } }) test("refreshes cached files when the version changes", async () => { - const tmp = await tmpdir() + const first = await pull( + [{ name: "deploy", version: "1", files: ["SKILL.md"] }], + { "/catalog/deploy/SKILL.md": "# Old" }, + ) try { - const first = await pull( - [{ name: "deploy", version: "1", files: ["SKILL.md"] }], - { - [`${base}deploy/SKILL.md`]: "# Old", - }, - tmp, - ) const second = await pull( [{ name: "deploy", version: "2", files: ["SKILL.md"] }], - { - [`${base}deploy/SKILL.md`]: "# New", - }, - tmp, + { "/catalog/deploy/SKILL.md": "# New" }, + first, ) expect(await fs.readFile(path.join(first.directories[0], "SKILL.md"), "utf8")).toBe("# New") - expect(second.requests).toContain(`${base}deploy/SKILL.md`) + expect(second.requests).toContain(`${first.base}deploy/SKILL.md`) const third = await pull( [{ name: "deploy", version: "2", files: ["SKILL.md"] }], - { [`${base}deploy/SKILL.md`]: "# Ignored" }, - tmp, + { "/catalog/deploy/SKILL.md": "# Ignored" }, + first, ) - expect(third.requests).toEqual([`${base}index.json`]) + expect(third.requests).toEqual([`${first.base}index.json`]) } finally { - await tmp[Symbol.asyncDispose]() + await dispose(first) } }) test("publishes complete updates and removes stale files", async () => { - const tmp = await tmpdir() + const first = await pull( + [{ name: "deploy", version: "1", files: ["SKILL.md", "old.md"] }], + { + "/catalog/deploy/SKILL.md": "# Old", + "/catalog/deploy/old.md": "old reference", + }, + ) try { - const first = await pull( - [{ name: "deploy", version: "1", files: ["SKILL.md", "old.md"] }], - { - [`${base}deploy/SKILL.md`]: "# Old", - [`${base}deploy/old.md`]: "old reference", - }, - tmp, - ) const root = first.directories[0] await pull( [{ name: "deploy", version: "2", files: ["SKILL.md", "missing.md"] }], - { [`${base}deploy/SKILL.md`]: "# Partial" }, - tmp, + { "/catalog/deploy/SKILL.md": "# Partial" }, + first, ) expect(await fs.readFile(path.join(root, "SKILL.md"), "utf8")).toBe("# Old") expect(await fs.readFile(path.join(root, "old.md"), "utf8")).toBe("old reference") - await pull([{ name: "deploy", version: "3", files: ["SKILL.md"] }], { [`${base}deploy/SKILL.md`]: "# New" }, tmp) + await pull( + [{ name: "deploy", version: "3", files: ["SKILL.md"] }], + { "/catalog/deploy/SKILL.md": "# New" }, + first, + ) expect(await fs.readFile(path.join(root, "SKILL.md"), "utf8")).toBe("# New") expect(await Bun.file(path.join(root, "old.md")).exists()).toBe(false) } finally { - await tmp[Symbol.asyncDispose]() + await dispose(first) } }) }) From f9504971737933fde17c0f2f442be08e1316c338 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sun, 5 Jul 2026 10:41:21 -0500 Subject: [PATCH 62/82] refactor(codemode): remove generic agent tool (#35420) --- packages/codemode/README.md | 14 +++------- packages/codemode/codemode.md | 4 +-- packages/codemode/src/codemode.ts | 35 ++++++------------------- packages/codemode/src/index.ts | 3 +-- packages/codemode/test/codemode.test.ts | 31 ++++++---------------- packages/core/src/tool/execute.ts | 3 +-- 6 files changed, 23 insertions(+), 67 deletions(-) diff --git a/packages/codemode/README.md b/packages/codemode/README.md index bd14a24fb0..54d31b4e31 100644 --- a/packages/codemode/README.md +++ b/packages/codemode/README.md @@ -4,7 +4,7 @@ Effect-native confined code execution over explicit, schema-described tools. CodeMode lets a model write a small JavaScript program that can call only the tools supplied by the host. The program can sequence calls, transform plain data, branch, loop, and run independent calls in parallel without receiving ambient filesystem, process, network, module, or application authority. -The package is currently private to this workspace. Its API is designed around three uses: +The package is currently private to this workspace. Its API is designed around one-shot and reusable execution: ```ts // One execution @@ -13,9 +13,6 @@ yield * CodeMode.execute({ tools, code }) // A reusable runtime const runtime = CodeMode.make({ tools, limits }) yield * runtime.execute(code) - -// One agent-facing code tool -const codeTool = runtime.agentTool() ``` ## Install @@ -117,10 +114,9 @@ const runtime = CodeMode.make({ runtime.catalog() // structured tool descriptions runtime.instructions() // model-facing syntax and tool guide runtime.execute(source) // ExecuteResult -runtime.agentTool() // { name, description, input, output, execute } ``` -`catalog`, `instructions`, and `agentTool` are projections of the same configured tool tree. `agentTool().description` is exactly `instructions()`. +`CodeMode.Input` and `CodeMode.Result` are Effect schemas for the execution request and result. Hosts can combine them with `runtime.instructions()` and `runtime.execute()` when constructing a framework-specific agent tool. ### Results @@ -165,9 +161,7 @@ const api = OpenAPI.fromSpec({ spec: await Bun.file("openapi.json").json(), // parsed document (no YAML) auth: { resolve: ({ name, scopes, operation }) => - name === "BearerAuth" - ? Effect.succeed({ type: "bearer", token }) - : Effect.succeed(undefined), + name === "BearerAuth" ? Effect.succeed({ type: "bearer", token }) : Effect.succeed(undefined), }, }) @@ -335,8 +329,6 @@ A program cannot gain authority through prose or generated code. It can only exe The public contract is guided by these equivalences: - `CodeMode.execute({ ...options, code })` is equivalent to `CodeMode.make(options).execute(code)`. -- `CodeMode.make(options).agentTool().execute({ code })` is equivalent to `CodeMode.make(options).execute(code)`. -- `CodeMode.make(options).agentTool().description` equals `CodeMode.make(options).instructions()`. - A tool implementation is not invoked unless its input has decoded successfully. - A tool result is not visible to the program unless its output has decoded and crossed the plain-data boundary successfully. - Unknown host failures do not become model-visible diagnostics; `ToolError` is the explicit safe-message channel. diff --git a/packages/codemode/codemode.md b/packages/codemode/codemode.md index 14fe18b875..81348a7c8f 100644 --- a/packages/codemode/codemode.md +++ b/packages/codemode/codemode.md @@ -246,7 +246,7 @@ maxOutputBytes? }` (defaults 10_000 / 100 / 32_000). This wave kept the other kn serialized values become truncated text + ` [result truncated: N bytes exceeds the M-byte output limit; return a smaller value]`; logs keep leading lines within the remaining budget - `[logs truncated: showing K of N lines]`; result gains `truncated: true` (also added to - `ExecuteResultSchema`). UTF-8-safe truncation (no split code points). (The in-sandbox + `CodeMode.Result`). UTF-8-safe truncation (no split code points). (The in-sandbox `maxDataBytes` check that used to throw first on oversized raw values died in Fix 5 - truncation is now the only result-size mechanism.) - **Search polish**: default limit 12 -> **10** (`defaultSearchLimit`); exact-path lookup - a @@ -575,7 +575,7 @@ configurable knobs; the internal limit system dies): `maxCollectionLength` (every array-length/object-field-count check - this knob was actively harmful: an MCP tool returning 20k rows failed). The `OperationLimitExceeded` and `AuditLimitExceeded` diagnostic kinds are gone from the `DiagnosticKind` union and - `ExecuteResultSchema` (fine - the package is unreleased). + `CodeMode.Result` (fine - the package is unreleased). - **Fixed constants, not knobs**: `TOOL_CALL_CONCURRENCY = 8` (codemode.ts; the fork semaphore) and `MAX_VALUE_DEPTH = 32` (tool-runtime.ts; the `copyIn` depth check - kept only because it produces a clearer error than a native stack-overflow RangeError; still diff --git a/packages/codemode/src/codemode.ts b/packages/codemode/src/codemode.ts index f8a01f23b0..6aa030e521 100644 --- a/packages/codemode/src/codemode.ts +++ b/packages/codemode/src/codemode.ts @@ -108,14 +108,14 @@ export type ExecuteFailure = { /** Result of executing a CodeMode program. Program failures are data, not Effect failures. */ export type ExecuteResult = ExecuteSuccess | ExecuteFailure -/** Reusable CodeMode configuration shared by `execute` and `agentTool`. */ +/** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */ export type CodeModeOptions = {}> = Omit, "code"> & { /** Progressive-disclosure configuration for the agent-facing tool catalog. */ readonly discovery?: DiscoveryOptions } -/** Input schema for the single agent-facing tool produced by `runtime.agentTool()`. */ -export const ExecuteInputSchema = Schema.Struct({ code: Schema.String }) +/** Schema for a CodeMode execution request. */ +const Input = Schema.Struct({ code: Schema.String }) const DiagnosticKindSchema = Schema.Literals([ "ParseError", @@ -130,8 +130,8 @@ const DiagnosticKindSchema = Schema.Literals([ "ExecutionFailure", ]) -/** Structured success or diagnostic result schema returned by CodeMode execution. */ -export const ExecuteResultSchema = Schema.Union([ +/** Schema for the structured success or diagnostic returned by CodeMode execution. */ +const Result = Schema.Union([ Schema.Struct({ ok: Schema.Literal(true), value: Schema.Json, @@ -153,23 +153,12 @@ export const ExecuteResultSchema = Schema.Union([ }), ]) -/** Agent-facing projection of a configured CodeMode runtime. */ -export type AgentToolDefinition = { - readonly name: "code" - readonly description: string - readonly input: typeof ExecuteInputSchema - readonly output: typeof ExecuteResultSchema - readonly execute: (input: { readonly code: string }) => Effect.Effect -} - /** Reusable confined runtime over one explicit tool tree. */ export type CodeModeRuntime = { /** Lists schema-described tool paths provided by the host. */ readonly catalog: () => ReadonlyArray /** Builds model-facing syntax guidance and visible tool signatures. */ readonly instructions: () => string - /** Projects the configured runtime as one agent-facing `code` tool. */ - readonly agentTool: () => AgentToolDefinition /** Executes a program using this runtime's configured host tools. */ readonly execute: (code: string) => Effect.Effect } @@ -4088,13 +4077,12 @@ export const execute = >( /** * Creates an Effect-native runtime over explicit, schema-described tools. * - * Use `execute` for host-driven execution or `agentTool` to expose one confined code tool to an - * agent framework. Tool requirements remain in the returned Effect environment. + * Use `execute` for host-driven execution. Tool requirements remain in the returned Effect environment. * * @example * ```ts * const runtime = CodeMode.make({ tools: { orders: { lookup } } }) - * const code = runtime.agentTool() + * const result = runtime.execute("return await tools.orders.lookup({ id: 'order_42' })") * ``` */ export const make = = {}>( @@ -4111,16 +4099,9 @@ export const make = = {}>( return { catalog: () => catalog, instructions: () => instructions, - agentTool: () => ({ - name: "code", - description: instructions, - input: ExecuteInputSchema, - output: ExecuteResultSchema, - execute: ({ code }) => executeProgram(code), - }), execute: executeProgram, } } /** Constructors for one-shot and reusable CodeMode execution. */ -export const CodeMode = { make, execute } +export const CodeMode = { Input, Result, make, execute } diff --git a/packages/codemode/src/index.ts b/packages/codemode/src/index.ts index 1aea6644da..9a21e9f640 100644 --- a/packages/codemode/src/index.ts +++ b/packages/codemode/src/index.ts @@ -1,10 +1,9 @@ -export { ToolError, CodeMode, ExecuteInputSchema, ExecuteResultSchema, toolError } from "./codemode.js" +export { ToolError, CodeMode, toolError } from "./codemode.js" export { Tool } from "./tool.js" export * as OpenAPI from "./openapi/index.js" export type { Definition as ToolDefinition, JsonSchema, ToolSchema } from "./tool.js" export type { ToolCallEnded, ToolCallHooks } from "./tool-runtime.js" export type { - AgentToolDefinition, CodeModeOptions, CodeModeRuntime, DataValue, diff --git a/packages/codemode/test/codemode.test.ts b/packages/codemode/test/codemode.test.ts index 4fda88b384..9db7739296 100644 --- a/packages/codemode/test/codemode.test.ts +++ b/packages/codemode/test/codemode.test.ts @@ -1,13 +1,6 @@ import { describe, expect, test } from "bun:test" import { Cause, Effect, Schema } from "effect" -import { - CodeMode, - ExecuteInputSchema, - ExecuteResultSchema, - Tool, - toolError, - type ExecutionLimits, -} from "../src/index.js" +import { CodeMode, Tool, toolError, type ExecutionLimits } from "../src/index.js" import type { Definition } from "../src/tool.js" const run = (tool: Definition) => @@ -235,7 +228,7 @@ describe("CodeMode console capture", () => { logs: ['Thread info: {"name":"Demo","count":2}', "[warn] careful"], toolCalls: [], }) - expect(Schema.decodeUnknownSync(ExecuteResultSchema)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) + expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) }) test("keeps logs captured before failures", async () => { @@ -371,7 +364,7 @@ describe("CodeMode output budget", () => { expect(result.value).toMatch( /^\{"data":"x+ \[result truncated: \d+ bytes exceeds the 40-byte output limit; return a smaller value\]$/, ) - expect(Schema.decodeUnknownSync(ExecuteResultSchema)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) + expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) }) test("keeps leading logs within the remaining budget and marks the cut", async () => { @@ -501,24 +494,16 @@ describe("CodeMode public contract", () => { const tools = { orders: { lookup } } const source = `return await tools.orders.lookup({ id: "order_42" })` - test("keeps one-shot, reusable, and agent-tool execution equivalent", async () => { + test("keeps one-shot and reusable execution equivalent", async () => { const runtime = CodeMode.make({ tools }) - const agentTool = runtime.agentTool() - const [oneShot, reusable, projected] = await Promise.all([ + const [oneShot, reusable] = await Promise.all([ Effect.runPromise(CodeMode.execute({ tools, code: source })), Effect.runPromise(runtime.execute(source)), - Effect.runPromise(agentTool.execute({ code: source })), ]) expect(reusable).toStrictEqual(oneShot) - expect(projected).toStrictEqual(oneShot) - expect(agentTool.name).toBe("code") - expect(agentTool.input).toBe(ExecuteInputSchema) - expect(agentTool.output).toBe(ExecuteResultSchema) - expect(agentTool.description).toBe(runtime.instructions()) - expect(Schema.decodeUnknownSync(ExecuteResultSchema)(JSON.parse(JSON.stringify(projected)))).toStrictEqual( - projected, - ) + expect(Schema.decodeUnknownSync(CodeMode.Input)({ code: source })).toStrictEqual({ code: source }) + expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(reusable)))).toStrictEqual(reusable) }) test("inlines a COMPLETE small catalog and keeps search registered but unadvertised", async () => { @@ -1035,7 +1020,7 @@ describe("CodeMode public contract", () => { value: { top: null, nested: [1, null] }, toolCalls: [], }) - expect(Schema.decodeUnknownSync(ExecuteResultSchema)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) + expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) }) test("rejects invalid configuration and discovery limits", async () => { diff --git a/packages/core/src/tool/execute.ts b/packages/core/src/tool/execute.ts index 67d1b21eaf..58dc097a0f 100644 --- a/packages/core/src/tool/execute.ts +++ b/packages/core/src/tool/execute.ts @@ -2,7 +2,6 @@ export * as ExecuteTool from "./execute" import { CodeMode, - ExecuteInputSchema, Tool, toolError, type DataValue, @@ -93,7 +92,7 @@ export const create = (options: { const discovery = runtime(() => Effect.fail(toolError("Execute context is unavailable"))) return make({ description: discovery.instructions(), - input: ExecuteInputSchema, + input: CodeMode.Input, output: ExecuteOutput, structured: ExecuteMetadata, toStructuredOutput: ({ output }) => ({ From f9d1d3b259cf6c1f2195068214941fc7a19cfd11 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sun, 5 Jul 2026 11:51:50 -0500 Subject: [PATCH 63/82] refactor(codemode): namespace public types (#35435) --- packages/codemode/README.md | 28 +- packages/codemode/codemode.md | 31 +-- packages/codemode/src/codemode.ts | 135 ++++------ packages/codemode/src/index.ts | 23 +- packages/codemode/src/openapi/index.ts | 4 +- packages/codemode/src/tool-runtime.ts | 5 +- packages/codemode/src/tool-schema.ts | 301 +++++++++++++++++++++ packages/codemode/src/tool.ts | 318 +---------------------- packages/codemode/test/codemode.test.ts | 12 +- packages/codemode/test/openapi.test.ts | 4 +- packages/codemode/test/parity.test.ts | 2 +- packages/codemode/test/promise.test.ts | 11 +- packages/codemode/test/signature.test.ts | 4 +- packages/core/src/tool/execute.ts | 20 +- 14 files changed, 423 insertions(+), 475 deletions(-) create mode 100644 packages/codemode/src/tool-schema.ts diff --git a/packages/codemode/README.md b/packages/codemode/README.md index 54d31b4e31..0be6d769c7 100644 --- a/packages/codemode/README.md +++ b/packages/codemode/README.md @@ -60,7 +60,7 @@ const result = `) ``` -`result` is always an `ExecuteResult`. Program, validation, limit, and tool failures are returned as diagnostics rather than failing the Effect. Host interruption remains interruption. +`result` is always a `CodeMode.Result`. Program, validation, limit, and tool failures are returned as diagnostics rather than failing the Effect. Host interruption remains interruption. Successful result values are JSON-safe data. A program that returns `undefined`, including by reaching the end without `return`, produces `null`; nested `undefined` values are normalized to `null` as well. @@ -83,6 +83,8 @@ const tool = Tool.make({ The description and schemas are part of the model-visible tool contract. Keep descriptions concrete and put authorization in `run` or in the service it calls. +Public tool types are grouped under the same namespace: `Tool.Definition`, `Tool.Options`, `Tool.SchemaType`, and `Tool.JsonSchema`. + ### `CodeMode.execute` Use `CodeMode.execute` for a single execution: @@ -113,30 +115,32 @@ const runtime = CodeMode.make({ runtime.catalog() // structured tool descriptions runtime.instructions() // model-facing syntax and tool guide -runtime.execute(source) // ExecuteResult +runtime.execute(source) // CodeMode.Result ``` -`CodeMode.Input` and `CodeMode.Result` are Effect schemas for the execution request and result. Hosts can combine them with `runtime.instructions()` and `runtime.execute()` when constructing a framework-specific agent tool. +`CodeMode.Input`, `CodeMode.Result`, `CodeMode.Success`, `CodeMode.Failure`, `CodeMode.Diagnostic`, and `CodeMode.DiagnosticKind` are both Effect schemas and their inferred TypeScript types. Hosts can combine `CodeMode.Input` and `CodeMode.Result` with `runtime.instructions()` and `runtime.execute()` when constructing a framework-specific agent tool. + +All other CodeMode types use the same namespace: `CodeMode.Options`, `CodeMode.ExecuteOptions`, `CodeMode.Runtime`, `CodeMode.ExecutionLimits`, `CodeMode.DiscoveryOptions`, `CodeMode.DataValue`, `CodeMode.ToolDescription`, and the `CodeMode.ToolCall*` observation types. ### Results ```ts -type ExecuteResult = ExecuteSuccess | ExecuteFailure +type Result = Success | Failure -interface ExecuteSuccess { +interface Success { readonly ok: true - readonly value: Schema.Json + readonly value: CodeMode.DataValue readonly logs?: ReadonlyArray readonly truncated?: boolean - readonly toolCalls: ReadonlyArray + readonly toolCalls: ReadonlyArray } -interface ExecuteFailure { +interface Failure { readonly ok: false - readonly error: Diagnostic + readonly error: CodeMode.Diagnostic readonly logs?: ReadonlyArray readonly truncated?: boolean - readonly toolCalls: ReadonlyArray + readonly toolCalls: ReadonlyArray } ``` @@ -300,7 +304,7 @@ import { toolError } from "@opencode-ai/codemode" run: ({ id }) => (authorized(id) ? loadOrder(id) : Effect.fail(toolError("Order is unavailable"))) ``` -Only the supplied message is model-visible. The optional cause is never returned in `ExecuteResult`; hosts should perform any required internal logging before crossing this boundary. +Only the supplied message is model-visible. The optional cause is never returned in `CodeMode.Result`; hosts should perform any required internal logging before crossing this boundary. ## Authority Boundary @@ -332,7 +336,7 @@ The public contract is guided by these equivalences: - A tool implementation is not invoked unless its input has decoded successfully. - A tool result is not visible to the program unless its output has decoded and crossed the plain-data boundary successfully. - Unknown host failures do not become model-visible diagnostics; `ToolError` is the explicit safe-message channel. -- Host interruption remains interruption rather than an `ExecuteFailure`. +- Host interruption remains interruption rather than a `CodeMode.Failure`. ## Non-Goals diff --git a/packages/codemode/codemode.md b/packages/codemode/codemode.md index 81348a7c8f..a94f1d4eec 100644 --- a/packages/codemode/codemode.md +++ b/packages/codemode/codemode.md @@ -220,9 +220,9 @@ wave; both packages typecheck clean. (render-only - no validation, values pass through; rendering handles `$defs`/`definitions` - `$ref`). `output` is **optional** -> signature renders `Promise` and the host result is exposed as-is. Discrimination via `Schema.isSchema`. New helpers exported from - `tool.ts`: `inputTypeScript`/`outputTypeScript`/`decodeInput`/`decodeOutput`/ + `tool-schema.ts`: `inputTypeScript`/`outputTypeScript`/`decodeInput`/`decodeOutput`/ `jsonSchemaToTypeScript`; `tool-runtime.ts` consumes them (no direct `Schema.*` use there - anymore). Types `JsonSchema`/`ToolSchema` exported from the index. Note: an empty + anymore). Types `Tool.JsonSchema`/`Tool.SchemaType` exported from the index. Note: an empty `Schema.Struct({})` renders as `{ } | Array` (effect's JSON Schema emission) - cosmetic, fixed in Wave 4. - **`output.*` API deleted**: `OutputItem`(+Schema), result `output` fields, the `output` @@ -237,7 +237,7 @@ wave; both packages typecheck clean. so failures are typed and observable). `message` is the model-safe failure message (`ToolError`/`ToolRuntimeError` message, else "Tool execution failed"). Interrupted calls fire no end event (timeout kills the whole execution anyway). -- **Limits collapse**: public `ExecutionLimits` = `{ timeoutMs?, maxToolCalls?, +- **Limits collapse**: public `CodeMode.ExecutionLimits` = `{ timeoutMs?, maxToolCalls?, maxOutputBytes? }` (defaults 10_000 / 100 / 32_000). This wave kept the other knobs as internal defaults reachable through an `@internal` `InternalExecutionLimits` type; Fix 5 later deleted that type and the internal limit system entirely. @@ -313,7 +313,7 @@ real MCP config. Package still 101 tests / 0 fail; opencode adapter suites still packages typecheck clean. - **Budgeted catalog** (`discoveryPlan` in `tool-runtime.ts`): the all-or-nothing - inline/search modes are gone - `DiscoveryMode` deleted, `DiscoveryOptions` is just + inline/search modes are gone - `DiscoveryMode` deleted, `CodeMode.DiscoveryOptions` is just `{ maxInlineCatalogBytes? }` (default 16,000 UTF-8 bytes; later converted to `maxInlineCatalogTokens`, default 4,000 estimated tokens - see Post-wave fixes). Port of the old opencode @@ -340,7 +340,7 @@ packages typecheck clean. read-the-description-before-calling guidance. (The flat prose layout this wave produced was later replaced wholesale by the markdown-section restructure - see Post-wave fixes - which also deleted this wave's worked example.) -- **Cosmetic renderer fixes** (`renderSchema` in `tool.ts`): an object schema with no +- **Cosmetic renderer fixes** (`renderSchema` in `tool-schema.ts`): an object schema with no properties renders `{}` (was `{ }`), and the empty `Schema.Struct({})` emission (`anyOf: [{ type: "object" }, { type: "array" }]`, no properties/items) collapses to `{}` (was `{ } | Array`). @@ -469,7 +469,7 @@ adapter needed **no changes**. `rankTools` algorithm in `packages/opencode/src/session/code-mode.ts` at git HEAD), replacing the word-set ranker in `tool-runtime.ts`. Searchable text per tool = path + description + input-schema property names + their `description` strings - extracted by - the new `inputProperties` helper in `tool.ts` (Effect Schemas via + the new `inputProperties` helper in `tool-schema.ts` (Effect Schemas via `Schema.toJsonSchemaDocument`, the same emission signature rendering uses; JSON Schemas read `properties` directly, resolving a trivial top-level `$ref`; try/catch falls back to path + description). Queries tokenize on camelCase boundaries + non-alphanumeric @@ -542,7 +542,7 @@ budget; namespaces must always be present): - `src/token.ts` added: copy of `@opencode-ai/core/util/token` (`round(chars / 4)`), so the package stays dependency-free; keep in sync if the core heuristic changes. -- `DiscoveryOptions.maxInlineCatalogBytes` -> `maxInlineCatalogTokens` (default 4,000 +- `CodeMode.DiscoveryOptions.maxInlineCatalogBytes` -> `maxInlineCatalogTokens` (default 4,000 estimated tokens ~ the old 16,000 bytes at 4 chars/token - behavior parity, not a size reduction). `discoveryPlan` charges `estimate(catalogLine(tool))` per line; cheapest-first - stop-on-first-miss unchanged at the time (stop-on-first-miss replaced by round-robin in @@ -558,7 +558,7 @@ budget; namespaces must always be present): **Fix 5 - internal limits removed** (user direction: only the three PUBLIC limits survive as configurable knobs; the internal limit system dies): -- `ExecutionLimits` (`timeoutMs` 10_000 / `maxToolCalls` 100 / `maxOutputBytes` 32_000 at +- `CodeMode.ExecutionLimits` (`timeoutMs` 10_000 / `maxToolCalls` 100 / `maxOutputBytes` 32_000 at the time; Fix 6 later removed the first two defaults. Same validation: safe integers, timeoutMs >= 1, others >= 0, RangeError otherwise) is now the ENTIRE limit surface - exactly the shape section 2's original locked spec named. @@ -602,7 +602,7 @@ configurable knobs; the internal limit system dies): enumeration operation-budget, codemode maxDataBytes/maxSourceBytes/maxOperations/ maxConcurrency-RangeError assertions, and the adapter's runaway-loop-via-operation-limit test - superseded by the package timeout regression test); rewrote the helpers that used - `InternalExecutionLimits` as a convenience to plain `ExecutionLimits` + `InternalExecutionLimits` as a convenience to plain `CodeMode.ExecutionLimits` (promise/enumeration/stdlib run helpers). Package suite: 154 pass / 0 fail; adapter suites: 34 + 16. @@ -633,7 +633,7 @@ Semantics: each described input/output field carries its schema `description` as express surface as JSDoc tags - `@deprecated`, `@default ` (unserializable defaults skipped), `@format`, `@minItems`/`@maxItems`; `*/` inside text is neutralized to `* /`; multiline descriptions become `*`-prefixed blocks with blank edges trimmed; undescribed, -untagged fields get no comment. Implementation: `renderSchema` in `tool.ts` grew a +untagged fields get no comment. Implementation: `renderSchema` in `tool-schema.ts` grew a `RenderContext` (`{ definitions, pretty }`), a `MAX_RENDER_DEPTH = 8` recursion ceiling plus a `$ref` `seen` guard (the renderer previously had neither - a cyclic `$defs` would have looped; it now degrades to the ref name/`unknown`), and try/catch totality on the public @@ -849,7 +849,7 @@ section 4 outer-truncation item the OPPOSITE way from "kill the outer one"): that relied on the old default now asserts the oversized result reaches the shared wrapper un-truncated. Suites: 210 + 50, tsgo clean both. -**Docs polish** (post-API-review): stale `DiscoveryOptions` JSDoc fixed (claimed default +**Docs polish** (post-API-review): stale `CodeMode.DiscoveryOptions` JSDoc fixed (claimed default 4,000 and alphabetical cheapest-first - now 2,000 and round-robin, matching Fix 8/9 reality) and the README's incorrect "`effect` as a peer dependency" line corrected (`effect` is a regular dependency; hosts depend on it themselves because the API surface is Effect-typed). @@ -949,16 +949,16 @@ child calls" gap): **Signature rendering + compound-assignment parity fixes** (externally reported, both verified real with failing tests before fixing): -- **Non-identifier property names in rendered signatures** (`src/tool.ts`): `renderSchema` +- **Non-identifier property names in rendered signatures** (`src/tool-schema.ts`): `renderSchema` emitted raw property names, so schema properties like `foo-bar`/`@type`/`x.y`/`123` rendered invalid TypeScript (`{ foo-bar?: string }`). Fixed with a `renderKey` helper - bare identifiers stay bare, everything else is `JSON.stringify`-quoted - applied in the single `field` closure both the compact and pretty renderings share. The - `identifierSegment` regex now lives in `tool.ts` (exported) and `tool-runtime.ts`'s + `identifierSegment` regex now lives in `tool-schema.ts` (internal) and `tool-runtime.ts`'s bracket-notation `toolExpression` imports it: one source of truth for "is this a bare identifier" across object keys and tool paths. Tests: `signature.test.ts` +4 (compact, pretty with JSDoc on a quoted key, JSON Schema input+output, Effect Schema struct). -- **Numeric schema unions keep their real alternatives** (`src/tool.ts`): the old +- **Numeric schema unions keep their real alternatives** (`src/tool-schema.ts`): the old `anyOf`/`oneOf` renderer collapsed any union containing `{ type: "number" }` to just `number`, dropping real JSON Schema alternatives (`string | number`, `number | null`, etc.). The collapse is now restricted to Effect's number-schema artifact @@ -1209,7 +1209,8 @@ Post-MVP (logged, not blocking an experimental flag): the workspace is the implementation source of truth for v4 behavior questions. - File map (this package): `src/codemode.ts` - types/limits/parser/Interpreter/execute/make; `src/tool-runtime.ts` - tool tree, `copyIn`/`copyOut`, search/discovery, invoke path; - `src/tool.ts` - `Tool.make` + JSON-Schema->TS rendering; `src/values.ts` - sandbox value + `src/tool.ts` - public `Tool` definitions; `src/tool-schema.ts` - schema rendering and decoding; + `src/values.ts` - sandbox value types; `src/tool-error.ts` - `ToolError`; tests in `test/{codemode,parity,stdlib}.test.ts`. - OpenCode file map (integration points): `src/tool/code-mode.ts` (the adapter, now a registry tool service - `CodeModeTool` + `catalogInstructions`; formerly diff --git a/packages/codemode/src/codemode.ts b/packages/codemode/src/codemode.ts index 6aa030e521..b207efe46a 100644 --- a/packages/codemode/src/codemode.ts +++ b/packages/codemode/src/codemode.ts @@ -19,8 +19,7 @@ import { ToolError } from "./tool-error.js" import { isSandboxValue, SandboxDate, SandboxMap, SandboxPromise, SandboxRegExp, SandboxSet } from "./values.js" /** A tool call admitted during an execution. */ -export type { ToolCall, ToolCallStarted, ToolDescription } from "./tool-runtime.js" -export { ToolError, toolError } from "./tool-error.js" +export type { ToolCall, ToolCallEnded, ToolCallHooks, ToolCallStarted, ToolDescription } from "./tool-runtime.js" /** Resource budgets enforced independently during each CodeMode program execution. */ export type ExecutionLimits = { @@ -74,50 +73,20 @@ export type ExecuteOptions = {}> = { onToolCallEnd?: (call: ToolRuntime.ToolCallEnded) => Effect.Effect> } -/** A normalized program diagnostic safe to return across an agent tool boundary. */ -export type Diagnostic = { - readonly kind: DiagnosticKind - readonly message: string - readonly location?: { readonly line: number; readonly column: number } - readonly suggestions?: ReadonlyArray -} - /** A JSON value that can cross the confined interpreter boundary. */ export type DataValue = Schema.Json -/** Successful execution after the result has crossed the plain-data boundary. */ -export type ExecuteSuccess = { - readonly ok: true - readonly value: DataValue - readonly logs?: ReadonlyArray - /** Present when the value or logs were truncated to fit `maxOutputBytes`. */ - readonly truncated?: boolean - readonly toolCalls: ReadonlyArray -} - -/** Failed execution with calls admitted before the diagnostic was produced. */ -export type ExecuteFailure = { - readonly ok: false - readonly error: Diagnostic - readonly logs?: ReadonlyArray - /** Present when the logs were truncated to fit `maxOutputBytes`. */ - readonly truncated?: boolean - readonly toolCalls: ReadonlyArray -} - -/** Result of executing a CodeMode program. Program failures are data, not Effect failures. */ -export type ExecuteResult = ExecuteSuccess | ExecuteFailure - /** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */ -export type CodeModeOptions = {}> = Omit, "code"> & { +export type Options = {}> = Omit, "code"> & { /** Progressive-disclosure configuration for the agent-facing tool catalog. */ readonly discovery?: DiscoveryOptions } -/** Schema for a CodeMode execution request. */ -const Input = Schema.Struct({ code: Schema.String }) +/** Schema for a host tool input containing CodeMode source. */ +export const Input = Schema.Struct({ code: Schema.String }) +export type Input = typeof Input.Type -const DiagnosticKindSchema = Schema.Literals([ +export const DiagnosticKind = Schema.Literals([ "ParseError", "UnsupportedSyntax", "UnknownTool", @@ -129,38 +98,52 @@ const DiagnosticKindSchema = Schema.Literals([ "ToolFailure", "ExecutionFailure", ]) +/** Stable categories produced by program, schema, tool, and limit failures. */ +export type DiagnosticKind = typeof DiagnosticKind.Type + +export const Diagnostic = Schema.Struct({ + kind: DiagnosticKind, + message: Schema.String, + location: Schema.optionalKey(Schema.Struct({ line: Schema.Number, column: Schema.Number })), + suggestions: Schema.optionalKey(Schema.Array(Schema.String)), +}) +/** A normalized program diagnostic safe to return across an agent tool boundary. */ +export type Diagnostic = typeof Diagnostic.Type + +const ToolCallSchema = Schema.Struct({ name: Schema.String }) +export const Success = Schema.Struct({ + ok: Schema.Literal(true), + value: Schema.Json, + logs: Schema.optionalKey(Schema.Array(Schema.String)), + truncated: Schema.optionalKey(Schema.Boolean), + toolCalls: Schema.Array(ToolCallSchema), +}) +/** Successful execution after the result has crossed the plain-data boundary. */ +export type Success = typeof Success.Type + +export const Failure = Schema.Struct({ + ok: Schema.Literal(false), + error: Diagnostic, + logs: Schema.optionalKey(Schema.Array(Schema.String)), + truncated: Schema.optionalKey(Schema.Boolean), + toolCalls: Schema.Array(ToolCallSchema), +}) +/** Failed execution with calls admitted before the diagnostic was produced. */ +export type Failure = typeof Failure.Type /** Schema for the structured success or diagnostic returned by CodeMode execution. */ -const Result = Schema.Union([ - Schema.Struct({ - ok: Schema.Literal(true), - value: Schema.Json, - logs: Schema.optionalKey(Schema.Array(Schema.String)), - truncated: Schema.optionalKey(Schema.Boolean), - toolCalls: Schema.Array(Schema.Struct({ name: Schema.String })), - }), - Schema.Struct({ - ok: Schema.Literal(false), - error: Schema.Struct({ - kind: DiagnosticKindSchema, - message: Schema.String, - location: Schema.optionalKey(Schema.Struct({ line: Schema.Number, column: Schema.Number })), - suggestions: Schema.optionalKey(Schema.Array(Schema.String)), - }), - logs: Schema.optionalKey(Schema.Array(Schema.String)), - truncated: Schema.optionalKey(Schema.Boolean), - toolCalls: Schema.Array(Schema.Struct({ name: Schema.String })), - }), -]) +export const Result = Schema.Union([Success, Failure]) +/** Result of executing a CodeMode program. Program failures are data, not Effect failures. */ +export type Result = typeof Result.Type /** Reusable confined runtime over one explicit tool tree. */ -export type CodeModeRuntime = { +export type Runtime = { /** Lists schema-described tool paths provided by the host. */ readonly catalog: () => ReadonlyArray /** Builds model-facing syntax guidance and visible tool signatures. */ readonly instructions: () => string /** Executes a program using this runtime's configured host tools. */ - readonly execute: (code: string) => Effect.Effect + readonly execute: (code: string) => Effect.Effect } type SourcePosition = { @@ -275,19 +258,6 @@ const errorBrandName = (value: unknown): string | undefined => ? ((value as Record)[ErrorBrand] as string | undefined) : undefined -/** Stable categories produced by program, schema, tool, and limit failures. */ -export type DiagnosticKind = - | "ParseError" - | "UnsupportedSyntax" - | "UnknownTool" - | "InvalidToolInput" - | "InvalidToolOutput" - | "InvalidDataValue" - | "ToolCallLimitExceeded" - | "TimeoutExceeded" - | "ToolFailure" - | "ExecutionFailure" - const arrayMethods = new Set([ "map", "filter", @@ -3943,7 +3913,7 @@ const executeWithLimits = >( options: ExecuteOptions, limits: ResolvedExecutionLimits, searchIndex: ToolRuntime.DiscoveryPlan["searchIndex"], -): Effect.Effect> => { +): Effect.Effect> => { const hooks = { ...(options.onToolCallStart === undefined ? {} : { onToolCallStart: options.onToolCallStart }), ...(options.onToolCallEnd === undefined ? {} : { onToolCallEnd: options.onToolCallEnd }), @@ -3975,7 +3945,7 @@ const executeWithLimits = >( value: result, ...logged(), toolCalls: tools.calls, - } satisfies ExecuteResult + } satisfies Result }).pipe((program) => { const timeoutMs = limits.timeoutMs if (timeoutMs === undefined) return program @@ -3988,7 +3958,7 @@ const executeWithLimits = >( error: { kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` }, ...logged(), toolCalls: tools.calls, - } satisfies ExecuteResult), + } satisfies Result), }), ) }) @@ -4002,7 +3972,7 @@ const executeWithLimits = >( error: normalizeError(Cause.squash(cause)), ...logged(), toolCalls: tools.calls, - } satisfies ExecuteResult), + } satisfies Result), ), Effect.map((result) => (limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes))), ) @@ -4026,7 +3996,7 @@ const utf8Truncate = (value: string, maxBytes: number): string => { * fails the execution; `truncated: true` marks affected results. Only runs when the host set * `maxOutputBytes` - with the limit absent, output passes through unbounded. */ -const boundOutput = (result: ExecuteResult, maxOutputBytes: number): ExecuteResult => { +const boundOutput = (result: Result, maxOutputBytes: number): Result => { let truncated = false let value: DataValue = null @@ -4068,7 +4038,7 @@ const boundOutput = (result: ExecuteResult, maxOutputBytes: number): ExecuteResu export const execute = >( options: ExecuteOptions, -): Effect.Effect> => { +): Effect.Effect> => { const tools = (options.tools ?? {}) as HostTools> ToolRuntime.assertValidTools(tools) return executeWithLimits(options, resolveExecutionLimits(options.limits), ToolRuntime.searchIndex(tools)) @@ -4086,8 +4056,8 @@ export const execute = >( * ``` */ export const make = = {}>( - options: CodeModeOptions = {} as CodeModeOptions, -): CodeModeRuntime> => { + options: Options = {} as Options, +): Runtime> => { const tools = (options.tools ?? {}) as HostTools> ToolRuntime.assertValidTools(tools) const limits = resolveExecutionLimits(options.limits) @@ -4102,6 +4072,3 @@ export const make = = {}>( execute: executeProgram, } } - -/** Constructors for one-shot and reusable CodeMode execution. */ -export const CodeMode = { Input, Result, make, execute } diff --git a/packages/codemode/src/index.ts b/packages/codemode/src/index.ts index 9a21e9f640..9201982500 100644 --- a/packages/codemode/src/index.ts +++ b/packages/codemode/src/index.ts @@ -1,21 +1,4 @@ -export { ToolError, CodeMode, toolError } from "./codemode.js" -export { Tool } from "./tool.js" +export * as CodeMode from "./codemode.js" +export * as Tool from "./tool.js" export * as OpenAPI from "./openapi/index.js" -export type { Definition as ToolDefinition, JsonSchema, ToolSchema } from "./tool.js" -export type { ToolCallEnded, ToolCallHooks } from "./tool-runtime.js" -export type { - CodeModeOptions, - CodeModeRuntime, - DataValue, - Diagnostic, - DiagnosticKind, - DiscoveryOptions, - ExecuteFailure, - ExecuteOptions, - ExecuteResult, - ExecuteSuccess, - ExecutionLimits, - ToolCall, - ToolCallStarted, - ToolDescription, -} from "./codemode.js" +export { ToolError, toolError } from "./tool-error.js" diff --git a/packages/codemode/src/openapi/index.ts b/packages/codemode/src/openapi/index.ts index 4ceda5eef0..7f1770ef36 100644 --- a/packages/codemode/src/openapi/index.ts +++ b/packages/codemode/src/openapi/index.ts @@ -1,5 +1,5 @@ import { HttpClient } from "effect/unstable/http" -import { Tool, type Definition } from "../tool.js" +import { make, type Definition } from "../tool.js" import { invoke } from "./runtime.js" import { componentDefinitions, @@ -102,7 +102,7 @@ export const fromSpec = (options: Options): Result => { setTool( tools, segments, - Tool.make({ + make({ description: operation.description ?? operation.summary ?? `${operation.method} ${path}`, input: inputSchema(input.fields, definitions), output: output.value, diff --git a/packages/codemode/src/tool-runtime.ts b/packages/codemode/src/tool-runtime.ts index 339737375c..268953b56a 100644 --- a/packages/codemode/src/tool-runtime.ts +++ b/packages/codemode/src/tool-runtime.ts @@ -6,10 +6,9 @@ import { identifierSegment, inputProperties, inputTypeScript, - isDefinition as isToolDefinition, outputTypeScript, - type Definition, -} from "./tool.js" +} from "./tool-schema.js" +import { isDefinition as isToolDefinition, type Definition } from "./tool.js" import { SandboxDate, SandboxMap, SandboxPromise, SandboxRegExp, SandboxSet } from "./values.js" const estimateTokens = (input: string) => Math.max(0, Math.round(input.length / 4)) diff --git a/packages/codemode/src/tool-schema.ts b/packages/codemode/src/tool-schema.ts new file mode 100644 index 0000000000..65c444083f --- /dev/null +++ b/packages/codemode/src/tool-schema.ts @@ -0,0 +1,301 @@ +import { JsonPointer, Schema } from "effect" +import type { Definition, JsonSchema, SchemaType } from "./tool.js" + +const isEffectSchema = (schema: SchemaType): schema is Schema.Decoder & Schema.Top => Schema.isSchema(schema) + +const renderLiteral = (value: unknown): string => JSON.stringify(value) ?? "unknown" + +/** + * Bare TypeScript identifier - usable unquoted as an object key (and, in the tool runtime, + * with dot access as a tool-path segment). Anything else must be quoted/bracketed. + */ +export const identifierSegment = /^[A-Za-z_$][A-Za-z0-9_$]*$/ + +/** Renders a property name as a valid TS object key: bare when an identifier, quoted otherwise. */ +const renderKey = (name: string): string => (identifierSegment.test(name) ? name : JSON.stringify(name)) + +const effectNumberSentinel = (schema: JsonSchema) => + schema.type === "string" && + Array.isArray(schema.enum) && + schema.enum.length === 1 && + (schema.enum[0] === "NaN" || schema.enum[0] === "Infinity" || schema.enum[0] === "-Infinity") + +const intersection = (members: ReadonlyArray): string => { + const concrete = members.filter((member) => member !== "unknown") + if (concrete.length === 0) return "unknown" + if (concrete.length === 1) return concrete[0] ?? "unknown" + return concrete.map((member) => (member.includes(" | ") ? `(${member})` : member)).join(" & ") +} + +/** + * Recursion ceiling for schema rendering. Object, array, and union recursion all increment + * depth, so this bounds every recursion path - pathological or structurally cyclic schemas + * degrade to `unknown` instead of overflowing the stack (rendering must never throw). + */ +const MAX_RENDER_DEPTH = 8 + +type RenderContext = { + readonly definitions: Readonly> + /** Indented, JSDoc-annotated multiline rendering (search results); compact single line otherwise. */ + readonly pretty: boolean +} + +const hasUnresolvedRef = ( + schema: JsonSchema, + definitions: Readonly>, + seen: ReadonlySet = new Set(), + visited: ReadonlySet = new Set(), +): boolean => { + if (visited.has(schema)) return false + const nextVisited = new Set([...visited, schema]) + if (schema.$ref !== undefined) { + const segment = schema.$ref.match(/^#\/(?:\$defs|definitions)\/([^/]+)$/)?.[1] + const name = segment === undefined ? undefined : JsonPointer.unescapeToken(segment) + if (name === undefined || definitions[name] === undefined || seen.has(name)) return true + if (hasUnresolvedRef(definitions[name], definitions, new Set([...seen, name]), nextVisited)) return true + } + return [ + ...(schema.anyOf ?? []), + ...(schema.oneOf ?? []), + ...(schema.allOf ?? []), + ...Object.values(schema.properties ?? {}), + ...(schema.items === undefined ? [] : [schema.items]), + ...(typeof schema.additionalProperties === "object" ? [schema.additionalProperties] : []), + ].some((item) => hasUnresolvedRef(item, definitions, seen, nextVisited)) +} + +/** + * Schema constraints a TypeScript type cannot express natively but a model benefits from, + * surfaced as JSDoc tags (`@deprecated`, `@default`, `@format`, `@minItems`, `@maxItems`). + */ +const docTags = (schema: JsonSchema): Array => { + const tags: Array = [] + if (schema.deprecated === true) tags.push("@deprecated") + if (schema.default !== undefined) { + try { + const rendered = JSON.stringify(schema.default) + if (rendered !== undefined) tags.push(`@default ${rendered}`) + } catch { + // unserializable default: skip rather than emit a broken tag + } + } + if (typeof schema.format === "string") tags.push(`@format ${schema.format}`) + if (typeof schema.minItems === "number") tags.push(`@minItems ${schema.minItems}`) + if (typeof schema.maxItems === "number") tags.push(`@maxItems ${schema.maxItems}`) + return tags +} + +/** + * Format a schema `description` plus `tags` as a JSDoc comment at the given indent, + * preserving multi-line text (a single line stays `/** ... *\/`; multiple lines become a + * `*`-prefixed block). `*\/` is neutralized so nothing can close the comment early, and + * blank leading/trailing lines are trimmed. Returns "" (else a trailing newline) so + * callers can prepend it directly to the field line. + */ +const jsdoc = (description: string | undefined, tags: ReadonlyArray, pad: string): string => { + const lines = [...(description === undefined ? [] : description.split("\n")), ...tags].map((line) => + line.replaceAll("*/", "* /").replace(/\s+$/, ""), + ) + while (lines.length > 0 && lines[0]!.trim() === "") lines.shift() + while (lines.length > 0 && lines[lines.length - 1]!.trim() === "") lines.pop() + if (lines.length === 0) return "" + if (lines.length === 1) return `${pad}/** ${lines[0]} */\n` + const body = lines.map((line) => `${pad} *${line === "" ? "" : ` ${line}`}`).join("\n") + return `${pad}/**\n${body}\n${pad} */\n` +} + +const renderSchema = ( + schema: JsonSchema, + ctx: RenderContext, + depth = 0, + seen: ReadonlySet = new Set(), +): string => { + if (depth > MAX_RENDER_DEPTH) return "unknown" + const nested = + schema.definitions === undefined && schema.$defs === undefined + ? ctx + : { ...ctx, definitions: { ...ctx.definitions, ...(schema.definitions ?? {}), ...(schema.$defs ?? {}) } } + if (schema.$ref) { + const segment = schema.$ref.match(/^#\/(?:\$defs|definitions)\/([^/]+)$/)?.[1] + const name = segment === undefined ? undefined : JsonPointer.unescapeToken(segment) + if (!name || !nested.definitions[name] || seen.has(name)) return "unknown" + return intersection([ + renderSchema(nested.definitions[name], nested, depth, new Set([...seen, name])), + renderSchema({ ...schema, $ref: undefined }, nested, depth + 1, seen), + ]) + } + if (schema.const !== undefined) return renderLiteral(schema.const) + if (schema.enum) return schema.enum.map(renderLiteral).join(" | ") + const alternatives = schema.anyOf ?? schema.oneOf + if (alternatives) { + // Effect's number schema emits `anyOf: [{ type: "number" }, { const: "NaN" }, + // { const: "Infinity" }, { const: "-Infinity" }]`. Collapse only that artifact; + // real JSON Schema unions such as `string | number` or `number | null` must keep + // every branch. + if ( + alternatives.some((item) => item.type === "number") && + alternatives.every((item) => item.type === "number" || effectNumberSentinel(item)) + ) + return "number" + // An empty Schema.Struct({}) emits `anyOf: [{ type: "object" }, { type: "array" }]` + // (no properties/items); render the bare shape as {} instead of `{} | Array`. + if ( + alternatives.length === 2 && + alternatives[0]?.type === "object" && + alternatives[0].properties === undefined && + alternatives[1]?.type === "array" && + alternatives[1].items === undefined + ) { + return "{}" + } + const members = alternatives.map((item) => renderSchema(item, nested, depth + 1, seen)) + if (members.some((member) => member === "unknown")) return "unknown" + return intersection([ + members.join(" | "), + renderSchema({ ...schema, anyOf: undefined, oneOf: undefined }, nested, depth + 1, seen), + ]) + } + if (schema.allOf) { + const members = schema.allOf.map((item) => renderSchema(item, nested, depth + 1, seen)) + if (schema.allOf.some((item) => hasUnresolvedRef(item, nested.definitions))) return "unknown" + return intersection([renderSchema({ ...schema, allOf: undefined }, nested, depth + 1, seen), ...members]) + } + if (Array.isArray(schema.type)) { + return schema.type.map((item) => renderSchema({ ...schema, type: item }, nested, depth + 1, seen)).join(" | ") + } + if (schema.type === "string") return "string" + if (schema.type === "number" || schema.type === "integer") return "number" + if (schema.type === "boolean") return "boolean" + if (schema.type === "null") return "null" + if (schema.type === "array") return `Array<${renderSchema(schema.items ?? {}, nested, depth + 1, seen)}>` + if (schema.type === "object" || schema.properties) { + const required = new Set(schema.required ?? []) + const properties = Object.entries(schema.properties ?? {}) + const additional = schema.additionalProperties + const indexType = + additional && typeof additional === "object" ? renderSchema(additional, nested, depth + 1, seen) : undefined + const field = ([name, value]: readonly [string, JsonSchema]) => + `${renderKey(name)}${required.has(name) ? "" : "?"}: ${renderSchema(value, nested, depth + 1, seen)}` + + if (!ctx.pretty) { + const fields = properties.map(field) + if (indexType !== undefined) fields.push(`[key: string]: ${indexType}`) + return fields.length === 0 ? "{}" : `{ ${fields.join("; ")} }` + } + + // Pretty: an indented block, each described field preceded by its JSDoc comment. + if (properties.length === 0 && indexType === undefined) return "{}" + const pad = " ".repeat(depth + 1) + const lines = properties.map( + (entry) => `${jsdoc(entry[1].description, docTags(entry[1]), pad)}${pad}${field(entry)}`, + ) + if (indexType !== undefined) lines.push(`${pad}[key: string]: ${indexType}`) + return `{\n${lines.join("\n")}\n${" ".repeat(depth)}}` + } + return "unknown" +} + +export const toTypeScript = (schema: Schema.Top, decoded = false, pretty = false): string => { + try { + const visible = decoded ? Schema.toType(schema) : schema + const document = Schema.toJsonSchemaDocument(visible) as { + readonly schema: JsonSchema + readonly definitions?: Readonly> + } + return renderSchema(document.schema, { definitions: document.definitions ?? {}, pretty }) + } catch { + return "unknown" + } +} + +/** Renders a raw JSON Schema document as a TypeScript type string. */ +export const jsonSchemaToTypeScript = (schema: JsonSchema, pretty = false): string => { + try { + return renderSchema(schema, { definitions: { ...(schema.definitions ?? {}), ...(schema.$defs ?? {}) }, pretty }) + } catch { + return "unknown" + } +} + +/** One input property of a tool, extracted best-effort from its input schema. */ +export type InputProperty = { + readonly name: string + readonly description: string | undefined + readonly required: boolean +} + +/** + * The property names, descriptions, and required flags of a tool's input schema - the raw + * material for search text. Best-effort: Effect Schemas go through their + * JSON Schema document (the same emission signature rendering uses); JSON Schemas are read + * directly, resolving a trivial top-level `$ref` into `$defs`/`definitions` when present. + * Anything unresolvable yields `[]` (search falls back to path + description). + */ +export const inputProperties = (definition: Definition): Array => { + try { + const document = isEffectSchema(definition.input) + ? (Schema.toJsonSchemaDocument(definition.input) as { + readonly schema: JsonSchema + readonly definitions?: Readonly> + }) + : { + schema: definition.input, + definitions: { ...(definition.input.definitions ?? {}), ...(definition.input.$defs ?? {}) }, + } + const definitions = document.definitions ?? {} + let schema = document.schema + if (schema.$ref !== undefined) { + const segment = schema.$ref.match(/^#\/(?:\$defs|definitions)\/([^/]+)$/)?.[1] + const name = segment === undefined ? undefined : JsonPointer.unescapeToken(segment) + const resolved = name === undefined ? undefined : definitions[name] + if (resolved === undefined) return [] + schema = resolved + } + const required = new Set(schema.required ?? []) + return Object.entries(schema.properties ?? {}).map(([name, value]) => ({ + name, + description: typeof value.description === "string" ? value.description : undefined, + required: required.has(name), + })) + } catch { + return [] + } +} + +/** + * The model-visible TypeScript type of a tool's input. `pretty` renders an indented + * multiline block with schema descriptions and constraints as JSDoc comments on the + * fields; the default stays the compact single-line form. + */ +export const inputTypeScript = (definition: Definition, pretty = false): string => + isEffectSchema(definition.input) + ? toTypeScript(definition.input, false, pretty) + : jsonSchemaToTypeScript(definition.input, pretty) + +/** + * The model-visible TypeScript type of a tool's result; tools without an output schema + * return `unknown`. `pretty` renders the JSDoc-annotated multiline form, as for inputs. + */ +export const outputTypeScript = (definition: Definition, pretty = false): string => + definition.output === undefined + ? "unknown" + : isEffectSchema(definition.output) + ? toTypeScript(definition.output, true, pretty) + : jsonSchemaToTypeScript(definition.output, pretty) + +/** + * Decodes tool input before `run` is invoked. Effect Schemas validate (throwing on failure); + * JSON-Schema-described inputs pass through unvalidated (render-only). + */ +export const decodeInput = (definition: Definition, value: unknown): unknown => + isEffectSchema(definition.input) ? Schema.decodeUnknownSync(definition.input)(value) : value + +/** + * Decodes a tool result before it is exposed to the program. Effect Schemas validate and + * transform (throwing on failure); JSON Schema outputs and tools without an output schema pass + * the host value through unchanged. + */ +export const decodeOutput = (definition: Definition, value: unknown): unknown => + definition.output !== undefined && isEffectSchema(definition.output) + ? Schema.decodeUnknownSync(definition.output)(value) + : value diff --git a/packages/codemode/src/tool.ts b/packages/codemode/src/tool.ts index e89f3d39d6..6c6863f99d 100644 --- a/packages/codemode/src/tool.ts +++ b/packages/codemode/src/tool.ts @@ -1,4 +1,4 @@ -import { Effect, JsonPointer, Schema } from "effect" +import { Effect, Schema } from "effect" /** * JSON Schema subset accepted for render-only tool schemas. @@ -30,25 +30,25 @@ export type JsonSchema = { } /** Either a validating Effect Schema or a render-only JSON Schema document. */ -export type ToolSchema = Schema.Decoder | JsonSchema +export type SchemaType = Schema.Decoder | JsonSchema /** Schema-backed tool definition consumed by a CodeMode tool tree. */ export type Definition = { readonly _tag: "CodeModeTool" readonly description: string - readonly input: ToolSchema - readonly output: ToolSchema | undefined + readonly input: SchemaType + readonly output: SchemaType | undefined readonly run: (input: unknown) => Effect.Effect } /** The value `run` receives: the decoded type for Effect Schemas, `unknown` for JSON Schemas. */ -export type InputType = S extends Schema.Decoder ? S["Type"] : unknown +type InputType = S extends Schema.Decoder ? S["Type"] : unknown /** The value `run` returns: the encoded type for Effect Schemas, `unknown` otherwise. */ -export type ResultType = S extends Schema.Decoder ? S["Encoded"] : unknown +type ResultType = S extends Schema.Decoder ? S["Encoded"] : unknown /** Options for defining one CodeMode tool. */ -export type Options = { +export type Options = { readonly description: string readonly input: I readonly output?: O @@ -58,305 +58,6 @@ export type Options(value: unknown): value is Definition => typeof value === "object" && value !== null && "_tag" in value && value._tag === "CodeModeTool" -const isEffectSchema = (schema: ToolSchema): schema is Schema.Decoder & Schema.Top => Schema.isSchema(schema) - -const renderLiteral = (value: unknown): string => JSON.stringify(value) ?? "unknown" - -/** - * Bare TypeScript identifier - usable unquoted as an object key (and, in the tool runtime, - * with dot access as a tool-path segment). Anything else must be quoted/bracketed. - */ -export const identifierSegment = /^[A-Za-z_$][A-Za-z0-9_$]*$/ - -/** Renders a property name as a valid TS object key: bare when an identifier, quoted otherwise. */ -const renderKey = (name: string): string => (identifierSegment.test(name) ? name : JSON.stringify(name)) - -const effectNumberSentinel = (schema: JsonSchema) => - schema.type === "string" && - Array.isArray(schema.enum) && - schema.enum.length === 1 && - (schema.enum[0] === "NaN" || schema.enum[0] === "Infinity" || schema.enum[0] === "-Infinity") - -const intersection = (members: ReadonlyArray): string => { - const concrete = members.filter((member) => member !== "unknown") - if (concrete.length === 0) return "unknown" - if (concrete.length === 1) return concrete[0] ?? "unknown" - return concrete.map((member) => (member.includes(" | ") ? `(${member})` : member)).join(" & ") -} - -/** - * Recursion ceiling for schema rendering. Object, array, and union recursion all increment - * depth, so this bounds every recursion path - pathological or structurally cyclic schemas - * degrade to `unknown` instead of overflowing the stack (rendering must never throw). - */ -const MAX_RENDER_DEPTH = 8 - -type RenderContext = { - readonly definitions: Readonly> - /** Indented, JSDoc-annotated multiline rendering (search results); compact single line otherwise. */ - readonly pretty: boolean -} - -const hasUnresolvedRef = ( - schema: JsonSchema, - definitions: Readonly>, - seen: ReadonlySet = new Set(), - visited: ReadonlySet = new Set(), -): boolean => { - if (visited.has(schema)) return false - const nextVisited = new Set([...visited, schema]) - if (schema.$ref !== undefined) { - const segment = schema.$ref.match(/^#\/(?:\$defs|definitions)\/([^/]+)$/)?.[1] - const name = segment === undefined ? undefined : JsonPointer.unescapeToken(segment) - if (name === undefined || definitions[name] === undefined || seen.has(name)) return true - if (hasUnresolvedRef(definitions[name], definitions, new Set([...seen, name]), nextVisited)) return true - } - return [ - ...(schema.anyOf ?? []), - ...(schema.oneOf ?? []), - ...(schema.allOf ?? []), - ...Object.values(schema.properties ?? {}), - ...(schema.items === undefined ? [] : [schema.items]), - ...(typeof schema.additionalProperties === "object" ? [schema.additionalProperties] : []), - ].some((item) => hasUnresolvedRef(item, definitions, seen, nextVisited)) -} - -/** - * Schema constraints a TypeScript type cannot express natively but a model benefits from, - * surfaced as JSDoc tags (`@deprecated`, `@default`, `@format`, `@minItems`, `@maxItems`). - */ -const docTags = (schema: JsonSchema): Array => { - const tags: Array = [] - if (schema.deprecated === true) tags.push("@deprecated") - if (schema.default !== undefined) { - try { - const rendered = JSON.stringify(schema.default) - if (rendered !== undefined) tags.push(`@default ${rendered}`) - } catch { - // unserializable default: skip rather than emit a broken tag - } - } - if (typeof schema.format === "string") tags.push(`@format ${schema.format}`) - if (typeof schema.minItems === "number") tags.push(`@minItems ${schema.minItems}`) - if (typeof schema.maxItems === "number") tags.push(`@maxItems ${schema.maxItems}`) - return tags -} - -/** - * Format a schema `description` plus `tags` as a JSDoc comment at the given indent, - * preserving multi-line text (a single line stays `/** ... *\/`; multiple lines become a - * `*`-prefixed block). `*\/` is neutralized so nothing can close the comment early, and - * blank leading/trailing lines are trimmed. Returns "" (else a trailing newline) so - * callers can prepend it directly to the field line. - */ -const jsdoc = (description: string | undefined, tags: ReadonlyArray, pad: string): string => { - const lines = [...(description === undefined ? [] : description.split("\n")), ...tags].map((line) => - line.replaceAll("*/", "* /").replace(/\s+$/, ""), - ) - while (lines.length > 0 && lines[0]!.trim() === "") lines.shift() - while (lines.length > 0 && lines[lines.length - 1]!.trim() === "") lines.pop() - if (lines.length === 0) return "" - if (lines.length === 1) return `${pad}/** ${lines[0]} */\n` - const body = lines.map((line) => `${pad} *${line === "" ? "" : ` ${line}`}`).join("\n") - return `${pad}/**\n${body}\n${pad} */\n` -} - -const renderSchema = ( - schema: JsonSchema, - ctx: RenderContext, - depth = 0, - seen: ReadonlySet = new Set(), -): string => { - if (depth > MAX_RENDER_DEPTH) return "unknown" - const nested = - schema.definitions === undefined && schema.$defs === undefined - ? ctx - : { ...ctx, definitions: { ...ctx.definitions, ...(schema.definitions ?? {}), ...(schema.$defs ?? {}) } } - if (schema.$ref) { - const segment = schema.$ref.match(/^#\/(?:\$defs|definitions)\/([^/]+)$/)?.[1] - const name = segment === undefined ? undefined : JsonPointer.unescapeToken(segment) - if (!name || !nested.definitions[name] || seen.has(name)) return "unknown" - return intersection([ - renderSchema(nested.definitions[name], nested, depth, new Set([...seen, name])), - renderSchema({ ...schema, $ref: undefined }, nested, depth + 1, seen), - ]) - } - if (schema.const !== undefined) return renderLiteral(schema.const) - if (schema.enum) return schema.enum.map(renderLiteral).join(" | ") - const alternatives = schema.anyOf ?? schema.oneOf - if (alternatives) { - // Effect's number schema emits `anyOf: [{ type: "number" }, { const: "NaN" }, - // { const: "Infinity" }, { const: "-Infinity" }]`. Collapse only that artifact; - // real JSON Schema unions such as `string | number` or `number | null` must keep - // every branch. - if ( - alternatives.some((item) => item.type === "number") && - alternatives.every((item) => item.type === "number" || effectNumberSentinel(item)) - ) - return "number" - // An empty Schema.Struct({}) emits `anyOf: [{ type: "object" }, { type: "array" }]` - // (no properties/items); render the bare shape as {} instead of `{} | Array`. - if ( - alternatives.length === 2 && - alternatives[0]?.type === "object" && - alternatives[0].properties === undefined && - alternatives[1]?.type === "array" && - alternatives[1].items === undefined - ) { - return "{}" - } - const members = alternatives.map((item) => renderSchema(item, nested, depth + 1, seen)) - if (members.some((member) => member === "unknown")) return "unknown" - return intersection([ - members.join(" | "), - renderSchema({ ...schema, anyOf: undefined, oneOf: undefined }, nested, depth + 1, seen), - ]) - } - if (schema.allOf) { - const members = schema.allOf.map((item) => renderSchema(item, nested, depth + 1, seen)) - if (schema.allOf.some((item) => hasUnresolvedRef(item, nested.definitions))) return "unknown" - return intersection([renderSchema({ ...schema, allOf: undefined }, nested, depth + 1, seen), ...members]) - } - if (Array.isArray(schema.type)) { - return schema.type.map((item) => renderSchema({ ...schema, type: item }, nested, depth + 1, seen)).join(" | ") - } - if (schema.type === "string") return "string" - if (schema.type === "number" || schema.type === "integer") return "number" - if (schema.type === "boolean") return "boolean" - if (schema.type === "null") return "null" - if (schema.type === "array") return `Array<${renderSchema(schema.items ?? {}, nested, depth + 1, seen)}>` - if (schema.type === "object" || schema.properties) { - const required = new Set(schema.required ?? []) - const properties = Object.entries(schema.properties ?? {}) - const additional = schema.additionalProperties - const indexType = - additional && typeof additional === "object" ? renderSchema(additional, nested, depth + 1, seen) : undefined - const field = ([name, value]: readonly [string, JsonSchema]) => - `${renderKey(name)}${required.has(name) ? "" : "?"}: ${renderSchema(value, nested, depth + 1, seen)}` - - if (!ctx.pretty) { - const fields = properties.map(field) - if (indexType !== undefined) fields.push(`[key: string]: ${indexType}`) - return fields.length === 0 ? "{}" : `{ ${fields.join("; ")} }` - } - - // Pretty: an indented block, each described field preceded by its JSDoc comment. - if (properties.length === 0 && indexType === undefined) return "{}" - const pad = " ".repeat(depth + 1) - const lines = properties.map( - (entry) => `${jsdoc(entry[1].description, docTags(entry[1]), pad)}${pad}${field(entry)}`, - ) - if (indexType !== undefined) lines.push(`${pad}[key: string]: ${indexType}`) - return `{\n${lines.join("\n")}\n${" ".repeat(depth)}}` - } - return "unknown" -} - -export const toTypeScript = (schema: Schema.Top, decoded = false, pretty = false): string => { - try { - const visible = decoded ? Schema.toType(schema) : schema - const document = Schema.toJsonSchemaDocument(visible) as { - readonly schema: JsonSchema - readonly definitions?: Readonly> - } - return renderSchema(document.schema, { definitions: document.definitions ?? {}, pretty }) - } catch { - return "unknown" - } -} - -/** Renders a raw JSON Schema document as a TypeScript type string. */ -export const jsonSchemaToTypeScript = (schema: JsonSchema, pretty = false): string => { - try { - return renderSchema(schema, { definitions: { ...(schema.definitions ?? {}), ...(schema.$defs ?? {}) }, pretty }) - } catch { - return "unknown" - } -} - -/** One input property of a tool, extracted best-effort from its input schema. */ -export type InputProperty = { - readonly name: string - readonly description: string | undefined - readonly required: boolean -} - -/** - * The property names, descriptions, and required flags of a tool's input schema - the raw - * material for search text. Best-effort: Effect Schemas go through their - * JSON Schema document (the same emission signature rendering uses); JSON Schemas are read - * directly, resolving a trivial top-level `$ref` into `$defs`/`definitions` when present. - * Anything unresolvable yields `[]` (search falls back to path + description). - */ -export const inputProperties = (definition: Definition): Array => { - try { - const document = isEffectSchema(definition.input) - ? (Schema.toJsonSchemaDocument(definition.input) as { - readonly schema: JsonSchema - readonly definitions?: Readonly> - }) - : { - schema: definition.input, - definitions: { ...(definition.input.definitions ?? {}), ...(definition.input.$defs ?? {}) }, - } - const definitions = document.definitions ?? {} - let schema = document.schema - if (schema.$ref !== undefined) { - const segment = schema.$ref.match(/^#\/(?:\$defs|definitions)\/([^/]+)$/)?.[1] - const name = segment === undefined ? undefined : JsonPointer.unescapeToken(segment) - const resolved = name === undefined ? undefined : definitions[name] - if (resolved === undefined) return [] - schema = resolved - } - const required = new Set(schema.required ?? []) - return Object.entries(schema.properties ?? {}).map(([name, value]) => ({ - name, - description: typeof value.description === "string" ? value.description : undefined, - required: required.has(name), - })) - } catch { - return [] - } -} - -/** - * The model-visible TypeScript type of a tool's input. `pretty` renders an indented - * multiline block with schema descriptions and constraints as JSDoc comments on the - * fields; the default stays the compact single-line form. - */ -export const inputTypeScript = (definition: Definition, pretty = false): string => - isEffectSchema(definition.input) - ? toTypeScript(definition.input, false, pretty) - : jsonSchemaToTypeScript(definition.input, pretty) - -/** - * The model-visible TypeScript type of a tool's result; tools without an output schema - * return `unknown`. `pretty` renders the JSDoc-annotated multiline form, as for inputs. - */ -export const outputTypeScript = (definition: Definition, pretty = false): string => - definition.output === undefined - ? "unknown" - : isEffectSchema(definition.output) - ? toTypeScript(definition.output, true, pretty) - : jsonSchemaToTypeScript(definition.output, pretty) - -/** - * Decodes tool input before `run` is invoked. Effect Schemas validate (throwing on failure); - * JSON-Schema-described inputs pass through unvalidated (render-only). - */ -export const decodeInput = (definition: Definition, value: unknown): unknown => - isEffectSchema(definition.input) ? Schema.decodeUnknownSync(definition.input)(value) : value - -/** - * Decodes a tool result before it is exposed to the program. Effect Schemas validate and - * transform (throwing on failure); JSON Schema outputs and tools without an output schema pass - * the host value through unchanged. - */ -export const decodeOutput = (definition: Definition, value: unknown): unknown => - definition.output !== undefined && isEffectSchema(definition.output) - ? Schema.decodeUnknownSync(definition.output)(value) - : value - /** * Defines one schema-described tool available to a CodeMode program through `tools.*`. * @@ -384,7 +85,7 @@ export const decodeOutput = (definition: Definition, value: unknown): unkn * }) * ``` */ -export const make = ( +export const make = ( options: Options, ): Definition => ({ _tag: "CodeModeTool", @@ -393,6 +94,3 @@ export const make = options.run(input as InputType), }) - -/** Constructors for schema-backed tools exposed inside CodeMode programs. */ -export const Tool = { make, isDefinition } diff --git a/packages/codemode/test/codemode.test.ts b/packages/codemode/test/codemode.test.ts index 9db7739296..087678c778 100644 --- a/packages/codemode/test/codemode.test.ts +++ b/packages/codemode/test/codemode.test.ts @@ -1,9 +1,8 @@ import { describe, expect, test } from "bun:test" import { Cause, Effect, Schema } from "effect" -import { CodeMode, Tool, toolError, type ExecutionLimits } from "../src/index.js" -import type { Definition } from "../src/tool.js" +import { CodeMode, Tool, toolError } from "../src/index.js" -const run = (tool: Definition) => +const run = (tool: Tool.Definition) => Effect.runPromise(CodeMode.make({ tools: { host: { call: tool } } }).execute("return await tools.host.call({})")) class UnsafeHostError extends Schema.TaggedErrorClass()("UnsafeHostError", { @@ -349,7 +348,7 @@ describe("CodeMode output budget", () => { }) test("truncates an oversized result value with a marker instead of failing", async () => { - const limits: ExecutionLimits = { maxOutputBytes: 40 } + const limits: CodeMode.ExecutionLimits = { maxOutputBytes: 40 } const result = await Effect.runPromise( CodeMode.execute({ code: `return { data: "${"x".repeat(200)}" }`, @@ -368,7 +367,7 @@ describe("CodeMode output budget", () => { }) test("keeps leading logs within the remaining budget and marks the cut", async () => { - const limits: ExecutionLimits = { maxOutputBytes: 40 } + const limits: CodeMode.ExecutionLimits = { maxOutputBytes: 40 } const result = await Effect.runPromise( CodeMode.execute({ code: ` @@ -502,7 +501,8 @@ describe("CodeMode public contract", () => { ]) expect(reusable).toStrictEqual(oneShot) - expect(Schema.decodeUnknownSync(CodeMode.Input)({ code: source })).toStrictEqual({ code: source }) + const input: CodeMode.Input = { code: source } + expect(Schema.decodeUnknownSync(CodeMode.Input)(input)).toStrictEqual(input) expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(reusable)))).toStrictEqual(reusable) }) diff --git a/packages/codemode/test/openapi.test.ts b/packages/codemode/test/openapi.test.ts index 99a0890091..a50460e8da 100644 --- a/packages/codemode/test/openapi.test.ts +++ b/packages/codemode/test/openapi.test.ts @@ -1,8 +1,8 @@ import { describe, expect, test } from "bun:test" import { Effect, Layer, Option } from "effect" import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" -import { CodeMode, OpenAPI } from "../src/index.js" -import { inputTypeScript, outputTypeScript, Tool } from "../src/tool.js" +import { CodeMode, OpenAPI, Tool } from "../src/index.js" +import { inputTypeScript, outputTypeScript } from "../src/tool-schema.js" const baseUrl = "http://localhost:4096" type Document = OpenAPI.Document diff --git a/packages/codemode/test/parity.test.ts b/packages/codemode/test/parity.test.ts index e5c1d83822..dfa8583183 100644 --- a/packages/codemode/test/parity.test.ts +++ b/packages/codemode/test/parity.test.ts @@ -3,7 +3,7 @@ import { Effect } from "effect" import { CodeMode } from "../src/index.js" import { ToolRuntime } from "../src/tool-runtime.js" -// Runs a CodeMode program with no host tools and returns the ExecuteResult. These tests pin the +// Runs a CodeMode program with no host tools and returns the CodeMode.Result. These tests pin the // JS-parity behaviors for the "99% of ordinary defensive JavaScript just works" goal: cases where // a strict interpreter would throw but idiomatic JS yields undefined / succeeds. // diff --git a/packages/codemode/test/promise.test.ts b/packages/codemode/test/promise.test.ts index 952b2fdc50..545d463abf 100644 --- a/packages/codemode/test/promise.test.ts +++ b/packages/codemode/test/promise.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test" import { Effect, Schema } from "effect" -import { CodeMode, Tool, toolError, type ExecuteResult, type ExecutionLimits } from "../src/index.js" +import { CodeMode, Tool, toolError } from "../src/index.js" // Wave 5 acceptance suite: first-class promise values. Un-awaited tool calls start eagerly on // supervised fibers, `await` settles them, and Promise.all/allSettled/race/resolve/reject are @@ -48,7 +48,10 @@ const failingTool = Tool.make({ run: () => Effect.fail(toolError("Lookup refused")), }) -const run = (code: string, options: { trace?: Trace; limits?: ExecutionLimits } = {}): Promise => { +const run = ( + code: string, + options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}, +): Promise => { const trace = options.trace ?? makeTrace() return Effect.runPromise( CodeMode.execute({ @@ -59,13 +62,13 @@ const run = (code: string, options: { trace?: Trace; limits?: ExecutionLimits } ) } -const value = async (code: string, options: { trace?: Trace; limits?: ExecutionLimits } = {}) => { +const value = async (code: string, options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}) => { const result = await run(code, options) if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) return result.value } -const error = async (code: string, options: { trace?: Trace; limits?: ExecutionLimits } = {}) => { +const error = async (code: string, options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}) => { const result = await run(code, options) if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) return result.error diff --git a/packages/codemode/test/signature.test.ts b/packages/codemode/test/signature.test.ts index 55b8ac020a..47345be7d7 100644 --- a/packages/codemode/test/signature.test.ts +++ b/packages/codemode/test/signature.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test" import { Effect, Schema } from "effect" -import { CodeMode } from "../src/index.js" -import { Tool, inputTypeScript, jsonSchemaToTypeScript, outputTypeScript } from "../src/tool.js" +import { CodeMode, Tool } from "../src/index.js" +import { inputTypeScript, jsonSchemaToTypeScript, outputTypeScript } from "../src/tool-schema.js" // A raw JSON Schema tool in the shape an MCP adapter produces: render-only input schema // whose property descriptions and constraints must surface as JSDoc in pretty signatures. diff --git a/packages/core/src/tool/execute.ts b/packages/core/src/tool/execute.ts index 58dc097a0f..f5bd776e5a 100644 --- a/packages/core/src/tool/execute.ts +++ b/packages/core/src/tool/execute.ts @@ -1,14 +1,6 @@ export * as ExecuteTool from "./execute" -import { - CodeMode, - Tool, - toolError, - type DataValue, - type ExecuteResult, - type ToolCallHooks, - type ToolDefinition, -} from "@opencode-ai/codemode" +import { CodeMode, Tool, toolError } from "@opencode-ai/codemode" import { ToolOutput } from "@opencode-ai/llm" import { Effect, Ref, Schema } from "effect" import { definition, make, settle, type AnyTool } from "./tool" @@ -57,9 +49,9 @@ export const create = (options: { }) => { const runtime = ( invoke: (name: string, registration: Registration, input: unknown) => Effect.Effect, - hooks?: ToolCallHooks, + hooks?: CodeMode.ToolCallHooks, ) => { - const tools: Record | Record>> = {} + const tools: Record | Record>> = {} for (const [name, registration] of options.registrations) { const child = definition(name, registration.tool) const value = Tool.make({ @@ -83,7 +75,7 @@ export const create = (options: { group[path] = value continue } - const entries: Record> = {} + const entries: Record> = {} entries[path] = value tools[namespace] = entries } @@ -178,7 +170,7 @@ function displayInput(input: unknown): Record | undefined { return input as Record } -function formatResult(result: ExecuteResult) { +function formatResult(result: CodeMode.Result) { const output = result.ok ? formatValue(result.value) : [result.error.message, ...(result.error.suggestions ?? []).filter((hint) => !result.error.message.includes(hint))] @@ -189,7 +181,7 @@ function formatResult(result: ExecuteResult) { return output === "" ? logs : `${output}\n\n${logs}` } -function formatValue(value: DataValue) { +function formatValue(value: CodeMode.DataValue) { if (typeof value === "string") return value return JSON.stringify(value, null, 2) ?? String(value) } From a9b7bd9e2f2d3ff4429940dbbd850a62b6f3776d Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 15:51:15 -0400 Subject: [PATCH 64/82] feat(core): manage configurable plugin generations --- packages/core/src/config.ts | 2 +- packages/core/src/config/plugin/agent.ts | 4 +- packages/core/src/config/plugin/command.ts | 4 +- packages/core/src/config/plugin/external.ts | 136 ------ packages/core/src/config/plugin/provider.ts | 4 +- packages/core/src/config/plugin/reference.ts | 4 +- packages/core/src/config/plugin/skill.ts | 4 +- packages/core/src/event.ts | 24 +- packages/core/src/location-services.ts | 60 ++- packages/core/src/plugin.ts | 139 ++---- packages/core/src/plugin/agent.ts | 4 +- packages/core/src/plugin/command.ts | 4 +- packages/core/src/plugin/host.ts | 2 - packages/core/src/plugin/internal.ts | 288 +++++------- packages/core/src/plugin/models-dev.ts | 4 +- packages/core/src/plugin/promise.ts | 7 +- packages/core/src/plugin/provider.ts | 3 +- packages/core/src/plugin/provider/alibaba.ts | 4 +- .../src/plugin/provider/amazon-bedrock.ts | 4 +- .../core/src/plugin/provider/anthropic.ts | 4 +- packages/core/src/plugin/provider/azure.ts | 6 +- packages/core/src/plugin/provider/cerebras.ts | 4 +- .../plugin/provider/cloudflare-ai-gateway.ts | 4 +- .../plugin/provider/cloudflare-workers-ai.ts | 4 +- packages/core/src/plugin/provider/cohere.ts | 4 +- .../core/src/plugin/provider/deepinfra.ts | 4 +- packages/core/src/plugin/provider/dynamic.ts | 4 +- packages/core/src/plugin/provider/gateway.ts | 4 +- .../src/plugin/provider/github-copilot.ts | 4 +- packages/core/src/plugin/provider/gitlab.ts | 4 +- .../core/src/plugin/provider/google-vertex.ts | 6 +- packages/core/src/plugin/provider/google.ts | 4 +- packages/core/src/plugin/provider/groq.ts | 4 +- packages/core/src/plugin/provider/kilo.ts | 4 +- .../core/src/plugin/provider/llmgateway.ts | 4 +- packages/core/src/plugin/provider/mistral.ts | 4 +- packages/core/src/plugin/provider/nvidia.ts | 4 +- .../src/plugin/provider/openai-compatible.ts | 4 +- packages/core/src/plugin/provider/openai.ts | 5 +- packages/core/src/plugin/provider/opencode.ts | 2 +- .../core/src/plugin/provider/openrouter.ts | 4 +- .../core/src/plugin/provider/perplexity.ts | 4 +- .../core/src/plugin/provider/sap-ai-core.ts | 4 +- .../src/plugin/provider/snowflake-cortex.ts | 4 +- .../core/src/plugin/provider/togetherai.ts | 4 +- packages/core/src/plugin/provider/venice.ts | 4 +- packages/core/src/plugin/provider/vercel.ts | 4 +- packages/core/src/plugin/provider/xai.ts | 4 +- packages/core/src/plugin/provider/zenmux.ts | 4 +- packages/core/src/plugin/sdk.ts | 6 +- packages/core/src/plugin/skill.ts | 4 +- packages/core/src/plugin/supervisor.ts | 270 +++++++++++ packages/core/src/plugin/variant.ts | 4 +- packages/core/src/state.ts | 29 +- packages/core/src/tool/apply-patch.ts | 2 +- packages/core/src/tool/edit.ts | 2 +- packages/core/src/tool/glob.ts | 2 +- packages/core/src/tool/grep.ts | 2 +- packages/core/src/tool/question.ts | 2 +- packages/core/src/tool/read.ts | 2 +- packages/core/src/tool/shell.ts | 2 +- packages/core/src/tool/skill.ts | 2 +- packages/core/src/tool/subagent.ts | 2 +- packages/core/src/tool/todowrite.ts | 2 +- packages/core/src/tool/webfetch.ts | 2 +- packages/core/src/tool/websearch.ts | 2 +- packages/core/src/tool/write.ts | 2 +- packages/core/test/config/plugin.test.ts | 437 ++++++++---------- packages/core/test/config/reload.test.ts | 19 +- packages/core/test/location-layer.test.ts | 126 ++++- packages/core/test/plugin.test.ts | 134 ++++-- .../test/plugin/fixtures/failing-plugin.ts | 7 + .../plugin/fixtures/variant-source-plugin.ts | 29 ++ packages/core/test/plugin/host.ts | 2 - .../core/test/plugin/provider-kilo.test.ts | 4 +- .../test/plugin/provider-llmgateway.test.ts | 4 +- .../core/test/plugin/provider-nvidia.test.ts | 4 +- .../test/plugin/provider-openrouter.test.ts | 4 +- .../plugin/provider-snowflake-cortex.test.ts | 6 +- .../core/test/plugin/provider-zenmux.test.ts | 4 +- packages/opencode/src/agent/agent.ts | 4 +- packages/plugin/src/v2/effect/plugin.ts | 5 +- packages/plugin/src/v2/promise/plugin.ts | 5 +- 83 files changed, 1127 insertions(+), 830 deletions(-) delete mode 100644 packages/core/src/config/plugin/external.ts create mode 100644 packages/core/src/plugin/supervisor.ts create mode 100644 packages/core/test/plugin/fixtures/failing-plugin.ts create mode 100644 packages/core/test/plugin/fixtures/variant-source-plugin.ts diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 48c380aef3..4bd33ca240 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -102,7 +102,7 @@ export class Info extends Schema.Class("Config.Info")({ description: "Named local directories or Git repositories available as external context", }), plugins: ConfigPlugin.Plugins.pipe(Schema.optional).annotate({ - description: "Ordered external plugin packages to load", + description: "Ordered plugin enablement directives and external package declarations", }), providers: Schema.Record(Schema.String, ConfigProvider.Info).pipe(Schema.optional), }) {} diff --git a/packages/core/src/config/plugin/agent.ts b/packages/core/src/config/plugin/agent.ts index 3aebf88fbe..fa8b61ce18 100644 --- a/packages/core/src/config/plugin/agent.ts +++ b/packages/core/src/config/plugin/agent.ts @@ -1,6 +1,6 @@ export * as ConfigAgentPlugin from "./agent" -import { define } from "../../plugin/internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import path from "path" import { Effect, Option, Schema, Stream } from "effect" import { AgentV2 } from "../../agent" @@ -34,7 +34,7 @@ const agentKeys = new Set([ ]) export const Plugin = define({ - id: "config-agent", + id: "opencode.config.agent", effect: Effect.fn(function* (ctx) { const config = yield* Config.Service const fs = yield* FSUtil.Service diff --git a/packages/core/src/config/plugin/command.ts b/packages/core/src/config/plugin/command.ts index 43ba4cd375..a7babbb5aa 100644 --- a/packages/core/src/config/plugin/command.ts +++ b/packages/core/src/config/plugin/command.ts @@ -1,6 +1,6 @@ export * as ConfigCommandPlugin from "./command" -import { define } from "../../plugin/internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import path from "path" import { Effect, Option, Schema, Stream } from "effect" import { CommandV2 } from "../../command" @@ -13,7 +13,7 @@ import { ConfigMarkdown } from "../markdown" const decodeCommand = Schema.decodeUnknownOption(ConfigCommand.Info) export const Plugin = define({ - id: "config-command", + id: "opencode.config.command", effect: Effect.fn(function* (ctx) { const config = yield* Config.Service const fs = yield* FSUtil.Service diff --git a/packages/core/src/config/plugin/external.ts b/packages/core/src/config/plugin/external.ts deleted file mode 100644 index 70271dec23..0000000000 --- a/packages/core/src/config/plugin/external.ts +++ /dev/null @@ -1,136 +0,0 @@ -export * as ConfigExternalPlugin from "./external" - -import type { Plugin as EffectPlugin } from "@opencode-ai/plugin/v2/effect" -import type { Plugin as PromisePlugin } from "@opencode-ai/plugin/v2/promise" -import { Effect, Schema } from "effect" -import path from "path" -import { fileURLToPath, pathToFileURL } from "url" -import { Config } from "../../config" -import { FSUtil } from "../../fs-util" -import { Location } from "../../location" -import { Npm } from "../../npm" -import { define } from "../../plugin/internal" -import { PluginPromise } from "../../plugin/promise" - -const PluginModule = Schema.Struct({ - default: Schema.Union([ - Schema.Struct({ - id: Schema.String, - effect: Schema.declare( - (input): input is EffectPlugin["effect"] => typeof input === "function", - ), - }), - Schema.Struct({ - id: Schema.String, - setup: Schema.declare( - (input): input is PromisePlugin["setup"] => typeof input === "function", - ), - }), - ]), -}) - -const PluginPackage = Schema.Struct({ - exports: Schema.optional(Schema.Unknown), - main: Schema.optional(Schema.String), - module: Schema.optional(Schema.String), -}) - -export const Plugin = define({ - id: "config-plugin", - effect: Effect.fn(function* (ctx) { - const config = yield* Config.Service - const fs = yield* FSUtil.Service - const location = yield* Location.Service - const npm = yield* Npm.Service - const load = Effect.fn("ConfigExternalPlugin.load")(function* () { - const configured: { package: string; options?: Record }[] = [] - - for (const entry of yield* config.entries()) { - if (entry.type === "document") { - const directory = entry.path ? path.dirname(entry.path) : location.directory - for (const item of entry.info.plugins ?? []) { - const ref = typeof item === "string" ? { package: item } : item - const packageName = (() => { - if (ref.package.startsWith("file://")) return fileURLToPath(ref.package) - if (ref.package.startsWith("./") || ref.package.startsWith("../")) { - return path.resolve(directory, ref.package) - } - return ref.package - })() - configured.push({ package: packageName, options: ref.options }) - } - } - - if (entry.type === "directory") { - const files = yield* fs - .glob("{plugin,plugins}/*.{ts,js}", { - cwd: entry.path, - absolute: true, - include: "file", - dot: true, - symlink: true, - }) - .pipe(Effect.orElseSucceed(() => [])) - const directories = yield* fs - .glob("{plugin,plugins}/*", { - cwd: entry.path, - absolute: true, - include: "all", - dot: true, - symlink: true, - }) - .pipe( - Effect.flatMap((items) => - Effect.filter(items, (item) => fs.isDir(item), { - concurrency: "unbounded", - }), - ), - Effect.orElseSucceed(() => []), - ) - const packages = yield* Effect.forEach( - directories.sort(), - (directory) => resolvePackageEntrypoint(fs, directory), - { concurrency: "unbounded" }, - ).pipe(Effect.map((items) => items.filter((item): item is string => item !== undefined))) - files.sort() - for (const file of files) configured.push({ package: file }) - for (const file of packages) configured.push({ package: file }) - } - } - - return yield* Effect.forEach(configured, (ref) => - Effect.gen(function* () { - const entrypoint = path.isAbsolute(ref.package) - ? pathToFileURL(ref.package).href - : (yield* npm.add(ref.package)).entrypoint - if (!entrypoint) return - yield* Effect.log({ msg: "loading plugin", id: ref.package, entrypoint }) - const mod = yield* Effect.promise(() => import(entrypoint)) - const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default - const plugin = "effect" in value ? value : PluginPromise.fromPromise(value) - return { - id: plugin.id, - effect: (host: Parameters[0]) => - plugin.effect({ ...host, options: ref.options ?? {} }), - } - }).pipe(Effect.catchCause(() => Effect.succeed(undefined))), - ).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined))) - }) - for (const plugin of yield* load()) yield* ctx.plugin.add(plugin) - }), -}) - -const resolvePackageEntrypoint = Effect.fnUntraced(function* (fs: FSUtil.Interface, directory: string) { - const pkg = yield* fs.readJson(path.join(directory, "package.json")).pipe( - Effect.flatMap(Schema.decodeUnknownEffect(PluginPackage)), - Effect.catch(() => Effect.succeed(undefined)), - ) - const exported = typeof pkg?.exports === "string" ? pkg.exports : undefined - const entries = [exported, pkg?.module, pkg?.main, "index.ts", "index.js"] - - return yield* Effect.forEach(entries, (entry) => { - if (!entry) return Effect.succeed(undefined) - const file = path.resolve(directory, entry) - return fs.isFile(file).pipe(Effect.map((exists) => (exists ? file : undefined))) - }).pipe(Effect.map((items) => items.find((item): item is string => item !== undefined))) -}) diff --git a/packages/core/src/config/plugin/provider.ts b/packages/core/src/config/plugin/provider.ts index d2d6a26029..320895d128 100644 --- a/packages/core/src/config/plugin/provider.ts +++ b/packages/core/src/config/plugin/provider.ts @@ -1,12 +1,12 @@ export * as ConfigProviderPlugin from "./provider" -import { define } from "../../plugin/internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { Effect, Stream } from "effect" import { Config } from "../../config" import { ModelV2 } from "../../model" export const Plugin = define({ - id: "config-provider", + id: "opencode.config.provider", effect: Effect.fn(function* (ctx) { const config = yield* Config.Service const loaded = { entries: yield* config.entries() } diff --git a/packages/core/src/config/plugin/reference.ts b/packages/core/src/config/plugin/reference.ts index d33332f92d..75e0cc10e4 100644 --- a/packages/core/src/config/plugin/reference.ts +++ b/packages/core/src/config/plugin/reference.ts @@ -1,6 +1,6 @@ export * as ConfigReferencePlugin from "./reference" -import { define } from "../../plugin/internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import path from "path" import { Effect, Stream } from "effect" import { Config } from "../../config" @@ -11,7 +11,7 @@ import { Global } from "../../global" import { Location } from "../../location" export const Plugin = define({ - id: "core/config-reference", + id: "opencode.config.reference", effect: Effect.fn(function* (ctx) { const config = yield* Config.Service const location = yield* Location.Service diff --git a/packages/core/src/config/plugin/skill.ts b/packages/core/src/config/plugin/skill.ts index ff83c53ff1..84546b901c 100644 --- a/packages/core/src/config/plugin/skill.ts +++ b/packages/core/src/config/plugin/skill.ts @@ -1,6 +1,6 @@ export * as ConfigSkillPlugin from "./skill" -import { define } from "../../plugin/internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import path from "path" import { Effect, Stream } from "effect" import { Config } from "../../config" @@ -10,7 +10,7 @@ import { Global } from "../../global" import { Location } from "../../location" export const Plugin = define({ - id: "config-skill", + id: "opencode.config.skill", effect: Effect.fn(function* (ctx) { const config = yield* Config.Service const global = yield* Global.Service diff --git a/packages/core/src/event.ts b/packages/core/src/event.ts index 3e352c6e6b..a5b052b42f 100644 --- a/packages/core/src/event.ts +++ b/packages/core/src/event.ts @@ -583,12 +583,32 @@ export const layerWith = (options?: LayerOptions) => .pipe(Effect.orDie) } + const local = (stream: Stream.Stream) => + Stream.unwrap( + Effect.serviceOption(Location.Service).pipe( + Effect.map((location) => + Option.match(location, { + onNone: () => stream, + onSome: (location) => + stream.pipe( + Stream.filter( + (event) => + !event.location || + (event.location.directory === location.directory && + event.location.workspaceID === location.workspaceID), + ), + ), + }), + ), + ), + ) + const subscribe = (definition: D): Stream.Stream> => - Stream.unwrap(getOrCreate(definition).pipe(Effect.map((pubsub) => Stream.fromPubSub(pubsub)))).pipe( + local(Stream.unwrap(getOrCreate(definition).pipe(Effect.map((pubsub) => Stream.fromPubSub(pubsub))))).pipe( Stream.map((event) => event as Payload), ) - const streamLive = (): Stream.Stream => Stream.fromPubSub(pubsub.live) + const streamLive = (): Stream.Stream => local(Stream.fromPubSub(pubsub.live)) const readAfter = ( aggregateID: string, diff --git a/packages/core/src/location-services.ts b/packages/core/src/location-services.ts index 2a4e0d6ef6..bbb60482c1 100644 --- a/packages/core/src/location-services.ts +++ b/packages/core/src/location-services.ts @@ -5,12 +5,16 @@ import { Catalog } from "./catalog" import { CommandV2 } from "./command" import { Config } from "./config" import { LayerNode } from "./effect/layer-node" -import { Node } from "./effect/app-node" +import { makeLocationNode, Node } from "./effect/app-node" +import { httpClient } from "./effect/app-node-platform" +import { EventV2 } from "./event" import { FileMutation } from "./file-mutation" import { FileSystem } from "./filesystem" import { FileSystemSearch } from "./filesystem/search" +import { FSUtil } from "./fs-util" import { Generate } from "./generate" import { Form } from "./form" +import { Global } from "./global" import { LocationWatcher } from "./filesystem/location-watcher" import { Image } from "./image" import { Integration } from "./integration" @@ -18,15 +22,20 @@ import { Location } from "./location" import { LocationMutation } from "./location-mutation" import { LocationServiceMap } from "./location-service-map" import { MCP } from "./mcp/index" +import { ModelsDev } from "./models-dev" +import { Npm } from "./npm" import { PermissionV2 } from "./permission" import { PluginV2 } from "./plugin" -import { PluginInternal } from "./plugin/internal" +import { PluginRuntime } from "./plugin/runtime" +import { SdkPlugins } from "./plugin/sdk" +import { PluginSupervisor } from "./plugin/supervisor" import { ProjectCopy } from "./project/copy" import { Pty } from "./pty" import { QuestionV2 } from "./question" import { Shell } from "./shell" import { Reference } from "./reference" import { ReferenceGuidance } from "./reference/guidance" +import { Ripgrep } from "./ripgrep" import { SessionRunnerLLM } from "./session/runner/llm" import { SessionRunnerModel } from "./session/runner/model" import { SessionCompaction } from "./session/compaction" @@ -42,11 +51,49 @@ import { SessionInstructions } from "./session/instructions" import { McpTool } from "./tool/mcp" import { ReadToolFileSystem } from "./tool/read-filesystem" import { ToolRegistry } from "./tool/registry" +import { WebSearchTool } from "./tool/websearch" import { ToolOutputStore } from "./tool-output-store" import { Vcs } from "./vcs" export { LocationServiceMap } from "./location-service-map" +const pluginSupervisorNode = makeLocationNode({ + service: PluginSupervisor.Service, + layer: PluginSupervisor.layer, + deps: [ + PluginV2.node, + SdkPlugins.node, + AgentV2.node, + Catalog.node, + CommandV2.node, + Config.node, + EventV2.node, + FileMutation.node, + FileSystem.node, + FSUtil.node, + Global.node, + httpClient, + Image.node, + Integration.node, + Location.node, + LocationMutation.node, + ModelsDev.node, + Npm.node, + PermissionV2.node, + PluginRuntime.node, + QuestionV2.node, + ReadToolFileSystem.node, + Reference.node, + Ripgrep.node, + SessionInstructions.node, + SessionTodo.node, + Shell.node, + SkillV2.node, + ToolRegistry.toolsNode, + WebSearchTool.configNode, + ], +}) + const locationServiceNodes = [ Location.node, Config.node, @@ -57,12 +104,11 @@ const locationServiceNodes = [ Catalog.node, AISDK.node, PluginV2.node, - PluginInternal.node, + pluginSupervisorNode, ProjectCopy.node, ProjectCopy.refreshNode, FileSystemSearch.node, FileSystem.node, - LocationWatcher.node, Pty.node, Shell.node, SkillV2.node, @@ -92,6 +138,8 @@ const locationServiceNodes = [ Snapshot.node, SessionRunnerLLM.node, Vcs.node, + // Start repository watches only after boot-critical filesystem and Git work. + LocationWatcher.node, ] as const satisfies readonly Node.LocationNode[] export const locationServices = LayerNode.group(locationServiceNodes) @@ -106,6 +154,7 @@ export function buildLocationServiceMap( LocationServiceMap.Service, LayerMap.make( (ref: Location.Ref) => { + const startedAt = performance.now() const allReplacements = replacements.concat([[Location.node, Location.boundNode(ref)]]) // Apply replacements during hoist, not afterward: replacements can // introduce new tagged dependencies (Location.boundNode depends on @@ -116,9 +165,10 @@ export function buildLocationServiceMap( return LayerNode.compile(location.node).pipe( Layer.fresh, Layer.tap(() => - Effect.logInfo("booting location services", { + Effect.logInfo("location services booted", { directory: ref.directory, workspaceID: ref.workspaceID, + durationMs: Math.round(performance.now() - startedAt), }), ), Layer.provide(LayerNode.compile(location.hoisted)), diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index a6ff337c62..8ffdf93ba1 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -1,8 +1,7 @@ export * as PluginV2 from "./plugin" import { makeLocationNode } from "./effect/app-node" -import { Context, Deferred, Effect, Exit, Layer, Scope } from "effect" -import type { Plugin as PluginDefinition } from "@opencode-ai/plugin/v2/effect" +import { Context, Effect, Exit, Layer, Scope, Semaphore } from "effect" import { Plugin } from "@opencode-ai/schema/plugin" import { AgentV2 } from "./agent" import { AISDK } from "./aisdk" @@ -10,7 +9,6 @@ import { Catalog } from "./catalog" import { CommandV2 } from "./command" import { EventV2 } from "./event" import { Integration } from "./integration" -import { KeyedMutex } from "./effect/keyed-mutex" import { Location } from "./location" import { PluginHost } from "./plugin/host" import { PluginRuntime } from "./plugin/runtime" @@ -27,9 +25,7 @@ export type Info = Plugin.Info export const Event = Plugin.Event export interface Interface { - readonly add: (id: ID, effect: PluginDefinition["effect"]) => Effect.Effect - readonly remove: (id: ID) => Effect.Effect - readonly wait: (id: ID) => Effect.Effect + readonly activate: (plugins: readonly import("@opencode-ai/plugin/v2/effect").Plugin[]) => Effect.Effect readonly list: () => Effect.Effect } @@ -39,110 +35,73 @@ const layer = Layer.effect( Service, Effect.gen(function* () { const events = yield* EventV2.Service - const locks = KeyedMutex.makeUnsafe() const scope = yield* Scope.make() const active = new Map() - const loading = new Set() - const waiters = new Map>>() - const failures = new Map>() - let host: Parameters[0] + const lock = Semaphore.makeUnsafe(1) + let generation: readonly ID[] | undefined = [] + let host: Parameters[0] - const add = Effect.fn("Plugin.add")(function* (id: ID, effect: PluginDefinition["effect"]) { - if (loading.has(id)) return yield* Effect.die(new Error(`Plugin load cycle detected for ${id}`)) + const activate = Effect.fn("Plugin.activate")(function* ( + plugins: readonly import("@opencode-ai/plugin/v2/effect").Plugin[], + ) { + const definitions = plugins.map((plugin) => ({ ...plugin, id: ID.make(plugin.id) })) + const ids = new Set() + for (const definition of definitions) { + if (ids.has(definition.id)) return yield* Effect.die(new Error(`Duplicate plugin ID: ${definition.id}`)) + ids.add(definition.id) + } - yield* locks.withLock(id)( - Effect.sync(() => { - loading.add(id) - failures.delete(id) - }).pipe( - Effect.andThen( - State.batch( - Effect.gen(function* () { - const existing = active.get(id) - active.delete(id) - if (existing) yield* Scope.close(existing, Exit.void).pipe(Effect.ignore) + yield* lock.withPermit( + Effect.gen(function* () { + if ( + generation !== undefined && + generation.length === definitions.length && + generation.every((id, index) => id === definitions[index]?.id) + ) { + return + } + generation = undefined + const exit = yield* State.batch( + Effect.gen(function* () { + const scopes = Array.from(active.values()).toReversed() + active.clear() + const inherit = yield* State.inherit() + yield* Effect.forEach(scopes, (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore), { + discard: true, + }) + for (const definition of definitions) { const child = yield* Scope.fork(scope) - yield* effect(host).pipe( - Scope.provide(child), - Effect.withSpan("Plugin.load", { attributes: { "plugin.id": id } }), + const loaded = yield* Effect.suspend(() => definition.effect(host)).pipe( + inherit, + Effect.updateContext((_context: Context.Context) => Context.make(Scope.Scope, child)), + Effect.withSpan("Plugin.load", { attributes: { "plugin.id": definition.id } }), + Effect.andThen(events.publish(Event.Added, { id: definition.id })), Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(child, exit) : Effect.void)), + Effect.exit, ) - yield* events.publish(Event.Added, { id }) - active.set(id, child) - yield* Effect.forEach(waiters.get(id) ?? [], (waiter) => Deferred.succeed(waiter, undefined), { - discard: true, - }) - waiters.delete(id) - }), - ), - ), - Effect.onExit((exit) => { - if (Exit.isSuccess(exit)) return Effect.void - failures.set(id, exit) - return Effect.forEach(waiters.get(id) ?? [], (waiter) => Deferred.done(waiter, exit), { - discard: true, - }).pipe(Effect.ensuring(Effect.sync(() => waiters.delete(id)))) - }), - Effect.ensuring(Effect.sync(() => loading.delete(id))), - ), - ) - }) - - const remove = Effect.fn("Plugin.remove")(function* (id: ID) { - if (loading.has(id)) return yield* Effect.die(new Error(`Cannot remove plugin ${id} while it is loading`)) - - yield* locks.withLock(id)( - State.batch( - Effect.gen(function* () { - const current = active.get(id) - active.delete(id) - failures.delete(id) - if (current) yield* Scope.close(current, Exit.void).pipe(Effect.ignore) - }), - ), - ) - }) - - const wait = Effect.fn("Plugin.wait")(function* (id: ID) { - const waiter = yield* Deferred.make() - const pending = yield* locks.withLock(id)( - Effect.sync(() => { - if (active.has(id)) return false - const failure = failures.get(id) - if (failure) return failure - const current = waiters.get(id) ?? new Set() - current.add(waiter) - waiters.set(id, current) - return true - }), - ) - if (!pending) return - if (typeof pending !== "boolean") return yield* pending - yield* Deferred.await(waiter).pipe( - Effect.ensuring( - locks.withLock(id)( - Effect.sync(() => { - const current = waiters.get(id) - current?.delete(waiter) - if (current?.size === 0) waiters.delete(id) + if (Exit.isFailure(loaded)) return loaded + active.set(definition.id, child) + } + return Exit.void }), - ), - ), + ) + if (Exit.isFailure(exit)) return yield* exit + generation = definitions.map((definition) => definition.id) + }), ) }) yield* Effect.addFinalizer((exit) => Effect.gen(function* () { active.clear() + generation = [] yield* State.batch(Scope.close(scope, exit)) }), ) const service = Service.of({ - add, - remove, - wait, + activate, list: Effect.fn("Plugin.list")(function* () { return Array.from(active.keys()).map((id) => ({ id })) }), diff --git a/packages/core/src/plugin/agent.ts b/packages/core/src/plugin/agent.ts index a0e3556ce8..7549089bf3 100644 --- a/packages/core/src/plugin/agent.ts +++ b/packages/core/src/plugin/agent.ts @@ -1,7 +1,7 @@ export * as AgentPlugin from "./agent" import path from "path" -import { define } from "./internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { Effect } from "effect" import { AgentV2 } from "../agent" import { Global } from "../global" @@ -100,7 +100,7 @@ Rules: - If the conversation ends with an imperative statement or request to the user (e.g. "Now please run the command and paste the console output"), always include that exact request in the summary` export const Plugin = define({ - id: "agent", + id: "opencode.agent", effect: Effect.fn(function* (ctx) { const location = yield* Location.Service const worktree = location.directory diff --git a/packages/core/src/plugin/command.ts b/packages/core/src/plugin/command.ts index 1989641238..7bb14dad31 100644 --- a/packages/core/src/plugin/command.ts +++ b/packages/core/src/plugin/command.ts @@ -1,13 +1,13 @@ export * as CommandPlugin from "./command" -import { define } from "./internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { Effect } from "effect" import { Location } from "../location" import PROMPT_INITIALIZE from "./command/initialize.txt" import PROMPT_REVIEW from "./command/review.txt" export const Plugin = define({ - id: "command", + id: "opencode.command", effect: Effect.fn(function* (ctx) { const location = yield* Location.Service yield* ctx.command.transform((draft) => { diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index 4c7bb8538c..2e58c6b144 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -273,8 +273,6 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Int }, plugin: { list: () => response(plugin.list()), - add: (input) => plugin.add(PluginV2.ID.make(input.id), input.effect), - remove: (id) => plugin.remove(PluginV2.ID.make(id)), }, reference: { list: () => response(reference.list()), diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index 939bb4e731..63637c96b0 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -1,16 +1,14 @@ export * as PluginInternal from "./internal" -import { makeLocationNode } from "../effect/app-node" -import { httpClient } from "../effect/app-node-platform" -import type { PluginContext } from "@opencode-ai/plugin/v2/effect" -import { Context, Effect, Layer, Scope } from "effect" +import type { Plugin } from "@opencode-ai/plugin/v2/effect" +import { Context, Effect, Scope } from "effect" +import { HttpClient } from "effect/unstable/http" import { AgentV2 } from "../agent" import { Catalog } from "../catalog" import { CommandV2 } from "../command" import { Config } from "../config" import { ConfigAgentPlugin } from "../config/plugin/agent" import { ConfigCommandPlugin } from "../config/plugin/command" -import { ConfigExternalPlugin } from "../config/plugin/external" import { ConfigProviderPlugin } from "../config/plugin/provider" import { ConfigReferencePlugin } from "../config/plugin/reference" import { ConfigSkillPlugin } from "../config/plugin/skill" @@ -25,8 +23,6 @@ import { Location } from "../location" import { LocationMutation } from "../location-mutation" import { ModelsDev } from "../models-dev" import { Npm } from "../npm" -import { PluginV2 } from "../plugin" -import { PluginRuntime } from "../plugin/runtime" import { PermissionV2 } from "../permission" import { QuestionV2 } from "../question" import { Reference } from "../reference" @@ -35,177 +31,137 @@ import { SessionInstructions } from "../session/instructions" import { SessionTodo } from "../session/todo" import { Shell } from "../shell" import { SkillV2 } from "../skill" -import { State } from "../state" -import { ToolRegistry } from "../tool/registry" -import { Tools } from "../tool/tools" -import { HttpClient } from "effect/unstable/http" -import { AgentPlugin } from "./agent" -import { CommandPlugin } from "./command" -import { ModelsDevPlugin } from "./models-dev" -import { ProviderPlugins } from "./provider" -import { SdkPlugins } from "./sdk" -import { SkillPlugin } from "./skill" -import { VariantPlugin } from "./variant" import { ApplyPatchTool } from "../tool/apply-patch" import { EditTool } from "../tool/edit" import { GlobTool } from "../tool/glob" import { GrepTool } from "../tool/grep" import { QuestionTool } from "../tool/question" -import { ReadTool } from "../tool/read" import { ReadToolFileSystem } from "../tool/read-filesystem" +import { ReadTool } from "../tool/read" import { ShellTool } from "../tool/shell" import { SkillTool } from "../tool/skill" import { SubagentTool } from "../tool/subagent" import { TodoWriteTool } from "../tool/todowrite" +import { Tools } from "../tool/tools" import { WebFetchTool } from "../tool/webfetch" import { WebSearchTool } from "../tool/websearch" import { WriteTool } from "../tool/write" +import { AgentPlugin } from "./agent" +import { CommandPlugin } from "./command" +import { ModelsDevPlugin } from "./models-dev" +import { ProviderPlugins } from "./provider" +import { PluginRuntime } from "./runtime" +import { SkillPlugin } from "./skill" +import { VariantPlugin } from "./variant" -export type Requirements = - | AgentV2.Service - | Catalog.Service - | CommandV2.Service - | Config.Service - | EventV2.Service - | FileMutation.Service - | FileSystem.Service - | FSUtil.Service - | Global.Service - | HttpClient.HttpClient - | Image.Service - | Integration.Service - | Location.Service - | LocationMutation.Service - | ModelsDev.Service - | Npm.Service - | PermissionV2.Service - | PluginRuntime.Service - | QuestionV2.Service - | ReadToolFileSystem.Service - | Reference.Service - | Ripgrep.Service - | SessionInstructions.Service - | SessionTodo.Service - | Shell.Service - | SkillV2.Service - | Tools.Service - | WebSearchTool.ConfigService - -export interface Plugin { - readonly id: string - readonly effect: (context: PluginContext) => Effect.Effect -} - -export function define(plugin: Plugin) { - return plugin -} - -const layer = Layer.effectDiscard( - Effect.gen(function* () { - const plugin = yield* PluginV2.Service - const sdkPlugins = yield* SdkPlugins.Service - const services = Context.mergeAll( - Context.make(Catalog.Service, yield* Catalog.Service), - Context.make(CommandV2.Service, yield* CommandV2.Service), - Context.make(Integration.Service, yield* Integration.Service), - Context.make(AgentV2.Service, yield* AgentV2.Service), - Context.make(Config.Service, yield* Config.Service), - Context.make(Location.Service, yield* Location.Service), - Context.make(ModelsDev.Service, yield* ModelsDev.Service), - Context.make(Npm.Service, yield* Npm.Service), - Context.make(EventV2.Service, yield* EventV2.Service), - Context.make(FSUtil.Service, yield* FSUtil.Service), - Context.make(FileSystem.Service, yield* FileSystem.Service), - Context.make(Global.Service, yield* Global.Service), - Context.make(HttpClient.HttpClient, yield* HttpClient.HttpClient), - Context.make(LocationMutation.Service, yield* LocationMutation.Service), - Context.make(FileMutation.Service, yield* FileMutation.Service), - Context.make(Image.Service, yield* Image.Service), - Context.make(PermissionV2.Service, yield* PermissionV2.Service), - Context.make(QuestionV2.Service, yield* QuestionV2.Service), - Context.make(ReadToolFileSystem.Service, yield* ReadToolFileSystem.Service), - Context.make(SessionInstructions.Service, yield* SessionInstructions.Service), - Context.make(SessionTodo.Service, yield* SessionTodo.Service), - Context.make(SkillV2.Service, yield* SkillV2.Service), - Context.make(Reference.Service, yield* Reference.Service), - Context.make(Ripgrep.Service, yield* Ripgrep.Service), - Context.make(Shell.Service, yield* Shell.Service), - Context.make(Tools.Service, yield* Tools.Service), - Context.make(PluginRuntime.Service, yield* PluginRuntime.Service), - Context.make(WebSearchTool.ConfigService, yield* WebSearchTool.ConfigService), - ) - const add = (input: Plugin) => - plugin.add(PluginV2.ID.make(input.id), (context: PluginContext) => - input.effect(context).pipe(Effect.provide(services)), - ) - - yield* State.batch( - Effect.gen(function* () { - yield* add(ConfigReferencePlugin.Plugin) - yield* add(AgentPlugin.Plugin) - yield* add(CommandPlugin.Plugin) - yield* add(SkillPlugin.Plugin) - yield* add(ModelsDevPlugin) - yield* add(ConfigExternalPlugin.Plugin) - yield* add(ApplyPatchTool.Plugin) - yield* add(EditTool.Plugin) - yield* add(GlobTool.Plugin) - yield* add(GrepTool.Plugin) - yield* add(QuestionTool.Plugin) - yield* add(ReadTool.Plugin) - yield* add(ShellTool.Plugin) - yield* add(SkillTool.Plugin) - yield* add(SubagentTool.Plugin) - yield* add(TodoWriteTool.Plugin) - yield* add(WebFetchTool.Plugin) - yield* add(WebSearchTool.Plugin) - yield* add(WriteTool.Plugin) - yield* add(ConfigAgentPlugin.Plugin) - yield* add(ConfigCommandPlugin.Plugin) - yield* add(ConfigSkillPlugin.Plugin) - for (const item of ProviderPlugins) yield* add(item) - yield* add(ConfigProviderPlugin.Plugin) - yield* add(VariantPlugin.Plugin) - // Embedder-contributed plugins are added last so they layer over config. - for (const plugin of sdkPlugins.all()) yield* add(plugin) - }), - ).pipe(Effect.withSpan("PluginInternal.boot"), Effect.forkScoped({ startImmediately: true })) - }), -) - -export const node = makeLocationNode({ - name: "plugin-internal", - layer, - deps: [ - Catalog.node, - CommandV2.node, - PluginV2.node, - Integration.node, - AgentV2.node, - Config.node, - Location.node, - LocationMutation.node, - FileMutation.node, - Image.node, - ModelsDev.node, - Npm.node, - EventV2.node, - FSUtil.node, - FileSystem.node, - Global.node, - httpClient, - PermissionV2.node, - QuestionV2.node, - ReadToolFileSystem.node, - SessionInstructions.node, - SessionTodo.node, - SkillV2.node, - Reference.node, - Ripgrep.node, - Shell.node, - ToolRegistry.toolsNode, - PluginRuntime.node, - SdkPlugins.node, - WebSearchTool.configNode, - ], +const services = Effect.fn("PluginInternal.services")(function* () { + const agent = yield* AgentV2.Service + const catalog = yield* Catalog.Service + const command = yield* CommandV2.Service + const config = yield* Config.Service + const events = yield* EventV2.Service + const mutation = yield* FileMutation.Service + const filesystem = yield* FileSystem.Service + const fs = yield* FSUtil.Service + const global = yield* Global.Service + const http = yield* HttpClient.HttpClient + const image = yield* Image.Service + const integration = yield* Integration.Service + const location = yield* Location.Service + const locationMutation = yield* LocationMutation.Service + const models = yield* ModelsDev.Service + const npm = yield* Npm.Service + const permission = yield* PermissionV2.Service + const runtime = yield* PluginRuntime.Service + const question = yield* QuestionV2.Service + const read = yield* ReadToolFileSystem.Service + const reference = yield* Reference.Service + const ripgrep = yield* Ripgrep.Service + const instructions = yield* SessionInstructions.Service + const todo = yield* SessionTodo.Service + const shell = yield* Shell.Service + const skill = yield* SkillV2.Service + const tools = yield* Tools.Service + const websearch = yield* WebSearchTool.ConfigService + return Context.mergeAll( + Context.make(AgentV2.Service, agent), + Context.make(Catalog.Service, catalog), + Context.make(CommandV2.Service, command), + Context.make(Config.Service, config), + Context.make(EventV2.Service, events), + Context.make(FileMutation.Service, mutation), + Context.make(FileSystem.Service, filesystem), + Context.make(FSUtil.Service, fs), + Context.make(Global.Service, global), + Context.make(HttpClient.HttpClient, http), + Context.make(Image.Service, image), + Context.make(Integration.Service, integration), + Context.make(Location.Service, location), + Context.make(LocationMutation.Service, locationMutation), + Context.make(ModelsDev.Service, models), + Context.make(Npm.Service, npm), + Context.make(PermissionV2.Service, permission), + Context.make(PluginRuntime.Service, runtime), + Context.make(QuestionV2.Service, question), + Context.make(ReadToolFileSystem.Service, read), + Context.make(Reference.Service, reference), + Context.make(Ripgrep.Service, ripgrep), + Context.make(SessionInstructions.Service, instructions), + Context.make(SessionTodo.Service, todo), + Context.make(Shell.Service, shell), + Context.make(SkillV2.Service, skill), + Context.make(Tools.Service, tools), + Context.make(WebSearchTool.ConfigService, websearch), + ) +}) + +type ContextServices = A extends Context.Context ? R : never + +export type Requirements = ContextServices>> + +export type InternalPlugin = Plugin + +const pre = [ + AgentPlugin.Plugin, + CommandPlugin.Plugin, + SkillPlugin.Plugin, + ModelsDevPlugin, + ...ProviderPlugins, + ApplyPatchTool.Plugin, + EditTool.Plugin, + GlobTool.Plugin, + GrepTool.Plugin, + QuestionTool.Plugin, + ReadTool.Plugin, + ShellTool.Plugin, + SkillTool.Plugin, + SubagentTool.Plugin, + TodoWriteTool.Plugin, + WebFetchTool.Plugin, + WebSearchTool.Plugin, + WriteTool.Plugin, +] as const satisfies readonly InternalPlugin[] + +const post = [ + ConfigReferencePlugin.Plugin, + ConfigAgentPlugin.Plugin, + ConfigCommandPlugin.Plugin, + ConfigSkillPlugin.Plugin, + ConfigProviderPlugin.Plugin, + VariantPlugin.Plugin, +] as const satisfies readonly InternalPlugin[] + +export const list = Effect.fn("PluginInternal.list")(function* () { + const context = yield* services() + const resolve = (plugins: readonly InternalPlugin[]) => + plugins.map( + (plugin): Plugin => ({ + id: plugin.id, + effect: (host) => plugin.effect(host).pipe(Effect.provide(context)), + }), + ) + return { + pre: resolve(pre), + post: resolve(post), + } }) diff --git a/packages/core/src/plugin/models-dev.ts b/packages/core/src/plugin/models-dev.ts index 27c176ed67..23a166e267 100644 --- a/packages/core/src/plugin/models-dev.ts +++ b/packages/core/src/plugin/models-dev.ts @@ -1,4 +1,4 @@ -import { define } from "./internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import type { ModelV2Info } from "@opencode-ai/sdk/v2/types" import { Effect, Stream } from "effect" import { EventV2 } from "../event" @@ -197,7 +197,7 @@ function applyModel( } export const ModelsDevPlugin = define({ - id: "models-dev", + id: "opencode.models-dev", effect: Effect.fn(function* (ctx) { const modelsDev = yield* ModelsDev.Service const events = yield* EventV2.Service diff --git a/packages/core/src/plugin/promise.ts b/packages/core/src/plugin/promise.ts index b315d3214a..bcd3db1323 100644 --- a/packages/core/src/plugin/promise.ts +++ b/packages/core/src/plugin/promise.ts @@ -9,7 +9,7 @@ type Registration = { readonly dispose: () => Promise } /** * Adapts a Promise plugin into an Effect plugin so the existing Effect-only - * loader (`PluginV2` / `PluginInternal`) can run it unchanged. + * loader (`PluginV2` / `PluginSupervisor`) can run it unchanged. * * Hook registrations created during the async `setup` attach to the plugin's * scope, so unloading the plugin disposes them. The captured fiber context @@ -93,11 +93,6 @@ export function fromPromise(plugin: Plugin) { }, plugin: { list: (input) => run(host.plugin.list(input)), - add: (input) => { - const child = fromPromise(input) - return run(host.plugin.add(child)) - }, - remove: (id) => run(host.plugin.remove(id)), }, reference: { list: (input) => run(host.reference.list(input)), diff --git a/packages/core/src/plugin/provider.ts b/packages/core/src/plugin/provider.ts index 1749b474ed..7c17bcc4c7 100644 --- a/packages/core/src/plugin/provider.ts +++ b/packages/core/src/plugin/provider.ts @@ -31,9 +31,8 @@ import { VenicePlugin } from "./provider/venice" import { XAIPlugin } from "./provider/xai" import { ZenmuxPlugin } from "./provider/zenmux" import type { PluginInternal } from "./internal" -import type { Scope } from "effect" -export const ProviderPlugins: PluginInternal.Plugin[] = [ +export const ProviderPlugins: PluginInternal.InternalPlugin[] = [ AlibabaPlugin, AmazonBedrockPlugin, AnthropicPlugin, diff --git a/packages/core/src/plugin/provider/alibaba.ts b/packages/core/src/plugin/provider/alibaba.ts index c5c4be0d0b..607e565d4a 100644 --- a/packages/core/src/plugin/provider/alibaba.ts +++ b/packages/core/src/plugin/provider/alibaba.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const AlibabaPlugin = define({ - id: "alibaba", + id: "opencode.provider.alibaba", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/amazon-bedrock.ts b/packages/core/src/plugin/provider/amazon-bedrock.ts index cbf9defc09..0bc3ced462 100644 --- a/packages/core/src/plugin/provider/amazon-bedrock.ts +++ b/packages/core/src/plugin/provider/amazon-bedrock.ts @@ -1,6 +1,6 @@ import { Effect } from "effect" import type { LanguageModelV3 } from "@ai-sdk/provider" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { ProviderV2 } from "../../provider" type MantleSDK = { @@ -60,7 +60,7 @@ function selectMantleModel(sdk: MantleSDK, modelID: string) { } export const AmazonBedrockPlugin = define({ - id: "amazon-bedrock", + id: "opencode.provider.amazon-bedrock", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/provider/anthropic.ts b/packages/core/src/plugin/provider/anthropic.ts index efbd50b818..3a8a7c8659 100644 --- a/packages/core/src/plugin/provider/anthropic.ts +++ b/packages/core/src/plugin/provider/anthropic.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const AnthropicPlugin = define({ - id: "anthropic", + id: "opencode.provider.anthropic", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/provider/azure.ts b/packages/core/src/plugin/provider/azure.ts index 2e73e620bf..3269c7d2d9 100644 --- a/packages/core/src/plugin/provider/azure.ts +++ b/packages/core/src/plugin/provider/azure.ts @@ -1,5 +1,5 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { ProviderV2 } from "../../provider" function selectLanguage(sdk: any, modelID: string, useChat: boolean) { @@ -11,7 +11,7 @@ function selectLanguage(sdk: any, modelID: string, useChat: boolean) { } export const AzurePlugin = define({ - id: "azure", + id: "opencode.provider.azure", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { @@ -54,7 +54,7 @@ export const AzurePlugin = define({ }) export const AzureCognitiveServicesPlugin = define({ - id: "azure-cognitive-services", + id: "opencode.provider.azure-cognitive-services", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { const resourceName = process.env.AZURE_COGNITIVE_SERVICES_RESOURCE_NAME diff --git a/packages/core/src/plugin/provider/cerebras.ts b/packages/core/src/plugin/provider/cerebras.ts index 57029cfba7..20e724d707 100644 --- a/packages/core/src/plugin/provider/cerebras.ts +++ b/packages/core/src/plugin/provider/cerebras.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const CerebrasPlugin = define({ - id: "cerebras", + id: "opencode.provider.cerebras", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/provider/cloudflare-ai-gateway.ts b/packages/core/src/plugin/provider/cloudflare-ai-gateway.ts index d416f6f19d..afab0c36df 100644 --- a/packages/core/src/plugin/provider/cloudflare-ai-gateway.ts +++ b/packages/core/src/plugin/provider/cloudflare-ai-gateway.ts @@ -1,10 +1,10 @@ import os from "os" import { InstallationVersion } from "../../installation/version" import { Effect, Option, Schema } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const CloudflareAIGatewayPlugin = define({ - id: "cloudflare-ai-gateway", + id: "opencode.provider.cloudflare-ai-gateway", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/cloudflare-workers-ai.ts b/packages/core/src/plugin/provider/cloudflare-workers-ai.ts index 762ceb4d96..b2db49e4db 100644 --- a/packages/core/src/plugin/provider/cloudflare-workers-ai.ts +++ b/packages/core/src/plugin/provider/cloudflare-workers-ai.ts @@ -1,13 +1,13 @@ import os from "os" import { InstallationVersion } from "../../installation/version" import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { ProviderV2 } from "../../provider" const providerID = ProviderV2.ID.make("cloudflare-workers-ai") export const CloudflareWorkersAIPlugin = define({ - id: "cloudflare-workers-ai", + id: "opencode.provider.cloudflare-workers-ai", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { const item = evt.provider.get(providerID) diff --git a/packages/core/src/plugin/provider/cohere.ts b/packages/core/src/plugin/provider/cohere.ts index 0ca0708577..8b0831604a 100644 --- a/packages/core/src/plugin/provider/cohere.ts +++ b/packages/core/src/plugin/provider/cohere.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const CoherePlugin = define({ - id: "cohere", + id: "opencode.provider.cohere", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/deepinfra.ts b/packages/core/src/plugin/provider/deepinfra.ts index 1b23e08ba4..e8316012ad 100644 --- a/packages/core/src/plugin/provider/deepinfra.ts +++ b/packages/core/src/plugin/provider/deepinfra.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const DeepInfraPlugin = define({ - id: "deepinfra", + id: "opencode.provider.deepinfra", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/dynamic.ts b/packages/core/src/plugin/provider/dynamic.ts index c84a6ed51f..2e51674ba0 100644 --- a/packages/core/src/plugin/provider/dynamic.ts +++ b/packages/core/src/plugin/provider/dynamic.ts @@ -1,10 +1,10 @@ import { Effect } from "effect" import { pathToFileURL } from "url" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { Npm } from "../../npm" export const DynamicProviderPlugin = define({ - id: "dynamic-provider", + id: "opencode.provider.dynamic", effect: Effect.fn(function* (ctx) { const npm = yield* Npm.Service yield* ctx.aisdk.sdk( diff --git a/packages/core/src/plugin/provider/gateway.ts b/packages/core/src/plugin/provider/gateway.ts index f097dcaca3..07249391a0 100644 --- a/packages/core/src/plugin/provider/gateway.ts +++ b/packages/core/src/plugin/provider/gateway.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const GatewayPlugin = define({ - id: "gateway", + id: "opencode.provider.gateway", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/github-copilot.ts b/packages/core/src/plugin/provider/github-copilot.ts index d116058493..2a4881edc0 100644 --- a/packages/core/src/plugin/provider/github-copilot.ts +++ b/packages/core/src/plugin/provider/github-copilot.ts @@ -1,6 +1,6 @@ import { Effect } from "effect" import { ModelV2 } from "../../model" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { ProviderV2 } from "../../provider" function shouldUseResponses(modelID: string) { @@ -12,7 +12,7 @@ function shouldUseResponses(modelID: string) { } export const GithubCopilotPlugin = define({ - id: "github-copilot", + id: "opencode.provider.github-copilot", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { const item = evt.provider.get(ProviderV2.ID.githubCopilot) diff --git a/packages/core/src/plugin/provider/gitlab.ts b/packages/core/src/plugin/provider/gitlab.ts index 8723cdaac2..5cd4b94858 100644 --- a/packages/core/src/plugin/provider/gitlab.ts +++ b/packages/core/src/plugin/provider/gitlab.ts @@ -1,11 +1,11 @@ import os from "os" import { InstallationVersion } from "../../installation/version" import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { ProviderV2 } from "../../provider" export const GitLabPlugin = define({ - id: "gitlab", + id: "opencode.provider.gitlab", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/google-vertex.ts b/packages/core/src/plugin/provider/google-vertex.ts index b87fe61a32..630e353ef0 100644 --- a/packages/core/src/plugin/provider/google-vertex.ts +++ b/packages/core/src/plugin/provider/google-vertex.ts @@ -1,5 +1,5 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { ProviderV2 } from "../../provider" function resolveProject(options: Record) { @@ -55,7 +55,7 @@ function authFetch(fetchWithRuntimeOptions?: unknown) { } export const GoogleVertexPlugin = define({ - id: "google-vertex", + id: "opencode.provider.google-vertex", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { @@ -111,7 +111,7 @@ export const GoogleVertexPlugin = define({ }) export const GoogleVertexAnthropicPlugin = define({ - id: "google-vertex-anthropic", + id: "opencode.provider.google-vertex-anthropic", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/provider/google.ts b/packages/core/src/plugin/provider/google.ts index 476af5b912..3d2013a523 100644 --- a/packages/core/src/plugin/provider/google.ts +++ b/packages/core/src/plugin/provider/google.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const GooglePlugin = define({ - id: "google", + id: "opencode.provider.google", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/groq.ts b/packages/core/src/plugin/provider/groq.ts index 0bddb44309..d84ece2151 100644 --- a/packages/core/src/plugin/provider/groq.ts +++ b/packages/core/src/plugin/provider/groq.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const GroqPlugin = define({ - id: "groq", + id: "opencode.provider.groq", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/kilo.ts b/packages/core/src/plugin/provider/kilo.ts index 5d4c0d65d8..d901474ef2 100644 --- a/packages/core/src/plugin/provider/kilo.ts +++ b/packages/core/src/plugin/provider/kilo.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const KiloPlugin = define({ - id: "kilo", + id: "opencode.provider.kilo", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/provider/llmgateway.ts b/packages/core/src/plugin/provider/llmgateway.ts index 005880c6f3..68c319b673 100644 --- a/packages/core/src/plugin/provider/llmgateway.ts +++ b/packages/core/src/plugin/provider/llmgateway.ts @@ -1,9 +1,9 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { Integration } from "../../integration" export const LLMGatewayPlugin = define({ - id: "llmgateway", + id: "opencode.provider.llmgateway", effect: Effect.fn(function* (ctx) { const integrations = yield* Integration.Service const configured = new Set((yield* integrations.list()).map((integration) => integration.id)) diff --git a/packages/core/src/plugin/provider/mistral.ts b/packages/core/src/plugin/provider/mistral.ts index a731975659..92bc09abec 100644 --- a/packages/core/src/plugin/provider/mistral.ts +++ b/packages/core/src/plugin/provider/mistral.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const MistralPlugin = define({ - id: "mistral", + id: "opencode.provider.mistral", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/nvidia.ts b/packages/core/src/plugin/provider/nvidia.ts index b1b9c9b117..4597f3070a 100644 --- a/packages/core/src/plugin/provider/nvidia.ts +++ b/packages/core/src/plugin/provider/nvidia.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const NvidiaPlugin = define({ - id: "nvidia", + id: "opencode.provider.nvidia", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/provider/openai-compatible.ts b/packages/core/src/plugin/provider/openai-compatible.ts index d602ed0ff9..3854bdcde2 100644 --- a/packages/core/src/plugin/provider/openai-compatible.ts +++ b/packages/core/src/plugin/provider/openai-compatible.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const OpenAICompatiblePlugin = define({ - id: "openai-compatible", + id: "opencode.provider.openai-compatible", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/openai.ts b/packages/core/src/plugin/provider/openai.ts index 990a82554e..1b27511e49 100644 --- a/packages/core/src/plugin/provider/openai.ts +++ b/packages/core/src/plugin/provider/openai.ts @@ -2,7 +2,6 @@ import { createServer } from "node:http" import type { IntegrationOAuthMethodRegistration } from "@opencode-ai/plugin/v2/effect/integration" import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { Deferred, Effect, Option, Schema, Semaphore, Stream } from "effect" -import type { Scope } from "effect" import { Credential } from "../../credential" import { EventV2 } from "../../event" import { InstallationVersion } from "../../installation/version" @@ -159,7 +158,7 @@ const headless = { } satisfies IntegrationOAuthMethodRegistration export const OpenAIPlugin = define({ - id: "openai", + id: "opencode.provider.openai", effect: Effect.fn(function* (ctx) { const events = yield* EventV2.Service const loading = Semaphore.makeUnsafe(1) @@ -225,7 +224,7 @@ export const OpenAIPlugin = define({ }), ) }), -} satisfies PluginInternal.Plugin) +} satisfies PluginInternal.InternalPlugin) function headers(contentType: string) { return { "Content-Type": contentType, "User-Agent": `opencode/${InstallationVersion}` } diff --git a/packages/core/src/plugin/provider/opencode.ts b/packages/core/src/plugin/provider/opencode.ts index bfa84ecd78..1316c3e4d0 100644 --- a/packages/core/src/plugin/provider/opencode.ts +++ b/packages/core/src/plugin/provider/opencode.ts @@ -75,7 +75,7 @@ function oauth(http: HttpClient.HttpClient) { } export const OpencodePlugin = define({ - id: "opencode", + id: "opencode.provider.opencode", effect: Effect.fn(function* (ctx) { const events = yield* EventV2.Service const http = yield* HttpClient.HttpClient diff --git a/packages/core/src/plugin/provider/openrouter.ts b/packages/core/src/plugin/provider/openrouter.ts index 458ea1cd9b..a255844fdb 100644 --- a/packages/core/src/plugin/provider/openrouter.ts +++ b/packages/core/src/plugin/provider/openrouter.ts @@ -1,9 +1,9 @@ import { Effect } from "effect" import { ModelV2 } from "../../model" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const OpenRouterPlugin = define({ - id: "openrouter", + id: "opencode.provider.openrouter", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/provider/perplexity.ts b/packages/core/src/plugin/provider/perplexity.ts index 44c1ef2fc0..9eb5b1e246 100644 --- a/packages/core/src/plugin/provider/perplexity.ts +++ b/packages/core/src/plugin/provider/perplexity.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const PerplexityPlugin = define({ - id: "perplexity", + id: "opencode.provider.perplexity", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/sap-ai-core.ts b/packages/core/src/plugin/provider/sap-ai-core.ts index b6c3a540e6..ede4e31d40 100644 --- a/packages/core/src/plugin/provider/sap-ai-core.ts +++ b/packages/core/src/plugin/provider/sap-ai-core.ts @@ -1,11 +1,11 @@ import { Effect } from "effect" import { pathToFileURL } from "url" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { Npm } from "../../npm" import { ProviderV2 } from "../../provider" export const SapAICorePlugin = define({ - id: "sap-ai-core", + id: "opencode.provider.sap-ai-core", effect: Effect.fn(function* (ctx) { const npm = yield* Npm.Service yield* ctx.aisdk.sdk( diff --git a/packages/core/src/plugin/provider/snowflake-cortex.ts b/packages/core/src/plugin/provider/snowflake-cortex.ts index 788ac63eb0..2e6cc9f9b4 100644 --- a/packages/core/src/plugin/provider/snowflake-cortex.ts +++ b/packages/core/src/plugin/provider/snowflake-cortex.ts @@ -1,5 +1,5 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { ProviderV2 } from "../../provider" type FetchLike = (url: string | URL | Request, init?: RequestInit) => Promise @@ -65,7 +65,7 @@ export function cortexFetch(upstream: FetchLike = fetch) { } export const SnowflakeCortexPlugin = define({ - id: "snowflake-cortex", + id: "opencode.provider.snowflake-cortex", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/togetherai.ts b/packages/core/src/plugin/provider/togetherai.ts index 8022e0de66..d9454cfd24 100644 --- a/packages/core/src/plugin/provider/togetherai.ts +++ b/packages/core/src/plugin/provider/togetherai.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const TogetherAIPlugin = define({ - id: "togetherai", + id: "opencode.provider.togetherai", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/venice.ts b/packages/core/src/plugin/provider/venice.ts index 1a602ffd50..c9d5b163ae 100644 --- a/packages/core/src/plugin/provider/venice.ts +++ b/packages/core/src/plugin/provider/venice.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const VenicePlugin = define({ - id: "venice", + id: "opencode.provider.venice", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/vercel.ts b/packages/core/src/plugin/provider/vercel.ts index 8ff4d14098..0df949b1be 100644 --- a/packages/core/src/plugin/provider/vercel.ts +++ b/packages/core/src/plugin/provider/vercel.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const VercelPlugin = define({ - id: "vercel", + id: "opencode.provider.vercel", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/provider/xai.ts b/packages/core/src/plugin/provider/xai.ts index 8145a3480a..76ec1df1a7 100644 --- a/packages/core/src/plugin/provider/xai.ts +++ b/packages/core/src/plugin/provider/xai.ts @@ -1,9 +1,9 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { ProviderV2 } from "../../provider" export const XAIPlugin = define({ - id: "xai", + id: "opencode.provider.xai", effect: Effect.fn(function* (ctx) { yield* ctx.aisdk.sdk( Effect.fn(function* (evt) { diff --git a/packages/core/src/plugin/provider/zenmux.ts b/packages/core/src/plugin/provider/zenmux.ts index 4562d6bd2e..099a3affca 100644 --- a/packages/core/src/plugin/provider/zenmux.ts +++ b/packages/core/src/plugin/provider/zenmux.ts @@ -1,8 +1,8 @@ import { Effect } from "effect" -import { define } from "../internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const ZenmuxPlugin = define({ - id: "zenmux", + id: "opencode.provider.zenmux", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((evt) => { for (const item of evt.provider.list()) { diff --git a/packages/core/src/plugin/sdk.ts b/packages/core/src/plugin/sdk.ts index 78173a50a9..221fb5fae9 100644 --- a/packages/core/src/plugin/sdk.ts +++ b/packages/core/src/plugin/sdk.ts @@ -14,9 +14,9 @@ const defaultStore = makeStore() /** * Holds the plugins an embedder (the `@opencode-ai/sdk-next` host) contributes, - * so `PluginInternal` can add them on every Location boot through the ordinary - * `ctx.plugin.add` seam — the same path `ConfigExternalPlugin` uses for plugins - * discovered from config. A plugin registered after a Location has booted only + * so `PluginSupervisor` can add them on every Location boot through the ordinary + * generation path that `PluginSupervisor` uses for plugins discovered from + * config. A plugin registered after a Location has booted only * applies to Locations booted afterward, matching config-plugin timing; * embedders register at startup before creating Sessions. * diff --git a/packages/core/src/plugin/skill.ts b/packages/core/src/plugin/skill.ts index c9eca99118..f6ca2ef4af 100644 --- a/packages/core/src/plugin/skill.ts +++ b/packages/core/src/plugin/skill.ts @@ -2,7 +2,7 @@ export * as SkillPlugin from "./skill" -import { define } from "./internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" import { Effect } from "effect" import { AbsolutePath } from "../schema" import { SkillV2 } from "../skill" @@ -25,7 +25,7 @@ const REPORT_DESCRIPTION = "Use when the user wants to report an opencode issue or bug. Collect standard diagnostics, add user-specific reproduction context, and publish the issue with GitHub CLI." export const Plugin = define({ - id: "skill", + id: "opencode.skill", effect: Effect.fn(function* (ctx) { const reportContent = yield* reportContentWithDiagnostics() yield* ctx.skill.transform((draft) => { diff --git a/packages/core/src/plugin/supervisor.ts b/packages/core/src/plugin/supervisor.ts new file mode 100644 index 0000000000..19410e5001 --- /dev/null +++ b/packages/core/src/plugin/supervisor.ts @@ -0,0 +1,270 @@ +export * as PluginSupervisor from "./supervisor" + +import type { Plugin } from "@opencode-ai/plugin/v2/effect" +import { Event } from "@opencode-ai/schema/config" +import { Context, Effect, Fiber, Layer, Schema, Semaphore, Stream } from "effect" +import path from "path" +import { fileURLToPath, pathToFileURL } from "url" +import { Config } from "../config" +import { ConfigPlugin } from "../config/plugin" +import { EventV2 } from "../event" +import { FSUtil } from "../fs-util" +import { Location } from "../location" +import { Npm } from "../npm" +import { PluginV2 } from "../plugin" +import { PluginPromise } from "../plugin/promise" +import { PluginInternal } from "./internal" +import { SdkPlugins } from "./sdk" + +const PluginModule = Schema.Struct({ + default: Schema.Union([ + Schema.Struct({ + id: Schema.String, + effect: Schema.declare((input): input is Plugin["effect"] => typeof input === "function"), + }), + Schema.Struct({ + id: Schema.String, + setup: Schema.declare[0]["setup"]>( + (input): input is Parameters[0]["setup"] => typeof input === "function", + ), + }), + ]), +}) + +const PluginPackage = Schema.Struct({ + exports: Schema.optional(Schema.Unknown), + main: Schema.optional(Schema.String), + module: Schema.optional(Schema.String), +}) + +type Operation = + | { + readonly type: "add" + readonly target: string + readonly options: Record + } + | { + readonly type: "remove" + readonly target: string + } + +type Candidate = + | { + readonly type: "definition" + readonly definition: Plugin + } + | { + readonly type: "package" + readonly specifier: string + readonly options: Record + } + +type ConfiguredPackage = { + readonly operation: Extract + enabled: boolean +} + +function parse(input: ConfigPlugin.Plugin): Operation { + if (typeof input !== "string") { + return { type: "add", target: input.package, options: input.options ?? {} } + } + if (!input.startsWith("-")) return { type: "add", target: input, options: {} } + if (input.length === 1) throw new Error("Plugin remove operation requires a target") + return { type: "remove", target: input.slice(1) } +} + +const scan = Effect.fn("PluginSupervisor.scan")(function* (entries: readonly Config.Entry[]) { + const fs = yield* FSUtil.Service + const location = yield* Location.Service + const discovered = yield* Effect.forEach( + entries.filter((entry): entry is Config.Directory => entry.type === "directory"), + (entry) => discoverDirectory(fs, entry.path), + ).pipe(Effect.map((items) => items.flat())) + const configured = entries + .filter((entry): entry is Config.Document => entry.type === "document") + .flatMap((entry) => + (entry.info.plugins ?? []).map(parse).map((operation) => { + const directory = entry.path ? path.dirname(entry.path) : location.directory + const target = operation.target.startsWith("file://") + ? fileURLToPath(operation.target) + : operation.target.startsWith("./") || operation.target.startsWith("../") + ? path.resolve(directory, operation.target) + : operation.target + return operation.type === "add" ? { ...operation, target } : { type: "remove" as const, target } + }), + ) + // Explicit config is applied last so it can remove auto-discovered packages. + return [...discovered, ...configured] +}) + +const resolve = Effect.fn("PluginSupervisor.resolve")(function* ( + pre: readonly Plugin[], + post: readonly Plugin[], + operations: readonly Operation[], +) { + const plan = apply(pre, post, operations) + return yield* load(plan) +}) + +function apply(pre: readonly Plugin[], post: readonly Plugin[], operations: readonly Operation[]) { + const matches = (selector: string, target: string) => + selector === "*" || (selector.endsWith(".*") ? target.startsWith(selector.slice(0, -1)) : selector === target) + const plugins = [...pre, ...post] + const enabled = new Set(plugins.map((plugin) => plugin.id)) + const packages = new Map() + + for (const operation of operations) { + if (operation.type === "remove") { + plugins.filter((plugin) => matches(operation.target, plugin.id)).forEach((plugin) => enabled.delete(plugin.id)) + packages.forEach((item, target) => { + if (matches(operation.target, target)) item.enabled = false + }) + continue + } + + const matched = plugins.filter((plugin) => matches(operation.target, plugin.id)) + const selectsDefinitions = + matched.length > 0 || + operation.target === "*" || + operation.target.endsWith(".*") || + operation.target.startsWith("opencode.") + if (selectsDefinitions) { + matched.forEach((plugin) => enabled.add(plugin.id)) + packages.forEach((item, target) => { + if (matches(operation.target, target)) item.enabled = true + }) + continue + } + + packages.set(operation.target, { operation, enabled: true }) + } + + const definitions: Candidate[] = pre.flatMap((definition) => + enabled.has(definition.id) ? [{ type: "definition", definition }] : [], + ) + const configured: Candidate[] = Array.from(packages.values()).flatMap((item) => + item.enabled ? [{ type: "package", specifier: item.operation.target, options: item.operation.options }] : [], + ) + const posts: Candidate[] = post.flatMap((definition) => + enabled.has(definition.id) ? [{ type: "definition", definition }] : [], + ) + return [...definitions, ...configured, ...posts] +} + +const load = Effect.fn("PluginSupervisor.load")(function* (plan: readonly Candidate[]) { + return yield* Effect.forEach(plan, (candidate) => { + if (candidate.type === "definition") return Effect.succeed(candidate.definition) + return Effect.gen(function* () { + const npm = yield* Npm.Service + const entrypoint = path.isAbsolute(candidate.specifier) + ? pathToFileURL(candidate.specifier).href + : (yield* npm.add(candidate.specifier)).entrypoint + if (!entrypoint) return + yield* Effect.log({ msg: "loading plugin", id: candidate.specifier, entrypoint }) + const mod = yield* Effect.promise(() => import(entrypoint)) + const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default + const plugin = "effect" in value ? value : PluginPromise.fromPromise(value) + return { + id: plugin.id, + effect: (host) => plugin.effect({ ...host, options: candidate.options }), + } satisfies Plugin + }).pipe(Effect.catchCause(() => Effect.succeed(undefined))) + }).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined))) +}) + +function discoverDirectory(fs: FSUtil.Interface, directory: string) { + return Effect.gen(function* () { + const files = yield* fs + .glob("{plugin,plugins}/*.{ts,js}", { + cwd: directory, + absolute: true, + include: "file", + dot: true, + symlink: true, + }) + .pipe(Effect.orElseSucceed(() => [])) + const directories = yield* fs + .glob("{plugin,plugins}/*", { + cwd: directory, + absolute: true, + include: "all", + dot: true, + symlink: true, + }) + .pipe( + Effect.flatMap((items) => Effect.filter(items, (item) => fs.isDir(item), { concurrency: "unbounded" })), + Effect.orElseSucceed(() => []), + ) + const packages = yield* Effect.forEach(directories.sort(), (directory) => resolvePackageEntrypoint(fs, directory), { + concurrency: "unbounded", + }).pipe(Effect.map((items) => items.filter((item): item is string => item !== undefined))) + return [...files.sort(), ...packages].map((target): Operation => ({ type: "add", target, options: {} })) + }) +} + +const resolvePackageEntrypoint = Effect.fnUntraced(function* (fs: FSUtil.Interface, directory: string) { + const pkg = yield* fs.readJson(path.join(directory, "package.json")).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(PluginPackage)), + Effect.catch(() => Effect.succeed(undefined)), + ) + const exported = typeof pkg?.exports === "string" ? pkg.exports : undefined + const entries = [exported, pkg?.module, pkg?.main, "index.ts", "index.js"] + + return yield* Effect.forEach(entries, (entry) => { + if (!entry) return Effect.succeed(undefined) + const file = path.resolve(directory, entry) + return fs.isFile(file).pipe(Effect.map((exists) => (exists ? file : undefined))) + }).pipe(Effect.map((items) => items.find((item): item is string => item !== undefined))) +}) + +export interface Interface { + readonly ready: Effect.Effect +} + +export class Service extends Context.Service()("@opencode/PluginSupervisor") {} + +const layer = Layer.effect( + Service, + Effect.gen(function* () { + const registry = yield* PluginV2.Service + const sdk = yield* SdkPlugins.Service + const config = yield* Config.Service + const events = yield* EventV2.Service + const lock = Semaphore.makeUnsafe(1) + let applied: string | undefined + const reload = Effect.fn("PluginSupervisor.reload")(() => + lock.withPermit( + Effect.gen(function* () { + // Resolve OpenCode's internal plugins with their privileged Location services. + const internal = yield* PluginInternal.list() + // Combine internal plugins with host-contributed SDK plugins in boot order. + const pre = [...internal.pre, ...sdk.all()] + // Read the current layered config before resolving plugin directives and packages. + const entries = yield* config.entries() + // Skip duplicate watcher notifications and config edits unrelated to plugins. + const operations = yield* scan(entries) + const version = JSON.stringify(operations) + if (version === applied) return + // Apply config operations and load enabled package plugins into one ordered generation. + const plugins = yield* resolve(pre, internal.post, operations) + // Replace the active generation in one scoped, batched activation. + yield* registry.activate(plugins) + applied = version + }), + ), + ) + yield* events.subscribe(Event.Updated).pipe( + Stream.runForEach(() => + reload().pipe(Effect.catchCause((cause) => Effect.logError("failed to reload plugins", { cause }))), + ), + Effect.forkScoped({ startImmediately: true }), + ) + const fiber = yield* reload().pipe( + Effect.withSpan("PluginSupervisor.boot"), + Effect.forkScoped({ startImmediately: true }), + ) + return Service.of({ ready: Fiber.join(fiber) }) + }), +) + +export { layer } diff --git a/packages/core/src/plugin/variant.ts b/packages/core/src/plugin/variant.ts index 7c6e688399..499a2a32bf 100644 --- a/packages/core/src/plugin/variant.ts +++ b/packages/core/src/plugin/variant.ts @@ -2,10 +2,10 @@ export * as VariantPlugin from "./variant" import type { ModelV2Info } from "@opencode-ai/sdk/v2/types" import { Effect } from "effect" -import { define } from "./internal" +import { define } from "@opencode-ai/plugin/v2/effect/plugin" export const Plugin = define({ - id: "variant", + id: "opencode.variant", effect: Effect.fn(function* (ctx) { yield* ctx.catalog.transform((catalog) => { for (const record of catalog.provider.list()) { diff --git a/packages/core/src/state.ts b/packages/core/src/state.ts index ab3457fc18..93dcdb4e5d 100644 --- a/packages/core/src/state.ts +++ b/packages/core/src/state.ts @@ -26,21 +26,32 @@ export interface Transformable { readonly reload: Reload } -const CurrentBatch = Context.Reference | undefined>("@opencode/State/CurrentBatch", { +type Batch = { + active: boolean + readonly reloads: Set +} + +const CurrentBatch = Context.Reference("@opencode/State/CurrentBatch", { defaultValue: () => undefined, }) export function batch(effect: Effect.Effect) { return Effect.gen(function* () { const current = yield* CurrentBatch - if (current) return yield* effect - const reloads = new Set() - const result = yield* effect.pipe(Effect.provideService(CurrentBatch, reloads)) - yield* Effect.forEach(reloads, (reload) => reload(), { discard: true }) - return result + if (current?.active) return yield* effect + const batch: Batch = { active: true, reloads: new Set() } + const exit = yield* effect.pipe(Effect.provideService(CurrentBatch, batch), Effect.exit) + batch.active = false + yield* Effect.forEach(batch.reloads, (reload) => reload(), { discard: true }) + return yield* exit }) } +export const inherit = Effect.fnUntraced(function* () { + const batch = yield* CurrentBatch + return (effect: Effect.Effect) => Effect.provideService(effect, CurrentBatch, batch) +}) + export interface Options { /** Creates the base value for initial state and every scoped-transform reload. */ readonly initial: () => State @@ -100,8 +111,8 @@ export function create(options: Options): Inte transforms = transforms.filter((item) => item !== transform) return Effect.gen(function* () { const batch = yield* CurrentBatch - if (batch) { - batch.add(reload) + if (batch?.active) { + batch.reloads.add(reload) return } yield* materialize() @@ -116,7 +127,7 @@ export function create(options: Options): Inte ) yield* Scope.addFinalizer(scope, dispose) const batch = yield* CurrentBatch - if (batch) batch.add(reload) + if (batch?.active) batch.reloads.add(reload) else yield* reload() return { dispose } }), diff --git a/packages/core/src/tool/apply-patch.ts b/packages/core/src/tool/apply-patch.ts index 2f481d8a0d..6700e6e1ba 100644 --- a/packages/core/src/tool/apply-patch.ts +++ b/packages/core/src/tool/apply-patch.ts @@ -55,7 +55,7 @@ type Prepared = }) export const Plugin = { - id: "core-apply-patch-tool", + id: "opencode.tool.apply-patch", effect: Effect.fn("ApplyPatchTool.Plugin")(function* (ctx: PluginContext) { const mutation = yield* LocationMutation.Service const files = yield* FileMutation.Service diff --git a/packages/core/src/tool/edit.ts b/packages/core/src/tool/edit.ts index 17ff28cfc1..bb9bb4dee9 100644 --- a/packages/core/src/tool/edit.ts +++ b/packages/core/src/tool/edit.ts @@ -86,7 +86,7 @@ export const toModelOutput = (output: Output, oldString: string, newString: stri // TODO: Add LSP notification and diagnostics after V2 LSP runtime exists. export const Plugin = { - id: "core-edit-tool", + id: "opencode.tool.edit", effect: Effect.fn("EditTool.Plugin")(function* (ctx: PluginContext) { const mutation = yield* LocationMutation.Service const files = yield* FileMutation.Service diff --git a/packages/core/src/tool/glob.ts b/packages/core/src/tool/glob.ts index dcea52120f..753e36cab5 100644 --- a/packages/core/src/tool/glob.ts +++ b/packages/core/src/tool/glob.ts @@ -35,7 +35,7 @@ export const toModelOutput = (output: ModelOutput) => { /** Glob leaf that defaults its filesystem root to the active Location. */ export const Plugin = { - id: "core-glob-tool", + id: "opencode.tool.glob", effect: Effect.fn("GlobTool.Plugin")(function* (ctx: PluginContext) { const fs = yield* FSUtil.Service const ripgrep = yield* Ripgrep.Service diff --git a/packages/core/src/tool/grep.ts b/packages/core/src/tool/grep.ts index 35ac537c91..685925aa04 100644 --- a/packages/core/src/tool/grep.ts +++ b/packages/core/src/tool/grep.ts @@ -49,7 +49,7 @@ export const toModelOutput = (output: ModelOutput) => { /** Grep leaf that defaults its filesystem root to the active Location. */ export const Plugin = { - id: "core-grep-tool", + id: "opencode.tool.grep", effect: Effect.fn("GrepTool.Plugin")(function* (ctx: PluginContext) { const fs = yield* FSUtil.Service const ripgrep = yield* Ripgrep.Service diff --git a/packages/core/src/tool/question.ts b/packages/core/src/tool/question.ts index 218edb57e9..9bf4249add 100644 --- a/packages/core/src/tool/question.ts +++ b/packages/core/src/tool/question.ts @@ -43,7 +43,7 @@ export const toModelOutput = ( } export const Plugin = { - id: "core-question-tool", + id: "opencode.tool.question", effect: Effect.fn("QuestionTool.Plugin")(function* (ctx: PluginContext) { const question = yield* QuestionV2.Service const permission = yield* PermissionV2.Service diff --git a/packages/core/src/tool/read.ts b/packages/core/src/tool/read.ts index 16e229d97d..de03a97974 100644 --- a/packages/core/src/tool/read.ts +++ b/packages/core/src/tool/read.ts @@ -31,7 +31,7 @@ const Input = LocationInput const Output = Schema.Union([FileSystem.Content, ReadToolFileSystem.TextPage, ReadToolFileSystem.ListPage]) export const Plugin = { - id: "core-read-tool", + id: "opencode.tool.read", effect: Effect.fn("ReadTool.Plugin")(function* (ctx: PluginContext) { const reader = yield* ReadToolFileSystem.Service const mutation = yield* LocationMutation.Service diff --git a/packages/core/src/tool/shell.ts b/packages/core/src/tool/shell.ts index c3644e4810..cd0c428a61 100644 --- a/packages/core/src/tool/shell.ts +++ b/packages/core/src/tool/shell.ts @@ -99,7 +99,7 @@ const externalCommandDirectories = Effect.fn("ShellTool.externalCommandDirectori }) export const Plugin = { - id: "core-shell-tool", + id: "opencode.tool.shell", effect: Effect.fn("ShellTool.Plugin")(function* (ctx: PluginContext) { const runtime = yield* PluginRuntime.Service const scope = yield* Scope.Scope diff --git a/packages/core/src/tool/skill.ts b/packages/core/src/tool/skill.ts index 1c5d23a047..669e36c4c8 100644 --- a/packages/core/src/tool/skill.ts +++ b/packages/core/src/tool/skill.ts @@ -53,7 +53,7 @@ const unableToLoad = (name: string, error?: unknown) => new ToolFailure({ message: `Unable to load skill ${name}`, error }) export const Plugin = { - id: "core-skill-tool", + id: "opencode.tool.skill", effect: Effect.fn("SkillTool.Plugin")(function* (ctx: PluginContext) { const fs = yield* FSUtil.Service const skills = yield* SkillV2.Service diff --git a/packages/core/src/tool/subagent.ts b/packages/core/src/tool/subagent.ts index 517d1ce65f..50db674ef2 100644 --- a/packages/core/src/tool/subagent.ts +++ b/packages/core/src/tool/subagent.ts @@ -38,7 +38,7 @@ export const description = [ ].join("\n") export const Plugin = { - id: "core-subagent-tool", + id: "opencode.tool.subagent", effect: Effect.fn("SubagentTool.Plugin")(function* (ctx: PluginContext) { const runtime = yield* PluginRuntime.Service const agents = yield* AgentV2.Service diff --git a/packages/core/src/tool/todowrite.ts b/packages/core/src/tool/todowrite.ts index 5f34ebd5aa..279792e38a 100644 --- a/packages/core/src/tool/todowrite.ts +++ b/packages/core/src/tool/todowrite.ts @@ -21,7 +21,7 @@ export type Output = typeof Output.Type export const toModelOutput = (output: Output) => JSON.stringify(output.todos, null, 2) export const Plugin = { - id: "core-todowrite-tool", + id: "opencode.tool.todowrite", effect: Effect.fn("TodoWriteTool.Plugin")(function* (ctx: PluginContext) { const todos = yield* SessionTodo.Service const permission = yield* PermissionV2.Service diff --git a/packages/core/src/tool/webfetch.ts b/packages/core/src/tool/webfetch.ts index efac4a2a75..b729fb43f7 100644 --- a/packages/core/src/tool/webfetch.ts +++ b/packages/core/src/tool/webfetch.ts @@ -113,7 +113,7 @@ const convert = (content: string, contentType: string, format: Format) => { } export const Plugin = { - id: "core-webfetch-tool", + id: "opencode.tool.webfetch", effect: Effect.fn("WebFetchTool.Plugin")(function* (ctx: PluginContext) { const http = yield* HttpClient.HttpClient const permission = yield* PermissionV2.Service diff --git a/packages/core/src/tool/websearch.ts b/packages/core/src/tool/websearch.ts index 80a2422cee..d0c984b89a 100644 --- a/packages/core/src/tool/websearch.ts +++ b/packages/core/src/tool/websearch.ts @@ -188,7 +188,7 @@ const Output = Schema.Struct({ }) export const Plugin = { - id: "core-websearch-tool", + id: "opencode.tool.websearch", effect: Effect.fn("WebSearchTool.Plugin")(function* (ctx: PluginContext) { const http = yield* HttpClient.HttpClient const config = yield* ConfigService diff --git a/packages/core/src/tool/write.ts b/packages/core/src/tool/write.ts index 73885b2187..ca89665be4 100644 --- a/packages/core/src/tool/write.ts +++ b/packages/core/src/tool/write.ts @@ -43,7 +43,7 @@ export const toModelOutput = (output: Output) => // TODO: Add LSP notification and diagnostics after V2 LSP runtime exists. export const Plugin = { - id: "core-write-tool", + id: "opencode.tool.write", effect: Effect.fn("WriteTool.Plugin")(function* (ctx: PluginContext) { const mutation = yield* LocationMutation.Service const files = yield* FileMutation.Service diff --git a/packages/core/test/config/plugin.test.ts b/packages/core/test/config/plugin.test.ts index b72a62df8a..c3c84d8101 100644 --- a/packages/core/test/config/plugin.test.ts +++ b/packages/core/test/config/plugin.test.ts @@ -1,252 +1,225 @@ +import fs from "fs/promises" import path from "path" import { describe, expect } from "bun:test" -import { Effect, Schema } from "effect" +import { define } from "@opencode-ai/plugin/v2/effect" import { AgentV2 } from "@opencode-ai/core/agent" -import { Config } from "@opencode-ai/core/config" -import { ConfigExternalPlugin } from "@opencode-ai/core/config/plugin/external" -import { FSUtil } from "@opencode-ai/core/fs-util" +import { Catalog } from "@opencode-ai/core/catalog" +import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { EventV2 } from "@opencode-ai/core/event" import { Location } from "@opencode-ai/core/location" -import { Npm } from "@opencode-ai/core/npm" +import { LocationServiceMap } from "@opencode-ai/core/location-services" import { PluginV2 } from "@opencode-ai/core/plugin" -import { PluginHost } from "@opencode-ai/core/plugin/host" +import { SdkPlugins } from "@opencode-ai/core/plugin/sdk" +import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor" +import { ModelV2 } from "@opencode-ai/core/model" +import { ProviderV2 } from "@opencode-ai/core/provider" import { AbsolutePath } from "@opencode-ai/core/schema" +import { Effect } from "effect" +import { Database } from "../../src/database/database" +import { tmpdir } from "../fixture/tmpdir" import { testEffect } from "../lib/effect" -import { PluginTestLayer } from "../plugin/fixture" -const it = testEffect(PluginTestLayer) -const decode = Schema.decodeUnknownSync(Config.Info) +const it = testEffect( + AppNodeBuilder.build(LayerNode.group([Database.node, EventV2.node, SdkPlugins.node, LocationServiceMap.node])), +) -describe("ConfigExternalPlugin", () => { - it.live("resolves and loads a configured Promise plugin with options", () => +describe("PluginSupervisor config", () => { + it.live("applies selectors in order", () => + withLocation( + { plugins: ["-opencode.provider.*", "opencode.provider.openai"] }, + Effect.gen(function* () { + const plugins = yield* PluginV2.Service + yield* ready() + expect( + (yield* plugins.list()).map((plugin) => plugin.id).filter((id) => id.startsWith("opencode.provider.")), + ).toEqual([PluginV2.ID.make("opencode.provider.openai")]) + }), + ), + ) + + it.live("loads configured Promise plugins with options", () => + withLocation( + { + plugins: [ + "-*", + { + package: path.join(import.meta.dir, "../plugin/fixtures/config-promise-plugin.ts"), + options: { description: "Loaded from config" }, + }, + ], + }, + Effect.gen(function* () { + yield* ready() + const agents = yield* AgentV2.Service + expect(yield* agents.get(AgentV2.ID.make("configured"))).toMatchObject({ + description: "Loaded from config", + mode: "subagent", + }) + }), + ), + ) + + it.live("loads configured Effect plugins with options", () => + withLocation( + { + plugins: [ + "-*", + { + package: path.join(import.meta.dir, "../plugin/fixtures/config-effect-plugin.ts"), + options: { description: "Effect plugin from config" }, + }, + ], + }, + Effect.gen(function* () { + yield* ready() + const agents = yield* AgentV2.Service + expect(yield* agents.get(AgentV2.ID.make("effect-configured"))).toMatchObject({ + description: "Effect plugin from config", + mode: "subagent", + }) + }), + ), + ) + + it.live("ignores invalid packages and continues loading", () => + withLocation( + { + plugins: [ + "-*", + path.join(import.meta.dir, "../plugin/fixtures/missing-plugin.ts"), + path.join(import.meta.dir, "../plugin/fixtures/invalid-plugin.ts"), + { + package: path.join(import.meta.dir, "../plugin/fixtures/config-promise-plugin.ts"), + options: { description: "Loaded after invalid plugins" }, + }, + ], + }, + Effect.gen(function* () { + yield* ready() + const agents = yield* AgentV2.Service + expect(yield* agents.get(AgentV2.ID.make("configured"))).toMatchObject({ + description: "Loaded after invalid plugins", + }) + }), + ), + ) + + it.live("loads auto-discovered plugin files and packages", () => + withLocation( + undefined, + Effect.gen(function* () { + yield* ready() + const agents = yield* AgentV2.Service + expect(yield* agents.get(AgentV2.ID.make("directory"))).toMatchObject({ + description: "Loaded from plugin directory", + }) + expect(yield* agents.get(AgentV2.ID.make("folder"))).toMatchObject({ + description: "Loaded from plugin folder", + }) + }), + true, + ), + ) + + it.live("applies explicit removals after auto-discovery", () => + withLocation( + { plugins: ["-*"] }, + Effect.gen(function* () { + yield* ready() + const agents = yield* AgentV2.Service + expect(yield* agents.get(AgentV2.ID.make("directory"))).toBeUndefined() + expect(yield* agents.get(AgentV2.ID.make("folder"))).toBeUndefined() + }), + true, + ), + ) + + it.live("loads user plugins before internal post plugins", () => Effect.gen(function* () { - const plugins = yield* PluginV2.Service - const agents = yield* AgentV2.Service - const fs = yield* FSUtil.Service - const location = yield* Location.Service - const npm = yield* Npm.Service - const host = yield* PluginHost.make(plugins) - const document = path.join(import.meta.dir, "opencode.json") + const sdk = yield* SdkPlugins.Service + yield* sdk.register(define({ id: "sdk-order", effect: () => Effect.void })) + yield* withLocation( + { + plugins: [ + path.join(import.meta.dir, "../plugin/fixtures/config-promise-plugin.ts"), + path.join(import.meta.dir, "../plugin/fixtures/variant-source-plugin.ts"), + ], + }, + Effect.gen(function* () { + yield* ready() + const registry = yield* PluginV2.Service + const ids = (yield* registry.list()).map((plugin) => String(plugin.id)) + expect(ids.indexOf("opencode.agent")).toBeLessThan(ids.indexOf("sdk-order")) + expect(ids.indexOf("sdk-order")).toBeLessThan(ids.indexOf("config-promise-plugin")) + expect(ids.indexOf("config-promise-plugin")).toBeLessThan(ids.indexOf("variant-source")) + expect(ids.indexOf("variant-source")).toBeLessThan(ids.indexOf("opencode.config.provider")) + expect(ids.indexOf("opencode.config.provider")).toBeLessThan(ids.indexOf("opencode.variant")) - yield* ConfigExternalPlugin.Plugin.effect(host).pipe( - Effect.provideService(PluginV2.Service, plugins), - Effect.provideService(FSUtil.Service, fs), - Effect.provideService(Location.Service, location), - Effect.provideService(Npm.Service, npm), - Effect.provideService( - Config.Service, - Config.Service.of({ - entries: () => - Effect.succeed([ - new Config.Document({ - type: "document", - path: document, - info: decode({ - plugins: [ - { - package: "../plugin/fixtures/config-promise-plugin.ts", - options: { description: "Loaded from config" }, - }, - ], - }), - }), - ]), - }), - ), + const catalog = yield* Catalog.Service + expect( + (yield* catalog.model.get(ProviderV2.ID.make("configured"), ModelV2.ID.make("glm-5.2")))?.variants, + ).toEqual([ + expect.objectContaining({ id: "high", headers: { custom: "true" } }), + expect.objectContaining({ id: "max", settings: { reasoningEffort: "max" } }), + ]) + }), ) - - expect(yield* waitForAgent(agents, "configured")).toMatchObject({ - description: "Loaded from config", - mode: "subagent", - }) }), ) - it.live("loads a configured Effect plugin with options", () => - Effect.gen(function* () { - const plugins = yield* PluginV2.Service - const agents = yield* AgentV2.Service - const fs = yield* FSUtil.Service - const location = yield* Location.Service - const npm = yield* Npm.Service - const host = yield* PluginHost.make(plugins) + it.live("allows variant generation to be disabled", () => + withLocation( + { + plugins: [path.join(import.meta.dir, "../plugin/fixtures/variant-source-plugin.ts"), "-opencode.variant"], + }, + Effect.gen(function* () { + yield* ready() + const registry = yield* PluginV2.Service + expect((yield* registry.list()).map((plugin) => String(plugin.id))).not.toContain("opencode.variant") - yield* ConfigExternalPlugin.Plugin.effect(host).pipe( - Effect.provideService(PluginV2.Service, plugins), - Effect.provideService(FSUtil.Service, fs), - Effect.provideService(Location.Service, location), - Effect.provideService(Npm.Service, npm), - Effect.provideService( - Config.Service, - Config.Service.of({ - entries: () => - Effect.succeed([ - new Config.Document({ - type: "document", - path: path.join(import.meta.dir, "opencode.json"), - info: decode({ - plugins: [ - { - package: "../plugin/fixtures/config-effect-plugin.ts", - options: { description: "Effect plugin from config" }, - }, - ], - }), - }), - ]), - }), - ), - ) - - expect(yield* waitForAgent(agents, "effect-configured")).toMatchObject({ - description: "Effect plugin from config", - mode: "subagent", - }) - }), - ) - - it.live("ignores invalid plugins and continues loading", () => - Effect.gen(function* () { - const plugins = yield* PluginV2.Service - const agents = yield* AgentV2.Service - const fs = yield* FSUtil.Service - const location = yield* Location.Service - const npm = yield* Npm.Service - const host = yield* PluginHost.make(plugins) - - yield* ConfigExternalPlugin.Plugin.effect(host).pipe( - Effect.provideService(PluginV2.Service, plugins), - Effect.provideService(FSUtil.Service, fs), - Effect.provideService(Location.Service, location), - Effect.provideService(Npm.Service, npm), - Effect.provideService( - Config.Service, - Config.Service.of({ - entries: () => - Effect.succeed([ - new Config.Document({ - type: "document", - path: path.join(import.meta.dir, "opencode.json"), - info: decode({ - plugins: [ - "../plugin/fixtures/missing-plugin.ts", - "../plugin/fixtures/invalid-plugin.ts", - { - package: "../plugin/fixtures/config-promise-plugin.ts", - options: { description: "Loaded after invalid plugins" }, - }, - ], - }), - }), - ]), - }), - ), - ) - - expect(yield* waitForAgent(agents, "configured")).toMatchObject({ - description: "Loaded after invalid plugins", - }) - }), - ) - - it.live("installs and resolves npm plugin packages", () => - Effect.gen(function* () { - const plugins = yield* PluginV2.Service - const agents = yield* AgentV2.Service - const fs = yield* FSUtil.Service - const location = yield* Location.Service - const host = yield* PluginHost.make(plugins) - let installed: string | undefined - const npm = Npm.Service.of({ - add: (spec) => - Effect.sync(() => { - installed = spec - return { - directory: import.meta.dir, - entrypoint: path.join(import.meta.dir, "../plugin/fixtures/config-promise-plugin.ts"), - } - }), - install: () => Effect.void, - which: () => Effect.succeed(undefined), - }) - - yield* ConfigExternalPlugin.Plugin.effect(host).pipe( - Effect.provideService(PluginV2.Service, plugins), - Effect.provideService(FSUtil.Service, fs), - Effect.provideService(Location.Service, location), - Effect.provideService(Npm.Service, npm), - Effect.provideService( - Config.Service, - Config.Service.of({ - entries: () => - Effect.succeed([ - new Config.Document({ - type: "document", - info: decode({ - plugins: [ - { - package: "example-plugin@1.0.0", - options: { description: "Installed from npm" }, - }, - ], - }), - }), - ]), - }), - ), - ) - - expect(yield* waitForAgent(agents, "configured")).toMatchObject({ - description: "Installed from npm", - }) - expect(installed).toBe("example-plugin@1.0.0") - }), - ) - - it.live("loads plugin files from config directories", () => - Effect.gen(function* () { - const plugins = yield* PluginV2.Service - const agents = yield* AgentV2.Service - const fs = yield* FSUtil.Service - const location = yield* Location.Service - const npm = yield* Npm.Service - const host = yield* PluginHost.make(plugins) - - yield* ConfigExternalPlugin.Plugin.effect(host).pipe( - Effect.provideService(PluginV2.Service, plugins), - Effect.provideService(FSUtil.Service, fs), - Effect.provideService(Location.Service, location), - Effect.provideService(Npm.Service, npm), - Effect.provideService( - Config.Service, - Config.Service.of({ - entries: () => - Effect.succeed([ - new Config.Directory({ - type: "directory", - path: AbsolutePath.make(path.join(import.meta.dir, "fixtures")), - }), - ]), - }), - ), - ) - - expect(yield* waitForAgent(agents, "directory")).toMatchObject({ - description: "Loaded from plugin directory", - mode: "subagent", - }) - expect(yield* waitForAgent(agents, "folder")).toMatchObject({ - description: "Loaded from plugin folder", - mode: "subagent", - }) - }), + const catalog = yield* Catalog.Service + expect( + (yield* catalog.model.get(ProviderV2.ID.make("configured"), ModelV2.ID.make("glm-5.2")))?.variants, + ).toEqual([expect.objectContaining({ id: "high", headers: { custom: "true" } })]) + }), + ), ) }) -const waitForAgent = Effect.fnUntraced(function* (agents: AgentV2.Interface, id: string) { - for (let attempt = 0; attempt < 100; attempt++) { - const agent = yield* agents.get(AgentV2.ID.make(id)) - if (agent) return agent - yield* Effect.sleep("10 millis") - } - return yield* Effect.die(`Timed out waiting for agent ${id}`) +const ready = Effect.fnUntraced(function* () { + const supervisor = yield* PluginSupervisor.Service + yield* supervisor.ready }) + +function withLocation(config: unknown, effect: Effect.Effect, fixtures = false) { + return Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.tap((tmp) => + Effect.promise(async () => { + if (fixtures) { + const directory = path.join(tmp.path, ".opencode") + await fs.mkdir(directory, { recursive: true }) + await Promise.all( + ["plugin", "plugins"].map((name) => + fs.symlink(path.join(import.meta.dir, "fixtures", name), path.join(directory, name), "dir"), + ), + ) + } + if (config !== undefined) { + const directory = fixtures ? path.join(tmp.path, ".opencode") : tmp.path + await fs.mkdir(directory, { recursive: true }) + await fs.writeFile(path.join(directory, "opencode.json"), JSON.stringify(config)) + } + }), + ), + Effect.flatMap((tmp) => + effect.pipe( + Effect.scoped, + Effect.provide(LocationServiceMap.Service.get(Location.Ref.make({ directory: AbsolutePath.make(tmp.path) }))), + ), + ), + ) +} diff --git a/packages/core/test/config/reload.test.ts b/packages/core/test/config/reload.test.ts index 3550bddb95..e5f8bd10fc 100644 --- a/packages/core/test/config/reload.test.ts +++ b/packages/core/test/config/reload.test.ts @@ -7,7 +7,6 @@ import { CommandV2 } from "@opencode-ai/core/command" import { Config } from "@opencode-ai/core/config" import { ConfigAgentPlugin } from "@opencode-ai/core/config/plugin/agent" import { ConfigCommandPlugin } from "@opencode-ai/core/config/plugin/command" -import { ConfigExternalPlugin } from "@opencode-ai/core/config/plugin/external" import { ConfigProviderPlugin } from "@opencode-ai/core/config/plugin/provider" import { ConfigReferencePlugin } from "@opencode-ai/core/config/plugin/reference" import { ConfigSkillPlugin } from "@opencode-ai/core/config/plugin/skill" @@ -37,7 +36,7 @@ describe("config plugin reloads", () => { const references = yield* Reference.Service const skills = yield* SkillV2.Service const host = yield* PluginHost.make(plugins) - let entries: Config.Entry[] = [config("first", "First plugin")] + let entries: Config.Entry[] = [config("first")] const service = Config.Service.of({ entries: () => Effect.sync(() => entries) }) const setup = (effect: Effect.Effect) => effect.pipe(Effect.provideService(Config.Service, service)) @@ -47,7 +46,6 @@ describe("config plugin reloads", () => { yield* setup(ConfigSkillPlugin.Plugin.effect(host)) yield* setup(ConfigReferencePlugin.Plugin.effect(host)) yield* setup(ConfigProviderPlugin.Plugin.effect(host)) - yield* setup(ConfigExternalPlugin.Plugin.effect(host)) expect((yield* agents.get(AgentV2.ID.make("first")))?.description).toBe("First agent") expect((yield* commands.get("first"))?.description).toBe("First command") @@ -56,9 +54,8 @@ describe("config plugin reloads", () => { ).toBe(true) expect((yield* references.list()).map((reference) => reference.name)).toEqual(["first"]) expect(yield* catalog.provider.get(ProviderV2.ID.make("first"))).toBeDefined() - expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("First plugin") - entries = [config("second", "Second plugin")] + entries = [config("second")] yield* events.publish(ConfigSchema.Event.Updated, {}) yield* waitUntil( Effect.gen(function* () { @@ -80,12 +77,11 @@ describe("config plugin reloads", () => { expect( (yield* skills.sources()).some((source) => source.type === "directory" && source.path === "/skills/second"), ).toBe(true) - expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("First plugin") }).pipe(Effect.provideService(Global.Service, Global.Service.of(Global.make()))), ) }) -function config(name: string, pluginDescription?: string) { +function config(name: string) { return new Config.Document({ type: "document", path: document, @@ -95,15 +91,6 @@ function config(name: string, pluginDescription?: string) { skills: [`/skills/${name}`], references: { [name]: `/references/${name}` }, providers: { [name]: { models: { chat: { name: `${title(name)} model` } } } }, - plugins: - pluginDescription === undefined - ? [] - : [ - { - package: "../plugin/fixtures/config-promise-plugin.ts", - options: { description: pluginDescription }, - }, - ], }), }) } diff --git a/packages/core/test/location-layer.test.ts b/packages/core/test/location-layer.test.ts index 0f17b0dd2b..be6e150680 100644 --- a/packages/core/test/location-layer.test.ts +++ b/packages/core/test/location-layer.test.ts @@ -1,7 +1,8 @@ import fs from "fs/promises" import path from "path" import { describe, expect } from "bun:test" -import { DateTime, Effect, Equal, Hash, Schema } from "effect" +import { Config } from "@opencode-ai/schema/config" +import { Context, DateTime, Effect, Equal, Hash, Schema, Stream } from "effect" import { define } from "@opencode-ai/plugin/v2/effect" import { AgentV2 } from "@opencode-ai/core/agent" import { Catalog } from "@opencode-ai/core/catalog" @@ -10,6 +11,7 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { LocationServiceMap } from "@opencode-ai/core/location-services" import { Location } from "@opencode-ai/core/location" import { PluginV2 } from "@opencode-ai/core/plugin" +import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor" import { ModelV2 } from "@opencode-ai/core/model" import { ProjectV2 } from "@opencode-ai/core/project" import { ProviderV2 } from "@opencode-ai/core/provider" @@ -27,6 +29,124 @@ import { ToolRegistry } from "../src/tool/registry" const it = testEffect(AppNodeBuilder.build(LayerNode.group([Database.node, EventV2.node, LocationServiceMap.node]))) describe("LocationServiceMap", () => { + it.live("applies ordered plugin config operations during boot", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((dir) => + Effect.gen(function* () { + yield* Effect.promise(() => + fs.writeFile(path.join(dir.path, "opencode.json"), JSON.stringify({ plugins: ["-*", "opencode.agent"] })), + ) + const plugins = yield* Effect.gen(function* () { + const plugins = yield* PluginV2.Service + yield* (yield* PluginSupervisor.Service).ready + return yield* plugins.list() + }).pipe( + Effect.scoped, + Effect.provide( + LocationServiceMap.Service.get(Location.Ref.make({ directory: AbsolutePath.make(dir.path) })), + ), + ) + + expect(plugins.map((plugin) => plugin.id)).toEqual([PluginV2.ID.make("opencode.agent")]) + }), + ), + ), + ) + + it.live("reloads the plugin generation after config updates", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((dir) => + Effect.gen(function* () { + const file = path.join(dir.path, "opencode.json") + yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ plugins: ["-*", "opencode.agent"] }))) + yield* Effect.gen(function* () { + const registry = yield* PluginV2.Service + const supervisor = yield* PluginSupervisor.Service + yield* supervisor.ready + expect((yield* registry.list()).map((plugin) => String(plugin.id))).toEqual(["opencode.agent"]) + + yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ plugins: ["-*", "opencode.command"] }))) + for (let attempt = 0; attempt < 100; attempt++) { + if ((yield* registry.list()).some((plugin) => plugin.id === "opencode.command")) break + yield* Effect.sleep("20 millis") + } + + expect((yield* registry.list()).map((plugin) => String(plugin.id))).toEqual(["opencode.command"]) + + yield* Effect.promise(() => + fs.writeFile( + file, + JSON.stringify({ + plugins: ["-*", path.join(import.meta.dir, "plugin/fixtures/failing-plugin.ts")], + }), + ), + ) + for (let attempt = 0; attempt < 100; attempt++) { + if ((yield* registry.list()).length === 0) break + yield* Effect.sleep("20 millis") + } + expect(yield* registry.list()).toEqual([]) + + yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ plugins: ["-*", "opencode.agent"] }))) + for (let attempt = 0; attempt < 100; attempt++) { + if ((yield* registry.list()).some((plugin) => plugin.id === "opencode.agent")) break + yield* Effect.sleep("20 millis") + } + expect((yield* registry.list()).map((plugin) => String(plugin.id))).toEqual(["opencode.agent"]) + }).pipe( + Effect.scoped, + Effect.provide( + LocationServiceMap.Service.get(Location.Ref.make({ directory: AbsolutePath.make(dir.path) })), + ), + ) + }), + ), + ), + ) + + it.live("routes located events only to their location", () => + Effect.acquireRelease( + Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), + (dirs) => Effect.promise(() => Promise.all(dirs.map((dir) => dir[Symbol.asyncDispose]())).then(() => undefined)), + ).pipe( + Effect.flatMap(([first, second]) => + Effect.scoped( + Effect.gen(function* () { + const locations = yield* LocationServiceMap.Service + const events = yield* EventV2.Service + const firstRef = Location.Ref.make({ directory: AbsolutePath.make(first.path) }) + const secondRef = Location.Ref.make({ directory: AbsolutePath.make(second.path) }) + const firstContext = yield* locations.contextEffect(firstRef) + const secondContext = yield* locations.contextEffect(secondRef) + const received = { first: 0, second: 0 } + yield* events.subscribe(Config.Event.Updated).pipe( + Stream.runForEach(() => Effect.sync(() => received.first++)), + Effect.provideContext(firstContext), + Effect.forkScoped({ startImmediately: true }), + ) + yield* events.subscribe(Config.Event.Updated).pipe( + Stream.runForEach(() => Effect.sync(() => received.second++)), + Effect.provideContext(secondContext), + Effect.forkScoped({ startImmediately: true }), + ) + yield* Effect.sleep("10 millis") + + yield* events.publish(Config.Event.Updated, {}, { location: firstRef }) + yield* Effect.sleep("10 millis") + + expect(received).toEqual({ first: 1, second: 0 }) + }), + ), + ), + ), + ) + it.live("reuses cached services for constructed and decoded location refs", () => Effect.acquireRelease( Effect.promise(() => tmpdir()), @@ -64,7 +184,7 @@ describe("LocationServiceMap", () => { const catalog = yield* Catalog.Service yield* catalog.transform((editor) => editor.provider.update(providerID, () => {})) const registry = yield* ToolRegistry.Service - // Tool plugins register during the forked PluginInternal boot; wait for + // Tool plugins register during the forked PluginSupervisor boot; wait for // every expected tool rather than relying on batch ordering. yield* Effect.forEach( [ @@ -257,7 +377,7 @@ describe("LocationServiceMap", () => { }) .pipe(Effect.asVoid), }) - yield* plugins.add(PluginV2.ID.make(reviewer.id), reviewer.effect) + yield* plugins.activate([{ id: PluginV2.ID.make(reviewer.id), effect: reviewer.effect }]) expect(yield* (yield* AgentV2.Service).get(AgentV2.ID.make("reviewer"))).toMatchObject({ description: "Reviews code", diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 266d487862..8917171929 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -1,5 +1,5 @@ import { describe, expect } from "bun:test" -import { Effect, Exit, Fiber, Schema, Stream } from "effect" +import { Context, Effect, Exit, Fiber, Schema, Stream } from "effect" import { define } from "@opencode-ai/plugin/v2/effect" import { Config as ConfigSchema } from "@opencode-ai/schema/config" import { AgentV2 } from "@opencode-ai/core/agent" @@ -16,6 +16,8 @@ import { PluginTestLayer } from "./plugin/fixture" const it = testEffect(PluginTestLayer) +class Secret extends Context.Service()("@opencode/test/PluginSecret") {} + describe("PluginV2", () => { it.live("exposes public events through the plugin context", () => Effect.gen(function* () { @@ -35,43 +37,15 @@ describe("PluginV2", () => { }), ) - it.effect("waits for a plugin and returns immediately once active", () => - Effect.gen(function* () { - const plugins = yield* PluginV2.Service - const id = PluginV2.ID.make("waited") - const waiting = yield* plugins.wait(id).pipe(Effect.forkChild) - - yield* plugins.add(id, () => Effect.void) - yield* Fiber.join(waiting) - yield* plugins.wait(id) - }), - ) - - it.effect("propagates plugin activation defects to waiters", () => - Effect.gen(function* () { - const plugins = yield* PluginV2.Service - const id = PluginV2.ID.make("failed") - const waiting = yield* plugins.wait(id).pipe(Effect.exit, Effect.forkChild) - - const added = yield* plugins.add(id, () => Effect.die("boom")).pipe(Effect.exit) - const pending = yield* Fiber.join(waiting) - const later = yield* plugins.wait(id).pipe(Effect.exit) - - expect(Exit.isFailure(added)).toBe(true) - expect(Exit.isFailure(pending)).toBe(true) - expect(Exit.isFailure(later)).toBe(true) - }), - ) - - it.effect("adds, replaces, and removes plugins", () => + it.effect("skips identical generations and replaces changed plugin IDs", () => Effect.gen(function* () { const plugins = yield* PluginV2.Service const agents = yield* AgentV2.Service let description = "first" - const managed = () => + const managed = (id: string) => define({ - id: "managed", + id, effect: (ctx) => ctx.agent .transform((agents) => @@ -82,19 +56,101 @@ describe("PluginV2", () => { .pipe(Effect.asVoid), }) - yield* plugins.add(PluginV2.ID.make("managed"), managed().effect) + yield* plugins.activate([managed("managed")]) expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("first") description = "second" - yield* plugins.add(PluginV2.ID.make("managed"), managed().effect) + yield* plugins.activate([managed("managed")]) + expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("first") + + yield* plugins.activate([managed("managed-next")]) expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("second") - yield* plugins.remove(PluginV2.ID.make("managed")) + yield* plugins.activate([]) expect(yield* agents.get(AgentV2.ID.make("configured"))).toBeUndefined() }), ) + it.effect("rejects duplicate IDs before replacing the active generation", () => + Effect.gen(function* () { + const plugins = yield* PluginV2.Service + const active = PluginV2.ID.make("active") + const duplicate = PluginV2.ID.make("duplicate") + yield* plugins.activate([{ id: active, effect: () => Effect.void }]) + + const result = yield* plugins + .activate([ + { id: duplicate, effect: () => Effect.void }, + { id: duplicate, effect: () => Effect.void }, + ]) + .pipe(Effect.exit) + + expect(Exit.isFailure(result)).toBe(true) + expect(yield* plugins.list()).toEqual([{ id: active }]) + }), + ) + + it.effect("retries the same generation after materialization fails", () => + Effect.gen(function* () { + const plugins = yield* PluginV2.Service + let fail = true + const plugin = define({ + id: "retry", + effect: (ctx) => + ctx.agent + .transform(() => { + if (fail) throw new Error("materialization failed") + }) + .pipe(Effect.asVoid), + }) + + expect(Exit.isFailure(yield* plugins.activate([plugin]).pipe(Effect.exit))).toBe(true) + fail = false + yield* plugins.activate([plugin]) + + expect(yield* plugins.list()).toEqual([{ id: PluginV2.ID.make("retry") }]) + }), + ) + + it.effect("closes the previous generation in reverse order", () => + Effect.gen(function* () { + const plugins = yield* PluginV2.Service + const closed: string[] = [] + yield* plugins.activate( + ["first", "second"].map((id) => ({ + id: PluginV2.ID.make(id), + effect: () => Effect.addFinalizer(() => Effect.sync(() => closed.push(id))), + })), + ) + + yield* plugins.activate([]) + + expect(closed).toEqual(["second", "first"]) + }), + ) + + it.effect("isolates plugins from ambient services", () => + Effect.gen(function* () { + const plugins = yield* PluginV2.Service + let visible = true + const plugin = define({ + id: "isolated", + effect: () => + Effect.serviceOption(Secret).pipe( + Effect.tap((secret) => Effect.sync(() => (visible = secret._tag === "Some"))), + Effect.asVoid, + ), + }) + + yield* plugins + .activate([{ id: PluginV2.ID.make(plugin.id), effect: plugin.effect }]) + .pipe(Effect.provideService(Secret, "secret")) + + expect(visible).toBe(false) + }), + ) + it.effect("registers location tools through the plugin context", () => Effect.gen(function* () { const plugins = yield* PluginV2.Service @@ -114,12 +170,12 @@ describe("PluginV2", () => { .pipe(Effect.orDie), }) - yield* plugins.add(PluginV2.ID.make(plugin.id), plugin.effect) + yield* plugins.activate([{ id: PluginV2.ID.make(plugin.id), effect: plugin.effect }]) expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toContain( "plugin_tool", ) - yield* plugins.remove(PluginV2.ID.make(plugin.id)) + yield* plugins.activate([]) expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).not.toContain( "plugin_tool", ) @@ -149,7 +205,7 @@ describe("PluginV2", () => { }), }) - yield* plugins.add(PluginV2.ID.make(plugin.id), plugin.effect) + yield* plugins.activate([{ id: PluginV2.ID.make(plugin.id), effect: plugin.effect }]) expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toEqual([ "plain", @@ -201,7 +257,7 @@ describe("PluginV2", () => { }), }) - yield* plugins.add(PluginV2.ID.make(plugin.id), plugin.effect) + yield* plugins.activate([{ id: PluginV2.ID.make(plugin.id), effect: plugin.effect }]) const materialized = yield* registry.materialize({ model: testModel }) const settlement = yield* materialized.settle({ diff --git a/packages/core/test/plugin/fixtures/failing-plugin.ts b/packages/core/test/plugin/fixtures/failing-plugin.ts new file mode 100644 index 0000000000..4daac0acd0 --- /dev/null +++ b/packages/core/test/plugin/fixtures/failing-plugin.ts @@ -0,0 +1,7 @@ +import { define } from "@opencode-ai/plugin/v2/effect" +import { Effect } from "effect" + +export default define({ + id: "failing-plugin", + effect: () => Effect.die("plugin failed"), +}) diff --git a/packages/core/test/plugin/fixtures/variant-source-plugin.ts b/packages/core/test/plugin/fixtures/variant-source-plugin.ts new file mode 100644 index 0000000000..087a714227 --- /dev/null +++ b/packages/core/test/plugin/fixtures/variant-source-plugin.ts @@ -0,0 +1,29 @@ +import { define } from "@opencode-ai/plugin/v2/effect" +import { Effect } from "effect" + +export default define({ + id: "variant-source", + effect: (ctx) => + ctx.catalog + .transform((catalog) => { + catalog.provider.update("configured", (provider) => { + provider.api = { type: "aisdk", package: "@ai-sdk/openai-compatible" } + }) + catalog.model.update("configured", "glm-5.2", (model) => { + model.api = { + id: "glm-5.2", + type: "aisdk", + package: "@ai-sdk/openai-compatible", + } + model.variants = [ + { + id: "high", + settings: {}, + headers: { custom: "true" }, + body: {}, + }, + ] + }) + }) + .pipe(Effect.asVoid), +}) diff --git a/packages/core/test/plugin/host.ts b/packages/core/test/plugin/host.ts index 63ac18e31e..8ef98c6530 100644 --- a/packages/core/test/plugin/host.ts +++ b/packages/core/test/plugin/host.ts @@ -59,8 +59,6 @@ export function host(overrides: Overrides = {}): PluginContext { }, plugin: overrides.plugin ?? { list: () => Effect.die("unused plugin.list"), - add: () => Effect.die("unused plugin.add"), - remove: () => Effect.die("unused plugin.remove"), }, reference: overrides.reference ?? { list: () => Effect.die("unused reference.list"), diff --git a/packages/core/test/plugin/provider-kilo.test.ts b/packages/core/test/plugin/provider-kilo.test.ts index b34ceb2d5b..bec50272ef 100644 --- a/packages/core/test/plugin/provider-kilo.test.ts +++ b/packages/core/test/plugin/provider-kilo.test.ts @@ -19,7 +19,9 @@ const addPlugin = Effect.fn(function* () { describe("KiloPlugin", () => { it.effect("is registered so legacy referer headers can be applied", () => - Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("kilo"))), + Effect.sync(() => + expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.kilo")), + ), ) it.effect("applies legacy referer headers only to kilo", () => diff --git a/packages/core/test/plugin/provider-llmgateway.test.ts b/packages/core/test/plugin/provider-llmgateway.test.ts index 5dce7cdcf7..8cc45c6027 100644 --- a/packages/core/test/plugin/provider-llmgateway.test.ts +++ b/packages/core/test/plugin/provider-llmgateway.test.ts @@ -21,7 +21,9 @@ const addPlugin = Effect.fn(function* () { describe("LLMGatewayPlugin", () => { it.effect("is registered so legacy referer headers can be applied", () => - Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("llmgateway"))), + Effect.sync(() => + expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.llmgateway")), + ), ) it.effect("applies legacy referer headers only to enabled llmgateway", () => diff --git a/packages/core/test/plugin/provider-nvidia.test.ts b/packages/core/test/plugin/provider-nvidia.test.ts index 260ffff689..baf763c8d1 100644 --- a/packages/core/test/plugin/provider-nvidia.test.ts +++ b/packages/core/test/plugin/provider-nvidia.test.ts @@ -19,7 +19,9 @@ const addPlugin = Effect.fn(function* () { describe("NvidiaPlugin", () => { it.effect("is registered so legacy referer headers can be applied", () => - Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("nvidia"))), + Effect.sync(() => + expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.nvidia")), + ), ) it.effect("applies NVIDIA tracking headers only to nvidia", () => diff --git a/packages/core/test/plugin/provider-openrouter.test.ts b/packages/core/test/plugin/provider-openrouter.test.ts index d611f40363..e0be8b5fa7 100644 --- a/packages/core/test/plugin/provider-openrouter.test.ts +++ b/packages/core/test/plugin/provider-openrouter.test.ts @@ -22,7 +22,9 @@ const addPlugin = Effect.fn(function* () { describe("OpenRouterPlugin", () => { it.effect("is registered so legacy OpenRouter behavior can be applied", () => - Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("openrouter"))), + Effect.sync(() => + expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.openrouter")), + ), ) it.effect("applies legacy referer headers only to openrouter", () => diff --git a/packages/core/test/plugin/provider-snowflake-cortex.test.ts b/packages/core/test/plugin/provider-snowflake-cortex.test.ts index cd67feb40e..a1265b6a8f 100644 --- a/packages/core/test/plugin/provider-snowflake-cortex.test.ts +++ b/packages/core/test/plugin/provider-snowflake-cortex.test.ts @@ -43,9 +43,11 @@ function withEnv(vars: Record, effect: () = describe("SnowflakeCortexPlugin", () => { it.effect("is registered in ProviderPlugins before OpenAICompatiblePlugin", () => Effect.sync(() => { - expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("snowflake-cortex")) + expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.snowflake-cortex")) const ids = ProviderPlugins.map((p) => p.id) - expect(ids.indexOf("snowflake-cortex")).toBeLessThan(ids.indexOf("openai-compatible")) + expect(ids.indexOf("opencode.provider.snowflake-cortex")).toBeLessThan( + ids.indexOf("opencode.provider.openai-compatible"), + ) }), ) diff --git a/packages/core/test/plugin/provider-zenmux.test.ts b/packages/core/test/plugin/provider-zenmux.test.ts index b9d34a1f5b..0ce286d612 100644 --- a/packages/core/test/plugin/provider-zenmux.test.ts +++ b/packages/core/test/plugin/provider-zenmux.test.ts @@ -24,7 +24,9 @@ function required(value: T | undefined): T { describe("ZenmuxPlugin", () => { it.effect("is registered so legacy referer headers can be applied", () => - Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("zenmux"))), + Effect.sync(() => + expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.zenmux")), + ), ) it.effect("applies the exact legacy Zenmux headers", () => diff --git a/packages/opencode/src/agent/agent.ts b/packages/opencode/src/agent/agent.ts index 536a642fe4..cd0eb32f7c 100644 --- a/packages/opencode/src/agent/agent.ts +++ b/packages/opencode/src/agent/agent.ts @@ -29,8 +29,8 @@ import { ProviderV2 } from "@opencode-ai/core/provider" import { ModelV2 } from "@opencode-ai/core/model" import { LocationServiceMap, locationServiceMapLayer } from "@opencode-ai/core/location-services" import { Reference } from "@opencode-ai/core/reference" +import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor" import { Location } from "@opencode-ai/core/location" -import { PluginV2 } from "@opencode-ai/core/plugin" export const Info = Schema.Struct({ name: Schema.String, @@ -101,7 +101,7 @@ const layer = Layer.effect( const skillDirs = yield* skill.dirs() const referenceDirs = Object.keys(cfg.references ?? cfg.reference ?? {}).length ? yield* Effect.gen(function* () { - yield* (yield* PluginV2.Service).wait(PluginV2.ID.make("core/config-reference")) + yield* (yield* PluginSupervisor.Service).ready return (yield* (yield* Reference.Service).list()).map((reference) => reference.path) }).pipe(Effect.provide(locations.get(Location.Ref.make({ directory: AbsolutePath.make(ctx.directory) })))) : [] diff --git a/packages/plugin/src/v2/effect/plugin.ts b/packages/plugin/src/v2/effect/plugin.ts index 77629bdfca..66f57caf60 100644 --- a/packages/plugin/src/v2/effect/plugin.ts +++ b/packages/plugin/src/v2/effect/plugin.ts @@ -11,7 +11,4 @@ export function define(plugin: Plugin) { return plugin } -export interface PluginDomain extends PluginApi { - readonly add: (plugin: Plugin) => Effect.Effect - readonly remove: (id: string) => Effect.Effect -} +export interface PluginDomain extends PluginApi {} diff --git a/packages/plugin/src/v2/promise/plugin.ts b/packages/plugin/src/v2/promise/plugin.ts index afb6c16f0e..eb91b9df53 100644 --- a/packages/plugin/src/v2/promise/plugin.ts +++ b/packages/plugin/src/v2/promise/plugin.ts @@ -10,7 +10,4 @@ export function define(plugin: Plugin) { return plugin } -export interface PluginDomain extends PluginApi { - readonly add: (plugin: Plugin) => Promise - readonly remove: (id: string) => Promise -} +export interface PluginDomain extends PluginApi {} From c3d26c4912c1664d2371d5fc194cd667e8654f8a Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 15:53:50 -0400 Subject: [PATCH 65/82] feat(core): improve runtime observability --- packages/cli/src/index.ts | 14 ++-- packages/core/src/event-logger.ts | 24 +++++++ .../core/src/filesystem/location-watcher.ts | 65 ++++++++++--------- packages/core/src/snapshot.ts | 2 +- packages/core/test/event-logger.test.ts | 45 +++++++++++++ packages/server/src/routes.ts | 2 + 6 files changed, 112 insertions(+), 40 deletions(-) create mode 100644 packages/core/src/event-logger.ts create mode 100644 packages/core/test/event-logger.test.ts diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 64116b9b76..5514c3816e 100755 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,10 +1,10 @@ #!/usr/bin/env bun -import { NodeFileSystem, NodeRuntime, NodeServices } from "@effect/platform-node" -import { Effect, Layer, Logger, References } from "effect" +import { NodeRuntime, NodeServices } from "@effect/platform-node" +import { Effect } from "effect" import { Commands } from "./commands/commands" import { Runtime } from "./framework/runtime" -import { Logging } from "@opencode-ai/core/observability/logging" +import { Observability } from "@opencode-ai/core/observability" import { Updater } from "./services/updater" import { InstallationChannel, InstallationVersion, InstallationLocal } from "@opencode-ai/core/installation/version" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" @@ -12,12 +12,6 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Global } from "@opencode-ai/core/global" import { AppProcess } from "@opencode-ai/core/process" -const LoggingLayer = Logger.layer(Logging.loggers(), { mergeWithExisting: false }).pipe( - Layer.provide(NodeFileSystem.layer), - Layer.orDie, - Layer.merge(Layer.succeed(References.MinimumLogLevel, Logging.minimumLogLevel())), -) - const Handlers = Runtime.handlers(Commands, { $: () => import("./commands/handlers/default"), api: () => import("./commands/handlers/api"), @@ -53,7 +47,7 @@ Effect.logInfo("cli starting", { Effect.annotateLogs({ role: "cli" }), Effect.provide(Updater.layer), Effect.provide(AppNodeBuilder.build(LayerNode.group([Global.node, AppProcess.node]))), - Effect.provide(LoggingLayer), + Effect.provide(Observability.layer), Effect.provide(NodeServices.layer), Effect.scoped, Effect.tap(() => Effect.sync(() => process.exit(0))), diff --git a/packages/core/src/event-logger.ts b/packages/core/src/event-logger.ts new file mode 100644 index 0000000000..f07c96320e --- /dev/null +++ b/packages/core/src/event-logger.ts @@ -0,0 +1,24 @@ +export * as EventLogger from "./event-logger" + +import { Effect, Layer } from "effect" +import { makeGlobalNode } from "./effect/app-node" +import { EventV2 } from "./event" + +const Types = new Set([ + "agent.updated", + "catalog.updated", + "command.updated", + "config.updated", +]) + +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + const events = yield* EventV2.Service + const unsubscribe = yield* events.listen((event) => + Types.has(event.type) ? Effect.logInfo("event", { event }) : Effect.void, + ) + yield* Effect.addFinalizer(() => unsubscribe) + }), +) + +export const node = makeGlobalNode({ name: "event-logger", layer, deps: [EventV2.node] }) diff --git a/packages/core/src/filesystem/location-watcher.ts b/packages/core/src/filesystem/location-watcher.ts index 1566d3d8ff..613b43b5f8 100644 --- a/packages/core/src/filesystem/location-watcher.ts +++ b/packages/core/src/filesystem/location-watcher.ts @@ -34,46 +34,53 @@ const layer = Layer.effect( const fs = yield* FSUtil.Service const git = yield* Git.Service const configService = yield* Config.Service - const config = (yield* configService.entries()) - .filter((entry): entry is Config.Document => entry.type === "document") - .flatMap((item) => item.info.watcher?.ignore ?? []) const publish = (update: { type: "create" | "update" | "delete"; path: string }) => events.publish(FileSystem.Event.Changed, { file: update.path, event: update.type === "create" ? "add" : update.type === "update" ? "change" : "unlink", }) - if (path.resolve(location.directory) !== path.resolve(os.homedir())) { - yield* watcher - .subscribe({ - path: location.directory, - type: "directory", - ignore: [...Ignore.PATTERNS, ...config, ...protecteds(location.directory)], - }) - .pipe(Stream.runForEach(publish), Effect.forkScoped({ startImmediately: true })) - } else { - yield* Effect.logInfo("location watcher skipped home directory", { directory: location.directory }) - } + yield* Effect.gen(function* () { + const config = (yield* configService.entries()) + .filter((entry): entry is Config.Document => entry.type === "document") + .flatMap((item) => item.info.watcher?.ignore ?? []) + const home = path.resolve(location.directory) === path.resolve(os.homedir()) - if (location.vcs?.type === "git") { - const resolved = (yield* git.repo.discover(location.directory))?.gitDirectory - const vcs = resolved ? yield* fs.realPath(resolved).pipe(Effect.catch(() => Effect.succeed(resolved))) : undefined - if (vcs && !config.includes(".git") && !config.includes(vcs) && (!resolved || !config.includes(resolved))) { - const ignore = (yield* fs.readDirectoryEntries(vcs).pipe(Effect.catch(() => Effect.succeed([])))).flatMap( - (entry) => (entry.name === "HEAD" ? [] : [entry.name]), - ) + if (!home) { yield* watcher - .subscribe({ path: vcs, type: "directory", ignore }) - .pipe(Stream.runForEach(publish), Effect.forkScoped({ startImmediately: true })) + .subscribe({ + path: location.directory, + type: "directory", + ignore: [...Ignore.PATTERNS, ...config, ...protecteds(location.directory)], + }) + .pipe(Stream.runForEach(publish), Effect.forkScoped) } - } + if (home) { + yield* Effect.logInfo("location watcher skipped home directory", { directory: location.directory }) + } + + if (location.vcs?.type === "git") { + const resolved = (yield* git.repo.discover(location.directory))?.gitDirectory + const vcs = resolved + ? yield* fs.realPath(resolved).pipe(Effect.catch(() => Effect.succeed(resolved))) + : undefined + if (vcs && !config.includes(".git") && !config.includes(vcs) && (!resolved || !config.includes(resolved))) { + const ignore = (yield* fs.readDirectoryEntries(vcs).pipe(Effect.catch(() => Effect.succeed([])))).flatMap( + (entry) => (entry.name === "HEAD" ? [] : [entry.name]), + ) + yield* watcher + .subscribe({ path: vcs, type: "directory", ignore }) + .pipe(Stream.runForEach(publish), Effect.forkScoped) + } + } + }).pipe( + Effect.withSpan("LocationWatcher.start", { attributes: { directory: location.directory } }), + Effect.catchCause((cause) => Effect.logError("failed to init location watcher service", { cause })), + Effect.forkScoped, + ) return Service.of({}) - }).pipe( - Effect.catchCause((cause) => - Effect.logError("failed to init location watcher service", { cause }).pipe(Effect.as(Service.of({}))), - ), - ), + }), ) export const node = makeLocationNode({ diff --git a/packages/core/src/snapshot.ts b/packages/core/src/snapshot.ts index 79a2b6cda8..9843e69226 100644 --- a/packages/core/src/snapshot.ts +++ b/packages/core/src/snapshot.ts @@ -224,7 +224,7 @@ const layer = Layer.effect( }) return Service.of({ capture, files, diff, preview, restore, checkout }) - }), + }).pipe(Effect.withSpan("Snapshot.boot")), ) export const node = makeLocationNode({ diff --git a/packages/core/test/event-logger.test.ts b/packages/core/test/event-logger.test.ts new file mode 100644 index 0000000000..ef48d7abbd --- /dev/null +++ b/packages/core/test/event-logger.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Layer, Logger } from "effect" +import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { Database } from "@opencode-ai/core/database/database" +import { EventV2 } from "@opencode-ai/core/event" +import { EventLogger } from "@opencode-ai/core/event-logger" +import { Agent } from "@opencode-ai/schema/agent" +import { Catalog } from "@opencode-ai/schema/catalog" +import { Command } from "@opencode-ai/schema/command" +import { Config } from "@opencode-ai/schema/config" +import { McpEvent } from "@opencode-ai/schema/mcp-event" + +const UnlistedUpdated = EventV2.ephemeral({ type: "test.updated", schema: {} }) + +describe("EventLogger", () => { + test("logs explicitly listed updated events", async () => { + const output = new Array>() + const logger = Logger.map(Logger.formatStructured, (entry) => { + output.push(entry) + }) + + await Effect.gen(function* () { + const events = yield* EventV2.Service + yield* events.publish(Agent.Event.Updated, {}) + yield* events.publish(Catalog.Event.Updated, {}) + yield* events.publish(Command.Event.Updated, {}) + yield* events.publish(Config.Event.Updated, {}) + yield* events.publish(McpEvent.StatusChanged, { server: "example" }) + yield* events.publish(UnlistedUpdated, {}) + }).pipe( + Effect.provide(AppNodeBuilder.build(LayerNode.group([Database.node, EventV2.node, EventLogger.node]))), + Effect.provide(Logger.layer([logger])), + Effect.scoped, + Effect.runPromise, + ) + + expect(output.map((entry) => entry.message)).toEqual([ + ["event", { event: expect.objectContaining({ type: "agent.updated" }) }], + ["event", { event: expect.objectContaining({ type: "catalog.updated" }) }], + ["event", { event: expect.objectContaining({ type: "command.updated" }) }], + ["event", { event: expect.objectContaining({ type: "config.updated" }) }], + ]) + }) +}) diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index c5e43989d0..da63120bd8 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -3,6 +3,7 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { httpClient } from "@opencode-ai/core/effect/app-node-platform" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { EventV2 } from "@opencode-ai/core/event" +import { EventLogger } from "@opencode-ai/core/event-logger" import { Credential } from "@opencode-ai/core/credential" import { PermissionSaved } from "@opencode-ai/core/permission/saved" import { PtyTicket } from "@opencode-ai/core/pty/ticket" @@ -31,6 +32,7 @@ import { sessionLocationLayer } from "./middleware/session-location" const applicationServices = LayerNode.group([ Database.node, EventV2.node, + EventLogger.node, httpClient, ToolOutputStore.cleanupNode, Job.node, From a75978815a234c93c1049b78a695f93dc98c14db Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 15:58:43 -0400 Subject: [PATCH 66/82] feat(server): add loaded locations debug endpoint --- packages/client/src/effect/api/api.ts | 8 +++++ .../client/src/effect/generated/client.ts | 6 ++++ .../client/src/promise/generated/client.ts | 14 +++++++++ .../client/src/promise/generated/types.ts | 2 ++ packages/client/test/promise.test.ts | 2 ++ packages/protocol/src/api.ts | 3 ++ packages/protocol/src/client.ts | 1 + packages/protocol/src/groups/debug.ts | 15 ++++++++++ packages/sdk/js/src/v2/gen/sdk.gen.ts | 21 ++++++++++++++ packages/sdk/js/src/v2/gen/types.gen.ts | 29 +++++++++++++++++++ packages/server/src/handlers.ts | 2 ++ packages/server/src/handlers/debug.ts | 14 +++++++++ packages/server/src/routes.ts | 2 +- 13 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 packages/protocol/src/groups/debug.ts create mode 100644 packages/server/src/handlers/debug.ts diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 3f4c852be1..866747dafa 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -862,6 +862,13 @@ export interface VcsApi { readonly diff: VcsDiffOperation } +export type Endpoint25_0Output = EffectValue> +export type DebugLocationOperation = () => Effect.Effect + +export interface DebugApi { + readonly location: DebugLocationOperation +} + export interface AppApi { readonly health: HealthApi readonly location: LocationApi @@ -888,4 +895,5 @@ export interface AppApi { readonly reference: ReferenceApi readonly projectCopy: ProjectCopyApi readonly vcs: VcsApi + readonly debug: DebugApi } diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index a9a91eb8c6..2a253cf016 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -1043,6 +1043,11 @@ const Endpoint24_1 = (raw: RawClient["server.vcs"]) => (input: Endpoint24_1Input const adaptGroup24 = (raw: RawClient["server.vcs"]) => ({ status: Endpoint24_0(raw), diff: Endpoint24_1(raw) }) +const Endpoint25_0 = (raw: RawClient["server.debug"]) => () => + raw["debug.location"]({}).pipe(Effect.mapError(mapClientError)) + +const adaptGroup25 = (raw: RawClient["server.debug"]) => ({ location: Endpoint25_0(raw) }) + const adaptClient = (raw: RawClient) => ({ health: adaptGroup0(raw["server.health"]), location: adaptGroup1(raw["server.location"]), @@ -1069,6 +1074,7 @@ const adaptClient = (raw: RawClient) => ({ reference: adaptGroup22(raw["server.reference"]), projectCopy: adaptGroup23(raw["server.projectCopy"]), vcs: adaptGroup24(raw["server.vcs"]), + debug: adaptGroup25(raw["server.debug"]), }) export const make = (options?: { readonly baseUrl?: URL | string }) => diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 79368764c7..f5fe29506e 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -173,6 +173,7 @@ import type { VcsStatusOutput, VcsDiffInput, VcsDiffOutput, + DebugLocationOutput, } from "./types" import { ClientError } from "./client-error" @@ -1448,6 +1449,19 @@ export function make(options: ClientOptions) { requestOptions, ), }, + debug: { + location: (requestOptions?: RequestOptions) => + request( + { + method: "GET", + path: `/api/debug/location`, + successStatus: 200, + declaredStatuses: [401, 400], + empty: false, + }, + requestOptions, + ), + }, } } diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 151f0ff03f..c4ed970247 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -6003,3 +6003,5 @@ export type VcsDiffOutput = { readonly status?: "added" | "deleted" | "modified" }> } + +export type DebugLocationOutput = ReadonlyArray<{ readonly directory: string; readonly workspaceID?: string }> diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index d445a69c08..2dbd58a858 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -30,7 +30,9 @@ test("exposes every standard HTTP API group", () => { "reference", "projectCopy", "vcs", + "debug", ]) + expect(Object.keys(client.debug)).toEqual(["location"]) expect(Object.keys(client.message)).toEqual(["list"]) expect(Object.keys(client.integration)).toEqual([ "list", diff --git a/packages/protocol/src/api.ts b/packages/protocol/src/api.ts index 04d60888d7..2f91fae332 100644 --- a/packages/protocol/src/api.ts +++ b/packages/protocol/src/api.ts @@ -16,6 +16,7 @@ import type { Definition } from "@opencode-ai/schema/event" import { AgentGroup } from "./groups/agent.js" import { PluginGroup } from "./groups/plugin.js" import { HealthGroup } from "./groups/health.js" +import { DebugGroup } from "./groups/debug.js" import { PtyGroup } from "./groups/pty.js" import { ShellGroup } from "./groups/shell.js" import { makeQuestionGroup } from "./groups/question.js" @@ -81,6 +82,7 @@ type ApiGroups< Event extends HttpApiGroup.Any, > = | typeof HealthGroup + | typeof DebugGroup | LocationGroups | FormGroups | SessionGroups @@ -165,6 +167,7 @@ const makeApiFromGroup = < .add(ReferenceGroup.middleware(locationMiddleware)) .add(ProjectCopyGroup.middleware(locationMiddleware)) .add(VcsGroup.middleware(locationMiddleware)) + .add(DebugGroup) .annotateMerge( OpenApi.annotations({ title: "opencode HttpApi", diff --git a/packages/protocol/src/client.ts b/packages/protocol/src/client.ts index 3976289ed9..3d2993a02b 100644 --- a/packages/protocol/src/client.ts +++ b/packages/protocol/src/client.ts @@ -34,6 +34,7 @@ export const ClientApi: ClientApiShape = makeDefaultApi({ export const groupNames = { "server.health": "health", + "server.debug": "debug", "server.location": "location", "server.agent": "agent", "server.plugin": "plugin", diff --git a/packages/protocol/src/groups/debug.ts b/packages/protocol/src/groups/debug.ts new file mode 100644 index 0000000000..f41b02b864 --- /dev/null +++ b/packages/protocol/src/groups/debug.ts @@ -0,0 +1,15 @@ +import { Location } from "@opencode-ai/schema/location" +import { Schema } from "effect" +import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" + +export const DebugGroup = HttpApiGroup.make("server.debug").add( + HttpApiEndpoint.get("debug.location", "/api/debug/location", { + success: Schema.Array(Location.Ref), + }).annotateMerge( + OpenApi.annotations({ + identifier: "v2.debug.location", + summary: "List loaded locations", + description: "List locations currently loaded by the server.", + }), + ), +) diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index ae8318d78e..59484dddfb 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -276,6 +276,8 @@ import type { V2CredentialRemoveResponses, V2CredentialUpdateErrors, V2CredentialUpdateResponses, + V2DebugLocationErrors, + V2DebugLocationResponses, V2EventChangesErrors, V2EventChangesResponses, V2EventSubscribeErrors, @@ -8036,6 +8038,20 @@ export class Vcs2 extends HeyApiClient { } } +export class Debug extends HeyApiClient { + /** + * List loaded locations + * + * List locations currently loaded by the server. + */ + public location(options?: Options) { + return (options?.client ?? this.client).get({ + url: "/api/debug/location", + ...options, + }) + } +} + export class V2 extends HeyApiClient { private _health?: Health get health(): Health { @@ -8156,6 +8172,11 @@ export class V2 extends HeyApiClient { get vcs(): Vcs2 { return (this._vcs ??= new Vcs2({ client: this.client })) } + + private _debug?: Debug + get debug(): Debug { + return (this._debug ??= new Debug({ client: this.client })) + } } export class OpencodeClient extends HeyApiClient { diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 2b6e1d031f..6db6b405b8 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -19054,6 +19054,35 @@ export type V2VcsDiffResponses = { export type V2VcsDiffResponse = V2VcsDiffResponses[keyof V2VcsDiffResponses] +export type V2DebugLocationData = { + body?: never + path?: never + query?: never + url: "/api/debug/location" +} + +export type V2DebugLocationErrors = { + /** + * InvalidRequestError + */ + 400: InvalidRequestErrorV2 + /** + * UnauthorizedError + */ + 401: UnauthorizedErrorV2 +} + +export type V2DebugLocationError = V2DebugLocationErrors[keyof V2DebugLocationErrors] + +export type V2DebugLocationResponses = { + /** + * Success + */ + 200: Array +} + +export type V2DebugLocationResponse = V2DebugLocationResponses[keyof V2DebugLocationResponses] + export type PtyConnectData = { body?: never path: { diff --git a/packages/server/src/handlers.ts b/packages/server/src/handlers.ts index bfae813372..896cbbc592 100644 --- a/packages/server/src/handlers.ts +++ b/packages/server/src/handlers.ts @@ -13,6 +13,7 @@ import { EventHandler } from "./handlers/event" import { AgentHandler } from "./handlers/agent" import { PluginHandler } from "./handlers/plugin" import { HealthHandler } from "./handlers/health" +import { DebugHandler } from "./handlers/debug" import { PtyHandler } from "./handlers/pty" import { ShellHandler } from "./handlers/shell" import { QuestionHandler } from "./handlers/question" @@ -27,6 +28,7 @@ import { VcsHandler } from "./handlers/vcs" export const handlers = Layer.mergeAll( HealthHandler, + DebugHandler, LocationHandler, AgentHandler, PluginHandler, diff --git a/packages/server/src/handlers/debug.ts b/packages/server/src/handlers/debug.ts new file mode 100644 index 0000000000..f5ffd536e4 --- /dev/null +++ b/packages/server/src/handlers/debug.ts @@ -0,0 +1,14 @@ +import { LocationServiceMap } from "@opencode-ai/core/location-service-map" +import { Effect, Option, RcMap } from "effect" +import { HttpApiBuilder } from "effect/unstable/httpapi" +import { Api } from "../api" + +export const DebugHandler = HttpApiBuilder.group(Api, "server.debug", (handlers) => + handlers.handle( + "debug.location", + Effect.fn(function* () { + const locations = Option.getOrThrow(yield* Effect.serviceOption(LocationServiceMap.Service)) + return Array.from(yield* RcMap.keys(locations.rcMap)) + }), + ), +) diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index da63120bd8..f5e616392f 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -83,7 +83,7 @@ function makeRoutes( : AppNodeBuilder.build(applicationServices, replacements) return HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe( - Layer.provide(handlers), + Layer.provide(handlers.pipe(Layer.provide(serviceLayer))), Layer.provide(formLocationLayer), Layer.provide(sessionLocationLayer), Layer.provide(layer), From baacb2e7769cb849790ee435e048672e7e771448 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 16:14:02 -0400 Subject: [PATCH 67/82] fix(core): tolerate invalid OTLP configuration --- packages/core/src/observability.ts | 8 ++++- .../core/test/effect/observability.test.ts | 36 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/packages/core/src/observability.ts b/packages/core/src/observability.ts index 22285974d8..e99d8919d2 100644 --- a/packages/core/src/observability.ts +++ b/packages/core/src/observability.ts @@ -8,6 +8,12 @@ import { OtlpSerialization } from "effect/unstable/observability" import { Logging } from "./observability/logging" import { Otlp } from "./observability/otlp" +const local = Logger.layer(Logging.loggers(), { mergeWithExisting: false }).pipe( + Layer.provide(NodeFileSystem.layer), + Layer.orDie, + Layer.merge(Layer.succeed(References.MinimumLogLevel, Logging.minimumLogLevel())), +) + export const layer = Layer.unwrap( Effect.gen(function* () { const logs = Logger.layer([...Logging.loggers(), ...Otlp.loggers()], { mergeWithExisting: false }).pipe( @@ -19,6 +25,6 @@ export const layer = Layer.unwrap( ) return Layer.merge(logs, yield* Effect.promise(Otlp.tracingLayer)) }), -) +).pipe(Layer.catchCause(() => local)) export const node = LayerNode.make({ name: "observability", layer, deps: [] }) diff --git a/packages/core/test/effect/observability.test.ts b/packages/core/test/effect/observability.test.ts index 4758563f28..c075986364 100644 --- a/packages/core/test/effect/observability.test.ts +++ b/packages/core/test/effect/observability.test.ts @@ -52,6 +52,42 @@ describe("resource", () => { }) }) +test("falls back to local logging when OTLP initialization fails", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-observability-test-")) + await using _ = { + async [Symbol.asyncDispose]() { + await fs.rm(dir, { recursive: true, force: true }) + }, + } + const child = Bun.spawn( + [ + process.execPath, + "--eval", + ` + import { Effect } from "effect" + import { Observability } from "./src/observability.ts" + await Effect.void.pipe(Effect.provide(Observability.layer), Effect.scoped, Effect.runPromise) + `, + ], + { + cwd: path.join(import.meta.dir, "../.."), + env: { + ...process.env, + OTEL_EXPORTER_OTLP_ENDPOINT: "://invalid", + XDG_CACHE_HOME: path.join(dir, "cache"), + XDG_CONFIG_HOME: path.join(dir, "config"), + XDG_DATA_HOME: path.join(dir, "data"), + XDG_STATE_HOME: path.join(dir, "state"), + }, + stdout: "ignore", + stderr: "pipe", + }, + ) + const [exitCode, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]) + + expect({ exitCode, stderr }).toEqual({ exitCode: 0, stderr: "" }) +}) + test("file logger appends concurrent runs with a run on every line", async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-log-test-")) await using _ = { From 08741f6b9357f37948295b9c6f1a42923b3eeab1 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 16:22:04 -0400 Subject: [PATCH 68/82] fix(core): scope observability to server --- packages/cli/src/index.ts | 14 ++++++++++---- packages/server/src/routes.ts | 2 ++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 5514c3816e..64116b9b76 100755 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,10 +1,10 @@ #!/usr/bin/env bun -import { NodeRuntime, NodeServices } from "@effect/platform-node" -import { Effect } from "effect" +import { NodeFileSystem, NodeRuntime, NodeServices } from "@effect/platform-node" +import { Effect, Layer, Logger, References } from "effect" import { Commands } from "./commands/commands" import { Runtime } from "./framework/runtime" -import { Observability } from "@opencode-ai/core/observability" +import { Logging } from "@opencode-ai/core/observability/logging" import { Updater } from "./services/updater" import { InstallationChannel, InstallationVersion, InstallationLocal } from "@opencode-ai/core/installation/version" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" @@ -12,6 +12,12 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Global } from "@opencode-ai/core/global" import { AppProcess } from "@opencode-ai/core/process" +const LoggingLayer = Logger.layer(Logging.loggers(), { mergeWithExisting: false }).pipe( + Layer.provide(NodeFileSystem.layer), + Layer.orDie, + Layer.merge(Layer.succeed(References.MinimumLogLevel, Logging.minimumLogLevel())), +) + const Handlers = Runtime.handlers(Commands, { $: () => import("./commands/handlers/default"), api: () => import("./commands/handlers/api"), @@ -47,7 +53,7 @@ Effect.logInfo("cli starting", { Effect.annotateLogs({ role: "cli" }), Effect.provide(Updater.layer), Effect.provide(AppNodeBuilder.build(LayerNode.group([Global.node, AppProcess.node]))), - Effect.provide(Observability.layer), + Effect.provide(LoggingLayer), Effect.provide(NodeServices.layer), Effect.scoped, Effect.tap(() => Effect.sync(() => process.exit(0))), diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index f5e616392f..606fde0b84 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -4,6 +4,7 @@ import { httpClient } from "@opencode-ai/core/effect/app-node-platform" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { EventV2 } from "@opencode-ai/core/event" import { EventLogger } from "@opencode-ai/core/event-logger" +import { Observability } from "@opencode-ai/core/observability" import { Credential } from "@opencode-ai/core/credential" import { PermissionSaved } from "@opencode-ai/core/permission/saved" import { PtyTicket } from "@opencode-ai/core/pty/ticket" @@ -91,6 +92,7 @@ function makeRoutes( Layer.provide(schemaErrorLayer), Layer.provide(auth), Layer.provide(serviceLayer), + Layer.provide(Observability.layer), ) } From 6ffecf9345bff67fed2dff22173fc88700bd1721 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 16:54:17 -0400 Subject: [PATCH 69/82] fix(core): reload local plugins on file changes --- packages/core/src/plugin.ts | 36 +++++---- packages/core/src/plugin/supervisor.ts | 51 ++++++++---- packages/core/test/config/plugin.test.ts | 77 ++++++++++++++++++- packages/core/test/location-layer.test.ts | 5 +- packages/core/test/plugin.test.ts | 45 +++++------ .../core/test/plugin/provider-kilo.test.ts | 4 +- .../test/plugin/provider-llmgateway.test.ts | 4 +- .../core/test/plugin/provider-nvidia.test.ts | 4 +- .../test/plugin/provider-openrouter.test.ts | 4 +- .../plugin/provider-snowflake-cortex.test.ts | 2 +- .../core/test/plugin/provider-zenmux.test.ts | 4 +- packages/core/test/shared-schema.test.ts | 4 - 12 files changed, 164 insertions(+), 76 deletions(-) diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index 8ffdf93ba1..1b57d9fc5e 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -1,8 +1,9 @@ export * as PluginV2 from "./plugin" +import type { Plugin } from "@opencode-ai/plugin/v2/effect" +import { Event, ID, type Info } from "@opencode-ai/schema/plugin" import { makeLocationNode } from "./effect/app-node" import { Context, Effect, Exit, Layer, Scope, Semaphore } from "effect" -import { Plugin } from "@opencode-ai/schema/plugin" import { AgentV2 } from "./agent" import { AISDK } from "./aisdk" import { Catalog } from "./catalog" @@ -18,14 +19,8 @@ import { State } from "./state" import { ToolRegistry } from "./tool/registry" import { ToolHooks } from "./tool/hooks" -export const ID = Plugin.ID -export type ID = typeof ID.Type -export const Info = Plugin.Info -export type Info = Plugin.Info -export const Event = Plugin.Event - export interface Interface { - readonly activate: (plugins: readonly import("@opencode-ai/plugin/v2/effect").Plugin[]) => Effect.Effect + readonly activate: (plugins: readonly { readonly plugin: Plugin; readonly version?: string }[]) => Effect.Effect readonly list: () => Effect.Effect } @@ -36,16 +31,20 @@ const layer = Layer.effect( Effect.gen(function* () { const events = yield* EventV2.Service const scope = yield* Scope.make() - const active = new Map() + const active = new Map() const lock = Semaphore.makeUnsafe(1) - let generation: readonly ID[] | undefined = [] - let host: Parameters[0] + let generation: readonly { readonly id: typeof ID.Type; readonly version?: string }[] | undefined = [] + let host: Parameters[0] const activate = Effect.fn("Plugin.activate")(function* ( - plugins: readonly import("@opencode-ai/plugin/v2/effect").Plugin[], + plugins: readonly { readonly plugin: Plugin; readonly version?: string }[], ) { - const definitions = plugins.map((plugin) => ({ ...plugin, id: ID.make(plugin.id) })) - const ids = new Set() + const definitions = plugins.map((entry) => ({ + ...entry.plugin, + id: ID.make(entry.plugin.id), + ...(entry.version === undefined ? {} : { version: entry.version }), + })) + const ids = new Set() for (const definition of definitions) { if (ids.has(definition.id)) return yield* Effect.die(new Error(`Duplicate plugin ID: ${definition.id}`)) ids.add(definition.id) @@ -56,7 +55,9 @@ const layer = Layer.effect( if ( generation !== undefined && generation.length === definitions.length && - generation.every((id, index) => id === definitions[index]?.id) + generation.every( + (plugin, index) => plugin.id === definitions[index]?.id && plugin.version === definitions[index]?.version, + ) ) { return } @@ -87,7 +88,10 @@ const layer = Layer.effect( }), ) if (Exit.isFailure(exit)) return yield* exit - generation = definitions.map((definition) => definition.id) + generation = definitions.map((definition) => ({ + id: definition.id, + ...(definition.version === undefined ? {} : { version: definition.version }), + })) }), ) }) diff --git a/packages/core/src/plugin/supervisor.ts b/packages/core/src/plugin/supervisor.ts index 19410e5001..4d648a7d6f 100644 --- a/packages/core/src/plugin/supervisor.ts +++ b/packages/core/src/plugin/supervisor.ts @@ -2,7 +2,7 @@ export * as PluginSupervisor from "./supervisor" import type { Plugin } from "@opencode-ai/plugin/v2/effect" import { Event } from "@opencode-ai/schema/config" -import { Context, Effect, Fiber, Layer, Schema, Semaphore, Stream } from "effect" +import { Context, Effect, Fiber, Layer, Option, Schema, Semaphore, Stream } from "effect" import path from "path" import { fileURLToPath, pathToFileURL } from "url" import { Config } from "../config" @@ -42,6 +42,7 @@ type Operation = readonly type: "add" readonly target: string readonly options: Record + readonly mtime?: number } | { readonly type: "remove" @@ -57,6 +58,7 @@ type Candidate = readonly type: "package" readonly specifier: string readonly options: Record + readonly mtime?: number } type ConfiguredPackage = { @@ -94,7 +96,16 @@ const scan = Effect.fn("PluginSupervisor.scan")(function* (entries: readonly Con }), ) // Explicit config is applied last so it can remove auto-discovered packages. - return [...discovered, ...configured] + return yield* Effect.forEach([...discovered, ...configured], (operation) => { + if (operation.type === "remove" || !path.isAbsolute(operation.target)) return Effect.succeed(operation) + return fs.stat(operation.target).pipe( + Effect.map((info) => ({ + ...operation, + mtime: Option.getOrElse(info.mtime, () => new Date(0)).getTime(), + })), + Effect.catch(() => Effect.succeed(operation)), + ) + }) }) const resolve = Effect.fn("PluginSupervisor.resolve")(function* ( @@ -143,7 +154,16 @@ function apply(pre: readonly Plugin[], post: readonly Plugin[], operations: read enabled.has(definition.id) ? [{ type: "definition", definition }] : [], ) const configured: Candidate[] = Array.from(packages.values()).flatMap((item) => - item.enabled ? [{ type: "package", specifier: item.operation.target, options: item.operation.options }] : [], + item.enabled + ? [ + { + type: "package", + specifier: item.operation.target, + options: item.operation.options, + ...(item.operation.mtime === undefined ? {} : { mtime: item.operation.mtime }), + }, + ] + : [], ) const posts: Candidate[] = post.flatMap((definition) => enabled.has(definition.id) ? [{ type: "definition", definition }] : [], @@ -153,21 +173,29 @@ function apply(pre: readonly Plugin[], post: readonly Plugin[], operations: read const load = Effect.fn("PluginSupervisor.load")(function* (plan: readonly Candidate[]) { return yield* Effect.forEach(plan, (candidate) => { - if (candidate.type === "definition") return Effect.succeed(candidate.definition) + if (candidate.type === "definition") return Effect.succeed({ plugin: candidate.definition }) return Effect.gen(function* () { const npm = yield* Npm.Service const entrypoint = path.isAbsolute(candidate.specifier) ? pathToFileURL(candidate.specifier).href : (yield* npm.add(candidate.specifier)).entrypoint if (!entrypoint) return - yield* Effect.log({ msg: "loading plugin", id: candidate.specifier, entrypoint }) - const mod = yield* Effect.promise(() => import(entrypoint)) + // Bun currently ignores query parameters when caching file:// imports. + const source = + candidate.mtime === undefined + ? entrypoint + : `${candidate.specifier.replaceAll("\\", "/")}?mtime=${candidate.mtime}` + yield* Effect.log({ msg: "loading plugin", id: candidate.specifier, entrypoint: source }) + const mod = yield* Effect.promise(() => import(source)) const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default const plugin = "effect" in value ? value : PluginPromise.fromPromise(value) return { - id: plugin.id, - effect: (host) => plugin.effect({ ...host, options: candidate.options }), - } satisfies Plugin + plugin: { + id: plugin.id, + effect: (host) => plugin.effect({ ...host, options: candidate.options }), + } satisfies Plugin, + ...(candidate.mtime === undefined ? {} : { version: String(candidate.mtime) }), + } }).pipe(Effect.catchCause(() => Effect.succeed(undefined))) }).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined))) }) @@ -231,7 +259,6 @@ const layer = Layer.effect( const config = yield* Config.Service const events = yield* EventV2.Service const lock = Semaphore.makeUnsafe(1) - let applied: string | undefined const reload = Effect.fn("PluginSupervisor.reload")(() => lock.withPermit( Effect.gen(function* () { @@ -241,15 +268,11 @@ const layer = Layer.effect( const pre = [...internal.pre, ...sdk.all()] // Read the current layered config before resolving plugin directives and packages. const entries = yield* config.entries() - // Skip duplicate watcher notifications and config edits unrelated to plugins. const operations = yield* scan(entries) - const version = JSON.stringify(operations) - if (version === applied) return // Apply config operations and load enabled package plugins into one ordered generation. const plugins = yield* resolve(pre, internal.post, operations) // Replace the active generation in one scoped, batched activation. yield* registry.activate(plugins) - applied = version }), ), ) diff --git a/packages/core/test/config/plugin.test.ts b/packages/core/test/config/plugin.test.ts index c3c84d8101..34a69ffbc5 100644 --- a/packages/core/test/config/plugin.test.ts +++ b/packages/core/test/config/plugin.test.ts @@ -1,7 +1,10 @@ import fs from "fs/promises" import path from "path" +import { pathToFileURL } from "url" import { describe, expect } from "bun:test" import { define } from "@opencode-ai/plugin/v2/effect" +import { Config as ConfigSchema } from "@opencode-ai/schema/config" +import { Plugin } from "@opencode-ai/schema/plugin" import { AgentV2 } from "@opencode-ai/core/agent" import { Catalog } from "@opencode-ai/core/catalog" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" @@ -33,7 +36,7 @@ describe("PluginSupervisor config", () => { yield* ready() expect( (yield* plugins.list()).map((plugin) => plugin.id).filter((id) => id.startsWith("opencode.provider.")), - ).toEqual([PluginV2.ID.make("opencode.provider.openai")]) + ).toEqual([Plugin.ID.make("opencode.provider.openai")]) }), ), ) @@ -122,6 +125,43 @@ describe("PluginSupervisor config", () => { ), ) + it.live("reloads an auto-discovered plugin when its file changes", () => + withLocation( + undefined, + Effect.gen(function* () { + yield* ready() + const agents = yield* AgentV2.Service + const events = yield* EventV2.Service + const location = yield* Location.Service + const plugins = yield* PluginV2.Service + const file = path.join(location.directory, ".opencode", "plugin", "mutable.ts") + const first = (yield* plugins.list()).find((plugin) => plugin.id === "mutable-plugin")?.id + + expect(first).toBeDefined() + expect((yield* agents.get(AgentV2.ID.make("mutable")))?.description).toBe("first") + + yield* Effect.promise(async () => { + await fs.writeFile(file, mutablePlugin("second")) + const modified = new Date(Date.now() + 5_000) + await fs.utimes(file, modified, modified) + }) + yield* events.publish(ConfigSchema.Event.Updated, {}) + yield* waitUntil( + Effect.gen(function* () { + const current = (yield* plugins.list()).find((plugin) => plugin.id === "mutable-plugin")?.id + return current === first && (yield* agents.get(AgentV2.ID.make("mutable")))?.description === "second" + }), + ) + }), + false, + async (directory) => { + const plugin = path.join(directory, ".opencode", "plugin") + await fs.mkdir(plugin, { recursive: true }) + await fs.writeFile(path.join(plugin, "mutable.ts"), mutablePlugin("first")) + }, + ), + ) + it.live("applies explicit removals after auto-discovery", () => withLocation( { plugins: ["-*"] }, @@ -192,13 +232,19 @@ const ready = Effect.fnUntraced(function* () { yield* supervisor.ready }) -function withLocation(config: unknown, effect: Effect.Effect, fixtures = false) { +function withLocation( + config: unknown, + effect: Effect.Effect, + fixtures = false, + prepare?: (directory: string) => Promise, +) { return Effect.acquireRelease( Effect.promise(() => tmpdir()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ).pipe( Effect.tap((tmp) => Effect.promise(async () => { + await prepare?.(tmp.path) if (fixtures) { const directory = path.join(tmp.path, ".opencode") await fs.mkdir(directory, { recursive: true }) @@ -223,3 +269,30 @@ function withLocation(config: unknown, effect: Effect.Effect, ), ) } + +function mutablePlugin(description: string) { + const plugin = pathToFileURL(path.join(import.meta.dir, "../../../plugin/src/v2/promise/index.ts")).href + return ` +import { define } from ${JSON.stringify(plugin)} + +export default define({ + id: "mutable-plugin", + setup: async (ctx) => { + await ctx.agent.transform((agents) => { + agents.update("mutable", (agent) => { + agent.description = ${JSON.stringify(description)} + agent.mode = "subagent" + }) + }) + }, +}) +` +} + +const waitUntil = Effect.fnUntraced(function* (condition: Effect.Effect) { + for (let attempt = 0; attempt < 200; attempt++) { + if (yield* condition) return + yield* Effect.sleep("10 millis") + } + return yield* Effect.die("Timed out waiting for plugin reload") +}) diff --git a/packages/core/test/location-layer.test.ts b/packages/core/test/location-layer.test.ts index be6e150680..f0bef9fd32 100644 --- a/packages/core/test/location-layer.test.ts +++ b/packages/core/test/location-layer.test.ts @@ -2,6 +2,7 @@ import fs from "fs/promises" import path from "path" import { describe, expect } from "bun:test" import { Config } from "@opencode-ai/schema/config" +import { Plugin } from "@opencode-ai/schema/plugin" import { Context, DateTime, Effect, Equal, Hash, Schema, Stream } from "effect" import { define } from "@opencode-ai/plugin/v2/effect" import { AgentV2 } from "@opencode-ai/core/agent" @@ -50,7 +51,7 @@ describe("LocationServiceMap", () => { ), ) - expect(plugins.map((plugin) => plugin.id)).toEqual([PluginV2.ID.make("opencode.agent")]) + expect(plugins.map((plugin) => plugin.id)).toEqual([Plugin.ID.make("opencode.agent")]) }), ), ), @@ -377,7 +378,7 @@ describe("LocationServiceMap", () => { }) .pipe(Effect.asVoid), }) - yield* plugins.activate([{ id: PluginV2.ID.make(reviewer.id), effect: reviewer.effect }]) + yield* plugins.activate([{ plugin: reviewer }]) expect(yield* (yield* AgentV2.Service).get(AgentV2.ID.make("reviewer"))).toMatchObject({ description: "Reviews code", diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 8917171929..6037f4538b 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -2,6 +2,7 @@ import { describe, expect } from "bun:test" import { Context, Effect, Exit, Fiber, Schema, Stream } from "effect" import { define } from "@opencode-ai/plugin/v2/effect" import { Config as ConfigSchema } from "@opencode-ai/schema/config" +import { Plugin } from "@opencode-ai/schema/plugin" import { AgentV2 } from "@opencode-ai/core/agent" import { EventV2 } from "@opencode-ai/core/event" import { PluginV2 } from "@opencode-ai/core/plugin" @@ -37,15 +38,15 @@ describe("PluginV2", () => { }), ) - it.effect("skips identical generations and replaces changed plugin IDs", () => + it.effect("skips identical generations and replaces changed plugin versions", () => Effect.gen(function* () { const plugins = yield* PluginV2.Service const agents = yield* AgentV2.Service let description = "first" - const managed = (id: string) => + const managed = () => define({ - id, + id: "managed", effect: (ctx) => ctx.agent .transform((agents) => @@ -56,15 +57,15 @@ describe("PluginV2", () => { .pipe(Effect.asVoid), }) - yield* plugins.activate([managed("managed")]) + yield* plugins.activate([{ plugin: managed() }]) expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("first") description = "second" - yield* plugins.activate([managed("managed")]) + yield* plugins.activate([{ plugin: managed() }]) expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("first") - yield* plugins.activate([managed("managed-next")]) + yield* plugins.activate([{ plugin: managed(), version: "next" }]) expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("second") yield* plugins.activate([]) @@ -75,14 +76,14 @@ describe("PluginV2", () => { it.effect("rejects duplicate IDs before replacing the active generation", () => Effect.gen(function* () { const plugins = yield* PluginV2.Service - const active = PluginV2.ID.make("active") - const duplicate = PluginV2.ID.make("duplicate") - yield* plugins.activate([{ id: active, effect: () => Effect.void }]) + const active = Plugin.ID.make("active") + const duplicate = "duplicate" + yield* plugins.activate([{ plugin: { id: active, effect: () => Effect.void } }]) const result = yield* plugins .activate([ - { id: duplicate, effect: () => Effect.void }, - { id: duplicate, effect: () => Effect.void }, + { plugin: { id: duplicate, effect: () => Effect.void } }, + { plugin: { id: duplicate, effect: () => Effect.void } }, ]) .pipe(Effect.exit) @@ -105,11 +106,11 @@ describe("PluginV2", () => { .pipe(Effect.asVoid), }) - expect(Exit.isFailure(yield* plugins.activate([plugin]).pipe(Effect.exit))).toBe(true) + expect(Exit.isFailure(yield* plugins.activate([{ plugin }]).pipe(Effect.exit))).toBe(true) fail = false - yield* plugins.activate([plugin]) + yield* plugins.activate([{ plugin }]) - expect(yield* plugins.list()).toEqual([{ id: PluginV2.ID.make("retry") }]) + expect(yield* plugins.list()).toEqual([{ id: Plugin.ID.make("retry") }]) }), ) @@ -119,8 +120,10 @@ describe("PluginV2", () => { const closed: string[] = [] yield* plugins.activate( ["first", "second"].map((id) => ({ - id: PluginV2.ID.make(id), - effect: () => Effect.addFinalizer(() => Effect.sync(() => closed.push(id))), + plugin: { + id, + effect: () => Effect.addFinalizer(() => Effect.sync(() => closed.push(id))), + }, })), ) @@ -143,9 +146,7 @@ describe("PluginV2", () => { ), }) - yield* plugins - .activate([{ id: PluginV2.ID.make(plugin.id), effect: plugin.effect }]) - .pipe(Effect.provideService(Secret, "secret")) + yield* plugins.activate([{ plugin }]).pipe(Effect.provideService(Secret, "secret")) expect(visible).toBe(false) }), @@ -170,7 +171,7 @@ describe("PluginV2", () => { .pipe(Effect.orDie), }) - yield* plugins.activate([{ id: PluginV2.ID.make(plugin.id), effect: plugin.effect }]) + yield* plugins.activate([{ plugin }]) expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toContain( "plugin_tool", ) @@ -205,7 +206,7 @@ describe("PluginV2", () => { }), }) - yield* plugins.activate([{ id: PluginV2.ID.make(plugin.id), effect: plugin.effect }]) + yield* plugins.activate([{ plugin }]) expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toEqual([ "plain", @@ -257,7 +258,7 @@ describe("PluginV2", () => { }), }) - yield* plugins.activate([{ id: PluginV2.ID.make(plugin.id), effect: plugin.effect }]) + yield* plugins.activate([{ plugin }]) const materialized = yield* registry.materialize({ model: testModel }) const settlement = yield* materialized.settle({ diff --git a/packages/core/test/plugin/provider-kilo.test.ts b/packages/core/test/plugin/provider-kilo.test.ts index bec50272ef..1ff356523c 100644 --- a/packages/core/test/plugin/provider-kilo.test.ts +++ b/packages/core/test/plugin/provider-kilo.test.ts @@ -19,9 +19,7 @@ const addPlugin = Effect.fn(function* () { describe("KiloPlugin", () => { it.effect("is registered so legacy referer headers can be applied", () => - Effect.sync(() => - expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.kilo")), - ), + Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.kilo")), ) it.effect("applies legacy referer headers only to kilo", () => diff --git a/packages/core/test/plugin/provider-llmgateway.test.ts b/packages/core/test/plugin/provider-llmgateway.test.ts index 8cc45c6027..8f4af57889 100644 --- a/packages/core/test/plugin/provider-llmgateway.test.ts +++ b/packages/core/test/plugin/provider-llmgateway.test.ts @@ -21,9 +21,7 @@ const addPlugin = Effect.fn(function* () { describe("LLMGatewayPlugin", () => { it.effect("is registered so legacy referer headers can be applied", () => - Effect.sync(() => - expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.llmgateway")), - ), + Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.llmgateway")), ) it.effect("applies legacy referer headers only to enabled llmgateway", () => diff --git a/packages/core/test/plugin/provider-nvidia.test.ts b/packages/core/test/plugin/provider-nvidia.test.ts index baf763c8d1..c176cef4ac 100644 --- a/packages/core/test/plugin/provider-nvidia.test.ts +++ b/packages/core/test/plugin/provider-nvidia.test.ts @@ -19,9 +19,7 @@ const addPlugin = Effect.fn(function* () { describe("NvidiaPlugin", () => { it.effect("is registered so legacy referer headers can be applied", () => - Effect.sync(() => - expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.nvidia")), - ), + Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.nvidia")), ) it.effect("applies NVIDIA tracking headers only to nvidia", () => diff --git a/packages/core/test/plugin/provider-openrouter.test.ts b/packages/core/test/plugin/provider-openrouter.test.ts index e0be8b5fa7..60dfc67b51 100644 --- a/packages/core/test/plugin/provider-openrouter.test.ts +++ b/packages/core/test/plugin/provider-openrouter.test.ts @@ -22,9 +22,7 @@ const addPlugin = Effect.fn(function* () { describe("OpenRouterPlugin", () => { it.effect("is registered so legacy OpenRouter behavior can be applied", () => - Effect.sync(() => - expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.openrouter")), - ), + Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.openrouter")), ) it.effect("applies legacy referer headers only to openrouter", () => diff --git a/packages/core/test/plugin/provider-snowflake-cortex.test.ts b/packages/core/test/plugin/provider-snowflake-cortex.test.ts index a1265b6a8f..4de00105b7 100644 --- a/packages/core/test/plugin/provider-snowflake-cortex.test.ts +++ b/packages/core/test/plugin/provider-snowflake-cortex.test.ts @@ -43,7 +43,7 @@ function withEnv(vars: Record, effect: () = describe("SnowflakeCortexPlugin", () => { it.effect("is registered in ProviderPlugins before OpenAICompatiblePlugin", () => Effect.sync(() => { - expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.snowflake-cortex")) + expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.snowflake-cortex") const ids = ProviderPlugins.map((p) => p.id) expect(ids.indexOf("opencode.provider.snowflake-cortex")).toBeLessThan( ids.indexOf("opencode.provider.openai-compatible"), diff --git a/packages/core/test/plugin/provider-zenmux.test.ts b/packages/core/test/plugin/provider-zenmux.test.ts index 0ce286d612..9c44800ebc 100644 --- a/packages/core/test/plugin/provider-zenmux.test.ts +++ b/packages/core/test/plugin/provider-zenmux.test.ts @@ -24,9 +24,7 @@ function required(value: T | undefined): T { describe("ZenmuxPlugin", () => { it.effect("is registered so legacy referer headers can be applied", () => - Effect.sync(() => - expect(ProviderPlugins.map((item) => item.id)).toContain(PluginV2.ID.make("opencode.provider.zenmux")), - ), + Effect.sync(() => expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.zenmux")), ) it.effect("applies the exact legacy Zenmux headers", () => diff --git a/packages/core/test/shared-schema.test.ts b/packages/core/test/shared-schema.test.ts index ecdd555fa8..7d227aac19 100644 --- a/packages/core/test/shared-schema.test.ts +++ b/packages/core/test/shared-schema.test.ts @@ -22,14 +22,12 @@ import { FileSystem } from "@opencode-ai/schema/filesystem" import { Integration } from "@opencode-ai/schema/integration" import { LLM } from "@opencode-ai/schema/llm" import { Permission } from "@opencode-ai/schema/permission" -import { Plugin } from "@opencode-ai/schema/plugin" import { Pty } from "@opencode-ai/schema/pty" import { Reference } from "@opencode-ai/schema/reference" import { SessionTodo } from "@opencode-ai/schema/session-todo" import { Skill } from "@opencode-ai/schema/skill" import { AbsolutePath, DateTimeUtcFromMillis, optional, statics } from "@opencode-ai/schema/schema" import { ProviderV2 } from "@opencode-ai/core/provider" -import { PluginV2 } from "@opencode-ai/core/plugin" test("Core reuses the canonical shared schemas", async () => { const [ @@ -129,8 +127,6 @@ test("Core reuses the canonical shared schemas", async () => { [corePermission.Ruleset, Permission.Ruleset], [corePermissionV1.Event, PermissionV1.Event], [coreProjectCopy.Event, ProjectDirectories.Event], - [PluginV2.ID, Plugin.ID], - [PluginV2.Event, Plugin.Event], [corePty.Info, Pty.Info], [corePty.Event, Pty.Event], [coreProject.ID, Project.ID], From 33cb536879be44f15214130b5b65d5c3f170766a Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 17:21:39 -0400 Subject: [PATCH 70/82] feat(plugin): publish generation updates --- .../client/src/promise/generated/types.ts | 8 ++++ packages/core/src/plugin.ts | 1 + packages/core/test/plugin.test.ts | 5 ++ packages/schema/src/plugin.ts | 6 ++- packages/schema/test/event-manifest.test.ts | 3 ++ packages/sdk/js/src/v2/gen/types.gen.ts | 46 +++++++++++++++++++ packages/tui/src/app.tsx | 6 +++ 7 files changed, 74 insertions(+), 1 deletion(-) diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index c4ed970247..f58135023c 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -4974,6 +4974,14 @@ export type EventSubscribeOutput = readonly location?: { readonly directory: string; readonly workspaceID?: string } readonly data: { readonly id: string } } + | { + readonly id: string + readonly created: number + readonly metadata?: { readonly [x: string]: unknown } + readonly type: "plugin.updated" + readonly location?: { readonly directory: string; readonly workspaceID?: string } + readonly data: {} + } | { readonly id: string readonly created: number diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index 1b57d9fc5e..907920c10e 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -92,6 +92,7 @@ const layer = Layer.effect( id: definition.id, ...(definition.version === undefined ? {} : { version: definition.version }), })) + yield* events.publish(Event.Updated, {}) }), ) }) diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 6037f4538b..e437feb066 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -42,7 +42,11 @@ describe("PluginV2", () => { Effect.gen(function* () { const plugins = yield* PluginV2.Service const agents = yield* AgentV2.Service + const events = yield* EventV2.Service let description = "first" + const updated = yield* events + .subscribe(Plugin.Event.Updated) + .pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped({ startImmediately: true })) const managed = () => define({ @@ -67,6 +71,7 @@ describe("PluginV2", () => { yield* plugins.activate([{ plugin: managed(), version: "next" }]) expect((yield* agents.get(AgentV2.ID.make("configured")))?.description).toBe("second") + expect(yield* Fiber.join(updated)).toHaveLength(2) yield* plugins.activate([]) expect(yield* agents.get(AgentV2.ID.make("configured"))).toBeUndefined() diff --git a/packages/schema/src/plugin.ts b/packages/schema/src/plugin.ts index 40379e3051..4a003f1199 100644 --- a/packages/schema/src/plugin.ts +++ b/packages/schema/src/plugin.ts @@ -15,4 +15,8 @@ const Added = ephemeral({ type: "plugin.added", schema: { id: ID }, }) -export const Event = { Added, Definitions: inventory(Added) } +const Updated = ephemeral({ + type: "plugin.updated", + schema: {}, +}) +export const Event = { Added, Updated, Definitions: inventory(Added, Updated) } diff --git a/packages/schema/test/event-manifest.test.ts b/packages/schema/test/event-manifest.test.ts index 0147c7469b..da344ba528 100644 --- a/packages/schema/test/event-manifest.test.ts +++ b/packages/schema/test/event-manifest.test.ts @@ -15,6 +15,7 @@ import { EventManifest } from "../src/event-manifest.js" import { FileSystemV1 } from "../src/filesystem-v1.js" import { IdeEvent } from "../src/ide-event.js" import { McpEvent } from "../src/mcp-event.js" +import { Plugin } from "../src/plugin.js" import { SessionEvent } from "../src/session-event.js" import { SessionTodo } from "../src/session-todo.js" import { SessionV1 } from "../src/session-v1.js" @@ -46,6 +47,7 @@ describe("public event manifest", () => { EventManifest.Definitions.map((definition) => definition.type), ) expect(EventManifest.Latest.get("agent.updated")).toBe(Agent.Event.Updated) + expect(EventManifest.Latest.get("plugin.updated")).toBe(Plugin.Event.Updated) expect(EventManifest.Server.get("mcp.status.changed")).toBe(McpEvent.StatusChanged) expect(EventManifest.Server.has("mcp.tools.changed")).toBe(false) expect(Agent.Event.Updated.durable).toBeUndefined() @@ -70,6 +72,7 @@ describe("public event manifest", () => { expect(Permission.Event.Definitions).toEqual([Permission.Event.Asked, Permission.Event.Replied]) expect(Form.Event.Definitions).toEqual([Form.Event.Created, Form.Event.Replied, Form.Event.Cancelled]) expect(Reference.Event.Definitions).toEqual([Reference.Event.Updated]) + expect(Plugin.Event.Definitions).toEqual([Plugin.Event.Added, Plugin.Event.Updated]) expect(McpEvent.Definitions).toEqual([McpEvent.ToolsChanged, McpEvent.StatusChanged]) expect(EventManifest.Latest.has("mcp.browser.open.failed")).toBe(false) expect(EventManifest.Latest.has("ide.installed")).toBe(false) diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 6db6b405b8..5b9d40cad5 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -63,6 +63,7 @@ export type Event = | EventPermissionV2Asked | EventPermissionV2Replied | EventPluginAdded + | EventPluginUpdated | EventProjectDirectoriesUpdated | EventCommandUpdated | EventConfigUpdated @@ -1325,6 +1326,13 @@ export type GlobalEvent = { id: string } } + | { + id: string + type: "plugin.updated" + properties: { + [key: string]: unknown + } + } | { id: string type: "project.directories.updated" @@ -3071,6 +3079,7 @@ export type V2Event = | PermissionV2Asked | PermissionV2Replied | PluginAdded + | PluginUpdated | ProjectDirectoriesUpdated | CommandUpdated | ConfigUpdated @@ -5957,6 +5966,19 @@ export type PluginAdded = { } } +export type PluginUpdated = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "plugin.updated" + location?: LocationRef + data: { + [key: string]: unknown + } +} + export type ProjectDirectoriesUpdated = { id: string created: number @@ -7274,6 +7296,14 @@ export type EventPluginAdded = { } } +export type EventPluginUpdated = { + id: string + type: "plugin.updated" + properties: { + [key: string]: unknown + } +} + export type EventProjectDirectoriesUpdated = { id: string type: "project.directories.updated" @@ -10380,6 +10410,21 @@ export type PluginAdded2 = { } } +export type PluginUpdated2 = { + id: string + created: number + metadata?: { + [key: string]: unknown + } + type: "plugin.updated" + location?: LocationRef2 + data: + | { + [key: string]: unknown + } + | Array +} + export type ProjectDirectoriesUpdated2 = { id: string created: number @@ -11192,6 +11237,7 @@ export type V2EventV2 = | PermissionV2Asked2 | PermissionV2Replied2 | PluginAdded2 + | PluginUpdated2 | ProjectDirectoriesUpdated2 | CommandUpdated2 | ConfigUpdated2 diff --git a/packages/tui/src/app.tsx b/packages/tui/src/app.tsx index a3b2c31973..b769a436a0 100644 --- a/packages/tui/src/app.tsx +++ b/packages/tui/src/app.tsx @@ -1040,6 +1040,12 @@ function App(props: { onSnapshot?: () => Promise; pluginHost: TuiPlugi }) }) + event.on("plugin.updated", (_evt, { directory, workspace }) => { + if (directory !== project.instance.directory()) return + if (workspace !== project.workspace.current()) return + toast.show({ variant: "success", message: "Plugins reloaded" }) + }) + event.on("tui.session.select", (evt, { workspace }) => { if (workspace !== project.workspace.current()) return route.navigate({ From 7b88de47c303c428c7b6dbafced21ab920ba5888 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 18:21:23 -0400 Subject: [PATCH 71/82] chore(client): publish client package --- script/publish.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/script/publish.ts b/script/publish.ts index 5ee296a6cf..4fcf0890ba 100755 --- a/script/publish.ts +++ b/script/publish.ts @@ -41,6 +41,9 @@ await $`bun ./packages/schema/script/publish.ts` console.log("\n=== protocol ===\n") await $`bun ./packages/protocol/script/publish.ts` +console.log("\n=== client ===\n") +await $`bun ./packages/client/script/publish.ts` + console.log("\n=== cli ===\n") await $`bun ./packages/cli/script/publish.ts` From 652e8ff3fbb7bfca0f93b81c2a7215e7188492dd Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sun, 5 Jul 2026 18:31:15 -0400 Subject: [PATCH 72/82] fix(client): resolve codegen workspace version --- bun.lock | 1 + packages/httpapi-codegen/package.json | 1 + 2 files changed, 2 insertions(+) diff --git a/bun.lock b/bun.lock index 3ca6fd949d..7d4a912af1 100644 --- a/bun.lock +++ b/bun.lock @@ -530,6 +530,7 @@ }, "packages/httpapi-codegen": { "name": "@opencode-ai/httpapi-codegen", + "version": "0.0.0", "dependencies": { "effect": "catalog:", "prettier": "3.6.2", diff --git a/packages/httpapi-codegen/package.json b/packages/httpapi-codegen/package.json index 84aa736531..f2a5e4da79 100644 --- a/packages/httpapi-codegen/package.json +++ b/packages/httpapi-codegen/package.json @@ -1,6 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode-ai/httpapi-codegen", + "version": "0.0.0", "private": true, "type": "module", "exports": { From 5bcf8d5a0b118652c9a298de68a334b4700bc15a Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Sun, 5 Jul 2026 19:35:30 -0500 Subject: [PATCH 73/82] feat(tui): render session forms (#35421) --- packages/tui/src/context/data.tsx | 31 + .../feature-plugins/system/notifications.ts | 16 + packages/tui/src/routes/session/form.tsx | 1009 +++++++++++++++++ packages/tui/src/routes/session/index.tsx | 17 +- .../test/cli/cmd/tui/notifications.test.ts | 70 +- packages/tui/test/cli/tui/data.test.tsx | 70 ++ packages/tui/test/fixture/tui-sdk.ts | 7 +- 7 files changed, 1202 insertions(+), 18 deletions(-) create mode 100644 packages/tui/src/routes/session/form.tsx diff --git a/packages/tui/src/context/data.tsx b/packages/tui/src/context/data.tsx index 82a7150c9e..1528b83cd0 100644 --- a/packages/tui/src/context/data.tsx +++ b/packages/tui/src/context/data.tsx @@ -1,6 +1,8 @@ import type { AgentV2Info, CommandV2Info, + FormFormInfo, + FormUrlInfo, IntegrationInfo, LocationRef, McpServer, @@ -29,6 +31,8 @@ export type DataSessionStatus = "idle" | "running" const messageIDFromEvent = (eventID: string) => eventID.replace(/^evt_/, "msg_") +export type FormInfo = FormFormInfo | FormUrlInfo + type LocationData = { agent?: AgentV2Info[] command?: CommandV2Info[] @@ -54,6 +58,8 @@ type Data = { message: Record permission: Record question: Record + // Pending forms keyed by session ID. + form: Record } project: { permission: Record @@ -88,6 +94,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ message: {}, permission: {}, question: {}, + form: {}, }, project: { permission: {}, @@ -602,6 +609,22 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ ), ) break + case "form.created": + if (store.session.form[event.data.form.sessionID]?.some((form) => form.id === event.data.form.id)) break + setStore("session", "form", event.data.form.sessionID, [ + ...(store.session.form[event.data.form.sessionID] ?? []), + mutable(event.data.form), + ]) + break + case "form.replied": + case "form.cancelled": + setStore( + "session", + "form", + event.data.sessionID, + (store.session.form[event.data.sessionID] ?? []).filter((form) => form.id !== event.data.id), + ) + break case "shell.created": setStore("location", locationKey(event.location ?? defaultLocation()), (data) => ({ ...data, @@ -728,6 +751,14 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({ setStore("session", "question", sessionID, mutable(await sdk.api.question.list({ sessionID }))) }, }, + form: { + list(sessionID: string) { + return store.session.form[sessionID] + }, + async refresh(sessionID: string) { + setStore("session", "form", sessionID, mutable(await sdk.api.form.list({ sessionID }))) + }, + }, }, project: { permission: { diff --git a/packages/tui/src/feature-plugins/system/notifications.ts b/packages/tui/src/feature-plugins/system/notifications.ts index 416ba8c466..a5033b62e0 100644 --- a/packages/tui/src/feature-plugins/system/notifications.ts +++ b/packages/tui/src/feature-plugins/system/notifications.ts @@ -29,9 +29,25 @@ function sessionErrorMessage(error: SessionError) { const tui: TuiPlugin = async (api) => { const active = new Set() const errored = new Set() + const forms = new Set() const questions = new Set() const permissions = new Set() + api.event.on("form.created", (event) => { + if (event.data.form.sessionID === "global") return + if (forms.has(event.data.form.id)) return + forms.add(event.data.form.id) + notify(api, event.data.form.sessionID, "Input needs response", "question") + }) + + api.event.on("form.replied", (event) => { + forms.delete(event.data.id) + }) + + api.event.on("form.cancelled", (event) => { + forms.delete(event.data.id) + }) + api.event.on("question.asked", (event) => { if (questions.has(event.data.id)) return questions.add(event.data.id) diff --git a/packages/tui/src/routes/session/form.tsx b/packages/tui/src/routes/session/form.tsx new file mode 100644 index 0000000000..e6f7a4818c --- /dev/null +++ b/packages/tui/src/routes/session/form.tsx @@ -0,0 +1,1009 @@ +import { createStore } from "solid-js/store" +import { createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js" +import { useRenderer, useTerminalDimensions } from "@opentui/solid" +import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core" +import open from "open" +import { selectedForeground, tint, useTheme } from "../../context/theme" +import type { FormFormInfo, FormValue } from "@opencode-ai/sdk/v2" +import type { FormInfo } from "../../context/data" +import { useSDK } from "../../context/sdk" +import { SplitBorder } from "../../ui/border" +import { useTuiConfig } from "../../config" +import { useBindings, useOpencodeModeStack } from "../../keymap" + +const FORM_MODE = "form" + +type Field = FormFormInfo["fields"][number] + +function fieldLabel(field: Field) { + return field.title ?? field.key +} + +function truncate(label: string, max: number) { + return label.length > max ? label.slice(0, max - 1).trimEnd() + "…" : label +} + +function validateText(field: Field, text: string): string | undefined { + if (field.type !== "string") return + if (field.minLength !== undefined && text.length < field.minLength) + return `Must be at least ${field.minLength} characters` + if (field.maxLength !== undefined && text.length > field.maxLength) + return `Must be at most ${field.maxLength} characters` + if (field.pattern !== undefined) { + try { + if (!new RegExp(field.pattern).test(text)) return `Must match pattern: ${field.pattern}` + } catch { + return `Invalid pattern: ${field.pattern}` + } + } + if (field.format === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text)) return "Expected an email address" + if (field.format === "uri") { + try { + new URL(text) + } catch { + return "Expected a URL" + } + } + if (field.format === "date") { + const date = new Date(`${text}T00:00:00.000Z`) + if (!/^\d{4}-\d{2}-\d{2}$/.test(text) || Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== text) + return "Expected a date (YYYY-MM-DD)" + } + if (field.format === "date-time" && Number.isNaN(new Date(text).getTime())) return "Expected a date and time" +} + +function validateSelection(field: Field, value: FormValue | undefined) { + if (field.type !== "multiselect" || value === undefined) return + if (!Array.isArray(value)) return "Expected selections" + if (field.required && value.length === 0) return "Select at least one option" + if (field.minItems !== undefined && value.length < field.minItems) return `Select at least ${field.minItems}` + if (field.maxItems !== undefined && value.length > field.maxItems) return `Select at most ${field.maxItems}` +} + +function validateValue(field: Field, value: FormValue | undefined) { + if (value === undefined) return field.required ? "Answer required" : undefined + if (field.required && (value === "" || (Array.isArray(value) && value.length === 0))) { + return field.type === "multiselect" ? "Select at least one option" : "Answer required" + } + if (field.type === "string") { + if (typeof value !== "string") return "Expected text" + const invalid = validateText(field, value) + if (invalid) return invalid + if (field.options && !field.custom && !field.options.some((option) => option.value === value)) { + return "Select an available option" + } + return + } + if (field.type === "number" || field.type === "integer") { + if (typeof value !== "number" || !Number.isFinite(value)) return "Expected a number" + if (field.type === "integer" && !Number.isInteger(value)) return "Expected an integer" + if (typeof field.minimum === "number" && value < field.minimum) return `Must be at least ${field.minimum}` + if (typeof field.maximum === "number" && value > field.maximum) return `Must be at most ${field.maximum}` + return + } + if (field.type === "boolean") return typeof value === "boolean" ? undefined : "Expected yes or no" + const invalid = validateSelection(field, value) + if (invalid) return invalid + if ( + Array.isArray(value) && + !field.custom && + value.some((item) => !field.options.some((option) => option.value === item)) + ) { + return "Select only available options" + } +} + +function fieldRows(field: Field): { value: FormValue; label: string; description?: string }[] { + if (field.type === "boolean") + return [ + { value: true, label: "Yes" }, + { value: false, label: "No" }, + ] + if (field.type === "multiselect" || (field.type === "string" && field.options)) + return (field.options ?? []).map((option) => ({ + value: option.value, + label: option.label, + description: option.description, + })) + return [] +} + +function selectedRow(field: Field | undefined, value: FormValue | undefined) { + if (!field || value === undefined || Array.isArray(value)) return 0 + const rows = fieldRows(field) + const index = rows.findIndex((row) => row.value === value) + if (index !== -1) return index + if (typeof value === "string" && field.type === "string" && field.options && field.custom) return rows.length + return 0 +} + +function customDefault(field: Field) { + if (field.type !== "string" || !field.options || !field.custom || typeof field.default !== "string") return + if (!field.options.some((option) => option.value === field.default)) return field.default +} + +function display(field: Field, value: FormValue | undefined) { + if (value === undefined) return "" + const label = (item: string | number | boolean) => + fieldRows(field).find((row) => row.value === item)?.label ?? String(item) + if (Array.isArray(value)) return value.length === 0 ? "(none)" : value.map(label).join(", ") + return label(value) +} + +export function FormPrompt(props: { form: FormInfo }) { + return props.form.mode === "url" ? : +} + +function UrlPrompt(props: { form: FormInfo & { mode: "url" } }) { + const sdk = useSDK() + const { theme } = useTheme() + const modeStack = useOpencodeModeStack() + const message = createMemo(() => { + const value = props.form.metadata?.["message"] + return typeof value === "string" ? value : undefined + }) + + onMount(() => onCleanup(modeStack.push(FORM_MODE))) + + useBindings(() => ({ + mode: FORM_MODE, + enabled: true, + commands: [ + { + name: "app.exit", + title: "Dismiss form", + category: "Form", + run() { + void sdk.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }) + }, + }, + ], + bindings: [ + { + key: "return", + desc: "Open link", + group: "Form", + cmd: () => { + void open(props.form.url) + }, + }, + { + key: "escape", + desc: "Dismiss form", + group: "Form", + cmd: () => { + void sdk.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }) + }, + }, + ], + })) + + return ( + + + {props.form.title ?? "Input requested"} + + {message()} + + {props.form.url} + + + + enter open link + + + esc dismiss + + + + ) +} + +function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) { + const sdk = useSDK() + const { theme } = useTheme() + const renderer = useRenderer() + const dimensions = useTerminalDimensions() + const tuiConfig = useTuiConfig() + const modeStack = useOpencodeModeStack() + + const [tabHover, setTabHover] = createSignal(null) + const [store, setStore] = createStore({ + tab: 0, + answers: Object.fromEntries( + props.form.fields.flatMap((field) => (field.default === undefined ? [] : [[field.key, field.default]])), + ) as Record, + custom: Object.fromEntries( + props.form.fields.flatMap((field) => { + const value = customDefault(field) + return value === undefined ? [] : [[field.key, value]] + }), + ) as Record, + selected: selectedRow(props.form.fields[0], props.form.fields[0]?.default), + editing: false, + error: "", + }) + + let textarea: TextareaRenderable | undefined + let review: ScrollBoxRenderable | undefined + + const fields = createMemo(() => { + const answers: Record = {} + return props.form.fields.filter((field) => { + const active = (field.when ?? []).every((when) => { + const value = answers[when.key] + if (value === undefined) return false + const hit = Array.isArray(value) ? value.some((item) => item === when.value) : value === when.value + return when.op === "eq" ? hit : !hit + }) + if (active) answers[field.key] = store.answers[field.key] + return active + }) + }) + const single = createMemo(() => { + const list = fields() + if (props.form.fields.length !== 1) return false + if (list.length !== 1) return false + const field = list[0]! + return field.type === "boolean" || (field.type === "string" && field.options !== undefined) + }) + const tabs = createMemo(() => (single() ? 1 : fields().length + 1)) + const tabbed = createMemo(() => { + const width = fields().reduce((sum, item) => sum + truncate(fieldLabel(item), 24).length + 3, "Confirm".length + 3) + return width <= dimensions().width - 8 + }) + const answered = createMemo( + () => + fields().filter((item) => { + const value = store.answers[item.key] + return value !== undefined + }).length, + ) + const field = createMemo(() => fields()[Math.min(store.tab, fields().length - 1)]) + const confirm = createMemo(() => !single() && store.tab >= fields().length) + const rows = createMemo(() => { + const current = field() + if (!current) return [] + const configured = fieldRows(current) + const value = store.answers[current.key] + if (current.type !== "multiselect" || !Array.isArray(value)) return configured + const known = new Set(configured.map((row) => row.value)) + return [ + ...configured, + ...value.filter((item) => !known.has(item)).map((item) => ({ value: item, label: item, description: undefined })), + ] + }) + const textual = createMemo(() => { + if (confirm()) return false + const current = field() + if (!current) return false + if (current.type === "number" || current.type === "integer") return true + return current.type === "string" && current.options === undefined + }) + const custom = createMemo(() => { + const current = field() + if (!current) return false + if (current.type === "string" && current.options !== undefined) return current.custom === true + if (current.type === "multiselect") return current.custom === true + return false + }) + const multi = createMemo(() => field()?.type === "multiselect") + const placeholder = createMemo(() => { + const current = field() + if (current?.type === "string") { + if (current.placeholder) return current.placeholder + if (current.format === "email") return "name@example.com" + if (current.format === "uri") return "https://example.com" + if (current.format === "date") return "YYYY-MM-DD" + if (current.format === "date-time") return "YYYY-MM-DDTHH:MM:SSZ" + } + if (current?.type === "number" || current?.type === "integer") { + const minimum = typeof current.minimum === "number" ? current.minimum : undefined + const maximum = typeof current.maximum === "number" ? current.maximum : undefined + if (minimum !== undefined && maximum !== undefined) return `${minimum}-${maximum}` + if (minimum !== undefined) return `at least ${minimum}` + if (maximum !== undefined) return `at most ${maximum}` + } + return "Type your answer" + }) + const other = createMemo(() => custom() && store.selected === rows().length) + const input = createMemo(() => store.custom[field()?.key ?? ""] ?? "") + const customPicked = createMemo(() => { + const value = input() + if (!value) return false + const answer = store.answers[field()?.key ?? ""] + if (Array.isArray(answer)) return answer.includes(value) + return answer === value + }) + + function answer(key: string, value: FormValue | undefined) { + setStore("answers", { ...store.answers, [key]: value }) + setStore("error", "") + } + + function replySingle(field: Field, value: FormValue) { + sdk.api.form + .reply({ + sessionID: props.form.sessionID, + formID: props.form.id, + answer: { [field.key]: value }, + }) + .catch((error: unknown) => { + setStore( + "error", + typeof error === "object" && error !== null && "message" in error && typeof error.message === "string" + ? error.message + : "Invalid answer", + ) + }) + } + + function pick(value: FormValue, customValue?: string) { + const current = field() + if (!current) return + const invalid = validateValue(current, value) + if (invalid) { + setStore("error", invalid) + return + } + answer(current.key, value) + if (customValue !== undefined) setStore("custom", { ...store.custom, [current.key]: customValue }) + if (single()) { + replySingle(current, value) + return + } + selectTab(store.tab + 1) + } + + function toggle(value: string) { + const current = field() + if (!current) return + const existing = store.answers[current.key] + const list = Array.isArray(existing) ? [...existing] : [] + const index = list.indexOf(value) + if (index === -1) list.push(value) + if (index !== -1) list.splice(index, 1) + answer(current.key, list) + } + + function validateCurrent() { + if (confirm()) return true + const current = field() + if (!current) return true + const invalid = validateValue(current, store.answers[current.key]) + if (!invalid) return true + setStore("error", invalid) + return false + } + + function selectTab(index: number) { + if (!confirm() && index > store.tab && !validateCurrent()) return + const next = fields()[index] + setStore("tab", index) + setStore("selected", selectedRow(next, next ? store.answers[next.key] : undefined)) + setStore("editing", false) + setStore("error", "") + } + + function selectOption() { + if (other()) { + if (!multi()) { + setStore("editing", true) + return + } + const value = input() + if (value && customPicked()) { + toggle(value) + return + } + setStore("editing", true) + return + } + const row = rows()[store.selected] + if (!row) return + if (multi()) { + toggle(String(row.value)) + return + } + pick(row.value) + } + + function commitInput(text: string) { + const current = field() + if (!current) return false + const isTextual = textual() + const isMulti = multi() + if (!text) { + const previous = store.custom[current.key] + const existing = store.answers[current.key] + const values = Array.isArray(existing) ? existing.filter((value) => value !== previous) : [] + const value = !isTextual && isMulti && Array.isArray(existing) ? values : undefined + const invalid = validateValue(current, value) + if (invalid) { + setStore("error", invalid) + return false + } + answer(current.key, value) + setStore("custom", { ...store.custom, [current.key]: "" }) + setStore("editing", false) + return true + } + + if (isTextual && (current.type === "number" || current.type === "integer")) { + const value = Number(text) + const invalid = validateValue(current, value) + if (invalid) { + setStore("error", invalid) + return false + } + answer(current.key, value) + } + + if (isTextual && current.type === "string") { + const invalid = validateValue(current, text) + if (invalid) { + setStore("error", invalid) + return false + } + answer(current.key, text) + } + + if (!isTextual && isMulti) { + const previous = store.custom[current.key] + const existing = store.answers[current.key] + const values = Array.isArray(existing) ? [...existing] : [] + if (previous) { + const index = values.indexOf(previous) + if (index !== -1) values.splice(index, 1) + } + if (!values.includes(text)) values.push(text) + answer(current.key, values) + } + + if (!isTextual && !isMulti) { + const invalid = validateValue(current, text) + if (invalid) { + setStore("error", invalid) + return false + } + answer(current.key, text) + } + + const configured = current.type === "string" && current.options?.some((option) => option.value === text) + setStore("custom", { ...store.custom, [current.key]: isMulti || configured ? "" : text }) + setStore("editing", false) + return true + } + + function submitInput(text: string, direction: 1 | -1 = 1) { + if (!commitInput(text)) { + if (direction === -1) selectTab((store.tab + direction + tabs()) % tabs()) + return + } + if (!single()) selectTab((store.tab + direction + tabs()) % tabs()) + } + + function selectTabFromMouse(target?: Field) { + const targetIndex = () => { + const index = target ? fields().findIndex((field) => field.key === target.key) : fields().length + return index === -1 ? fields().length : index + } + const move = () => selectTab(targetIndex()) + if (!textual() && !store.editing) { + move() + return + } + if (!commitInput(textarea?.plainText?.trim() ?? "")) { + if (targetIndex() < store.tab) move() + return + } + move() + } + + onMount(() => onCleanup(modeStack.push(FORM_MODE))) + + useBindings(() => ({ + mode: FORM_MODE, + enabled: (store.editing || textual()) && !confirm(), + commands: [ + { + name: "prompt.clear", + title: "Clear answer edit", + category: "Form", + run() { + const text = textarea?.plainText ?? "" + if (!text) { + setStore("editing", false) + return + } + textarea?.setText("") + }, + }, + ], + bindings: [ + { + key: "escape", + desc: "Cancel answer edit", + group: "Form", + cmd: () => { + if (textual()) { + void sdk.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }) + return + } + setStore("editing", false) + }, + }, + ...tuiConfig.keybinds.get("prompt.clear"), + { + key: "tab", + desc: "Next field", + group: "Form", + cmd: () => { + const text = textarea?.plainText?.trim() ?? "" + submitInput(text) + }, + }, + { + key: "shift+tab", + desc: "Previous field", + group: "Form", + cmd: () => { + const text = textarea?.plainText?.trim() ?? "" + submitInput(text, -1) + }, + }, + { + key: "return", + desc: "Submit answer edit", + group: "Form", + cmd: () => { + const text = textarea?.plainText?.trim() ?? "" + const current = field() + if (!current) return + if (textual()) { + submitInput(text) + return + } + const wasMulti = multi() + if (!commitInput(text) || wasMulti || !text) return + if (single()) { + replySingle(current, text) + return + } + selectTab(store.tab + 1) + }, + }, + ], + })) + + useBindings(() => { + const total = rows().length + (custom() ? 1 : 0) + const max = Math.min(total, 9) + + return { + mode: FORM_MODE, + enabled: !store.editing && !textual(), + commands: [ + { + name: "app.exit", + title: "Dismiss form", + category: "Form", + run() { + void sdk.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }) + }, + }, + ], + bindings: [ + { + key: "left", + desc: "Previous field", + group: "Form", + cmd: () => selectTab((store.tab - 1 + tabs()) % tabs()), + }, + { + key: "h", + desc: "Previous field", + group: "Form", + cmd: () => selectTab((store.tab - 1 + tabs()) % tabs()), + }, + { key: "right", desc: "Next field", group: "Form", cmd: () => selectTab((store.tab + 1) % tabs()) }, + { key: "l", desc: "Next field", group: "Form", cmd: () => selectTab((store.tab + 1) % tabs()) }, + { + key: "tab", + desc: "Next field", + group: "Form", + cmd: () => selectTab((store.tab + 1) % tabs()), + }, + { + key: "shift+tab", + desc: "Previous field", + group: "Form", + cmd: () => selectTab((store.tab - 1 + tabs()) % tabs()), + }, + ...(confirm() + ? [ + { + key: "return", + desc: "Submit form", + group: "Form", + cmd: () => { + const invalid = fields().find((field) => validateValue(field, store.answers[field.key])) + if (invalid) { + setStore("error", validateValue(invalid, store.answers[invalid.key]) ?? "Invalid answer") + return + } + sdk.api.form + .reply({ + sessionID: props.form.sessionID, + formID: props.form.id, + answer: Object.fromEntries( + fields().flatMap((field) => { + const value = store.answers[field.key] + return value === undefined ? [] : [[field.key, value] as const] + }), + ), + }) + .catch((error: unknown) => { + setStore( + "error", + typeof error === "object" && + error !== null && + "message" in error && + typeof error.message === "string" + ? error.message + : "Invalid answer", + ) + }) + }, + }, + { + key: "escape", + desc: "Dismiss form", + group: "Form", + cmd: () => { + void sdk.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }) + }, + }, + { key: "up", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(-1) }, + { key: "k", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(-1) }, + { key: "down", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(1) }, + { key: "j", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(1) }, + ...tuiConfig.keybinds.get("app.exit"), + ] + : [ + ...Array.from({ length: max }, (_, index) => ({ + key: String(index + 1), + desc: `Select answer ${index + 1}`, + group: "Form", + cmd: () => { + setStore("selected", index) + selectOption() + }, + })), + { + key: "up", + desc: "Previous answer", + group: "Form", + cmd: () => setStore("selected", (store.selected - 1 + total) % total), + }, + { + key: "k", + desc: "Previous answer", + group: "Form", + cmd: () => setStore("selected", (store.selected - 1 + total) % total), + }, + { + key: "down", + desc: "Next answer", + group: "Form", + cmd: () => setStore("selected", (store.selected + 1) % total), + }, + { + key: "j", + desc: "Next answer", + group: "Form", + cmd: () => setStore("selected", (store.selected + 1) % total), + }, + { key: "return", desc: "Select answer", group: "Form", cmd: () => selectOption() }, + { + key: "escape", + desc: "Dismiss form", + group: "Form", + cmd: () => { + void sdk.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }) + }, + }, + ...tuiConfig.keybinds.get("app.exit"), + ]), + ], + } + }) + + return ( + + + + + {props.form.title} + + + + + + {confirm() ? "Review" : `Field ${Math.min(store.tab, fields().length - 1) + 1} of ${fields().length}`} + + + · {answered()}/{fields().length} answered + + + + + + + {(item, index) => { + const isTab = () => index() === store.tab + const isAnswered = () => store.answers[item.key] !== undefined + return ( + setTabHover(index())} + onMouseOut={() => setTabHover(null)} + onMouseUp={() => { + if (renderer.getSelection()?.getSelectedText()) return + selectTabFromMouse(item) + }} + > + + {truncate(fieldLabel(item), 24)} + + + ) + }} + + setTabHover("confirm")} + onMouseOut={() => setTabHover(null)} + onMouseUp={() => { + if (renderer.getSelection()?.getSelectedText()) return + selectTabFromMouse() + }} + > + Confirm + + + + + + + + + {field()!.description ?? fieldLabel(field()!)} + {field()!.required ? " (required)" : ""} + {multi() ? " (select all that apply)" : ""} + + + + +