Compare commits

..

3 Commits

Author SHA1 Message Date
Kit Langton 7e52e16cbe refactor(core): narrow shell spawn handling 2026-08-08 13:19:34 -04:00
Kit Langton 49d68f9a90 refactor(core): hide shell platform failures 2026-08-08 13:10:44 -04:00
Kit Langton 5bd88822c7 fix(core): settle shell spawn failures 2026-08-08 13:02:58 -04:00
83 changed files with 1037 additions and 2384 deletions
+28 -27
View File
@@ -45,34 +45,35 @@ const isToolResultValue = (value: unknown): value is ToolResultValue =>
(value.type === "text" || value.type === "json" || value.type === "error" || value.type === "content") && (value.type === "text" || value.type === "json" || value.type === "error" || value.type === "content") &&
"value" in value "value" in value
const toolResultValueSchema = Schema.Union([ export const ToolResultValue = Object.assign(
Schema.Struct({ Schema.Union([
type: Schema.Literal("json"), Schema.Struct({
value: Schema.Unknown, type: Schema.Literal("json"),
}), value: Schema.Unknown,
Schema.Struct({ }),
type: Schema.Literal("text"), Schema.Struct({
value: Schema.Unknown, type: Schema.Literal("text"),
}), value: Schema.Unknown,
Schema.Struct({ }),
type: Schema.Literal("error"), Schema.Struct({
value: Schema.Unknown, type: Schema.Literal("error"),
}), value: Schema.Unknown,
Schema.Struct({ }),
type: Schema.Literal("content"), Schema.Struct({
value: Schema.Array(Tool.Content), type: Schema.Literal("content"),
}), value: Schema.Array(Tool.Content),
]).annotate({ identifier: "LLM.ToolResult" }) }),
export type ToolResultValue = Schema.Schema.Type<typeof toolResultValueSchema> ]).annotate({ identifier: "LLM.ToolResult" }),
{
export const ToolResultValue = Object.assign(toolResultValueSchema, { is: isToolResultValue,
is: isToolResultValue, make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => {
make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => { if (isToolResultValue(value)) return value
if (isToolResultValue(value)) return value if (type === "content") return { type, value: Array.isArray(value) ? value : [] }
if (type === "content") return { type, value: Array.isArray(value) ? value : [] } return { type, value }
return { type, value } },
}, },
}) )
export type ToolResultValue = Schema.Schema.Type<typeof ToolResultValue>
export interface ToolOutput { export interface ToolOutput {
readonly structured: unknown readonly structured: unknown
+65 -6
View File
@@ -1,5 +1,7 @@
import type { AgentSideConnection, PermissionOption, ToolCallLocation } from "@agentclientprotocol/sdk" import type { AgentSideConnection, PermissionOption, ToolCallContent, ToolCallLocation } from "@agentclientprotocol/sdk"
import type { EventSubscribeOutput, OpenCodeClient } from "@opencode-ai/client/promise" import type { EventSubscribeOutput, OpenCodeClient } from "@opencode-ai/client/promise"
import { Patch } from "@opencode-ai/util/patch"
import { Result } from "effect"
import { isAbsolute, resolve } from "node:path" import { isAbsolute, resolve } from "node:path"
import { pendingToolCall, stringValue, toLocations, toToolKind, type ToolInput } from "./tool" import { pendingToolCall, stringValue, toLocations, toToolKind, type ToolInput } from "./tool"
@@ -26,8 +28,9 @@ export async function replyPermission(input: {
}) { }) {
const toolName = input.tool?.name ?? input.event.data.action const toolName = input.tool?.name ?? input.event.data.action
const toolInput = { ...input.event.data.metadata, ...input.tool?.input } const toolInput = { ...input.event.data.metadata, ...input.tool?.input }
const previews = await permissionPreviews(toolName, toolInput, input.cwd)
const toolCallID = input.event.data.source?.id ?? input.event.data.id const toolCallID = input.event.data.source?.id ?? input.event.data.id
const title = permissionTitle(toolName, toolInput, input.event.data.resources) const title = permissionTitle(toolName, toolInput, previews)
const result = await input.connection const result = await input.connection
.requestPermission({ .requestPermission({
sessionId: input.clientSessionID ?? input.sessionID, sessionId: input.clientSessionID ?? input.sessionID,
@@ -41,7 +44,8 @@ export async function replyPermission(input: {
}, },
cwd: input.cwd, cwd: input.cwd,
}), }),
locations: permissionLocations(toolName, toolInput, input.event.data.resources, input.cwd), locations: permissionLocations(toolName, toolInput, input.event.data.resources, input.cwd, previews),
...(previews.length > 0 ? { content: previews } : {}),
}, },
options, options,
}) })
@@ -90,8 +94,54 @@ export async function syncEditedFiles(input: {
) )
} }
function permissionTitle(toolName: string, input: ToolInput, resources: ReadonlyArray<string>) { async function permissionPreviews(toolName: string, input: ToolInput, cwd: string): Promise<ToolCallContent[]> {
if (toToolKind(toolName) === "edit" && resources.length > 1) return `${resources.length} files` const tool = toolName.toLocaleLowerCase()
if (tool === "patch" || tool === "apply_patch") return patchPreviews(input, cwd)
const path = filePath(input)
if (!path) return []
const oldText = await readText(path, cwd)
if (tool === "write") {
const content = stringValue(input.content)
return content === undefined ? [] : [{ type: "diff", path, oldText, newText: content }]
}
if (tool !== "edit") return []
const oldString = stringValue(input.oldString)
const newString = stringValue(input.newString)
if (oldString === undefined || newString === undefined) return []
const newText =
input.replaceAll === true ? oldText.replaceAll(oldString, newString) : oldText.replace(oldString, newString)
return [{ type: "diff", path, oldText, newText }]
}
async function patchPreviews(input: ToolInput, cwd: string): Promise<ToolCallContent[]> {
const patchText = stringValue(input.patchText)
if (!patchText) return []
try {
const parsed = Patch.parse(patchText)
if (Result.isFailure(parsed)) return []
return await Promise.all(
parsed.success.map(async (hunk): Promise<ToolCallContent> => {
const oldText = hunk.type === "add" ? "" : await readText(hunk.path, cwd)
if (hunk.type === "add") {
const newText = hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n`
return { type: "diff", path: hunk.path, oldText, newText }
}
if (hunk.type === "delete") return { type: "diff", path: hunk.path, oldText, newText: "" }
return {
type: "diff",
path: hunk.movePath ?? hunk.path,
oldText,
newText: Patch.derive(hunk.path, hunk.chunks, oldText).content,
}
}),
)
} catch {
return []
}
}
function permissionTitle(toolName: string, input: ToolInput, previews: ReadonlyArray<ToolCallContent>) {
if (previews.length > 1) return `${previews.length} files`
switch (toolName.toLocaleLowerCase()) { switch (toolName.toLocaleLowerCase()) {
case "external_directory": case "external_directory":
return stringValue(input.description) ?? stringValue(input.command) ?? stringValue(input.parentDir) return stringValue(input.description) ?? stringValue(input.command) ?? stringValue(input.parentDir)
@@ -107,7 +157,7 @@ function permissionTitle(toolName: string, input: ToolInput, resources: Readonly
case "write": case "write":
case "patch": case "patch":
case "apply_patch": case "apply_patch":
return filePath(input) return filePath(input) ?? (previews[0]?.type === "diff" ? previews[0].path : undefined)
default: default:
return undefined return undefined
} }
@@ -118,12 +168,21 @@ function permissionLocations(
input: ToolInput, input: ToolInput,
resources: ReadonlyArray<string>, resources: ReadonlyArray<string>,
cwd: string, cwd: string,
previews: ReadonlyArray<ToolCallContent>,
): ToolCallLocation[] { ): ToolCallLocation[] {
const paths = previews.flatMap((preview) => (preview.type === "diff" ? [preview.path] : []))
if (paths.length > 0) return [...new Set(paths)].map((path) => ({ path }))
const locations = toLocations(toolName, input, cwd) const locations = toLocations(toolName, input, cwd)
if (locations.length > 0) return locations if (locations.length > 0) return locations
return resources.filter((resource) => resource !== "*").map((path) => ({ path })) return resources.filter((resource) => resource !== "*").map((path) => ({ path }))
} }
function readText(path: string, cwd: string) {
return Bun.file(resolvePath(path, cwd))
.text()
.catch(() => "")
}
function filePath(input: ToolInput) { function filePath(input: ToolInput) {
return stringValue(input.path) ?? stringValue(input.filePath) ?? stringValue(input.filepath) return stringValue(input.path) ?? stringValue(input.filePath) ?? stringValue(input.filepath)
} }
@@ -211,7 +211,7 @@ describe("acp permission behavior", () => {
} }
}) })
test("authorizes edit resources and syncs the completed file", async () => { test("previews edits during approval and syncs the completed file", async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-permission-")) const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-permission-"))
const file = path.join(cwd, "file.ts") const file = path.join(cwd, "file.ts")
await fs.writeFile(file, "before") await fs.writeFile(file, "before")
@@ -240,7 +240,6 @@ describe("acp permission behavior", () => {
send( send(
permissionAsked("ses_edit", "perm_edit", { permissionAsked("ses_edit", "perm_edit", {
action: "edit", action: "edit",
resources: ["file.ts"],
source: { type: "tool", messageID: "msg_edit", id: "call_edit" }, source: { type: "tool", messageID: "msg_edit", id: "call_edit" },
}), }),
) )
@@ -279,8 +278,8 @@ describe("acp permission behavior", () => {
title: "file.ts", title: "file.ts",
kind: "edit", kind: "edit",
locations: [{ path: "file.ts" }], locations: [{ path: "file.ts" }],
content: [{ type: "diff", path: "file.ts", oldText: "before", newText: "after" }],
}) })
expect(permissionRequests[0]?.toolCall.content).toBeUndefined()
expect(writes).toEqual([{ sessionId: "ses_edit", path: file, content: "after" }]) expect(writes).toEqual([{ sessionId: "ses_edit", path: file, content: "after" }])
} finally { } finally {
await fixture.stop() await fixture.stop()
@@ -288,7 +287,7 @@ describe("acp permission behavior", () => {
} }
}) })
test("authorizes and syncs each file in a patch", async () => { test("previews and syncs each file in a patch", async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-patch-permission-")) const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-patch-permission-"))
await Promise.all([ await Promise.all([
fs.writeFile(path.join(cwd, "first.ts"), "one\n"), fs.writeFile(path.join(cwd, "first.ts"), "one\n"),
@@ -331,7 +330,6 @@ describe("acp permission behavior", () => {
send( send(
permissionAsked("ses_patch", "perm_patch", { permissionAsked("ses_patch", "perm_patch", {
action: "edit", action: "edit",
resources: ["first.ts", "second.ts"],
source: { type: "tool", messageID: "msg_patch", id: "call_patch" }, source: { type: "tool", messageID: "msg_patch", id: "call_patch" },
}), }),
) )
@@ -373,8 +371,11 @@ describe("acp permission behavior", () => {
title: "2 files", title: "2 files",
kind: "edit", kind: "edit",
locations: [{ path: "first.ts" }, { path: "second.ts" }], locations: [{ path: "first.ts" }, { path: "second.ts" }],
content: [
{ type: "diff", path: "first.ts", oldText: "one\n", newText: "two\n" },
{ type: "diff", path: "second.ts", oldText: "alpha\n", newText: "beta\n" },
],
}) })
expect(permissionRequests[0]?.toolCall.content).toBeUndefined()
expect(writes.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([ expect(writes.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([
{ sessionId: "ses_patch", path: path.join(cwd, "first.ts"), content: "two\n" }, { sessionId: "ses_patch", path: path.join(cwd, "first.ts"), content: "two\n" },
{ sessionId: "ses_patch", path: path.join(cwd, "second.ts"), content: "beta\n" }, { sessionId: "ses_patch", path: path.join(cwd, "second.ts"), content: "beta\n" },
@@ -555,7 +556,6 @@ function permissionAsked(
id: string, id: string,
input: { input: {
readonly action?: string readonly action?: string
readonly resources?: ReadonlyArray<string>
readonly metadata?: Record<string, unknown> readonly metadata?: Record<string, unknown>
readonly source?: { readonly type: "tool"; readonly messageID: string; readonly id: string } readonly source?: { readonly type: "tool"; readonly messageID: string; readonly id: string }
} = {}, } = {},
@@ -564,7 +564,7 @@ function permissionAsked(
id, id,
sessionID, sessionID,
action: input.action ?? "shell", action: input.action ?? "shell",
resources: [...(input.resources ?? ["*"])], resources: ["*"],
metadata: input.metadata ?? { command: "printf hello" }, metadata: input.metadata ?? { command: "printf hello" },
...(input.source ? { source: input.source } : {}), ...(input.source ? { source: input.source } : {}),
}) })
-2
View File
@@ -180,7 +180,6 @@ export type Endpoint5_12Input = {
readonly text: string readonly text: string
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
readonly agents?: ReadonlyArray<AgentAttachment> | undefined readonly agents?: ReadonlyArray<AgentAttachment> | undefined
readonly skills?: ReadonlyArray<PromptInput.SkillAttachment> | undefined
readonly metadata?: { readonly [x: string]: unknown } | undefined readonly metadata?: { readonly [x: string]: unknown } | undefined
readonly delivery?: "steer" | "queue" | undefined readonly delivery?: "steer" | "queue" | undefined
readonly resume?: boolean | undefined readonly resume?: boolean | undefined
@@ -197,7 +196,6 @@ export type Endpoint5_13Input = {
readonly model?: Model.Ref | undefined readonly model?: Model.Ref | undefined
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
readonly agents?: ReadonlyArray<AgentAttachment> | undefined readonly agents?: ReadonlyArray<AgentAttachment> | undefined
readonly skills?: ReadonlyArray<PromptInput.SkillAttachment> | undefined
readonly delivery?: "steer" | "queue" | undefined readonly delivery?: "steer" | "queue" | undefined
readonly resume?: boolean | undefined readonly resume?: boolean | undefined
} }
@@ -412,7 +412,6 @@ const Endpoint5_12 = (raw: RawClient["server.session"]) => (input: Endpoint5_12I
text: input["text"], text: input["text"],
files: input["files"], files: input["files"],
agents: input["agents"], agents: input["agents"],
skills: input["skills"],
metadata: input["metadata"], metadata: input["metadata"],
delivery: input["delivery"], delivery: input["delivery"],
resume: input["resume"], resume: input["resume"],
@@ -435,7 +434,6 @@ const Endpoint5_13 = (raw: RawClient["server.session"]) => (input: Endpoint5_13I
model: input["model"], model: input["model"],
files: input["files"], files: input["files"],
agents: input["agents"], agents: input["agents"],
skills: input["skills"],
delivery: input["delivery"], delivery: input["delivery"],
resume: input["resume"], resume: input["resume"],
}, },
@@ -615,7 +615,6 @@ export function make(options: ClientOptions) {
text: input["text"], text: input["text"],
files: input["files"], files: input["files"],
agents: input["agents"], agents: input["agents"],
skills: input["skills"],
metadata: input["metadata"], metadata: input["metadata"],
delivery: input["delivery"], delivery: input["delivery"],
resume: input["resume"], resume: input["resume"],
@@ -639,7 +638,6 @@ export function make(options: ClientOptions) {
model: input["model"], model: input["model"],
files: input["files"], files: input["files"],
agents: input["agents"], agents: input["agents"],
skills: input["skills"],
delivery: input["delivery"], delivery: input["delivery"],
resume: input["resume"], resume: input["resume"],
}, },
@@ -1080,8 +1080,6 @@ export type PromptFileAttachment = {
export type PromptAgentAttachment = { name: string; mention?: PromptMention } export type PromptAgentAttachment = { name: string; mention?: PromptMention }
export type PromptSkillAttachment = { id: string; name: string; text: string; mention?: PromptMention }
export type SessionMessageAssistantText = { type: "text"; text: string; state?: SessionMessageProviderState } export type SessionMessageAssistantText = { type: "text"; text: string; state?: SessionMessageProviderState }
export type SessionMessageAssistantReasoning = { export type SessionMessageAssistantReasoning = {
@@ -1567,7 +1565,6 @@ export type SessionMessageUser = {
text: string text: string
files?: Array<PromptFileAttachment> files?: Array<PromptFileAttachment>
agents?: Array<PromptAgentAttachment> agents?: Array<PromptAgentAttachment>
skills?: Array<PromptSkillAttachment>
type: "user" type: "user"
} }
@@ -1575,7 +1572,6 @@ export type SessionPendingUserData = {
text: string text: string
files?: Array<PromptFileAttachment> files?: Array<PromptFileAttachment>
agents?: Array<PromptAgentAttachment> agents?: Array<PromptAgentAttachment>
skills?: Array<PromptSkillAttachment>
metadata?: { [x: string]: JsonValue } metadata?: { [x: string]: JsonValue }
} }
@@ -1583,7 +1579,6 @@ export type SessionPendingUserData1 = {
text: string text: string
files?: Array<PromptFileAttachment> files?: Array<PromptFileAttachment>
agents?: Array<PromptAgentAttachment> agents?: Array<PromptAgentAttachment>
skills?: Array<PromptSkillAttachment>
metadata?: { [x: string]: any } metadata?: { [x: string]: any }
} }
@@ -2584,12 +2579,6 @@ export type SessionImportInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly name: string
readonly text: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly type: "user" readonly type: "user"
} }
| { | {
@@ -2835,12 +2824,6 @@ export type SessionImportInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly name: string
readonly text: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly type: "user" readonly type: "user"
} }
| { | {
@@ -3086,12 +3069,6 @@ export type SessionImportInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly name: string
readonly text: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly type: "user" readonly type: "user"
} }
| { | {
@@ -3343,10 +3320,6 @@ export type SessionPromptInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly metadata?: { readonly [x: string]: JsonValue } readonly metadata?: { readonly [x: string]: JsonValue }
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
@@ -3364,10 +3337,6 @@ export type SessionPromptInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly metadata?: { readonly [x: string]: JsonValue } readonly metadata?: { readonly [x: string]: JsonValue }
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
@@ -3385,10 +3354,6 @@ export type SessionPromptInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly metadata?: { readonly [x: string]: JsonValue } readonly metadata?: { readonly [x: string]: JsonValue }
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
@@ -3406,35 +3371,10 @@ export type SessionPromptInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly metadata?: { readonly [x: string]: JsonValue } readonly metadata?: { readonly [x: string]: JsonValue }
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["agents"] }["agents"]
readonly skills?: {
readonly id?: string | null
readonly text: string
readonly files?: ReadonlyArray<{
readonly uri: string
readonly name?: string
readonly description?: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly agents?: ReadonlyArray<{
readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly metadata?: { readonly [x: string]: JsonValue }
readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null
}["skills"]
readonly metadata?: { readonly metadata?: {
readonly id?: string | null readonly id?: string | null
readonly text: string readonly text: string
@@ -3448,10 +3388,6 @@ export type SessionPromptInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly metadata?: { readonly [x: string]: JsonValue } readonly metadata?: { readonly [x: string]: JsonValue }
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
@@ -3469,10 +3405,6 @@ export type SessionPromptInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly metadata?: { readonly [x: string]: JsonValue } readonly metadata?: { readonly [x: string]: JsonValue }
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
@@ -3490,10 +3422,6 @@ export type SessionPromptInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly metadata?: { readonly [x: string]: JsonValue } readonly metadata?: { readonly [x: string]: JsonValue }
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
@@ -3520,10 +3448,6 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["id"] }["id"]
@@ -3543,10 +3467,6 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["command"] }["command"]
@@ -3566,10 +3486,6 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["arguments"] }["arguments"]
@@ -3589,10 +3505,6 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["agent"] }["agent"]
@@ -3612,10 +3524,6 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["model"] }["model"]
@@ -3635,10 +3543,6 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["files"] }["files"]
@@ -3658,36 +3562,9 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["agents"] }["agents"]
readonly skills?: {
readonly id?: string | null
readonly command: string
readonly arguments?: string | null
readonly agent?: string | null
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
readonly files?: ReadonlyArray<{
readonly uri: string
readonly name?: string
readonly description?: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly agents?: ReadonlyArray<{
readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null
}["skills"]
readonly delivery?: { readonly delivery?: {
readonly id?: string | null readonly id?: string | null
readonly command: string readonly command: string
@@ -3704,10 +3581,6 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["delivery"] }["delivery"]
@@ -3727,10 +3600,6 @@ export type SessionCommandInput = {
readonly name: string readonly name: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string } readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}> }>
readonly skills?: ReadonlyArray<{
readonly id: string
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
}>
readonly delivery?: "steer" | "queue" | null readonly delivery?: "steer" | "queue" | null
readonly resume?: boolean | null readonly resume?: boolean | null
}["resume"] }["resume"]
+99 -58
View File
@@ -1,9 +1,13 @@
{ {
"version": "7", "version": "7",
"dialect": "sqlite", "dialect": "sqlite",
"id": "15060ec5-05f7-4b86-b2a5-9108609432b3", "id": "2d214a71-3b0a-48c1-a667-741952c4e188",
"prevIds": ["1551a157-8959-4ba9-a52b-4ea3b7b28cae"], "prevIds": ["f14a9b18-8207-487e-a3d3-227e629ba9ad"],
"ddl": [ "ddl": [
{
"name": "workspace",
"entityType": "tables"
},
{ {
"name": "account_state", "name": "account_state",
"entityType": "tables" "entityType": "tables"
@@ -69,8 +73,84 @@
"entityType": "tables" "entityType": "tables"
}, },
{ {
"name": "workspace", "type": "text",
"entityType": "tables" "notNull": false,
"autoincrement": false,
"default": null,
"generated": null,
"name": "id",
"entityType": "columns",
"table": "workspace"
},
{
"type": "text",
"notNull": true,
"autoincrement": false,
"default": null,
"generated": null,
"name": "type",
"entityType": "columns",
"table": "workspace"
},
{
"type": "text",
"notNull": true,
"autoincrement": false,
"default": "''",
"generated": null,
"name": "name",
"entityType": "columns",
"table": "workspace"
},
{
"type": "text",
"notNull": false,
"autoincrement": false,
"default": null,
"generated": null,
"name": "branch",
"entityType": "columns",
"table": "workspace"
},
{
"type": "text",
"notNull": false,
"autoincrement": false,
"default": null,
"generated": null,
"name": "directory",
"entityType": "columns",
"table": "workspace"
},
{
"type": "text",
"notNull": false,
"autoincrement": false,
"default": null,
"generated": null,
"name": "extra",
"entityType": "columns",
"table": "workspace"
},
{
"type": "text",
"notNull": true,
"autoincrement": false,
"default": null,
"generated": null,
"name": "project_id",
"entityType": "columns",
"table": "workspace"
},
{
"type": "integer",
"notNull": true,
"autoincrement": false,
"default": null,
"generated": null,
"name": "time_used",
"entityType": "columns",
"table": "workspace"
}, },
{ {
"type": "integer", "type": "integer",
@@ -1303,53 +1383,14 @@
"table": "session_v2" "table": "session_v2"
}, },
{ {
"type": "text", "columns": ["project_id"],
"notNull": false, "tableTo": "project",
"autoincrement": false, "columnsTo": ["id"],
"default": null, "onUpdate": "NO ACTION",
"generated": null, "onDelete": "CASCADE",
"name": "id", "nameExplicit": false,
"entityType": "columns", "name": "fk_workspace_project_id_project_id_fk",
"table": "workspace" "entityType": "fks",
},
{
"type": "text",
"notNull": true,
"autoincrement": false,
"default": null,
"generated": null,
"name": "provider",
"entityType": "columns",
"table": "workspace"
},
{
"type": "text",
"notNull": true,
"autoincrement": false,
"default": null,
"generated": null,
"name": "binding",
"entityType": "columns",
"table": "workspace"
},
{
"type": "integer",
"notNull": true,
"autoincrement": false,
"default": null,
"generated": null,
"name": "created_at",
"entityType": "columns",
"table": "workspace"
},
{
"type": "integer",
"notNull": true,
"autoincrement": false,
"default": null,
"generated": null,
"name": "last_used_at",
"entityType": "columns",
"table": "workspace" "table": "workspace"
}, },
{ {
@@ -1472,6 +1513,13 @@
"entityType": "pks", "entityType": "pks",
"table": "instruction_entry" "table": "instruction_entry"
}, },
{
"columns": ["id"],
"nameExplicit": false,
"name": "workspace_pk",
"table": "workspace",
"entityType": "pks"
},
{ {
"columns": ["id"], "columns": ["id"],
"nameExplicit": false, "nameExplicit": false,
@@ -1563,13 +1611,6 @@
"table": "session_v2", "table": "session_v2",
"entityType": "pks" "entityType": "pks"
}, },
{
"columns": ["id"],
"nameExplicit": false,
"name": "workspace_pk",
"table": "workspace",
"entityType": "pks"
},
{ {
"columns": [ "columns": [
{ {
@@ -0,0 +1,20 @@
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core"
import { ProjectTable } from "../project/sql"
import { Project } from "../project"
import { Workspace } from "../workspace"
export const WorkspaceTable = sqliteTable("workspace", {
id: text().$type<Workspace.ID>().primaryKey(),
type: text().notNull(),
name: text().notNull().default(""),
branch: text(),
directory: text(),
extra: text({ mode: "json" }),
project_id: text()
.$type<Project.ID>()
.notNull()
.references(() => ProjectTable.id, { onDelete: "cascade" }),
time_used: integer()
.notNull()
.$default(() => Date.now()),
})
-1
View File
@@ -42,6 +42,5 @@ export const migrations: DatabaseMigration.Migration[] = (
import("./migration/20260622202450_simplify_session_input"), import("./migration/20260622202450_simplify_session_input"),
import("./migration/20260804233008_loose_psylocke"), import("./migration/20260804233008_loose_psylocke"),
import("./migration/20260805200742_import_legacy_credentials"), import("./migration/20260805200742_import_legacy_credentials"),
import("./migration/20260808023530_workspace_domain"),
]) ])
).map((module) => module.default) ).map((module) => module.default)
@@ -1,22 +0,0 @@
import { Effect } from "effect"
import type { DatabaseMigration } from "../migration"
const migration: DatabaseMigration.Migration = {
id: "20260808023530_workspace_domain",
up(tx) {
return Effect.gen(function* () {
yield* tx.run(`DROP TABLE \`workspace\`;`)
yield* tx.run(`
CREATE TABLE \`workspace\` (
\`id\` text PRIMARY KEY,
\`provider\` text NOT NULL,
\`binding\` text NOT NULL,
\`created_at\` integer NOT NULL,
\`last_used_at\` integer NOT NULL
);
`)
})
},
}
export default migration
+13 -9
View File
@@ -4,6 +4,19 @@ import type { DatabaseMigration } from "./migration"
const schema: Omit<DatabaseMigration.Migration, "id"> = { const schema: Omit<DatabaseMigration.Migration, "id"> = {
up(tx) { up(tx) {
return Effect.gen(function* () { return Effect.gen(function* () {
yield* tx.run(`
CREATE TABLE \`workspace\` (
\`id\` text PRIMARY KEY,
\`type\` text NOT NULL,
\`name\` text DEFAULT '' NOT NULL,
\`branch\` text,
\`directory\` text,
\`extra\` text,
\`project_id\` text NOT NULL,
\`time_used\` integer NOT NULL,
CONSTRAINT \`fk_workspace_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE
);
`)
yield* tx.run(` yield* tx.run(`
CREATE TABLE \`account_state\` ( CREATE TABLE \`account_state\` (
\`id\` integer PRIMARY KEY, \`id\` integer PRIMARY KEY,
@@ -203,15 +216,6 @@ const schema: Omit<DatabaseMigration.Migration, "id"> = {
CONSTRAINT \`fk_session_v2_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE CONSTRAINT \`fk_session_v2_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE
); );
`) `)
yield* tx.run(`
CREATE TABLE \`workspace\` (
\`id\` text PRIMARY KEY,
\`provider\` text NOT NULL,
\`binding\` text NOT NULL,
\`created_at\` integer NOT NULL,
\`last_used_at\` integer NOT NULL
);
`)
yield* tx.run(`CREATE UNIQUE INDEX \`event_aggregate_seq_idx\` ON \`event\` (\`aggregate_id\`,\`seq\`);`) yield* tx.run(`CREATE UNIQUE INDEX \`event_aggregate_seq_idx\` ON \`event\` (\`aggregate_id\`,\`seq\`);`)
yield* tx.run(`CREATE INDEX \`event_aggregate_type_seq_idx\` ON \`event\` (\`aggregate_id\`,\`type\`,\`seq\`);`) yield* tx.run(`CREATE INDEX \`event_aggregate_type_seq_idx\` ON \`event\` (\`aggregate_id\`,\`type\`,\`seq\`);`)
yield* tx.run( yield* tx.run(
+2 -19
View File
@@ -5,8 +5,6 @@ import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner
import type { Files } from "./files" import type { Files } from "./files"
import { makeFiles } from "./index" import { makeFiles } from "./index"
import { makeLocalDriver } from "./local" import { makeLocalDriver } from "./local"
import { Location } from "../location"
import { Workspace } from "../workspace"
export interface Interface { export interface Interface {
readonly files: Files readonly files: Files
@@ -19,25 +17,10 @@ const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner const spawner = yield* ChildProcessSpawner
const location = yield* Location.Service return Service.of({ files: makeFiles(makeLocalDriver(spawner)), spawner })
const workspace = yield* Workspace.Service
const driver = location.workspaceID
? yield* workspace.connect(location.workspaceID).pipe(
// Environment has no error channel; an unknown or destroyed placement is a configuration defect by design.
Effect.mapError(
(cause) => new Error(`Failed to bind Environment to workspace ${location.workspaceID}`, { cause }),
),
Effect.orDie,
)
: makeLocalDriver(spawner)
return Service.of({ files: makeFiles(driver), spawner: driver.spawner })
}), }),
) )
export const node = makeLocationNode({ export const node = makeLocationNode({ service: Service, layer, deps: [CrossSpawnSpawner.node] })
service: Service,
layer,
deps: [CrossSpawnSpawner.node, Location.node, Workspace.node],
})
export * as EnvironmentService from "./environment" export * as EnvironmentService from "./environment"
+41 -30
View File
@@ -48,13 +48,15 @@ export const readText = Effect.fn("FileMutation.readText")(function* (files: Fil
return Bom.decodeBytes((yield* files.read(target)).bytes) return Bom.decodeBytes((yield* files.read(target)).bytes)
}) })
export const syncTextBom = Effect.fn("FileMutation.syncTextBom")((files: Files, target: string, bom: boolean) => export const syncTextBom = Effect.fn("FileMutation.syncTextBom")(function* (
Effect.gen(function* () { files: Files,
const synced = Bom.syncBytes((yield* files.read(target)).bytes, bom) target: string,
if (synced.bytes) yield* files.write(target, synced.bytes) bom: boolean,
return synced.text ) {
}).pipe(Effect.uninterruptible), const synced = Bom.syncBytes((yield* files.read(target)).bytes, bom)
) if (synced.bytes) yield* files.write(target, synced.bytes)
return synced.text
})
/** Share transaction locks across Location graphs that address the same file. */ /** Share transaction locks across Location graphs that address the same file. */
const transactionLocks = KeyedMutex.makeUnsafe<string>() const transactionLocks = KeyedMutex.makeUnsafe<string>()
@@ -68,10 +70,15 @@ const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const environment = yield* Environment.Service const environment = yield* Environment.Service
const locks = KeyedMutex.makeUnsafe<string>()
const withLock: Interface["withLock"] = (targets) => (effect) => const withLock: Interface["withLock"] = (targets) => (effect) =>
[...new Set(targets.map(FSUtil.resolve))] [...new Set(targets.map(FSUtil.resolve))]
.sort() .sort()
.reduceRight((result, target) => transactionLocks.withLock(target)(result), effect) .reduceRight((result, target) => transactionLocks.withLock(target)(result), effect)
const withTargetLock =
(target: Target) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
locks.withLock(target.absolute)(Effect.uninterruptible(effect))
const writeResult = (target: Target, existed: boolean): WriteResult => ({ const writeResult = (target: Target, existed: boolean): WriteResult => ({
operation: "write", operation: "write",
@@ -81,32 +88,36 @@ const layer = Layer.effect(
}) })
const write = Effect.fn("FileMutation.write")((input: WriteInput) => const write = Effect.fn("FileMutation.write")((input: WriteInput) =>
Effect.gen(function* () { withTargetLock(input.target)(
const existed = yield* environment.files.stat(input.target.absolute).pipe( Effect.gen(function* () {
Effect.as(true), const existed = yield* environment.files.stat(input.target.absolute).pipe(
Effect.catchTag("Environment.NotFound", () => Effect.succeed(false)), Effect.as(true),
) Effect.catchTag("Environment.NotFound", () => Effect.succeed(false)),
yield* environment.files.write( )
input.target.absolute, yield* environment.files.write(
typeof input.content === "string" ? new TextEncoder().encode(input.content) : input.content, input.target.absolute,
) typeof input.content === "string" ? new TextEncoder().encode(input.content) : input.content,
return writeResult(input.target, existed) )
}).pipe(Effect.uninterruptible), return writeResult(input.target, existed)
}),
),
) )
const writeTextPreservingBom = Effect.fn("FileMutation.writeTextPreservingBom")((input: TextWriteInput) => const writeTextPreservingBom = Effect.fn("FileMutation.writeTextPreservingBom")((input: TextWriteInput) =>
Effect.gen(function* () { withTargetLock(input.target)(
const next = Bom.split(input.content) Effect.gen(function* () {
const current = yield* environment.files.read(input.target.absolute, { offset: 0, length: 3 }).pipe( const next = Bom.split(input.content)
Effect.map((result) => result.bytes), const current = yield* environment.files.read(input.target.absolute, { offset: 0, length: 3 }).pipe(
Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)), Effect.map((result) => result.bytes),
) Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)),
yield* environment.files.write( )
input.target.absolute, yield* environment.files.write(
new TextEncoder().encode(Bom.join(next.text, Boolean(current && Bom.has(current)) || next.bom)), input.target.absolute,
) new TextEncoder().encode(Bom.join(next.text, Boolean(current && Bom.has(current)) || next.bom)),
return writeResult(input.target, current !== undefined) )
}).pipe(Effect.uninterruptible), return writeResult(input.target, current !== undefined)
}),
),
) )
return Service.of({ withLock, write, writeTextPreservingBom }) return Service.of({ withLock, write, writeTextPreservingBom })
-3
View File
@@ -11,7 +11,6 @@ import { Provider } from "@opencode-ai/schema/provider"
import { AbsolutePath } from "@opencode-ai/schema/schema" import { AbsolutePath } from "@opencode-ai/schema/schema"
import { Session } from "@opencode-ai/schema/session" import { Session } from "@opencode-ai/schema/session"
import { SessionMessage } from "@opencode-ai/schema/session-message" import { SessionMessage } from "@opencode-ai/schema/session-message"
import { Skill } from "@opencode-ai/schema/skill"
import { Workspace } from "@opencode-ai/schema/workspace" import { Workspace } from "@opencode-ai/schema/workspace"
import { WebSearch } from "@opencode-ai/schema/websearch" import { WebSearch } from "@opencode-ai/schema/websearch"
import { DateTime, Effect, Scope, Stream } from "effect" import { DateTime, Effect, Scope, Stream } from "effect"
@@ -297,7 +296,6 @@ export function fromPromise(plugin: Plugin) {
...input, ...input,
sessionID: Session.ID.make(input.sessionID), sessionID: Session.ID.make(input.sessionID),
id: input.id == null ? undefined : SessionMessage.ID.make(input.id), id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
skills: input.skills?.map((skill) => ({ ...skill, id: Skill.ID.make(skill.id) })),
delivery: input.delivery ?? undefined, delivery: input.delivery ?? undefined,
resume: input.resume ?? undefined, resume: input.resume ?? undefined,
}), }),
@@ -312,7 +310,6 @@ export function fromPromise(plugin: Plugin) {
id: input.id == null ? undefined : SessionMessage.ID.make(input.id), id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
agent: input.agent == null ? undefined : Agent.ID.make(input.agent), agent: input.agent == null ? undefined : Agent.ID.make(input.agent),
model: input.model == null ? undefined : model(input.model), model: input.model == null ? undefined : model(input.model),
skills: input.skills?.map((skill) => ({ ...skill, id: Skill.ID.make(skill.id) })),
arguments: input.arguments ?? undefined, arguments: input.arguments ?? undefined,
delivery: input.delivery ?? undefined, delivery: input.delivery ?? undefined,
resume: input.resume ?? undefined, resume: input.resume ?? undefined,
+4 -10
View File
@@ -233,7 +233,7 @@ const layer = Layer.effect(
const bus = yield* Bus.Service const bus = yield* Bus.Service
const watcher = yield* Watcher.Service const watcher = yield* Watcher.Service
const fs = yield* FSUtil.Service const fs = yield* FSUtil.Service
const ready = { current: yield* Deferred.make<void>() } const ready = yield* Deferred.make<void>()
let observed = 0 let observed = 0
// Configured local plugin files can live outside config roots, where the // Configured local plugin files can live outside config roots, where the
@@ -291,13 +291,7 @@ const layer = Layer.effect(
bus.subscribe([Event.Updated, SdkPlugins.Updated]), bus.subscribe([Event.Updated, SdkPlugins.Updated]),
).pipe( ).pipe(
// Make accepted work visible to flush before coalescing the burst. // Make accepted work visible to flush before coalescing the burst.
Stream.mapEffect(() => Stream.mapEffect(() => Effect.sync(() => ++observed)),
Effect.gen(function* () {
observed++
if (yield* Deferred.isDone(ready.current)) ready.current = yield* Deferred.make<void>()
return observed
}),
),
) )
yield* Stream.concat(Stream.succeed(0), updates).pipe( yield* Stream.concat(Stream.succeed(0), updates).pipe(
// Keep observing updates while activation runs, retaining only the latest generation request. // Keep observing updates while activation runs, retaining only the latest generation request.
@@ -306,12 +300,12 @@ const layer = Layer.effect(
Stream.runForEach((target) => Stream.runForEach((target) =>
Effect.gen(function* () { Effect.gen(function* () {
yield* activate() yield* activate()
if (observed === target) yield* Deferred.succeed(ready.current, undefined) if (observed === target) yield* Deferred.succeed(ready, undefined)
}).pipe(Effect.catchCause((cause) => Effect.logError("failed to reload plugins", { cause }))), }).pipe(Effect.catchCause((cause) => Effect.logError("failed to reload plugins", { cause }))),
), ),
Effect.forkScoped({ startImmediately: true }), Effect.forkScoped({ startImmediately: true }),
) )
return Service.of({ flush: Effect.suspend(() => Deferred.await(ready.current)) }) return Service.of({ flush: Deferred.await(ready) })
}), }),
) )
+7 -31
View File
@@ -218,11 +218,10 @@ export interface Interface {
text: string text: string
files?: PromptInput.Prompt["files"] files?: PromptInput.Prompt["files"]
agents?: PromptInput.Prompt["agents"] agents?: PromptInput.Prompt["agents"]
skills?: PromptInput.Prompt["skills"]
metadata?: Record<string, unknown> metadata?: Record<string, unknown>
delivery?: SessionPending.Delivery delivery?: SessionPending.Delivery
resume?: boolean resume?: boolean
}) => Effect.Effect<SessionPending.User, NotFoundError | PromptConflictError | AttachmentError | SkillNotFoundError> }) => Effect.Effect<SessionPending.User, NotFoundError | PromptConflictError | AttachmentError>
/** Generates text from current Session context without admitting input or mutating history. */ /** Generates text from current Session context without admitting input or mutating history. */
readonly generate: (input: { readonly generate: (input: {
sessionID: SessionSchema.ID sessionID: SessionSchema.ID
@@ -237,17 +236,11 @@ export interface Interface {
model?: Model.Ref model?: Model.Ref
files?: PromptInput.Prompt["files"] files?: PromptInput.Prompt["files"]
agents?: PromptInput.Prompt["agents"] agents?: PromptInput.Prompt["agents"]
skills?: PromptInput.Prompt["skills"]
delivery?: SessionPending.Delivery delivery?: SessionPending.Delivery
resume?: boolean resume?: boolean
}) => Effect.Effect< }) => Effect.Effect<
SessionPending.User, SessionPending.User,
| NotFoundError NotFoundError | PromptConflictError | AttachmentError | Command.NotFoundError | Command.EvaluationError
| PromptConflictError
| AttachmentError
| SkillNotFoundError
| Command.NotFoundError
| Command.EvaluationError
> >
readonly shell: (input: { readonly shell: (input: {
id?: Event.ID id?: Event.ID
@@ -572,11 +565,9 @@ const layer = Layer.effect(
// Resolved lazily so prompt admission only boots location services when an // Resolved lazily so prompt admission only boots location services when an
// image attachment actually needs the resizer. // image attachment actually needs the resizer.
const image = Image.Service.pipe(Effect.provide(locations.get(session.location))) const image = Image.Service.pipe(Effect.provide(locations.get(session.location)))
const skills = Skill.Service.pipe(Effect.provide(locations.get(session.location)))
const prompt = yield* resolvePrompt( const prompt = yield* resolvePrompt(
{ text: input.text, files: input.files, agents: input.agents, skills: input.skills }, { text: input.text, files: input.files, agents: input.agents },
image, image,
skills,
).pipe(Effect.provideService(FSUtil.Service, fs)) ).pipe(Effect.provideService(FSUtil.Service, fs))
const messageID = input.id ?? SessionMessage.ID.create() const messageID = input.id ?? SessionMessage.ID.create()
const admittedInput = SessionPending.Message.make({ const admittedInput = SessionPending.Message.make({
@@ -642,7 +633,6 @@ const layer = Layer.effect(
text: evaluated.text, text: evaluated.text,
files: input.files, files: input.files,
agents: input.agents, agents: input.agents,
skills: input.skills,
delivery: input.delivery, delivery: input.delivery,
resume: input.resume, resume: input.resume,
}) })
@@ -655,7 +645,9 @@ const layer = Layer.effect(
yield* execution.awaitIdle(input.sessionID) yield* execution.awaitIdle(input.sessionID)
const started = yield* Effect.gen(function* () { const started = yield* Effect.gen(function* () {
const shell = yield* Shell.Service const shell = yield* Shell.Service
return yield* shell.create({ command: input.command, cwd: session.location.directory, timeout: 0 }) return yield* shell
.create({ command: input.command, cwd: session.location.directory, timeout: 0 })
.pipe(Effect.orDie)
}).pipe(Effect.provide(locations.get(session.location))) }).pipe(Effect.provide(locations.get(session.location)))
yield* bus.publish( yield* bus.publish(
SessionEvent.Shell.Started, SessionEvent.Shell.Started,
@@ -905,28 +897,12 @@ function synthesizeTerminalShellInfo(started: ShellSchema.Info): ShellSchema.Inf
const resolvePrompt = Effect.fn("Session.resolvePrompt")(function* ( const resolvePrompt = Effect.fn("Session.resolvePrompt")(function* (
input: PromptInput.Prompt, input: PromptInput.Prompt,
image: Effect.Effect<Image.Interface>, image: Effect.Effect<Image.Interface>,
skills: Effect.Effect<Skill.Interface>,
) { ) {
const fs = yield* FSUtil.Service const fs = yield* FSUtil.Service
const files = input.files const files = input.files
? yield* Effect.forEach(input.files, (file) => materializeAttachment(fs, file, image), { concurrency: 8 }) ? yield* Effect.forEach(input.files, (file) => materializeAttachment(fs, file, image), { concurrency: 8 })
: undefined : undefined
const requested = input.skills return Prompt.make({ text: input.text, agents: input.agents, files })
const selected = yield* Effect.gen(function* () {
if (!requested?.length) return undefined
const available = yield* (yield* skills).list()
return yield* Effect.forEach(requested, (attachment) => {
const skill = available.find((item) => item.id === attachment.id)
if (!skill) return Effect.fail(new SkillNotFoundError({ skill: attachment.id }))
return Effect.succeed({
id: skill.id,
name: skill.name,
text: Skill.toModelOutput(skill, []),
mention: attachment.mention,
})
})
})
return Prompt.make({ text: input.text, agents: input.agents, files, skills: selected?.length ? selected : undefined })
}) })
const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
+1 -2
View File
@@ -124,8 +124,7 @@ const serialize = (message: SessionMessage.Info) => {
(file) => (file) =>
`[Attached ${file.mime}: ${file.name ?? (file.source.type === "uri" ? file.source.uri : "inline attachment")}]`, `[Attached ${file.mime}: ${file.name ?? (file.source.type === "uri" ? file.source.uri : "inline attachment")}]`,
) ?? [] ) ?? []
const skills = message.skills?.map((skill) => `[Attached skill: ${skill.name}]\n${skill.text}`) ?? [] return [`[User]: ${message.text}`, ...files].join("\n")
return [`[User]: ${message.text}`, ...skills, ...files].join("\n")
} }
if (message.type === "assistant") { if (message.type === "assistant") {
return message.content return message.content
+8 -1
View File
@@ -16,6 +16,7 @@ import { SessionPendingTable, SessionMessageTable, SessionTable } from "./sql"
import { Slug } from "../util/slug" import { Slug } from "../util/slug"
import { Money } from "@opencode-ai/schema/money" import { Money } from "@opencode-ai/schema/money"
import type { SessionSchema } from "./schema" import type { SessionSchema } from "./schema"
import { WorkspaceTable } from "../control-plane/workspace.sql"
type DatabaseService = Database.Interface["db"] type DatabaseService = Database.Interface["db"]
type CurrentDurableEvent = Extract<SessionEvent.Event, { readonly durable: object }> type CurrentDurableEvent = Extract<SessionEvent.Event, { readonly durable: object }>
@@ -375,6 +376,13 @@ const layer = Layer.effectDiscard(
.get() .get()
.pipe(Effect.orDie) .pipe(Effect.orDie)
if (!stored) return yield* Effect.die(new SessionAlreadyProjected()) if (!stored) return yield* Effect.die(new SessionAlreadyProjected())
if (!event.data.location.workspaceID) return
yield* db
.update(WorkspaceTable)
.set({ time_used: Date.now() })
.where(eq(WorkspaceTable.id, event.data.location.workspaceID))
.run()
.pipe(Effect.orDie)
}), }),
) )
yield* bus.project(SessionEvent.Moved, (event) => yield* bus.project(SessionEvent.Moved, (event) =>
@@ -445,7 +453,6 @@ const layer = Layer.effectDiscard(
text: input.data.text, text: input.data.text,
files: input.data.files, files: input.data.files,
agents: input.data.agents, agents: input.data.agents,
skills: input.data.skills,
time: { created: event.created }, time: { created: event.created },
} }
: { : {
@@ -184,7 +184,6 @@ function toLLMMessage(message: SessionMessage.Info, model: Model.Ref, providerMe
return [] return []
case "user": case "user":
const content = [ const content = [
...(message.skills ?? []).map((skill) => Message.text(skill.text)),
...(message.text === "" ? [] : [Message.text(message.text)]), ...(message.text === "" ? [] : [Message.text(message.text)]),
...(message.files ?? []).flatMap(attachmentContent), ...(message.files ?? []).flatMap(attachmentContent),
] ]
-9
View File
@@ -2,7 +2,6 @@ export * as SessionTransfer from "./transfer"
import { SessionTransfer } from "@opencode-ai/schema/session-transfer" import { SessionTransfer } from "@opencode-ai/schema/session-transfer"
import { Tool } from "@opencode-ai/schema/tool" import { Tool } from "@opencode-ai/schema/tool"
import { Skill } from "@opencode-ai/schema/skill"
import { eq, isNotNull, isNull, ne, or } from "drizzle-orm" import { eq, isNotNull, isNull, ne, or } from "drizzle-orm"
import { Context, DateTime, Effect, Layer, Schema } from "effect" import { Context, DateTime, Effect, Layer, Schema } from "effect"
import path from "path" import path from "path"
@@ -219,14 +218,6 @@ function sanitizeMessage(message: SessionMessage.Info): SessionMessage.Info {
? { ...agent.mention, text: redact("agent-mention", String(index), agent.mention.text) } ? { ...agent.mention, text: redact("agent-mention", String(index), agent.mention.text) }
: undefined, : undefined,
})), })),
skills: message.skills?.map((skill, index) => ({
...skill,
name: Skill.Name.make(redact("skill-name", String(index), skill.name)),
text: redact("skill", String(index), skill.text),
mention: skill.mention
? { ...skill.mention, text: redact("skill-mention", String(index), skill.mention.text) }
: undefined,
})),
} }
if (message.type === "synthetic") if (message.type === "synthetic")
return { return {
+17 -12
View File
@@ -5,6 +5,7 @@ import { Context, Deferred, Duration, Effect, Fiber, Layer, Schema, Stream } fro
import { ChildProcess } from "effect/unstable/process" import { ChildProcess } from "effect/unstable/process"
import { produce } from "immer" import { produce } from "immer"
import { Shell } from "@opencode-ai/schema/shell" import { Shell } from "@opencode-ai/schema/shell"
import { AppProcess } from "@opencode-ai/util/process"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node" import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { Config } from "./config" import { Config } from "./config"
import { Bus } from "./bus" import { Bus } from "./bus"
@@ -50,7 +51,7 @@ export interface Interface {
readonly create: <E = never, R = never>( readonly create: <E = never, R = never>(
input: Shell.CreateInput, input: Shell.CreateInput,
before?: (input: ShellCreateBefore) => Effect.Effect<void, E, R>, before?: (input: ShellCreateBefore) => Effect.Effect<void, E, R>,
) => Effect.Effect<Shell.Info, E, R> ) => Effect.Effect<Shell.Info, E | AppProcess.AppProcessError, R>
// Currently running commands only; exited shells are retained for get/output but excluded here. // Currently running commands only; exited shells are retained for get/output but excluded here.
readonly list: () => Effect.Effect<Shell.Info[]> readonly list: () => Effect.Effect<Shell.Info[]>
readonly get: (id: Shell.ID) => Effect.Effect<Shell.Info, NotFoundError> readonly get: (id: Shell.ID) => Effect.Effect<Shell.Info, NotFoundError>
@@ -213,19 +214,23 @@ export const layer = (options?: ShellSelect.Options) =>
// Spawn through the Environment and stream combined output to the file. The handle is scope-bound, so // Spawn through the Environment and stream combined output to the file. The handle is scope-bound, so
// the managing fiber keeps its scope open until the command terminates (it awaits `done` at the // the managing fiber keeps its scope open until the command terminates (it awaits `done` at the
// end). `create` returns once `ready` resolves with the registered session. // end). `create` returns once `ready` resolves with the registered session.
const ready = Deferred.makeUnsafe<Active>() const ready = Deferred.makeUnsafe<Active, AppProcess.AppProcessError>()
runFork( runFork(
Effect.scoped( Effect.scoped(
Effect.gen(function* () { Effect.gen(function* () {
const handle = yield* environment.spawner.spawn( const handle = yield* environment.spawner
ChildProcess.make(invocation.shell, args, { .spawn(
cwd: invocation.cwd, ChildProcess.make(invocation.shell, args, {
env: invocation.env, cwd: invocation.cwd,
stdin: "ignore", env: invocation.env,
detached: process.platform !== "win32", stdin: "ignore",
forceKillAfter: Duration.seconds(3), detached: process.platform !== "win32",
}), forceKillAfter: Duration.seconds(3),
) }),
)
.pipe(
Effect.mapError((cause) => new AppProcess.AppProcessError({ command: invocation.command, cause })),
)
const session: Active = { const session: Active = {
info: produce(info, (draft) => { info: produce(info, (draft) => {
draft.pid = handle.pid draft.pid = handle.pid
@@ -327,7 +332,7 @@ export const layer = (options?: ShellSelect.Options) =>
// release (kill) the process before its exit is observed. // release (kill) the process before its exit is observed.
yield* Deferred.await(session.done).pipe(Effect.catch(() => Effect.void)) yield* Deferred.await(session.done).pipe(Effect.catch(() => Effect.void))
}), }),
).pipe(Effect.catch(() => Effect.void)), ).pipe(Effect.catchTag("AppProcessError", (error) => Deferred.fail(ready, error))),
) )
const session = yield* Deferred.await(ready) const session = yield* Deferred.await(ready)
-19
View File
@@ -38,25 +38,6 @@ export { Event } from "@opencode-ai/schema/skill"
export const available = (skills: ReadonlyArray<Info>, agent: Agent.Info) => export const available = (skills: ReadonlyArray<Info>, agent: Agent.Info) =>
skills.filter((skill) => Permission.evaluate("skill", skill.id, agent.permissions).effect !== "deny") skills.filter((skill) => Permission.evaluate("skill", skill.id, agent.permissions).effect !== "deny")
export const toModelOutput = (skill: Info, files: ReadonlyArray<string>) => {
const directory = path.dirname(skill.location)
return [
`<skill_content name="${skill.name}">`,
`# Skill: ${skill.name}`,
"",
skill.content.trim(),
"",
`Base directory for this skill: ${directory}`,
"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.",
"Note: file list is sampled.",
"",
"<skill_files>",
...files.map((file) => `<file>${file}</file>`),
"</skill_files>",
"</skill_content>",
].join("\n")
}
const Frontmatter = Schema.Struct({ const Frontmatter = Schema.Struct({
name: Schema.String.pipe(Schema.optional), name: Schema.String.pipe(Schema.optional),
description: Schema.String.pipe(Schema.optional), description: Schema.String.pipe(Schema.optional),
+61 -55
View File
@@ -11,9 +11,11 @@ import { ToolFailure } from "@opencode-ai/ai"
import { FileDiff } from "@opencode-ai/schema/file-diff" import { FileDiff } from "@opencode-ai/schema/file-diff"
import { Bom } from "@opencode-ai/util/bom" import { Bom } from "@opencode-ai/util/bom"
import { Effect, Schema } from "effect" import { Effect, Schema } from "effect"
import path from "path"
import { Environment } from "../../environment" import { Environment } from "../../environment"
import { FileMutation } from "../../file-mutation" import { FileMutation } from "../../file-mutation"
import { Formatter } from "../../formatter" import { Formatter } from "../../formatter"
import { Location } from "../../location"
import { LocationMutation } from "../../location-mutation" import { LocationMutation } from "../../location-mutation"
import { Permission } from "../../permission" import { Permission } from "../../permission"
import { fileDiff } from "./file-diff" import { fileDiff } from "./file-diff"
@@ -85,7 +87,7 @@ const findLineOccurrences = (content: string, search: string) => {
if ( if (
!actual.every( !actual.every(
(item, lineIndex) => (item, lineIndex) =>
normalizeForMatch(item.text.trimEnd()) === normalizeForMatch(expected[lineIndex].trimEnd()), normalizeForMatch(item.text.trimEnd()) === normalizeForMatch(expected[lineIndex]!.trimEnd()),
) )
) )
return [] return []
@@ -112,6 +114,7 @@ export const Plugin = {
const fileMutation = yield* FileMutation.Service const fileMutation = yield* FileMutation.Service
const environment = yield* Environment.Service const environment = yield* Environment.Service
const formatter = yield* Formatter.Service const formatter = yield* Formatter.Service
const location = yield* Location.Service
const permission = yield* Permission.Service const permission = yield* Permission.Service
yield* ctx.tool yield* ctx.tool
@@ -151,69 +154,72 @@ export const Plugin = {
source: permissionSource, source: permissionSource,
}) })
} }
const original = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.catchTag("Environment.NotFound", () =>
Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })),
),
Effect.catchTag("Environment.WrongKind", (error) =>
error.actual === "directory"
? Effect.fail(new ToolFailure({ message: `Path is a directory, not a file: ${input.path}` }))
: Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}`, error })),
),
)
const source = original.text
const ending = source.includes(crlf) ? crlf : "\n"
const oldString = input.oldString.replaceAll(crlf, "\n").replaceAll("\n", ending)
const newString = input.newString.replaceAll(crlf, "\n").replaceAll("\n", ending)
const exact = findOccurrences(source, oldString)
// These one-to-one mappings preserve offsets into the original source.
const unicode =
exact.length > 0 ? [] : findOccurrences(normalizeForMatch(source), normalizeForMatch(oldString))
const trailing = exact.length > 0 || unicode.length > 0 ? [] : findLineOccurrences(source, oldString)
const matches = exact.length > 0 ? exact : unicode.length > 0 ? unicode : trailing
const replacements = matches.length
const replaced = (input.replaceAll === true ? matches : matches.slice(0, 1))
.toReversed()
.reduce(
(content, match) => `${content.slice(0, match.start)}${newString}${content.slice(match.end)}`,
source,
)
const preview =
replacements > 0 && (replacements === 1 || input.replaceAll === true)
? fileDiff(target.resource, source, replaced)
: undefined
yield* permission.assert({ yield* permission.assert({
action: "edit", action: "edit",
resources: [target.resource], resources: [target.resource],
save: ["*"], save: ["*"],
metadata: preview ? { files: [preview] } : undefined,
sessionID: context.sessionID, sessionID: context.sessionID,
agent: context.agent, agent: context.agent,
source: permissionSource, source: permissionSource,
}) })
return yield* fileMutation.withLock([target.absolute])( if (replacements === 0) {
Effect.gen(function* () { return yield* new ToolFailure({
const original = yield* FileMutation.readText(environment.files, target.absolute).pipe( message: `Could not find oldString in ${input.path}. It must match exactly, including whitespace and indentation.`,
Effect.catchTag("Environment.NotFound", () => })
Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })), }
), if (replacements > 1 && input.replaceAll !== true) {
Effect.catchTag("Environment.WrongKind", (error) => return yield* new ToolFailure({
error.actual === "directory" message: `Found ${replacements} matches for oldString, but expected exactly one. Add more surrounding context to make oldString unique, or set replaceAll to true to replace every occurrence.`,
? Effect.fail(new ToolFailure({ message: `Path is a directory, not a file: ${input.path}` })) })
: Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}`, error })), }
), const replacementBom = replaced.startsWith("\uFEFF")
) const result = yield* fileMutation.write({
const source = original.text target,
const ending = source.includes(crlf) ? crlf : "\n" content: Bom.join(replaced, original.bom || replacementBom),
const oldString = input.oldString.replaceAll(crlf, "\n").replaceAll("\n", ending) })
const newString = input.newString.replaceAll(crlf, "\n").replaceAll("\n", ending) const bom = original.bom || replacementBom
const exact = findOccurrences(source, oldString) const formatted = (yield* formatter.file(target.absolute))
// These one-to-one mappings preserve offsets into the original source. ? yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
const unicode = : (yield* FileMutation.readText(environment.files, target.absolute)).text
exact.length > 0 ? [] : findOccurrences(normalizeForMatch(source), normalizeForMatch(oldString)) return {
const trailing = exact.length > 0 || unicode.length > 0 ? [] : findLineOccurrences(source, oldString) files: [fileDiff(result.resource, source, formatted)],
const matches = exact.length > 0 ? exact : unicode.length > 0 ? unicode : trailing replacements,
const replacements = matches.length } satisfies Output
const replaced = (input.replaceAll === true ? matches : matches.slice(0, 1))
.toReversed()
.reduce(
(content, match) => `${content.slice(0, match.start)}${newString}${content.slice(match.end)}`,
source,
)
if (replacements === 0) {
return yield* new ToolFailure({
message: `Could not find oldString in ${input.path}. It must match exactly, including whitespace and indentation.`,
})
}
if (replacements > 1 && input.replaceAll !== true) {
return yield* new ToolFailure({
message: `Found ${replacements} matches for oldString, but expected exactly one. Add more surrounding context to make oldString unique, or set replaceAll to true to replace every occurrence.`,
})
}
const replacementBom = replaced.startsWith("\uFEFF")
const result = yield* fileMutation.write({
target,
content: Bom.join(replaced, original.bom || replacementBom),
})
const bom = original.bom || replacementBom
const formatted = (yield* formatter.file(target.absolute))
? yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
: (yield* FileMutation.readText(environment.files, target.absolute)).text
return {
files: [fileDiff(result.resource, source, formatted)],
replacements,
} satisfies Output
}),
)
}).pipe( }).pipe(
fileMutation.withLock([path.resolve(location.directory, input.path)]),
Effect.map((output) => ({ Effect.map((output) => ({
output, output,
content: `Edited ${output.files[0]?.file} (${output.replacements} replacement${output.replacements === 1 ? "" : "s"})`, content: `Edited ${output.files[0]?.file} (${output.replacements} replacement${output.replacements === 1 ? "" : "s"})`,
+187 -175
View File
@@ -3,7 +3,7 @@ export * as PatchTool from "./patch"
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin" import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
import { ToolFailure } from "@opencode-ai/ai" import { ToolFailure } from "@opencode-ai/ai"
import { FileDiff } from "@opencode-ai/schema/file-diff" import { FileDiff } from "@opencode-ai/schema/file-diff"
import { Effect, Schema } from "effect" import { Effect, Result, Schema } from "effect"
import path from "path" import path from "path"
import { Bom } from "@opencode-ai/util/bom" import { Bom } from "@opencode-ai/util/bom"
import { FSUtil } from "@opencode-ai/util/fs-util" import { FSUtil } from "@opencode-ai/util/fs-util"
@@ -93,6 +93,12 @@ export const Plugin = {
execute: (input, context) => { execute: (input, context) => {
const applied: Array<typeof Applied.Type> = [] const applied: Array<typeof Applied.Type> = []
const parsed = Patch.parse(input.patchText) const parsed = Patch.parse(input.patchText)
const lockTargets = Result.isSuccess(parsed)
? parsed.success.flatMap((hunk) => [
path.resolve(location.directory, hunk.path),
...(hunk.type === "update" && hunk.movePath ? [path.resolve(location.directory, hunk.movePath)] : []),
])
: []
const fail = (operation: string, error: unknown) => { const fail = (operation: string, error: unknown) => {
const completed = applied.map((item) => item.resource).join(", ") const completed = applied.map((item) => item.resource).join(", ")
return new ToolFailure({ return new ToolFailure({
@@ -112,196 +118,202 @@ export const Plugin = {
if (hunks.length === 0) { if (hunks.length === 0) {
return yield* new ToolFailure({ message: "patch rejected: empty patch" }) return yield* new ToolFailure({ message: "patch rejected: empty patch" })
} }
const plans = hunks.map((hunk) => ({ const prepared: Prepared[] = []
hunk, const targets: Target[] = []
target: resolveTarget(location, hunk.path), const updates = new Map<string, string>()
moveTarget: for (const hunk of hunks) {
hunk.type === "update" && hunk.movePath ? resolveTarget(location, hunk.movePath) : undefined, yield* Effect.gen(function* () {
})) const target = resolveTarget(location, hunk.path)
const targets = plans.flatMap((plan) => [plan.target, ...(plan.moveTarget ? [plan.moveTarget] : [])]) targets.push(target)
for (const target of targets) { if (target.externalDirectory) {
if (target.externalDirectory) { yield* permission.assert({
yield* permission.assert({ action: "external_directory",
action: "external_directory", resources: [target.externalDirectory.resource],
resources: [target.externalDirectory.resource], save: [target.externalDirectory.resource],
save: [target.externalDirectory.resource], metadata: {
metadata: { filepath: target.absolute,
filepath: target.absolute, parentDir: target.externalDirectory.directory,
parentDir: target.externalDirectory.directory, },
}, sessionID: context.sessionID,
sessionID: context.sessionID, agent: context.agent,
agent: context.agent, source,
source, })
}
if (hunk.type === "add") {
const content =
hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n`
prepared.push({
...hunk,
target,
content,
before: "",
after: Bom.split(content).text,
})
return
}
if (hunk.type === "delete") {
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.mapError(
(error) =>
new ToolFailure({
message: `patch verification failed: Failed to delete ${target.resource}: ${errorMessage(error)}`,
}),
),
)
prepared.push({ ...hunk, target, before: content.text, after: "" })
return
}
const previous = updates.get(target.absolute)
const original =
previous ??
(yield* Effect.gen(function* () {
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.mapError(
(error) =>
new ToolFailure({
message: `patch verification failed: Failed to read file to update ${target.absolute}: ${errorMessage(error)}`,
}),
),
)
return Bom.join(content.text, content.bom)
}))
const before = Bom.split(original).text
const update = yield* Effect.try({
try: () => Patch.derive(hunk.path, hunk.chunks, original),
catch: (error) => new ToolFailure({ message: `patch verification failed: ${errorMessage(error)}` }),
}) })
} const moveTarget = hunk.movePath ? resolveTarget(location, hunk.movePath) : undefined
if (moveTarget) targets.push(moveTarget)
if (moveTarget?.externalDirectory) {
yield* permission.assert({
action: "external_directory",
resources: [moveTarget.externalDirectory.resource],
save: [moveTarget.externalDirectory.resource],
metadata: {
filepath: moveTarget.absolute,
parentDir: moveTarget.externalDirectory.directory,
},
sessionID: context.sessionID,
agent: context.agent,
source,
})
}
prepared.push({
...hunk,
target,
content: Patch.joinBom(update.content, update.bom),
before,
after: update.content,
moveTarget,
})
if (!moveTarget) updates.set(target.absolute, Patch.joinBom(update.content, update.bom))
}).pipe(
Effect.mapError((error) =>
error instanceof ToolFailure
? error
: new ToolFailure({ message: `Unable to prepare patch at ${hunk.path}`, error }),
),
)
} }
const patchFiles = prepared.map((change) => patchFile(change))
yield* permission.assert({ yield* permission.assert({
action: "edit", action: "edit",
resources: [...new Set(targets.map((target) => target.resource))], resources: [...new Set(targets.map((target) => target.resource))],
save: ["*"], save: ["*"],
metadata: {
filepath: targets.map((target) => target.resource).join(", "),
diff: patchFiles.map((file) => `${file.patch}\n`).join(""),
files: patchFiles,
},
sessionID: context.sessionID, sessionID: context.sessionID,
agent: context.agent, agent: context.agent,
source, source,
}) })
return yield* mutation.withLock(targets.map((target) => target.absolute))( yield* Effect.forEach(
Effect.gen(function* () { prepared,
const prepared: Prepared[] = [] (change) =>
const updates = new Map<string, string>() Effect.gen(function* () {
for (const plan of plans) { if (change.type === "add") {
const hunk = plan.hunk yield* environment.files
const target = plan.target .write(change.target.absolute, new TextEncoder().encode(change.content))
yield* Effect.gen(function* () { .pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
if (hunk.type === "add") { applied.push({
const content = type: change.type,
hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n` resource: change.target.resource,
prepared.push({ target: change.target.absolute,
...hunk, })
target, return
content, }
before: "", if (change.type === "delete") {
after: Bom.split(content).text, yield* environment.files
}) .remove(change.target.absolute)
return .pipe(Effect.mapError((error) => fail(`Failed to delete ${change.target.resource}`, error)))
} applied.push({
if (hunk.type === "delete") { type: change.type,
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe( resource: change.target.resource,
Effect.mapError( target: change.target.absolute,
(error) => })
new ToolFailure({ return
message: `patch verification failed: Failed to delete ${target.resource}: ${errorMessage(error)}`, }
}), if (change.moveTarget) {
const moveTarget = change.moveTarget
yield* environment.files
.write(moveTarget.absolute, new TextEncoder().encode(change.content))
.pipe(Effect.mapError((error) => fail(`Failed to write ${moveTarget.resource}`, error)))
yield* environment.files
.remove(change.target.absolute)
.pipe(
Effect.mapError((error) =>
fail(`Wrote ${moveTarget.resource} but failed to remove ${change.target.resource}`, error),
), ),
) )
prepared.push({ ...hunk, target, before: content.text, after: "" }) applied.push({
return type: change.type,
} resource: change.moveTarget.resource,
const previous = updates.get(target.absolute) target: change.moveTarget.absolute,
const original =
previous ??
(yield* Effect.gen(function* () {
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.mapError(
(error) =>
new ToolFailure({
message: `patch verification failed: Failed to read file to update ${target.absolute}: ${errorMessage(error)}`,
}),
),
)
return Bom.join(content.text, content.bom)
}))
const before = Bom.split(original).text
const update = yield* Effect.try({
try: () => Patch.derive(hunk.path, hunk.chunks, original),
catch: (error) =>
new ToolFailure({ message: `patch verification failed: ${errorMessage(error)}` }),
}) })
const moveTarget = plan.moveTarget return
prepared.push({ }
...hunk, yield* environment.files
target, .write(change.target.absolute, new TextEncoder().encode(change.content))
content: Patch.joinBom(update.content, update.bom), .pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
before, applied.push({
after: update.content, type: change.type,
moveTarget, resource: change.target.resource,
}) target: change.target.absolute,
if (!moveTarget) updates.set(target.absolute, Patch.joinBom(update.content, update.bom)) })
}).pipe( }),
Effect.mapError((error) => { discard: true },
error instanceof ToolFailure
? error
: new ToolFailure({ message: `Unable to prepare patch at ${hunk.path}`, error }),
),
)
}
yield* Effect.forEach(
prepared,
(change) =>
Effect.gen(function* () {
if (change.type === "add") {
yield* environment.files
.write(change.target.absolute, new TextEncoder().encode(change.content))
.pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
applied.push({
type: change.type,
resource: change.target.resource,
target: change.target.absolute,
})
return
}
if (change.type === "delete") {
yield* environment.files
.remove(change.target.absolute)
.pipe(Effect.mapError((error) => fail(`Failed to delete ${change.target.resource}`, error)))
applied.push({
type: change.type,
resource: change.target.resource,
target: change.target.absolute,
})
return
}
if (change.moveTarget) {
const moveTarget = change.moveTarget
yield* environment.files
.write(moveTarget.absolute, new TextEncoder().encode(change.content))
.pipe(Effect.mapError((error) => fail(`Failed to write ${moveTarget.resource}`, error)))
yield* environment.files
.remove(change.target.absolute)
.pipe(
Effect.mapError((error) =>
fail(
`Wrote ${moveTarget.resource} but failed to remove ${change.target.resource}`,
error,
),
),
)
applied.push({
type: change.type,
resource: change.moveTarget.resource,
target: change.moveTarget.absolute,
})
return
}
yield* environment.files
.write(change.target.absolute, new TextEncoder().encode(change.content))
.pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
applied.push({
type: change.type,
resource: change.target.resource,
target: change.target.absolute,
})
}),
{ discard: true },
)
const formatted = new Map<string, string>()
yield* Effect.forEach(
[...new Set(applied.filter((item) => item.type !== "delete").map((item) => item.target))],
(target) =>
Effect.gen(function* () {
const current = yield* FileMutation.readText(environment.files, target).pipe(
Effect.mapError((error) => fail(`Failed to read ${target}`, error)),
)
formatted.set(
target,
(yield* formatter.file(target))
? yield* FileMutation.syncTextBom(environment.files, target, current.bom).pipe(
Effect.mapError((error) => fail(`Failed to sync ${target}`, error)),
)
: current.text,
)
}),
{ discard: true },
)
const files = yield* Effect.forEach(prepared, (change) => {
if (change.type === "delete") return Effect.succeed(patchFile(change))
const target = change.type === "update" && change.moveTarget ? change.moveTarget : change.target
return Effect.succeed(patchFile(change, formatted.get(target.absolute)))
})
return { applied, files }
}),
) )
const formatted = new Map<string, string>()
yield* Effect.forEach(
[...new Set(applied.filter((item) => item.type !== "delete").map((item) => item.target))],
(target) =>
Effect.gen(function* () {
const current = yield* FileMutation.readText(environment.files, target).pipe(
Effect.mapError((error) => fail(`Failed to read ${target}`, error)),
)
formatted.set(
target,
(yield* formatter.file(target))
? yield* FileMutation.syncTextBom(environment.files, target, current.bom).pipe(
Effect.mapError((error) => fail(`Failed to sync ${target}`, error)),
)
: current.text,
)
}),
{ discard: true },
)
const files = yield* Effect.forEach(prepared, (change) => {
if (change.type === "delete") return Effect.succeed(patchFile(change))
const target = change.type === "update" && change.moveTarget ? change.moveTarget : change.target
return Effect.succeed(patchFile(change, formatted.get(target.absolute)))
})
return { applied, files }
}).pipe( }).pipe(
mutation.withLock(lockTargets),
Effect.map((output) => ({ Effect.map((output) => ({
output, output,
content: toModelOutput(output), content: toModelOutput(output),
+19 -2
View File
@@ -26,7 +26,24 @@ export const description = [
"The skill ID must match one of the available skills in the instructions.", "The skill ID must match one of the available skills in the instructions.",
].join("\n") ].join("\n")
export const toModelOutput = Skill.toModelOutput export const toModelOutput = (skill: Skill.Info, files: ReadonlyArray<string>) => {
const directory = path.dirname(skill.location)
return [
`<skill_content name="${skill.name}">`,
`# Skill: ${skill.name}`,
"",
skill.content.trim(),
"",
`Base directory for this skill: ${directory}`,
"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.",
"Note: file list is sampled.",
"",
"<skill_files>",
...files.map((file) => `<file>${file}</file>`),
"</skill_files>",
"</skill_content>",
].join("\n")
}
const unableToLoad = (name: string, error?: unknown) => const unableToLoad = (name: string, error?: unknown) =>
new ToolFailure({ message: `Unable to load skill ${name}`, error }) new ToolFailure({ message: `Unable to load skill ${name}`, error })
@@ -70,7 +87,7 @@ export const Plugin = {
return { return {
name: skill.name, name: skill.name,
directory, directory,
output: Skill.toModelOutput(skill, files), output: toModelOutput(skill, files),
} }
}).pipe(Effect.mapError((error) => unableToLoad(input.id, error))) }).pipe(Effect.mapError((error) => unableToLoad(input.id, error)))
}).pipe( }).pipe(
+14 -10
View File
@@ -9,11 +9,13 @@ export * as WriteTool from "./write"
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin" import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
import { ToolFailure } from "@opencode-ai/ai" import { ToolFailure } from "@opencode-ai/ai"
import { Effect, Schema } from "effect" import { Effect, Schema } from "effect"
import { Bom } from "@opencode-ai/util/bom"
import { Environment } from "../../environment" import { Environment } from "../../environment"
import { FileMutation } from "../../file-mutation" import { FileMutation } from "../../file-mutation"
import { Formatter } from "../../formatter" import { Formatter } from "../../formatter"
import { LocationMutation } from "../../location-mutation" import { LocationMutation } from "../../location-mutation"
import { Permission } from "../../permission" import { Permission } from "../../permission"
import { fileDiff } from "./file-diff"
export const name = "write" export const name = "write"
@@ -75,24 +77,26 @@ export const Plugin = {
agent: context.agent, agent: context.agent,
source, source,
}) })
const current = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)),
)
const next = Bom.split(input.content)
const preview = fileDiff(target.resource, current?.text ?? "", next.text, current ? "modified" : "added")
yield* permission.assert({ yield* permission.assert({
action: "edit", action: "edit",
resources: [target.resource], resources: [target.resource],
save: ["*"], save: ["*"],
metadata: { files: [preview] },
sessionID: context.sessionID, sessionID: context.sessionID,
agent: context.agent, agent: context.agent,
source, source,
}) })
return yield* fileMutation.withLock([target.absolute])( const result = yield* fileMutation.writeTextPreservingBom({ target, content: input.content })
Effect.gen(function* () { const bom = (yield* FileMutation.readText(environment.files, target.absolute)).bom
const result = yield* fileMutation.writeTextPreservingBom({ target, content: input.content }) if (yield* formatter.file(target.absolute)) {
const bom = (yield* FileMutation.readText(environment.files, target.absolute)).bom yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
if (yield* formatter.file(target.absolute)) { }
yield* FileMutation.syncTextBom(environment.files, target.absolute, bom) return result
}
return result
}),
)
}).pipe( }).pipe(
Effect.map((output) => ({ output, content: toModelOutput(output) })), Effect.map((output) => ({ output, content: toModelOutput(output) })),
Effect.mapError((error) => new ToolFailure({ message: `Unable to write ${input.path}`, error })), Effect.mapError((error) => new ToolFailure({ message: `Unable to write ${input.path}`, error })),
+1 -214
View File
@@ -1,219 +1,6 @@
export * as Workspace from "./workspace" export * as Workspace from "./workspace"
import { Workspace } from "@opencode-ai/schema/workspace" import { Workspace } from "@opencode-ai/schema/workspace"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
import { eq } from "drizzle-orm"
import { Clock, Context, Duration, Effect, Exit, Layer, Ref, Schedule, Schema, Scope } from "effect"
import { systemError } from "effect/PlatformError"
import { make } from "effect/unstable/process/ChildProcessSpawner"
import type { Driver as EnvironmentDriver } from "./environment/driver"
import { Database } from "./database/database"
import { KeyedMutex } from "./effect/keyed-mutex"
import { WorkspaceDriver } from "./workspace/driver"
import { WorkspaceTable } from "./workspace/sql"
export const ID = Workspace.ID export const ID = Workspace.ID
export type ID = Workspace.ID export type ID = typeof ID.Type
export class Info extends Schema.Class<Info>("Workspace.Info")({
id: ID,
provider: Schema.String,
binding: WorkspaceDriver.Binding,
createdAt: Schema.Number,
lastUsedAt: Schema.Number,
}) {}
export class NotFound extends Schema.TaggedErrorClass<NotFound>()("Workspace.NotFound", { workspaceID: ID }) {}
export interface Interface {
readonly create: (provider: string) => Effect.Effect<Info, WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
readonly connect: (
workspaceID: ID,
) => Effect.Effect<EnvironmentDriver, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
readonly destroy: (
workspaceID: ID,
) => Effect.Effect<void, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
}
export interface Options {
readonly idleThreshold?: Duration.Input
readonly pollInterval?: Duration.Input
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Workspace") {}
interface Connection {
readonly driver: WorkspaceDriver.Interface
readonly environment: EnvironmentDriver
readonly saveBinding: (binding: WorkspaceDriver.Binding) => Effect.Effect<void>
readonly lastActivity: Ref.Ref<number>
readonly active: Ref.Ref<number>
readonly scope: Scope.Closeable
}
export const configured = (options: Options = {}) =>
makeGlobalNode({
service: Service,
layer: layer(options),
deps: [Database.node, WorkspaceDriver.node],
})
const layer = (options: Options) =>
Layer.effect(
Service,
Effect.gen(function* () {
const db = (yield* Database.Service).db
const registry = yield* WorkspaceDriver.RegistryService
const lifetime = yield* Scope.Scope
const connections = new Map<ID, Connection>()
const locks = KeyedMutex.makeUnsafe<ID>()
const idleThreshold = Duration.toMillis(options.idleThreshold ?? Duration.minutes(20))
const load = Effect.fn("Workspace.load")(function* (workspaceID: ID) {
const row = yield* db
.select()
.from(WorkspaceTable)
.where(eq(WorkspaceTable.id, workspaceID))
.get()
.pipe(Effect.orDie)
if (!row) return yield* new NotFound({ workspaceID })
return row
})
const open = Effect.fn("Workspace.open")(function* (workspaceID: ID) {
const existing = connections.get(workspaceID)
if (existing) return existing
const row = yield* load(workspaceID)
const driver = yield* registry.get(row.provider)
const saveBinding = (value: WorkspaceDriver.Binding) =>
db
.update(WorkspaceTable)
.set({ binding: value })
.where(eq(WorkspaceTable.id, workspaceID))
.run()
.pipe(Effect.orDie)
const scope = yield* Scope.fork(lifetime)
const environment = yield* driver.connect({ workspaceID, binding: row.binding, saveBinding }).pipe(
Effect.provideService(Scope.Scope, scope),
Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),
)
const now = yield* Clock.currentTimeMillis
const connection: Connection = {
driver,
environment,
saveBinding,
lastActivity: yield* Ref.make(now),
active: yield* Ref.make(0),
scope,
}
connections.set(workspaceID, connection)
yield* db
.update(WorkspaceTable)
.set({ last_used_at: now })
.where(eq(WorkspaceTable.id, workspaceID))
.run()
.pipe(Effect.orDie)
return connection
})
yield* Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis
yield* Effect.forEach(
[...connections.entries()],
([workspaceID, expected]) =>
locks.withLock(workspaceID)(
Effect.gen(function* () {
const connection = connections.get(workspaceID)
if (connection !== expected || (yield* Ref.get(connection.active)) > 0) return
const lastActivity = yield* Ref.get(connection.lastActivity)
if (now - lastActivity < idleThreshold) return
const row = yield* load(workspaceID)
// Deliberate: a racing spawn blocks, then wakes cleanly. Unlocking mid-suspend could reattach a sandbox being terminated.
yield* connection.driver.suspendForIdle({
workspaceID,
binding: row.binding,
saveBinding: connection.saveBinding,
})
yield* db
.update(WorkspaceTable)
.set({ last_used_at: lastActivity })
.where(eq(WorkspaceTable.id, workspaceID))
.run()
.pipe(Effect.orDie)
connections.delete(workspaceID)
yield* Scope.close(connection.scope, Exit.void)
}).pipe(Effect.catchCause((cause) => Effect.logError("workspace idle suspension failed", cause))),
),
{ concurrency: "unbounded", discard: true },
)
}).pipe(Effect.repeat(Schedule.spaced(options.pollInterval ?? Duration.minutes(1))), Effect.forkScoped)
return Service.of({
create: Effect.fn("Workspace.create")(function* (provider) {
const driver = yield* registry.get(provider)
const workspaceID = ID.create()
const result = yield* driver.create({ workspaceID })
const now = yield* Clock.currentTimeMillis
yield* db
.insert(WorkspaceTable)
.values({ id: workspaceID, provider, binding: result.binding, created_at: now, last_used_at: now })
.run()
.pipe(Effect.orDie)
return new Info({ id: workspaceID, provider, binding: result.binding, createdAt: now, lastUsedAt: now })
}),
connect: Effect.fn("Workspace.connect")(function* (workspaceID) {
const spawner = make((command) =>
Effect.acquireRelease(
locks.withLock(workspaceID)(
Effect.gen(function* () {
const connection = yield* open(workspaceID).pipe(
Effect.mapError((cause) =>
systemError({
_tag: "Unknown",
module: "Workspace",
method: "spawn",
description: `Failed to wake workspace ${workspaceID}`,
cause,
}),
),
)
yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)
yield* Ref.update(connection.active, (active) => active + 1)
return connection
}),
),
(connection) =>
locks.withLock(workspaceID)(
Effect.gen(function* () {
yield* Ref.update(connection.active, (active) => active - 1)
yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)
}),
),
).pipe(Effect.flatMap((connection) => connection.environment.spawner.spawn(command))),
)
// Overrides are connection-bound; per-spawn routing is required before any driver ships them, so they are deliberately omitted.
return { spawner }
}),
destroy: Effect.fn("Workspace.destroy")(function* (workspaceID) {
yield* locks.withLock(workspaceID)(
Effect.gen(function* () {
const row = yield* load(workspaceID)
const connection = connections.get(workspaceID)
connections.delete(workspaceID)
if (connection) yield* Scope.close(connection.scope, Exit.void)
const driver = yield* registry.get(row.provider)
yield* driver.destroy({ workspaceID, binding: row.binding })
yield* db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)
}),
)
}),
})
}),
)
export const node = configured()
// TODO(workspace-plan): add the boot janitor and ~23h safety snapshot rotation in a later PR.
// TODO(workspace-plan): make cold wake interruptible with a re-pin loop against janitor races.
// TODO(workspace-plan): consider RcMap at end-of-series consolidation; idle suspend and destroy need distinct finalizers.
-70
View File
@@ -1,70 +0,0 @@
export * as WorkspaceDriver from "./driver"
import { Workspace } from "@opencode-ai/schema/workspace"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
import { Context, Effect, Layer, Schema } from "effect"
import type { Scope } from "effect"
import type { Driver as EnvironmentDriver } from "../environment/driver"
/**
* Smallest provider-owned JSON value required to reconnect to the same
* provider resource. Core stores it opaquely and hands it back; only the
* owning driver reads inside.
*/
export const Binding = Schema.Record(Schema.String, Schema.Json)
export type Binding = typeof Binding.Type
export class Error extends Schema.TaggedErrorClass<Error>()("WorkspaceDriver.Error", {
message: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
}) {}
export class ProviderNotFound extends Schema.TaggedErrorClass<ProviderNotFound>()("WorkspaceDriver.ProviderNotFound", {
provider: Schema.String,
}) {}
export interface Interface {
readonly create: (input: {
readonly workspaceID: Workspace.ID
}) => Effect.Effect<{ readonly binding: Binding }, Error>
readonly connect: (input: {
readonly workspaceID: Workspace.ID
readonly binding: Binding
readonly saveBinding: (binding: Binding) => Effect.Effect<void>
}) => Effect.Effect<EnvironmentDriver, Error, Scope.Scope>
readonly suspendForIdle: (input: {
readonly workspaceID: Workspace.ID
readonly binding: Binding
readonly saveBinding: (binding: Binding) => Effect.Effect<void>
}) => Effect.Effect<void, Error>
readonly destroy: (input: {
readonly workspaceID: Workspace.ID
readonly binding: Binding
}) => Effect.Effect<void, Error>
}
export const make = (driver: Interface) => driver
export interface Registry {
readonly get: (provider: string) => Effect.Effect<Interface, ProviderNotFound>
}
export class RegistryService extends Context.Service<RegistryService, Registry>()(
"@opencode/WorkspaceDriverRegistry",
) {}
export const registry = (drivers: Readonly<Record<string, Interface>>): Registry => ({
get: (provider) => {
const driver = drivers[provider]
return driver ? Effect.succeed(driver) : Effect.fail(new ProviderNotFound({ provider }))
},
})
export const registryNode = (drivers: Readonly<Record<string, Interface>>) =>
makeGlobalNode({
service: RegistryService,
layer: Layer.succeed(RegistryService, RegistryService.of(registry(drivers))),
deps: [],
})
export const node = registryNode({})
-11
View File
@@ -1,11 +0,0 @@
import { Workspace } from "@opencode-ai/schema/workspace"
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
import type { WorkspaceDriver } from "./driver"
export const WorkspaceTable = sqliteTable("workspace", {
id: text().$type<Workspace.ID>().primaryKey(),
provider: text().notNull(),
binding: text({ mode: "json" }).$type<WorkspaceDriver.Binding>().notNull(),
created_at: integer().notNull(),
last_used_at: integer().notNull(),
})
+97 -3
View File
@@ -9,12 +9,11 @@ import { Environment } from "@opencode-ai/core/environment"
import { Location } from "@opencode-ai/core/location" import { Location } from "@opencode-ai/core/location"
import { LocationMutation } from "@opencode-ai/core/location-mutation" import { LocationMutation } from "@opencode-ai/core/location-mutation"
import { AbsolutePath } from "@opencode-ai/core/schema" import { AbsolutePath } from "@opencode-ai/core/schema"
import { type EnvironmentFilesTransform, transformEnvironmentFiles } from "./fixture/environment"
import { location } from "./fixture/location" import { location } from "./fixture/location"
import { tmpdir } from "./fixture/tmpdir" import { tmpdir } from "./fixture/tmpdir"
import { it } from "./lib/effect" import { it } from "./lib/effect"
function provide(directory: string, transformFiles: EnvironmentFilesTransform = () => ({})) { function provide(directory: string, environmentLayer = LayerNode.compile(Environment.node)) {
const activeLocation = Layer.succeed( const activeLocation = Layer.succeed(
Location.Service, Location.Service,
Location.Service.of(location({ directory: AbsolutePath.make(directory) })), Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
@@ -22,7 +21,7 @@ function provide(directory: string, transformFiles: EnvironmentFilesTransform =
return Effect.provide( return Effect.provide(
AppNodeBuilder.build(LayerNode.group([LocationMutation.node, FileMutation.node]), [ AppNodeBuilder.build(LayerNode.group([LocationMutation.node, FileMutation.node]), [
[Location.node, activeLocation], [Location.node, activeLocation],
[Environment.node, transformEnvironmentFiles(activeLocation, transformFiles)], [Environment.node, environmentLayer],
]), ]),
) )
} }
@@ -110,6 +109,49 @@ describe("FileMutation", () => {
), ),
) )
it.live("serializes concurrent writes to the same absolute target", () =>
withTmp((directory) =>
Effect.gen(function* () {
const targetPath = path.join(directory, "shared.txt")
yield* Effect.promise(() => fs.writeFile(targetPath, "initial"))
const firstStarted = yield* Deferred.make<void>()
const releaseFirst = yield* Deferred.make<void>()
const secondStarted = yield* Deferred.make<void>()
let writes = 0
const filesystem = instrumentWrites((write) =>
Effect.gen(function* () {
writes++
if (writes === 1) {
yield* Deferred.succeed(firstStarted, undefined)
yield* Deferred.await(releaseFirst)
} else {
yield* Deferred.succeed(secondStarted, undefined)
}
yield* write
}),
)
yield* Effect.gen(function* () {
const mutation = yield* LocationMutation.Service
const files = yield* FileMutation.Service
const firstPlan = yield* mutation.resolve({ path: "shared.txt" })
const secondPlan = yield* mutation.resolve({ path: "shared.txt" })
const first = yield* files.write({ target: firstPlan, content: "first" }).pipe(Effect.forkChild)
yield* Deferred.await(firstStarted)
const second = yield* files.write({ target: secondPlan, content: "second" }).pipe(Effect.forkChild)
yield* Effect.yieldNow
expect(yield* Deferred.isDone(secondStarted)).toBe(false)
yield* Deferred.succeed(releaseFirst, undefined)
yield* Deferred.await(secondStarted)
yield* Fiber.join(first)
yield* Fiber.join(second)
expect(yield* Effect.promise(() => fs.readFile(targetPath, "utf8"))).toBe("second")
}).pipe(provide(directory, filesystem))
}),
),
)
it.live("shares transaction locks across Location service instances", () => it.live("shares transaction locks across Location service instances", () =>
withTmp((directory) => withTmp((directory) =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -160,4 +202,56 @@ describe("FileMutation", () => {
}).pipe(provide(directory)), }).pipe(provide(directory)),
), ),
) )
it.live("allows distinct absolute targets to proceed independently", () =>
withTmp((directory) =>
Effect.gen(function* () {
const firstStarted = yield* Deferred.make<void>()
const releaseFirst = yield* Deferred.make<void>()
const secondFinished = yield* Deferred.make<void>()
const secondPath = path.join(directory, "second.txt")
let writes = 0
const filesystem = instrumentWrites((write) =>
++writes === 1
? Deferred.succeed(firstStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseFirst)),
Effect.andThen(write),
)
: write.pipe(Effect.andThen(Deferred.succeed(secondFinished, undefined))),
)
yield* Effect.gen(function* () {
const mutation = yield* LocationMutation.Service
const files = yield* FileMutation.Service
const firstPlan = yield* mutation.resolve({ path: "first.txt" })
const secondPlan = yield* mutation.resolve({ path: "second.txt" })
const first = yield* files.write({ target: firstPlan, content: "first" }).pipe(Effect.forkChild)
yield* Deferred.await(firstStarted)
const second = yield* files.write({ target: secondPlan, content: "second" }).pipe(Effect.forkChild)
yield* Deferred.await(secondFinished)
expect(yield* Effect.promise(() => fs.readFile(secondPath, "utf8"))).toBe("second")
yield* Deferred.succeed(releaseFirst, undefined)
yield* Fiber.join(first)
yield* Fiber.join(second)
}).pipe(provide(directory, filesystem))
}),
),
)
}) })
function instrumentWrites(run: <E>(write: Effect.Effect<void, E>, target: string) => Effect.Effect<void, E>) {
return Layer.effect(
Environment.Service,
Effect.gen(function* () {
const environment = yield* Environment.Service
return Environment.Service.of({
...environment,
files: {
...environment.files,
write: (target, content) => run(environment.files.write(target, content), target),
},
})
}),
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
}
-22
View File
@@ -1,22 +0,0 @@
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { Environment } from "@opencode-ai/core/environment"
import { Location } from "@opencode-ai/core/location"
import { Effect, Layer } from "effect"
export type EnvironmentFilesTransform = (files: Environment.Files) => Partial<Environment.Files>
export function transformEnvironmentFiles(
location: Layer.Layer<Location.Service>,
transform: EnvironmentFilesTransform = () => ({}),
) {
return Layer.effect(
Environment.Service,
Effect.gen(function* () {
const current = yield* Environment.Service
return Environment.Service.of({
...current,
files: { ...current.files, ...transform(current.files) },
})
}),
).pipe(Layer.provide(AppNodeBuilder.build(Environment.node, [[Location.node, location]])))
}
File diff suppressed because one or more lines are too long
+2 -4
View File
@@ -305,13 +305,11 @@ describe("LocationServiceMap", () => {
) )
yield* Deferred.await(started) yield* Deferred.await(started)
const flushFiber = yield* PluginSupervisor.Service.use((supervisor) => supervisor.flush).pipe( yield* PluginSupervisor.Service.use((supervisor) => supervisor.flush).pipe(
Effect.provide(context), Effect.provide(context),
Effect.forkChild({ startImmediately: true }), Effect.timeout("1 second"),
) )
expect(flushFiber.pollUnsafe()).toBeUndefined()
yield* Deferred.succeed(release, undefined) yield* Deferred.succeed(release, undefined)
yield* Fiber.join(flushFiber)
yield* Deferred.await(completed) yield* Deferred.await(completed)
}), }),
), ),
+1 -4
View File
@@ -3,15 +3,12 @@ import fs from "fs/promises"
import path from "path" import path from "path"
import { Effect } from "effect" import { Effect } from "effect"
import { LayerNode } from "@opencode-ai/util/effect/layer-node" import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { Location } from "@opencode-ai/core/location"
import { Ripgrep } from "@opencode-ai/core/ripgrep" import { Ripgrep } from "@opencode-ai/core/ripgrep"
import { RelativePath } from "@opencode-ai/core/schema" import { RelativePath } from "@opencode-ai/core/schema"
import { tmpdir } from "./fixture/tmpdir" import { tmpdir } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect" import { testEffect } from "./lib/effect"
import { tempLocationLayer } from "./fixture/location"
const it = testEffect(AppNodeBuilder.build(Ripgrep.node, [[Location.node, tempLocationLayer]])) const it = testEffect(LayerNode.compile(Ripgrep.node))
describe("Ripgrep", () => { describe("Ripgrep", () => {
it.live("globs files as an array", () => it.live("globs files as an array", () =>
@@ -3,8 +3,7 @@ import { Message } from "@opencode-ai/ai"
import { Model } from "@opencode-ai/core/model" import { Model } from "@opencode-ai/core/model"
import { Provider } from "@opencode-ai/core/provider" import { Provider } from "@opencode-ai/core/provider"
import { SessionMessage } from "@opencode-ai/core/session/message" import { SessionMessage } from "@opencode-ai/core/session/message"
import { AgentAttachment, Base64, FileAttachment, SkillAttachment } from "@opencode-ai/schema/prompt" import { AgentAttachment, Base64, FileAttachment } from "@opencode-ai/schema/prompt"
import { Skill } from "@opencode-ai/schema/skill"
import { toLLMMessages } from "@opencode-ai/core/session/runner/to-llm-message" import { toLLMMessages } from "@opencode-ai/core/session/runner/to-llm-message"
import { Agent } from "@opencode-ai/core/agent" import { Agent } from "@opencode-ai/core/agent"
import { Shell } from "@opencode-ai/schema/shell" import { Shell } from "@opencode-ai/schema/shell"
@@ -185,40 +184,6 @@ Recent work
}) })
}) })
test("lowers selected skill instructions with the original user prompt", () => {
const messages = toLLMMessages(
[
SessionMessage.User.make({
id: id("user-skill"),
type: "user",
text: "Design this API",
skills: [
SkillAttachment.make({
id: Skill.ID.make("api-design"),
name: Skill.Name.make("API design"),
text: "Start from the ideal call site.",
}),
],
time: { created },
}),
],
model,
)
expect(messages).toHaveLength(1)
expect(messages[0]).toMatchObject({
id: id("user-skill"),
role: "user",
content: [
{
type: "text",
text: "Start from the ideal call site.",
},
{ type: "text", text: "Design this API" },
],
})
})
test("decodes inline text attachment content", () => { test("decodes inline text attachment content", () => {
const messages = toLLMMessages( const messages = toLLMMessages(
[ [
-36
View File
@@ -15,7 +15,6 @@ import { SessionExecution } from "@opencode-ai/core/session/execution"
import { SessionMessage } from "@opencode-ai/core/session/message" import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionProjector } from "@opencode-ai/core/session/projector" import { SessionProjector } from "@opencode-ai/core/session/projector"
import { SessionStore } from "@opencode-ai/core/session/store" import { SessionStore } from "@opencode-ai/core/session/store"
import { SessionPending } from "@opencode-ai/core/session/pending"
import { Skill } from "@opencode-ai/core/skill" import { Skill } from "@opencode-ai/core/skill"
import { testEffect } from "./lib/effect" import { testEffect } from "./lib/effect"
@@ -56,41 +55,6 @@ const it = testEffect(
) )
describe("Session.skill", () => { describe("Session.skill", () => {
it.effect("attaches a resolved skill snapshot to a normal prompt", () =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const database = yield* Database.Service
const bus = yield* Bus.Service
const session = yield* sessions.create({ location })
const id = SessionMessage.ID.make("msg_skill_attachment")
yield* sessions.prompt({
id,
sessionID: session.id,
text: "Apply this guidance",
skills: [{ id: Skill.ID.make("effect"), mention: { start: 20, end: 27, text: "/effect" } }],
resume: false,
})
yield* SessionPending.promote(database.db, bus, session.id, "steer")
expect(yield* sessions.messages({ sessionID: session.id })).toContainEqual(
expect.objectContaining({
id,
type: "user",
text: "Apply this guidance",
skills: [
{
id: "effect",
name: "Effect",
text: expect.stringContaining("Use Effect"),
mention: { start: 20, end: 27, text: "/effect" },
},
],
}),
)
}),
)
it.effect("projects the caller-supplied message ID", () => it.effect("projects the caller-supplied message ID", () =>
Effect.gen(function* () { Effect.gen(function* () {
const sessions = yield* Session.Service const sessions = yield* Session.Service
+79 -85
View File
@@ -1,7 +1,7 @@
import fs from "fs/promises" import fs from "fs/promises"
import path from "path" import path from "path"
import { describe, expect } from "bun:test" import { describe, expect } from "bun:test"
import { Deferred, Effect, Fiber, Layer } from "effect" import { Effect, Layer } from "effect"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node" import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Environment } from "@opencode-ai/core/environment" import { Environment } from "@opencode-ai/core/environment"
@@ -14,7 +14,6 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
import { Session } from "@opencode-ai/core/session" import { Session } from "@opencode-ai/core/session"
import { Tool } from "@opencode-ai/core/tool" import { Tool } from "@opencode-ai/core/tool"
import { EditTool } from "@opencode-ai/core/tool/plugin/edit" import { EditTool } from "@opencode-ai/core/tool/plugin/edit"
import { transformEnvironmentFiles } from "./fixture/environment"
import { location } from "./fixture/location" import { location } from "./fixture/location"
import { tmpdir } from "./fixture/tmpdir" import { tmpdir } from "./fixture/tmpdir"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node" import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
@@ -40,7 +39,6 @@ const assertions: Permission.AssertInput[] = []
const writes: string[] = [] const writes: string[] = []
let reads = 0 let reads = 0
let denyAction: string | undefined let denyAction: string | undefined
let afterPermission = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void
let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false) let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
@@ -49,7 +47,6 @@ const permission = Layer.succeed(
Permission.Service.of({ Permission.Service.of({
assert: (input) => assert: (input) =>
Effect.sync(() => assertions.push(input)).pipe( Effect.sync(() => assertions.push(input)).pipe(
Effect.andThen(Effect.suspend(() => afterPermission(input))),
Effect.andThen( Effect.andThen(
input.action === denyAction input.action === denyAction
? Effect.fail( ? Effect.fail(
@@ -79,11 +76,33 @@ const reset = () => {
writes.length = 0 writes.length = 0
reads = 0 reads = 0
denyAction = undefined denyAction = undefined
afterPermission = () => Effect.void
afterRead = () => Effect.void afterRead = () => Effect.void
formatFile = () => Effect.succeed(false) formatFile = () => Effect.succeed(false)
} }
const environment = Layer.effect(
Environment.Service,
Effect.gen(function* () {
const current = yield* Environment.Service
return Environment.Service.of({
...current,
files: {
...current.files,
read: (target, range) =>
current.files
.read(target, range)
.pipe(
Effect.tap((result) =>
Effect.sync(() => reads++).pipe(Effect.andThen(Effect.suspend(() => afterRead(target, result.bytes)))),
),
),
write: (target, content) =>
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(current.files.write(target, content))),
},
})
}),
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => { const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
const activeLocation = Layer.succeed( const activeLocation = Layer.succeed(
Location.Service, Location.Service,
@@ -96,23 +115,7 @@ const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) =
AppNodeBuilder.build( AppNodeBuilder.build(
LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, editToolNode]), LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, editToolNode]),
[ [
[ [Environment.node, environment],
Environment.node,
transformEnvironmentFiles(activeLocation, (files) => ({
read: (target, range) =>
files
.read(target, range)
.pipe(
Effect.tap((result) =>
Effect.sync(() => reads++).pipe(
Effect.andThen(Effect.suspend(() => afterRead(target, result.bytes))),
),
),
),
write: (target, content) =>
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))),
})),
],
[Location.node, activeLocation], [Location.node, activeLocation],
[Formatter.node, formatter], [Formatter.node, formatter],
[Permission.node, permission], [Permission.node, permission],
@@ -177,7 +180,17 @@ describe("EditTool", () => {
}) })
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n") expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n")
expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }]) expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }])
expect(assertions[0]?.metadata).toBeUndefined() expect(assertions[0]?.metadata).toMatchObject({
files: [
{
file: "hello.txt",
status: "modified",
additions: 1,
deletions: 1,
patch: expect.stringContaining("-before\n+after"),
},
],
})
expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))]) expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))])
}), }),
), ),
@@ -342,7 +355,7 @@ describe("EditTool", () => {
error: { type: "permission.rejected", message: "Permission denied: edit" }, error: { type: "permission.rejected", message: "Permission denied: edit" },
}) })
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"]) expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
expect(reads).toBe(0) expect(reads).toBe(1)
expect(writes).toEqual([]) expect(writes).toEqual([])
expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before") expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before")
}), }),
@@ -379,7 +392,7 @@ describe("EditTool", () => {
}) })
expect(missing).toEqual(matching) expect(missing).toEqual(matching)
expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"]) expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"])
expect(reads).toBe(0) expect(reads).toBe(2)
expect(writes).toEqual([]) expect(writes).toEqual([])
}), }),
), ),
@@ -636,77 +649,58 @@ describe("EditTool", () => {
(tmp) => { (tmp) => {
reset() reset()
const target = path.join(tmp.path, "concurrent.txt") const target = path.join(tmp.path, "concurrent.txt")
return Effect.gen(function* () { afterRead = () => (reads === 1 ? Effect.sleep("50 millis") : Effect.void)
yield* Effect.promise(() => fs.writeFile(target, "one\ntwo\n")) return Effect.promise(() => fs.writeFile(target, "one\ntwo\n")).pipe(
const firstRead = yield* Deferred.make<void>() Effect.andThen(
const releaseFirst = yield* Deferred.make<void>() withTool(tmp.path, (registry) =>
const secondApproved = yield* Deferred.make<void>() Effect.all(
afterRead = () => [
reads === 1 executeTool(
? Deferred.succeed(firstRead, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst))) registry,
: Effect.void call({ path: "concurrent.txt", oldString: "one", newString: "ONE" }, "call-edit-one"),
afterPermission = (input) => ),
input.source?.id === "call-edit-two" executeTool(
? Deferred.succeed(secondApproved, undefined).pipe(Effect.asVoid) registry,
: Effect.void call({ path: "concurrent.txt", oldString: "two", newString: "TWO" }, "call-edit-two"),
),
const first = yield* withTool(tmp.path, (registry) => ],
executeTool( { concurrency: "unbounded" },
registry, ),
call({ path: "concurrent.txt", oldString: "one", newString: "ONE" }, "call-edit-one"),
), ),
).pipe(Effect.forkChild) ),
yield* Deferred.await(firstRead) Effect.andThen((results) =>
const second = yield* withTool(tmp.path, (registry) => Effect.gen(function* () {
executeTool( expect(results.map((result) => result.status)).toEqual(["completed", "completed"])
registry, expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
call({ path: "concurrent.txt", oldString: "two", newString: "TWO" }, "call-edit-two"), }),
), ),
).pipe(Effect.forkChild) )
yield* Deferred.await(secondApproved)
expect(reads).toBe(1)
yield* Deferred.succeed(releaseFirst, undefined)
expect((yield* Fiber.join(first)).status).toBe("completed")
expect((yield* Fiber.join(second)).status).toBe("completed")
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
})
}, },
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
), ),
) )
it.live("validates current content after permission succeeds", () => it.live("applies the edit when content changes after matching", () =>
Effect.acquireUseRelease( Effect.acquireUseRelease(
Effect.promise(() => tmpdir()), Effect.promise(() => tmpdir()),
(tmp) => { (tmp) => {
reset() reset()
const target = path.join(tmp.path, "concurrent.txt") const target = path.join(tmp.path, "concurrent.txt")
return Effect.gen(function* () { afterRead = () => (reads === 1 ? Effect.promise(() => fs.writeFile(target, "newer\n")) : Effect.void)
yield* Effect.promise(() => fs.writeFile(target, "before\n")) return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
const permissionReached = yield* Deferred.make<void>() Effect.andThen(
const releasePermission = yield* Deferred.make<void>() withTool(tmp.path, (registry) =>
afterPermission = (input) => executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
input.action === "edit" ),
? Deferred.succeed(permissionReached, undefined).pipe(Effect.andThen(Deferred.await(releasePermission))) ),
: Effect.void Effect.andThen((result) =>
Effect.gen(function* () {
const edit = yield* withTool(tmp.path, (registry) => expect(result).toMatchObject({ status: "completed", output: { replacements: 1 } })
executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })), expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
).pipe(Effect.forkChild) expect(writes).toEqual([target])
yield* Deferred.await(permissionReached) }),
expect(reads).toBe(0) ),
yield* Effect.promise(() => fs.writeFile(target, "newer\n")) )
yield* Deferred.succeed(releasePermission, undefined)
expect(yield* Fiber.join(edit)).toMatchObject({
status: "error",
error: { message: expect.stringContaining("Could not find oldString") },
})
expect(reads).toBe(1)
expect(writes).toEqual([])
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
})
}, },
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
), ),
+73 -99
View File
@@ -1,7 +1,7 @@
import fs from "fs/promises" import fs from "fs/promises"
import path from "path" import path from "path"
import { describe, expect } from "bun:test" import { describe, expect } from "bun:test"
import { Deferred, Effect, Exit, Fiber, Layer, Schema } from "effect" import { Effect, Exit, Layer, Schema } from "effect"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node" import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Environment } from "@opencode-ai/core/environment" import { Environment } from "@opencode-ai/core/environment"
@@ -14,7 +14,6 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
import { Session } from "@opencode-ai/core/session" import { Session } from "@opencode-ai/core/session"
import { Tool } from "@opencode-ai/core/tool" import { Tool } from "@opencode-ai/core/tool"
import { PatchTool } from "@opencode-ai/core/tool/plugin/patch" import { PatchTool } from "@opencode-ai/core/tool/plugin/patch"
import { transformEnvironmentFiles } from "./fixture/environment"
import { location } from "./fixture/location" import { location } from "./fixture/location"
import { tmpdir } from "./fixture/tmpdir" import { tmpdir } from "./fixture/tmpdir"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node" import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
@@ -33,11 +32,9 @@ let denyAction: string | undefined
let failRemoveTarget: string | undefined let failRemoveTarget: string | undefined
let failRemoveErrorTarget: string | undefined let failRemoveErrorTarget: string | undefined
let failWriteTarget: string | undefined let failWriteTarget: string | undefined
let reads = 0
let readsBeforeEditApproval = 0 let readsBeforeEditApproval = 0
let editApproved = false let editApproved = false
let afterEditApproval = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void let afterEditApproval = (): Effect.Effect<void> => Effect.void
let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false) let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
const permission = Layer.succeed( const permission = Layer.succeed(
@@ -48,7 +45,7 @@ const permission = Layer.succeed(
assertions.push(input) assertions.push(input)
if (input.action === "edit") editApproved = true if (input.action === "edit") editApproved = true
}).pipe( }).pipe(
Effect.andThen(input.action === "edit" ? Effect.suspend(() => afterEditApproval(input)) : Effect.void), Effect.andThen(input.action === "edit" ? Effect.suspend(afterEditApproval) : Effect.void),
Effect.andThen( Effect.andThen(
input.action === denyAction input.action === denyAction
? Effect.fail( ? Effect.fail(
@@ -79,14 +76,40 @@ const reset = () => {
failRemoveTarget = undefined failRemoveTarget = undefined
failRemoveErrorTarget = undefined failRemoveErrorTarget = undefined
failWriteTarget = undefined failWriteTarget = undefined
reads = 0
readsBeforeEditApproval = 0 readsBeforeEditApproval = 0
editApproved = false editApproved = false
afterEditApproval = () => Effect.void afterEditApproval = () => Effect.void
afterRead = () => Effect.void
formatFile = () => Effect.succeed(false) formatFile = () => Effect.succeed(false)
} }
const environment = Layer.effect(
Environment.Service,
Effect.gen(function* () {
const current = yield* Environment.Service
return Environment.Service.of({
...current,
files: {
...current.files,
read: (target, range) =>
Effect.sync(() => {
if (!editApproved) readsBeforeEditApproval++
}).pipe(Effect.andThen(current.files.read(target, range))),
remove: (target) => {
if (failRemoveTarget && path.basename(target) === failRemoveTarget) return Effect.die("forced remove failure")
if (failRemoveErrorTarget && path.basename(target) === failRemoveErrorTarget)
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced remove failure") }))
return current.files.remove(target)
},
write: (target, content) => {
if (failWriteTarget && path.basename(target) === failWriteTarget)
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced write failure") }))
return current.files.write(target, content)
},
},
})
}),
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
const withTool = <A, E, R>( const withTool = <A, E, R>(
directory: string, directory: string,
body: (registry: Tool.Interface) => Effect.Effect<A, E, R>, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>,
@@ -103,31 +126,7 @@ const withTool = <A, E, R>(
}).pipe( }).pipe(
Effect.provide( Effect.provide(
AppNodeBuilder.build(LayerNode.group([Tool.node, FileMutation.node, patchToolNode]), [ AppNodeBuilder.build(LayerNode.group([Tool.node, FileMutation.node, patchToolNode]), [
[ [Environment.node, environment],
Environment.node,
transformEnvironmentFiles(activeLocation, (files) => ({
read: (target, range) =>
Effect.sync(() => {
reads++
if (!editApproved) readsBeforeEditApproval++
}).pipe(
Effect.andThen(files.read(target, range)),
Effect.tap((result) => Effect.suspend(() => afterRead(target, result.bytes))),
),
remove: (target) => {
if (failRemoveTarget && path.basename(target) === failRemoveTarget)
return Effect.die("forced remove failure")
if (failRemoveErrorTarget && path.basename(target) === failRemoveErrorTarget)
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced remove failure") }))
return files.remove(target)
},
write: (target, content) => {
if (failWriteTarget && path.basename(target) === failWriteTarget)
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced write failure") }))
return files.write(target, content)
},
})),
],
[Location.node, activeLocation], [Location.node, activeLocation],
[Formatter.node, formatter], [Formatter.node, formatter],
[Permission.node, permission], [Permission.node, permission],
@@ -227,10 +226,14 @@ describe("PatchTool", () => {
action: "edit", action: "edit",
resources: ["nested/new.txt", "update.txt", "remove.txt"], resources: ["nested/new.txt", "update.txt", "remove.txt"],
save: ["*"], save: ["*"],
metadata: {
filepath: "nested/new.txt, update.txt, remove.txt",
diff: expect.stringContaining("Index:"),
files: expect.any(Array),
},
}, },
]) ])
expect(assertions[0]?.metadata).toBeUndefined() expect(readsBeforeEditApproval).toBe(2)
expect(readsBeforeEditApproval).toBe(0)
expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "nested/new.txt"), "utf8"))).toBe( expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "nested/new.txt"), "utf8"))).toBe(
"created\n", "created\n",
) )
@@ -271,69 +274,40 @@ describe("PatchTool", () => {
it.live("serializes concurrent patch transactions", () => it.live("serializes concurrent patch transactions", () =>
withTempTool((directory, registry) => { withTempTool((directory, registry) => {
const target = path.join(directory, "concurrent.txt") const target = path.join(directory, "concurrent.txt")
return Effect.gen(function* () { afterEditApproval = () =>
yield* Effect.promise(() => fs.writeFile(target, "one\ntwo\n")) assertions.filter((input) => input.action === "edit").length === 1 ? Effect.sleep("50 millis") : Effect.void
const firstRead = yield* Deferred.make<void>() return Effect.promise(() => fs.writeFile(target, "one\ntwo\n")).pipe(
const releaseFirst = yield* Deferred.make<void>() Effect.andThen(
const secondApproved = yield* Deferred.make<void>() Effect.all(
afterRead = () => [
reads === 1 executeTool(
? Deferred.succeed(firstRead, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst))) registry,
: Effect.void call(
afterEditApproval = (input) => "*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-one\n+ONE\n*** End Patch",
input.source?.id === "call-patch-two" "call-patch-one",
? Deferred.succeed(secondApproved, undefined).pipe(Effect.asVoid) ),
: Effect.void ),
executeTool(
const first = yield* executeTool( registry,
registry, call(
call("*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-one\n+ONE\n*** End Patch", "call-patch-one"), "*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-two\n+TWO\n*** End Patch",
).pipe(Effect.forkChild) "call-patch-two",
yield* Deferred.await(firstRead) ),
const second = yield* executeTool( ),
registry, ],
call("*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-two\n+TWO\n*** End Patch", "call-patch-two"), { concurrency: "unbounded" },
).pipe(Effect.forkChild) ),
yield* Deferred.await(secondApproved) ),
expect(reads).toBe(1) Effect.andThen((results) =>
Effect.gen(function* () {
yield* Deferred.succeed(releaseFirst, undefined) expect(results.map((result) => result.status)).toEqual(["completed", "completed"])
expect((yield* Fiber.join(first)).status).toBe("completed") expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
expect((yield* Fiber.join(second)).status).toBe("completed") }),
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n") ),
}) )
}), }),
) )
it.live("validates patch context after permission succeeds", () =>
withTempTool((directory, registry) =>
Effect.gen(function* () {
const target = path.join(directory, "current.txt")
yield* Effect.promise(() => fs.writeFile(target, "before\n"))
const permissionReached = yield* Deferred.make<void>()
const releasePermission = yield* Deferred.make<void>()
afterEditApproval = () =>
Deferred.succeed(permissionReached, undefined).pipe(Effect.andThen(Deferred.await(releasePermission)))
const patch = yield* executeTool(
registry,
call("*** Begin Patch\n*** Update File: current.txt\n@@\n-before\n+after\n*** End Patch"),
).pipe(Effect.forkChild)
yield* Deferred.await(permissionReached)
expect(reads).toBe(0)
yield* Effect.promise(() => fs.writeFile(target, "newer\n"))
yield* Deferred.succeed(releasePermission, undefined)
expect(yield* Fiber.join(patch)).toMatchObject({
status: "error",
error: { message: expect.stringContaining("Failed to find expected lines") },
})
expect(reads).toBe(1)
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
}),
),
)
it.live("returns file diffs for final formatted content", () => it.live("returns file diffs for final formatted content", () =>
withTempTool((directory, registry) => { withTempTool((directory, registry) => {
const target = path.join(directory, "formatted.txt") const target = path.join(directory, "formatted.txt")
@@ -816,7 +790,7 @@ describe("PatchTool", () => {
), ),
) )
it.live("approves external-directory and edit access before reading", () => it.live("approves an external directory before reading and requests edit permission afterward", () =>
Effect.acquireUseRelease( Effect.acquireUseRelease(
Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
([active, outside]) => { ([active, outside]) => {
@@ -833,7 +807,7 @@ describe("PatchTool", () => {
), ),
).toMatchObject({ status: "completed" }) ).toMatchObject({ status: "completed" })
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"]) expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
expect(readsBeforeEditApproval).toBe(0) expect(readsBeforeEditApproval).toBe(1)
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n") expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
}), }),
), ),
@@ -964,7 +938,7 @@ describe("PatchTool", () => {
), ),
) )
it.live("approves a relative external target before reading", () => it.live("approves a relative external target before reading and requests edit permission afterward", () =>
Effect.acquireUseRelease( Effect.acquireUseRelease(
Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
([active, outside]) => { ([active, outside]) => {
@@ -982,7 +956,7 @@ describe("PatchTool", () => {
), ),
).toMatchObject({ status: "completed" }) ).toMatchObject({ status: "completed" })
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"]) expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
expect(readsBeforeEditApproval).toBe(0) expect(readsBeforeEditApproval).toBe(1)
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n") expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
}), }),
), ),
+25
View File
@@ -286,6 +286,31 @@ describe("ShellTool", () => {
), ),
) )
it.live(
"reports a command that fails to spawn",
() =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) => {
reset()
const command = "printf before\0after"
return withSession(tmp.path, (registry) =>
executeTool(registry, call({ command })).pipe(
Effect.andThen((settled) =>
Effect.sync(() => {
expect(settled.status).toBe("error")
if (settled.status !== "error") return
expect(settled.error?.message).toContain("Command failed")
}),
),
),
)
},
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
),
{ timeout: 2_000 },
)
it.live("permissions compound commands separately", () => it.live("permissions compound commands separately", () =>
Effect.acquireUseRelease( Effect.acquireUseRelease(
Effect.promise(() => tmpdir()), Effect.promise(() => tmpdir()),
+5 -5
View File
@@ -105,9 +105,9 @@ describe("SkillTool", () => {
}), }),
).toMatchObject({ ).toMatchObject({
status: "completed", status: "completed",
content: [{ type: "text", text: Skill.toModelOutput(info, [reference]) }], content: [{ type: "text", text: SkillTool.toModelOutput(info, [reference]) }],
}) })
expect(Skill.toModelOutput(info, [reference])).toContain(`Base directory for this skill: ${directory}`) expect(SkillTool.toModelOutput(info, [reference])).toContain(`Base directory for this skill: ${directory}`)
expect( expect(
yield* executeTool(registry, { yield* executeTool(registry, {
sessionID, sessionID,
@@ -116,8 +116,8 @@ describe("SkillTool", () => {
}), }),
).toEqual({ ).toEqual({
status: "completed", status: "completed",
output: { name: "Effect", directory, output: Skill.toModelOutput(info, [reference]) }, output: { name: "Effect", directory, output: SkillTool.toModelOutput(info, [reference]) },
content: [{ type: "text", text: Skill.toModelOutput(info, [reference]) }], content: [{ type: "text", text: SkillTool.toModelOutput(info, [reference]) }],
metadata: { name: "Effect", directory }, metadata: { name: "Effect", directory },
}) })
expect(assertions).toMatchObject([ expect(assertions).toMatchObject([
@@ -168,7 +168,7 @@ describe("SkillTool", () => {
}), }),
).toMatchObject({ ).toMatchObject({
status: "completed", status: "completed",
content: [{ type: "text", text: Skill.toModelOutput(flat, []) }], content: [{ type: "text", text: SkillTool.toModelOutput(flat, []) }],
}) })
}).pipe(Effect.provide(skillToolLayer)) }).pipe(Effect.provide(skillToolLayer))
}), }),
+41 -139
View File
@@ -1,7 +1,7 @@
import fs from "fs/promises" import fs from "fs/promises"
import path from "path" import path from "path"
import { describe, expect } from "bun:test" import { describe, expect } from "bun:test"
import { Deferred, Effect, Fiber, Layer } from "effect" import { Effect, Layer } from "effect"
import { FileMutation } from "@opencode-ai/core/file-mutation" import { FileMutation } from "@opencode-ai/core/file-mutation"
import { Formatter } from "@opencode-ai/core/formatter" import { Formatter } from "@opencode-ai/core/formatter"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
@@ -13,9 +13,7 @@ import { Permission } from "@opencode-ai/core/permission"
import { AbsolutePath } from "@opencode-ai/core/schema" import { AbsolutePath } from "@opencode-ai/core/schema"
import { Session } from "@opencode-ai/core/session" import { Session } from "@opencode-ai/core/session"
import { Tool } from "@opencode-ai/core/tool" import { Tool } from "@opencode-ai/core/tool"
import { EditTool } from "@opencode-ai/core/tool/plugin/edit"
import { WriteTool } from "@opencode-ai/core/tool/plugin/write" import { WriteTool } from "@opencode-ai/core/tool/plugin/write"
import { transformEnvironmentFiles } from "./fixture/environment"
import { location } from "./fixture/location" import { location } from "./fixture/location"
import { tmpdir } from "./fixture/tmpdir" import { tmpdir } from "./fixture/tmpdir"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node" import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
@@ -28,26 +26,10 @@ const writeToolNode = makeLocationNode({
deps: [Tool.node, LocationMutation.node, FileMutation.node, Environment.node, Formatter.node, Permission.node], deps: [Tool.node, LocationMutation.node, FileMutation.node, Environment.node, Formatter.node, Permission.node],
}) })
const editToolNode = makeLocationNode({
name: "test/edit-tool-plugin",
layer: Layer.effectDiscard(registerToolPlugin(EditTool.Plugin)),
deps: [
Tool.node,
LocationMutation.node,
FileMutation.node,
Environment.node,
Formatter.node,
Location.node,
Permission.node,
],
})
const sessionID = Session.ID.make("ses_write_tool_test") const sessionID = Session.ID.make("ses_write_tool_test")
const assertions: Permission.AssertInput[] = [] const assertions: Permission.AssertInput[] = []
const writes: string[] = [] const writes: string[] = []
let reads = 0
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false) let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
let afterPermission = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void
let denyAction: string | undefined let denyAction: string | undefined
const permission = Layer.succeed( const permission = Layer.succeed(
@@ -55,7 +37,6 @@ const permission = Layer.succeed(
Permission.Service.of({ Permission.Service.of({
assert: (input) => assert: (input) =>
Effect.sync(() => assertions.push(input)).pipe( Effect.sync(() => assertions.push(input)).pipe(
Effect.andThen(Effect.suspend(() => afterPermission(input))),
Effect.andThen( Effect.andThen(
input.action === denyAction input.action === denyAction
? Effect.fail( ? Effect.fail(
@@ -83,17 +64,26 @@ const formatter = Layer.mock(Formatter.Service, {
const reset = () => { const reset = () => {
assertions.length = 0 assertions.length = 0
writes.length = 0 writes.length = 0
reads = 0
formatFile = () => Effect.succeed(false) formatFile = () => Effect.succeed(false)
afterPermission = () => Effect.void
denyAction = undefined denyAction = undefined
} }
const withTool = <A, E, R>( const environment = Layer.effect(
directory: string, Environment.Service,
body: (registry: Tool.Interface) => Effect.Effect<A, E, R>, Effect.gen(function* () {
options?: { edit?: boolean }, const current = yield* Environment.Service
) => { return Environment.Service.of({
...current,
files: {
...current.files,
write: (target, content) =>
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(current.files.write(target, content))),
},
})
}),
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
const activeLocation = Layer.succeed( const activeLocation = Layer.succeed(
Location.Service, Location.Service,
Location.Service.of(location({ directory: AbsolutePath.make(directory) })), Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
@@ -103,22 +93,9 @@ const withTool = <A, E, R>(
}).pipe( }).pipe(
Effect.provide( Effect.provide(
AppNodeBuilder.build( AppNodeBuilder.build(
LayerNode.group([ LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, writeToolNode]),
Tool.node,
LocationMutation.node,
FileMutation.node,
writeToolNode,
...(options?.edit ? [editToolNode] : []),
]),
[ [
[ [Environment.node, environment],
Environment.node,
transformEnvironmentFiles(activeLocation, (files) => ({
read: (target, range) => Effect.sync(() => reads++).pipe(Effect.andThen(files.read(target, range))),
write: (target, content) =>
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))),
})),
],
[Location.node, activeLocation], [Location.node, activeLocation],
[Formatter.node, formatter], [Formatter.node, formatter],
[Permission.node, permission], [Permission.node, permission],
@@ -134,12 +111,6 @@ const call = (input: typeof WriteTool.Input.Type, id = "call-write") => ({
call: { type: "tool-call" as const, id, name: "write", input }, call: { type: "tool-call" as const, id, name: "write", input },
}) })
const editCall = (input: typeof EditTool.Input.Type, id = "call-edit") => ({
sessionID,
...toolIdentity,
call: { type: "tool-call" as const, id, name: "edit", input },
})
const it = testEffect(Layer.empty) const it = testEffect(Layer.empty)
describe("WriteTool", () => { describe("WriteTool", () => {
@@ -166,7 +137,17 @@ describe("WriteTool", () => {
"created", "created",
) )
expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["src/new.txt"], save: ["*"] }]) expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["src/new.txt"], save: ["*"] }])
expect(assertions[0]?.metadata).toBeUndefined() expect(assertions[0]?.metadata).toMatchObject({
files: [
{
file: "src/new.txt",
status: "added",
additions: 1,
deletions: 0,
patch: expect.stringContaining("+created"),
},
],
})
expect(writes).toEqual([path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt")]) expect(writes).toEqual([path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt")])
}), }),
) )
@@ -214,7 +195,17 @@ describe("WriteTool", () => {
if (settled.status !== "completed") return if (settled.status !== "completed") return
expect(settled.content).toEqual([{ type: "text", text: "Wrote file successfully: existing.txt" }]) expect(settled.content).toEqual([{ type: "text", text: "Wrote file successfully: existing.txt" }])
expect(settled.output).toMatchObject({ resource: "existing.txt", existed: true }) expect(settled.output).toMatchObject({ resource: "existing.txt", existed: true })
expect(assertions[0]?.metadata).toBeUndefined() expect(assertions[0]?.metadata).toMatchObject({
files: [
{
file: "existing.txt",
status: "modified",
additions: 1,
deletions: 1,
patch: expect.stringMatching(/-before[\s\S]*\+after/),
},
],
})
expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "existing.txt"), "utf8"))).toBe( expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "existing.txt"), "utf8"))).toBe(
"after", "after",
) )
@@ -429,93 +420,4 @@ describe("WriteTool", () => {
), ),
), ),
) )
it.live("authorizes an edit while a write holds the same-path execution lock", () =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) => {
reset()
const target = path.join(tmp.path, "shared.txt")
return Effect.gen(function* () {
yield* Effect.promise(() => fs.writeFile(target, "initial"))
const formatting = yield* Deferred.make<void>()
const releaseFormatting = yield* Deferred.make<void>()
const editApproved = yield* Deferred.make<void>()
let formats = 0
formatFile = () =>
++formats === 1
? Deferred.succeed(formatting, undefined).pipe(
Effect.andThen(Deferred.await(releaseFormatting)),
Effect.as(false),
)
: Effect.succeed(false)
afterPermission = (input) =>
input.source?.id === "call-serialized-edit" && input.action === "edit"
? Deferred.succeed(editApproved, undefined).pipe(Effect.asVoid)
: Effect.void
const write = yield* withTool(
tmp.path,
(registry) =>
executeTool(registry, call({ path: "shared.txt", content: "before" }, "call-serialized-write")),
{ edit: true },
).pipe(Effect.forkChild)
yield* Deferred.await(formatting)
const edit = yield* withTool(
tmp.path,
(registry) =>
executeTool(
registry,
editCall({ path: "shared.txt", oldString: "before", newString: "after" }, "call-serialized-edit"),
),
{ edit: true },
).pipe(Effect.forkChild)
yield* Deferred.await(editApproved)
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("before")
yield* Deferred.succeed(releaseFormatting, undefined)
expect((yield* Fiber.join(write)).status).toBe("completed")
expect((yield* Fiber.join(edit)).status).toBe("completed")
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
})
},
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
),
)
it.live("does not hold the execution lock while waiting for permission", () =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) => {
reset()
const target = path.join(tmp.path, "shared.txt")
return Effect.gen(function* () {
yield* Effect.promise(() => fs.writeFile(target, "initial"))
const firstAsked = yield* Deferred.make<void>()
const releaseFirst = yield* Deferred.make<void>()
afterPermission = (input) =>
input.source?.id === "call-waiting-write" && input.action === "edit"
? Deferred.succeed(firstAsked, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst)))
: Effect.void
const first = yield* withTool(tmp.path, (registry) =>
executeTool(registry, call({ path: "shared.txt", content: "first" }, "call-waiting-write")),
).pipe(Effect.forkChild)
yield* Deferred.await(firstAsked)
expect(reads).toBe(0)
const second = yield* withTool(tmp.path, (registry) =>
executeTool(registry, call({ path: "shared.txt", content: "second" }, "call-approved-write")),
)
expect(second.status).toBe("completed")
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("second")
yield* Deferred.succeed(releaseFirst, undefined)
expect((yield* Fiber.join(first)).status).toBe("completed")
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("first")
})
},
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
),
)
}) })
-106
View File
@@ -1,106 +0,0 @@
import { beforeEach, expect } from "bun:test"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { Database } from "@opencode-ai/core/database/database"
import { makeMemoryDriver } from "@opencode-ai/core/environment"
import { Workspace } from "@opencode-ai/core/workspace"
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
import { WorkspaceTable } from "@opencode-ai/core/workspace/sql"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { eq } from "drizzle-orm"
import { Effect } from "effect"
import { TestClock } from "effect/testing"
import { ChildProcess } from "effect/unstable/process"
import { testEffect } from "./lib/effect"
const calls: Array<{ readonly operation: string; readonly binding?: WorkspaceDriver.Binding }> = []
const memory = makeMemoryDriver()
let failConnect = false
const driver = WorkspaceDriver.make({
create: ({ workspaceID }) => {
calls.push({ operation: "create" })
return Effect.succeed({ binding: { workspaceID, generation: 0 } })
},
connect: ({ binding }) => {
calls.push({ operation: "connect", binding })
if (failConnect) return Effect.fail(new WorkspaceDriver.Error({ message: "wake failed" }))
return Effect.succeed(memory)
},
suspendForIdle: ({ binding, saveBinding }) => {
calls.push({ operation: "suspendForIdle", binding })
return saveBinding({ ...binding, generation: Number(binding.generation) + 1, suspended: true })
},
destroy: ({ binding }) => {
calls.push({ operation: "destroy", binding })
return Effect.void
},
})
const it = testEffect(
AppNodeBuilder.build(
LayerNode.group([Database.node, Workspace.configured({ idleThreshold: "5 minutes", pollInterval: "1 minute" })]),
[[WorkspaceDriver.node, WorkspaceDriver.registryNode({ fake: driver })]],
),
)
beforeEach(() => {
calls.splice(0)
failConnect = false
})
it.effect("persists the workspace lifecycle and reconnects after idle suspension", () =>
Effect.gen(function* () {
const workspace = yield* Workspace.Service
const created = yield* workspace.create("fake")
expect(created.id.startsWith("wrk_")).toBe(true)
expect(created.binding).toEqual({ workspaceID: created.id, generation: 0 })
const environment = yield* workspace.connect(created.id)
expect(calls.map((call) => call.operation)).toEqual(["create"])
yield* TestClock.adjust("4 minutes")
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("activity"))).pipe(Effect.exit)
yield* TestClock.adjust("4 minutes")
expect(calls.map((call) => call.operation)).toEqual(["create", "connect"])
yield* TestClock.adjust("2 minutes")
expect(calls.map((call) => call.operation)).toEqual(["create", "connect", "suspendForIdle"])
const stored = yield* Database.Service.use(({ db }) =>
db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, created.id)).get(),
).pipe(Effect.orDie)
expect(stored?.binding).toEqual({ workspaceID: created.id, generation: 1, suspended: true })
expect(stored?.last_used_at).toBe(4 * 60 * 1000)
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("wake"))).pipe(Effect.exit)
expect(calls.map((call) => call.operation)).toEqual(["create", "connect", "suspendForIdle", "connect"])
expect(calls.at(-1)?.binding).toEqual({ workspaceID: created.id, generation: 1, suspended: true })
yield* workspace.destroy(created.id)
expect(calls.at(-1)?.operation).toBe("destroy")
}),
)
it.effect("surfaces wake failures through the spawn error channel", () =>
Effect.gen(function* () {
const workspace = yield* Workspace.Service
const created = yield* workspace.create("fake")
const environment = yield* workspace.connect(created.id)
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("connect"))).pipe(Effect.exit)
yield* TestClock.adjust("6 minutes")
failConnect = true
const error = yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("wake"))).pipe(Effect.flip)
expect(error).toMatchObject({
_tag: "PlatformError",
reason: {
_tag: "Unknown",
module: "Workspace",
method: "spawn",
description: `Failed to wake workspace ${created.id}`,
},
})
}),
)
-62
View File
@@ -1809,12 +1809,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
}, },
@@ -2023,12 +2017,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
}
},
"delivery": { "delivery": {
"anyOf": [ "anyOf": [
{ {
@@ -12853,25 +12841,6 @@
"required": ["name"], "required": ["name"],
"additionalProperties": false "additionalProperties": false
}, },
"Prompt.SkillAttachment": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"text": {
"type": "string"
},
"mention": {
"$ref": "#/components/schemas/Prompt.Mention"
}
},
"required": ["id", "name", "text"],
"additionalProperties": false
},
"Session.Message.User": { "Session.Message.User": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -12911,12 +12880,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"type": { "type": {
"type": "string", "type": "string",
"enum": ["user"] "enum": ["user"]
@@ -13874,19 +13837,6 @@
"required": ["uri"], "required": ["uri"],
"additionalProperties": false "additionalProperties": false
}, },
"PromptInput.SkillAttachment": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"mention": {
"$ref": "#/components/schemas/Prompt.Mention"
}
},
"required": ["id"],
"additionalProperties": false
},
"SessionPending.UserData": { "SessionPending.UserData": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -13905,12 +13855,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
} }
@@ -14820,12 +14764,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
} }
-1
View File
@@ -345,7 +345,6 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S>(sessionLo
model: Model.Ref.pipe(Schema.optional), model: Model.Ref.pipe(Schema.optional),
files: PromptInput.Prompt.fields.files, files: PromptInput.Prompt.fields.files,
agents: PromptInput.Prompt.fields.agents, agents: PromptInput.Prompt.fields.agents,
skills: PromptInput.Prompt.fields.skills,
delivery: SessionPending.Delivery.pipe(Schema.optional), delivery: SessionPending.Delivery.pipe(Schema.optional),
resume: Schema.Boolean.pipe(Schema.optional), resume: Schema.Boolean.pipe(Schema.optional),
}), }),
-8
View File
@@ -3,7 +3,6 @@ export * as PromptInput from "./prompt-input.js"
import { Schema } from "effect" import { Schema } from "effect"
import { AgentAttachment, PromptMention } from "./prompt.js" import { AgentAttachment, PromptMention } from "./prompt.js"
import { optional, statics } from "./schema.js" import { optional, statics } from "./schema.js"
import { Skill } from "./skill.js"
export interface FileAttachment extends Schema.Schema.Type<typeof FileAttachment> {} export interface FileAttachment extends Schema.Schema.Type<typeof FileAttachment> {}
export const FileAttachment = Schema.Struct({ export const FileAttachment = Schema.Struct({
@@ -20,15 +19,8 @@ export const FileAttachment = Schema.Struct({
) )
export interface Prompt extends Schema.Schema.Type<typeof Prompt> {} export interface Prompt extends Schema.Schema.Type<typeof Prompt> {}
export interface SkillAttachment extends Schema.Schema.Type<typeof SkillAttachment> {}
export const SkillAttachment = Schema.Struct({
id: Skill.ID,
mention: PromptMention.pipe(optional),
}).annotate({ identifier: "PromptInput.SkillAttachment" })
export const Prompt = Schema.Struct({ export const Prompt = Schema.Struct({
text: Schema.String, text: Schema.String,
files: Schema.Array(FileAttachment).pipe(optional), files: Schema.Array(FileAttachment).pipe(optional),
agents: Schema.Array(AgentAttachment).pipe(optional), agents: Schema.Array(AgentAttachment).pipe(optional),
skills: Schema.Array(SkillAttachment).pipe(optional),
}).annotate({ identifier: "PromptInput" }) }).annotate({ identifier: "PromptInput" })
+1 -12
View File
@@ -1,7 +1,6 @@
import { Schema } from "effect" import { Schema } from "effect"
import { optional } from "./schema.js" import { optional } from "./schema.js"
import { statics } from "./schema.js" import { statics } from "./schema.js"
import { Skill } from "./skill.js"
export interface PromptMention extends Schema.Schema.Type<typeof PromptMention> {} export interface PromptMention extends Schema.Schema.Type<typeof PromptMention> {}
export const PromptMention = Schema.Struct({ export const PromptMention = Schema.Struct({
@@ -53,31 +52,21 @@ export const AgentAttachment = Schema.Struct({
mention: PromptMention.pipe(optional), mention: PromptMention.pipe(optional),
}).annotate({ identifier: "Prompt.AgentAttachment" }) }).annotate({ identifier: "Prompt.AgentAttachment" })
export interface SkillAttachment extends Schema.Schema.Type<typeof SkillAttachment> {}
export const SkillAttachment = Schema.Struct({
id: Skill.ID,
name: Skill.Name,
text: Schema.String,
mention: PromptMention.pipe(optional),
}).annotate({ identifier: "Prompt.SkillAttachment" })
export interface Prompt extends Schema.Schema.Type<typeof Prompt> {} export interface Prompt extends Schema.Schema.Type<typeof Prompt> {}
export const Prompt = Schema.Struct({ export const Prompt = Schema.Struct({
text: Schema.String, text: Schema.String,
files: Schema.Array(FileAttachment).pipe(optional), files: Schema.Array(FileAttachment).pipe(optional),
agents: Schema.Array(AgentAttachment).pipe(optional), agents: Schema.Array(AgentAttachment).pipe(optional),
skills: Schema.Array(SkillAttachment).pipe(optional),
}) })
.annotate({ identifier: "Prompt" }) .annotate({ identifier: "Prompt" })
.pipe( .pipe(
statics((schema) => ({ statics((schema) => ({
equivalence: Schema.toEquivalence(schema), equivalence: Schema.toEquivalence(schema),
fromUserMessage: (input: Pick<Prompt, "text" | "files" | "agents" | "skills">) => fromUserMessage: (input: Pick<Prompt, "text" | "files" | "agents">) =>
schema.make({ schema.make({
text: input.text, text: input.text,
...(input.files === undefined ? {} : { files: input.files }), ...(input.files === undefined ? {} : { files: input.files }),
...(input.agents === undefined ? {} : { agents: input.agents }), ...(input.agents === undefined ? {} : { agents: input.agents }),
...(input.skills === undefined ? {} : { skills: input.skills }),
}), }),
})), })),
) )
-1
View File
@@ -58,7 +58,6 @@ export const User = Schema.Struct({
text: Prompt.fields.text, text: Prompt.fields.text,
files: Prompt.fields.files, files: Prompt.fields.files,
agents: Prompt.fields.agents, agents: Prompt.fields.agents,
skills: Prompt.fields.skills,
type: Schema.tag("user"), type: Schema.tag("user"),
}).annotate({ identifier: "Session.Message.User" }) }).annotate({ identifier: "Session.Message.User" })
-8
View File
@@ -313,7 +313,6 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
text: ctx.payload.text, text: ctx.payload.text,
files: ctx.payload.files, files: ctx.payload.files,
agents: ctx.payload.agents, agents: ctx.payload.agents,
skills: ctx.payload.skills,
metadata: ctx.payload.metadata, metadata: ctx.payload.metadata,
delivery: ctx.payload.delivery, delivery: ctx.payload.delivery,
resume: ctx.payload.resume, resume: ctx.payload.resume,
@@ -338,9 +337,6 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
Effect.catchTag("Session.AttachmentError", (error) => Effect.catchTag("Session.AttachmentError", (error) =>
Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })), Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })),
), ),
Effect.catchTag("Session.SkillNotFoundError", (error) =>
Effect.fail(new InvalidRequestError({ message: `Skill not found: ${error.skill}`, field: "skills" })),
),
), ),
} }
}), }),
@@ -359,7 +355,6 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
model: ctx.payload.model, model: ctx.payload.model,
files: ctx.payload.files, files: ctx.payload.files,
agents: ctx.payload.agents, agents: ctx.payload.agents,
skills: ctx.payload.skills,
delivery: ctx.payload.delivery, delivery: ctx.payload.delivery,
resume: ctx.payload.resume, resume: ctx.payload.resume,
}) })
@@ -399,9 +394,6 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
Effect.catchTag("Session.AttachmentError", (error) => Effect.catchTag("Session.AttachmentError", (error) =>
Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })), Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })),
), ),
Effect.catchTag("Session.SkillNotFoundError", (error) =>
Effect.fail(new InvalidRequestError({ message: `Skill not found: ${error.skill}`, field: "skills" })),
),
), ),
} }
}), }),
+3 -1
View File
@@ -21,7 +21,9 @@ export const ShellHandler = HttpApiBuilder.group(Api, "server.shell", (handlers)
Effect.fn(function* (ctx) { Effect.fn(function* (ctx) {
const shell = yield* Shell.Service const shell = yield* Shell.Service
const location = yield* Location.Service const location = yield* Location.Service
return yield* response(shell.create({ ...ctx.payload, cwd: ctx.payload.cwd || location.directory })) return yield* response(
shell.create({ ...ctx.payload, cwd: ctx.payload.cwd || location.directory }).pipe(Effect.orDie),
)
}), }),
) )
.handle( .handle(
-6
View File
@@ -28,7 +28,6 @@ import { SessionRestart } from "@opencode-ai/core/session/execution/restart"
import { PluginRuntime } from "@opencode-ai/core/plugin/runtime" import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
import { SdkPlugins } from "@opencode-ai/core/plugin/sdk" import { SdkPlugins } from "@opencode-ai/core/plugin/sdk"
import { WellKnown } from "@opencode-ai/core/wellknown" import { WellKnown } from "@opencode-ai/core/wellknown"
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
import { Watcher } from "@opencode-ai/core/filesystem/watcher" import { Watcher } from "@opencode-ai/core/filesystem/watcher"
import { HttpRouter } from "effect/unstable/http" import { HttpRouter } from "effect/unstable/http"
import { HttpApiBuilder } from "effect/unstable/httpapi" import { HttpApiBuilder } from "effect/unstable/httpapi"
@@ -44,7 +43,6 @@ import { formLocationLayer } from "./middleware/form-location"
import { sessionLocationLayer } from "./middleware/session-location" import { sessionLocationLayer } from "./middleware/session-location"
import { ServerInfo } from "./server-info" import { ServerInfo } from "./server-info"
import type { ServerOptions } from "./options" import type { ServerOptions } from "./options"
import { modalWorkspaceDriver, provider as modalProvider } from "./workspace/modal-workspace"
const applicationServices = LayerNode.group([ const applicationServices = LayerNode.group([
Database.node, Database.node,
@@ -117,10 +115,6 @@ function makeRoutes<AuthError, AuthServices>(
], ],
[PluginRuntime.node, PluginRuntime.layerWithCell(pluginRuntimeCell)], [PluginRuntime.node, PluginRuntime.layerWithCell(pluginRuntimeCell)],
[PluginRuntime.providerNode, PluginRuntime.providerNodeWithCell(pluginRuntimeCell)], [PluginRuntime.providerNode, PluginRuntime.providerNodeWithCell(pluginRuntimeCell)],
[
WorkspaceDriver.node,
WorkspaceDriver.registryNode({ [modalProvider]: modalWorkspaceDriver({ app: "opencode-workspaces" }) }),
],
] ]
const serviceLayer = options.simulation const serviceLayer = options.simulation
? Layer.unwrap( ? Layer.unwrap(
@@ -1,128 +0,0 @@
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
import { Effect, Option, Schema } from "effect"
import type { App, Image, ModalClient, ModalClientParams, Sandbox } from "modal"
import { createModalSandboxWithClient, makeModalDriver, type ModalImageSpec, openModalClient } from "./modal"
export const provider = "modal"
export const ModalBinding = Schema.Struct({
sandboxId: Schema.optional(Schema.String),
snapshotImageId: Schema.optional(Schema.String),
})
export type ModalBinding = typeof ModalBinding.Type
export interface ModalWorkspaceOptions {
readonly app: string
readonly client?: ModalClientParams
readonly image?: ModalImageSpec
}
export const modalWorkspaceDriver = (options: ModalWorkspaceOptions): WorkspaceDriver.Interface => {
const decodeBinding = Schema.decodeUnknownOption(ModalBinding)
let clientPromise: Promise<ModalClient> | undefined
let appPromise: Promise<App> | undefined
// The SDK client and app handle are shared for the process lifetime of this driver.
const client = () => (clientPromise ??= openModalClient(options.client))
const app = () =>
(appPromise ??= client().then((value) => value.apps.fromName(options.app, { createIfMissing: true })))
const attempt = <A>(run: () => Promise<A>) =>
Effect.tryPromise({ try: run, catch: (cause) => new WorkspaceDriver.Error({ cause }) })
const binding = (value: WorkspaceDriver.Binding): ModalBinding => Option.getOrElse(decodeBinding(value), () => ({}))
const live = async (lookup: () => Promise<Sandbox>) => {
const { NotFoundError } = await import("modal")
const sandbox = await lookup().catch((error) => {
if (error instanceof NotFoundError) return undefined
throw error
})
if (sandbox && (await sandbox.poll()) === null) return sandbox
}
const findLive = async (modalClient: ModalClient, value: ModalBinding, workspaceID: string) => {
if (value.sandboxId) {
const sandboxID = value.sandboxId
const sandbox = await live(() => modalClient.sandboxes.fromId(sandboxID))
if (sandbox) return sandbox
}
// Name fallback is valid only before the first snapshot; afterward a live named sandbox is stale by design.
if (value.snapshotImageId) return
return live(() => modalClient.sandboxes.fromName(options.app, workspaceID))
}
const createSandbox = async (workspaceID: string, image?: Image) => {
const { AlreadyExistsError } = await import("modal")
const modalClient = await client()
return createModalSandboxWithClient(
modalClient,
await app(),
{
image: options.image,
sandbox: {
name: workspaceID,
tags: { workspace: workspaceID },
timeoutMs: 24 * 60 * 60 * 1000,
},
},
image,
).catch((error) => {
if (error instanceof AlreadyExistsError) return modalClient.sandboxes.fromName(options.app, workspaceID)
throw error
})
}
const deleteImage = (modalClient: ModalClient, imageID?: string) =>
imageID ? attempt(() => modalClient.images.delete(imageID)).pipe(Effect.ignore) : Effect.void
const terminate = (sandbox?: Sandbox) =>
sandbox ? attempt(() => sandbox.terminate({ wait: true })).pipe(Effect.ignore) : Effect.void
return WorkspaceDriver.make({
create: ({ workspaceID }) =>
attempt(async () => {
const sandbox = await createSandbox(workspaceID)
return { binding: { sandboxId: sandbox.sandboxId } }
}),
connect: ({ workspaceID, binding: value, saveBinding }) =>
Effect.gen(function* () {
const modalBinding = binding(value)
const modalClient = yield* attempt(client)
const sandbox = yield* attempt(async () => {
const existing = await findLive(modalClient, modalBinding, workspaceID)
const image =
existing || !modalBinding.snapshotImageId
? undefined
: await modalClient.images.fromId(modalBinding.snapshotImageId)
return existing ?? createSandbox(workspaceID, image)
})
if (modalBinding.sandboxId !== sandbox.sandboxId) {
yield* saveBinding({ ...modalBinding, sandboxId: sandbox.sandboxId })
}
return makeModalDriver(sandbox)
}),
suspendForIdle: ({ workspaceID, binding: value, saveBinding }) =>
Effect.gen(function* () {
const modalBinding = binding(value)
const modalClient = yield* attempt(client)
const sandbox = yield* attempt(() => findLive(modalClient, modalBinding, workspaceID))
if (!sandbox) return
const snapshot = yield* attempt(() => sandbox.snapshotFilesystem({ ttlMs: null }))
yield* saveBinding({ snapshotImageId: snapshot.imageId })
yield* Effect.all([deleteImage(modalClient, modalBinding.snapshotImageId), terminate(sandbox)], {
concurrency: "unbounded",
discard: true,
})
}),
destroy: ({ workspaceID, binding: value }) =>
Effect.gen(function* () {
const modalBinding = binding(value)
const modalClient = yield* attempt(client)
const sandbox = yield* attempt(() => findLive(modalClient, modalBinding, workspaceID))
yield* Effect.all([terminate(sandbox), deleteImage(modalClient, modalBinding.snapshotImageId)], {
concurrency: "unbounded",
discard: true,
})
}),
})
}
+16 -37
View File
@@ -3,7 +3,7 @@ import { systemError } from "effect/PlatformError"
import type { Command, KillOptions } from "effect/unstable/process/ChildProcess" import type { Command, KillOptions } from "effect/unstable/process/ChildProcess"
import { ExitCode, make, makeHandle, ProcessId } from "effect/unstable/process/ChildProcessSpawner" import { ExitCode, make, makeHandle, ProcessId } from "effect/unstable/process/ChildProcessSpawner"
import type { Driver } from "@opencode-ai/core/environment" import type { Driver } from "@opencode-ai/core/environment"
import type { App, Image, ModalClient, ModalClientParams, Sandbox, SandboxCreateParams } from "modal" import type { ModalClientParams, Sandbox, SandboxCreateParams } from "modal"
const INNER_WRAPPER = ` const INNER_WRAPPER = `
pidfile=$1 pidfile=$1
@@ -44,14 +44,11 @@ export interface ModalImageSpec {
readonly dockerfileCommands: ReadonlyArray<string> readonly dockerfileCommands: ReadonlyArray<string>
} }
export interface ModalSandboxCreateOptions { export interface ModalSandboxOptions {
readonly image?: ModalImageSpec
readonly sandbox?: SandboxCreateParams
}
export interface ModalSandboxOptions extends ModalSandboxCreateOptions {
readonly app: string readonly app: string
readonly client?: ModalClientParams readonly client?: ModalClientParams
readonly image?: ModalImageSpec
readonly sandbox?: SandboxCreateParams
} }
/** /**
@@ -67,11 +64,19 @@ export const ubuntuImage: ModalImageSpec = {
/** Creates a Modal sandbox lazily, keeping the SDK off the server startup path when Modal is unused. */ /** Creates a Modal sandbox lazily, keeping the SDK off the server startup path when Modal is unused. */
export const createModalSandbox = async (options: ModalSandboxOptions) => { export const createModalSandbox = async (options: ModalSandboxOptions) => {
const client = await openModalClient(options.client) const { ModalClient } = await import("modal")
const client = new ModalClient(options.client)
const app = await client.apps.fromName(options.app, { createIfMissing: true }) const app = await client.apps.fromName(options.app, { createIfMissing: true })
const sandbox = await createModalSandboxWithClient(client, app, { const imageSpec = options.image ?? ubuntuImage
image: options.image, const image = client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
sandbox: options.sandbox, // Always Modal's Full-VM runtime (beta, enabled per account): a real kernel
// with real device nodes, so workspaces can run Docker and other
// kernel-dependent workloads. Costs versus gVisor, measured Aug 2026:
// per-exec floor ~285-535ms versus ~90-165ms, and filesystem snapshots only
// (no memory snapshots — acceptable; fs-snapshot is the persistence design).
const sandbox = await client.sandboxes.create(app, image, {
...options.sandbox,
experimentalOptions: { ...options.sandbox?.experimentalOptions, vm_runtime: true },
}) })
return { return {
driver: makeModalDriver(sandbox), driver: makeModalDriver(sandbox),
@@ -80,32 +85,6 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
} }
} }
export const openModalClient = async (params?: ModalClientParams) => {
const { ModalClient } = await import("modal")
return new ModalClient(params)
}
export const createModalSandboxWithClient = async (
client: ModalClient,
app: App,
options: ModalSandboxCreateOptions,
existingImage?: Image,
) => {
const imageSpec = options.image ?? ubuntuImage
const image =
existingImage ??
client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
// Always Modal's Full-VM runtime (beta, enabled per account): a real kernel
// with real device nodes, so workspaces can run Docker and other
// kernel-dependent workloads. Costs versus gVisor, measured Aug 2026:
// per-exec floor ~285-535ms versus ~90-165ms, and filesystem snapshots only
// (no memory snapshots — acceptable; fs-snapshot is the persistence design).
return client.sandboxes.create(app, image, {
...options.sandbox,
experimentalOptions: { ...options.sandbox?.experimentalOptions, vm_runtime: true },
})
}
/** /**
* Adapts Modal exec to the Environment driver. Files intentionally has no native * Adapts Modal exec to the Environment driver. Files intentionally has no native
* overrides: exec latency dominates payload work (VM runtime floor measured * overrides: exec latency dominates payload work (VM runtime floor measured
@@ -1,54 +0,0 @@
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { expect, test } from "bun:test"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { makeFiles } from "@opencode-ai/core/environment"
import { Workspace } from "@opencode-ai/core/workspace"
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
import { Effect, Layer } from "effect"
import { TestClock } from "effect/testing"
import { modalWorkspaceDriver, provider } from "../src/workspace/modal-workspace"
const enabled =
!!process.env.OPENCODE_TEST_MODAL &&
((!!process.env.MODAL_TOKEN_ID && !!process.env.MODAL_TOKEN_SECRET) ||
fs.existsSync(path.join(os.homedir(), ".modal.toml")))
const testLayer = Layer.provideMerge(
AppNodeBuilder.build(Workspace.configured({ idleThreshold: "1 minute", pollInterval: "1 minute" }), [
[
WorkspaceDriver.node,
WorkspaceDriver.registryNode({ [provider]: modalWorkspaceDriver({ app: "opencode-workspace-tests" }) }),
],
]),
TestClock.layer(),
)
const modalTest = enabled ? test : test.skip
modalTest(
"wakes a workspace from its filesystem snapshot",
() =>
Effect.runPromise(
Effect.gen(function* () {
const workspace = yield* Workspace.Service
yield* Effect.acquireUseRelease(
workspace.create(provider),
(created) =>
Effect.gen(function* () {
const environment = yield* workspace.connect(created.id)
const files = makeFiles(environment)
const file = `/tmp/opencode-workspace-${crypto.randomUUID()}.txt`
yield* files.write(file, new TextEncoder().encode("survived snapshot"))
yield* TestClock.adjust("2 minutes")
const restored = yield* files.read(file)
expect(new TextDecoder().decode(restored.bytes)).toBe("survived snapshot")
}),
(created) => workspace.destroy(created.id).pipe(Effect.ignore),
)
}).pipe(Effect.scoped, Effect.provide(testLayer)),
),
180_000,
)
-1
View File
@@ -12,7 +12,6 @@ export function generateSyntax(theme: ResolvedThemeTokens, mode: Mode) {
rule(["prompt"], theme.hue.accent[step]), rule(["prompt"], theme.hue.accent[step]),
rule(["extmark.file"], feedback.warning.default, { bold: true }), rule(["extmark.file"], feedback.warning.default, { bold: true }),
rule(["extmark.agent"], theme.categorical[0][step], { bold: true }), rule(["extmark.agent"], theme.categorical[0][step], { bold: true }),
rule(["extmark.skill"], theme.categorical[1][step], { bold: true }),
// V1 migration preserves its selected/inverse foreground in this action state. // V1 migration preserves its selected/inverse foreground in this action state.
rule(["extmark.paste"], theme.text.action.primary.focused, { rule(["extmark.paste"], theme.text.action.primary.focused, {
background: feedback.warning.default, background: feedback.warning.default,
+1 -2
View File
@@ -118,7 +118,6 @@ const sessionTabBindingCommands = [
"session.tab.select.7", "session.tab.select.7",
"session.tab.select.8", "session.tab.select.8",
"session.tab.select.9", "session.tab.select.9",
"session.tab.select.10",
] as const ] as const
const pinnedSessionBindingCommands = [ const pinnedSessionBindingCommands = [
@@ -715,7 +714,7 @@ function App(props: { pair?: DialogPairCredentials }) {
enabled: sessionTabs.enabled, enabled: sessionTabs.enabled,
run: () => sessionTabs.reopen(), run: () => sessionTabs.reopen(),
}, },
...Array.from({ length: 10 }, (_, i) => ({ ...Array.from({ length: 9 }, (_, i) => ({
name: `session.tab.select.${i + 1}`, name: `session.tab.select.${i + 1}`,
title: `Switch to tab ${i + 1}`, title: `Switch to tab ${i + 1}`,
category: "Session", category: "Session",
@@ -19,9 +19,8 @@ import { Locale } from "../../util/locale"
import type { PromptInfo, PromptPartRef } from "../../prompt/history" import type { PromptInfo, PromptPartRef } from "../../prompt/history"
import { useFrecency } from "../../prompt/frecency" import { useFrecency } from "../../prompt/frecency"
import { Keymap } from "../../context/keymap" import { Keymap } from "../../context/keymap"
import { displayCharAt, mentionTriggerIndex, slashTriggerIndex } from "../../prompt/display" import { displayCharAt, mentionTriggerIndex } from "../../prompt/display"
import type { FileSystemEntry } from "@opencode-ai/client" import type { FileSystemEntry } from "@opencode-ai/client"
import { Skill } from "@opencode-ai/schema/skill"
import { stringWidth } from "../../util/string-width" import { stringWidth } from "../../util/string-width"
import { parseFileLineRange, stripFileLineRange } from "../../prompt/parse" import { parseFileLineRange, stripFileLineRange } from "../../prompt/parse"
import { moveSelection, revealSelectionOffset } from "../../ui/select-controller" import { moveSelection, revealSelectionOffset } from "../../ui/select-controller"
@@ -40,7 +39,6 @@ export type AutocompleteOption = {
isDirectory?: boolean isDirectory?: boolean
onSelect?: () => void onSelect?: () => void
path?: string path?: string
kind?: "skill"
} }
export function Autocomplete(props: { export function Autocomplete(props: {
@@ -53,8 +51,6 @@ export function Autocomplete(props: {
ref: (ref: AutocompleteRef) => void ref: (ref: AutocompleteRef) => void
fileStyleId: number fileStyleId: number
agentStyleId: number agentStyleId: number
skillStyleId: number
hasSkill: (id: string) => boolean
promptPartTypeId: () => number promptPartTypeId: () => number
}) { }) {
const editor = useEditorContext() const editor = useEditorContext()
@@ -144,17 +140,14 @@ export function Autocomplete(props: {
text: string, text: string,
part: part:
| { type: "file"; value: NonNullable<PromptInfo["files"]>[number]; path?: string } | { type: "file"; value: NonNullable<PromptInfo["files"]>[number]; path?: string }
| { type: "agent"; value: NonNullable<PromptInfo["agents"]>[number] } | { type: "agent"; value: NonNullable<PromptInfo["agents"]>[number] },
| { type: "skill"; value: NonNullable<PromptInfo["skills"]>[number] },
) { ) {
if (part.type === "skill" && props.hasSkill(part.value.id)) return
const input = props.input() const input = props.input()
const currentCursorOffset = input.cursorOffset const currentCursorOffset = input.cursorOffset
const charAfterCursor = displayCharAt(props.value, currentCursorOffset) const charAfterCursor = displayCharAt(props.value, currentCursorOffset)
const needsSpace = charAfterCursor !== " " const needsSpace = charAfterCursor !== " "
const prefix = part.type === "skill" ? "/" : "@" const append = "@" + text + (needsSpace ? " " : "")
const append = prefix + text + (needsSpace ? " " : "")
input.cursorOffset = store.index input.cursorOffset = store.index
const startCursor = input.logicalCursor const startCursor = input.logicalCursor
@@ -164,12 +157,11 @@ export function Autocomplete(props: {
input.deleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col) input.deleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col)
input.insertText(append) input.insertText(append)
const virtualText = prefix + text const virtualText = "@" + text
const extmarkStart = store.index const extmarkStart = store.index
const extmarkEnd = extmarkStart + stringWidth(virtualText) const extmarkEnd = extmarkStart + stringWidth(virtualText)
const styleId = const styleId = part.type === "file" ? props.fileStyleId : props.agentStyleId
part.type === "file" ? props.fileStyleId : part.type === "skill" ? props.skillStyleId : props.agentStyleId
const extmarkId = input.extmarks.create({ const extmarkId = input.extmarks.create({
start: extmarkStart, start: extmarkStart,
@@ -203,20 +195,6 @@ export function Autocomplete(props: {
return return
} }
if (part.type === "skill") {
const skills = (draft.skills ??= [])
if (skills.some((skill) => skill.id === part.value.id)) return
if (part.value.mention) {
part.value.mention.start = extmarkStart
part.value.mention.end = extmarkEnd
part.value.mention.text = virtualText
}
const index = skills.length
skills.push(part.value)
props.setExtmark({ type: "skill", index }, extmarkId)
return
}
const agents = (draft.agents ??= []) const agents = (draft.agents ??= [])
if (part.value.mention) { if (part.value.mention) {
part.value.mention.start = extmarkStart part.value.mention.start = extmarkStart
@@ -455,12 +433,7 @@ export function Autocomplete(props: {
results.push({ results.push({
display: "/" + skill.id, display: "/" + skill.id,
description: skill.description, description: skill.description,
kind: "skill", onSelect: () => insertSlash(skill.id),
onSelect: () =>
insertPart(skill.id, {
type: "skill",
value: { id: Skill.ID.make(skill.id), mention: { start: 0, end: 0, text: "" } },
}),
}) })
} }
@@ -490,11 +463,7 @@ export function Autocomplete(props: {
// it shouldn't be additionally sorted by fuzzysort as it will loose the results // it shouldn't be additionally sorted by fuzzysort as it will loose the results
const fileOptions: AutocompleteOption[] = store.visible === "@" ? fileSearch.options : [] const fileOptions: AutocompleteOption[] = store.visible === "@" ? fileSearch.options : []
const nonFileOptions: AutocompleteOption[] = const nonFileOptions: AutocompleteOption[] =
store.visible === "@" store.visible === "@" ? [...referenceAliasesValue, ...agentsValue, ...mcpResources()] : [...commandsValue]
? [...referenceAliasesValue, ...agentsValue, ...mcpResources()]
: store.index === 0
? [...commandsValue]
: commandsValue.filter((item) => item.kind === "skill")
if (!searchValue) { if (!searchValue) {
return [...nonFileOptions, ...fileOptions] return [...nonFileOptions, ...fileOptions]
@@ -551,7 +520,7 @@ export function Autocomplete(props: {
function select() { function select() {
const selected = options()[store.selected] const selected = options()[store.selected]
if (!selected) return if (!selected) return
hide(true) hide()
selected.onSelect?.() selected.onSelect?.()
} }
@@ -639,18 +608,14 @@ export function Autocomplete(props: {
}) })
} }
function hide(removeToken = false) { function hide() {
if (removeToken && store.visible === "/") { const text = props.input().plainText
const input = props.input() if (store.visible === "/" && !text.endsWith(" ") && text.startsWith("/")) {
const cursorOffset = input.cursorOffset const cursor = props.input().logicalCursor
input.cursorOffset = store.index props.input().deleteRange(0, 0, cursor.row, cursor.col)
const start = input.logicalCursor
input.cursorOffset = cursorOffset
const end = input.logicalCursor
input.deleteRange(start.row, start.col, end.row, end.col)
// Sync the prompt store immediately since onContentChange is async // Sync the prompt store immediately since onContentChange is async
props.setPrompt((draft) => { props.setPrompt((draft) => {
draft.text = input.plainText draft.text = props.input().plainText
}) })
} }
setStore("visible", false) setStore("visible", false)
@@ -675,7 +640,9 @@ export function Autocomplete(props: {
// Typed text before the trigger // Typed text before the trigger
props.input().cursorOffset <= store.index || props.input().cursorOffset <= store.index ||
// There is a space between the trigger and the cursor // There is a space between the trigger and the cursor
props.input().getTextRange(store.index, props.input().cursorOffset).match(/\s/) props.input().getTextRange(store.index, props.input().cursorOffset).match(/\s/) ||
// "/<command>" is not the sole content
(store.visible === "/" && value.match(/^\S+\s+\S+\s*$/))
) { ) {
hide() hide()
} }
@@ -686,10 +653,10 @@ export function Autocomplete(props: {
const offset = props.input().cursorOffset const offset = props.input().cursorOffset
if (offset === 0) return if (offset === 0) return
const slash = slashTriggerIndex(value, offset) // Check for "/" at position 0 - reopen slash commands
if (slash !== undefined) { if (value.startsWith("/") && !value.slice(0, offset).match(/\s/)) {
show("/") show("/")
setStore("index", slash) setStore("index", 0)
return return
} }
+5 -46
View File
@@ -29,7 +29,6 @@ import { parseSlashHead } from "../../prompt/parse"
import { stringWidth } from "../../util/string-width" import { stringWidth } from "../../util/string-width"
import { createStore, produce, unwrap } from "solid-js/store" import { createStore, produce, unwrap } from "solid-js/store"
import { emptyPrompt, usePromptHistory, type PromptInfo, type PromptPartRef } from "../../prompt/history" import { emptyPrompt, usePromptHistory, type PromptInfo, type PromptPartRef } from "../../prompt/history"
import { Skill } from "@opencode-ai/schema/skill"
import { computePromptTraits } from "../../prompt/traits" import { computePromptTraits } from "../../prompt/traits"
import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../prompt/part" import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../prompt/part"
import { usePromptStash } from "../../prompt/stash" import { usePromptStash } from "../../prompt/stash"
@@ -274,7 +273,6 @@ export function Prompt(props: PromptProps) {
} }
const fileStyleId = syntax().getStyleId("extmark.file")! const fileStyleId = syntax().getStyleId("extmark.file")!
const agentStyleId = syntax().getStyleId("extmark.agent")! const agentStyleId = syntax().getStyleId("extmark.agent")!
const skillStyleId = syntax().getStyleId("extmark.skill")!
const pasteStyleId = syntax().getStyleId("extmark.paste")! const pasteStyleId = syntax().getStyleId("extmark.paste")!
let promptPartTypeId = 0 let promptPartTypeId = 0
const event = useEvent() const event = useEvent()
@@ -495,29 +493,12 @@ export function Prompt(props: PromptProps) {
<DialogSkill <DialogSkill
location={currentLocation.current} location={currentLocation.current}
onSelect={(skill) => { onSelect={(skill) => {
if (store.prompt.skills?.some((item) => item.id === skill)) return input.setText(`/${skill} `)
const text = `/${skill}` setStore("prompt", {
const start = input.cursorOffset ...emptyPrompt(),
input.insertText(text + " ") text: `/${skill} `,
const extmarkId = input.extmarks.create({
start,
end: start + promptOffsetWidth(text),
virtual: true,
styleId: skillStyleId,
typeId: promptPartTypeId,
}) })
setStore( input.gotoBufferEnd()
produce((draft) => {
draft.prompt.text = input.plainText
const skills = (draft.prompt.skills ??= [])
const index = skills.length
skills.push({
id: Skill.ID.make(skill),
mention: { start, end: start + promptOffsetWidth(text), text },
})
draft.extmarkToPart.set(extmarkId, { type: "skill", index })
}),
)
}} }}
/> />
)) ))
@@ -658,11 +639,6 @@ export function Prompt(props: PromptProps) {
ref: { type: "agent" as const, index }, ref: { type: "agent" as const, index },
styleId: agentStyleId, styleId: agentStyleId,
})), })),
...(prompt.skills ?? []).map((part, index) => ({
mention: part.mention,
ref: { type: "skill" as const, index },
styleId: skillStyleId,
})),
...prompt.pasted.map((part, index) => ({ ...prompt.pasted.map((part, index) => ({
mention: part.source, mention: part.source,
ref: { type: "pasted" as const, index }, ref: { type: "pasted" as const, index },
@@ -695,7 +671,6 @@ export function Prompt(props: PromptProps) {
const newMap = new Map<number, PromptPartRef>() const newMap = new Map<number, PromptPartRef>()
const files: NonNullable<PromptInfo["files"]> = [] const files: NonNullable<PromptInfo["files"]> = []
const agents: NonNullable<PromptInfo["agents"]> = [] const agents: NonNullable<PromptInfo["agents"]> = []
const skills: NonNullable<PromptInfo["skills"]> = []
const pasted: PromptInfo["pasted"] = [] const pasted: PromptInfo["pasted"] = []
for (const extmark of allExtmarks) { for (const extmark of allExtmarks) {
@@ -721,16 +696,6 @@ export function Prompt(props: PromptProps) {
newMap.set(extmark.id, { type: "agent", index }) newMap.set(extmark.id, { type: "agent", index })
continue continue
} }
if (ref.type === "skill") {
const part = draft.prompt.skills?.[ref.index]
if (!part?.mention) continue
part.mention.start = extmark.start
part.mention.end = extmark.end
const index = skills.length
skills.push(part)
newMap.set(extmark.id, { type: "skill", index })
continue
}
const part = draft.prompt.pasted[ref.index] const part = draft.prompt.pasted[ref.index]
if (!part) continue if (!part) continue
part.source.start = extmark.start part.source.start = extmark.start
@@ -743,7 +708,6 @@ export function Prompt(props: PromptProps) {
draft.extmarkToPart = newMap draft.extmarkToPart = newMap
draft.prompt.files = files draft.prompt.files = files
draft.prompt.agents = agents draft.prompt.agents = agents
draft.prompt.skills = skills
draft.prompt.pasted = pasted draft.prompt.pasted = pasted
}), }),
) )
@@ -1019,7 +983,6 @@ export function Prompt(props: PromptProps) {
) )
const slashHead = parseSlashHead(inputText, /\s/) const slashHead = parseSlashHead(inputText, /\s/)
const isSkill = const isSkill =
!(store.prompt.skills?.length ?? 0) &&
slashHead !== undefined && slashHead !== undefined &&
(data.location.skill.list(currentLocation.ref) ?? []).some( (data.location.skill.list(currentLocation.ref) ?? []).some(
(skill) => skill.slash === true && skill.id === slashHead.name, (skill) => skill.slash === true && skill.id === slashHead.name,
@@ -1117,7 +1080,6 @@ export function Prompt(props: PromptProps) {
model, model,
files: store.prompt.files, files: store.prompt.files,
agents: store.prompt.agents, agents: store.prompt.agents,
skills: store.prompt.skills?.length ? store.prompt.skills : undefined,
delivery, delivery,
}) })
.catch((error) => { .catch((error) => {
@@ -1184,7 +1146,6 @@ export function Prompt(props: PromptProps) {
text: inputText, text: inputText,
files: store.prompt.files, files: store.prompt.files,
agents: store.prompt.agents, agents: store.prompt.agents,
skills: store.prompt.skills?.length ? store.prompt.skills : undefined,
delivery, delivery,
}) })
.then( .then(
@@ -1724,8 +1685,6 @@ export function Prompt(props: PromptProps) {
value={store.prompt.text} value={store.prompt.text}
fileStyleId={fileStyleId} fileStyleId={fileStyleId}
agentStyleId={agentStyleId} agentStyleId={agentStyleId}
skillStyleId={skillStyleId}
hasSkill={(id) => store.prompt.skills?.some((skill) => skill.id === id) ?? false}
promptPartTypeId={() => promptPartTypeId} promptPartTypeId={() => promptPartTypeId}
/> />
</> </>
+5 -6
View File
@@ -10,7 +10,6 @@ import {
moveSessionTab, moveSessionTab,
NEW_SESSION_TAB_TITLE, NEW_SESSION_TAB_TITLE,
sessionTabComplete, sessionTabComplete,
sessionTabShortcutLabel,
seedSessionTabMotion, seedSessionTabMotion,
sessionTabOverflowWidth, sessionTabOverflowWidth,
type SessionTab, type SessionTab,
@@ -141,7 +140,7 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
const value = session() const value = session()
return value ? data.project.get(value.projectID) : undefined return value ? data.project.get(value.projectID) : undefined
}) })
const numberWidth = () => 2 const numberWidth = () => String(index() + 1).length + 1
const titleWidth = () => Math.max(1, width() - numberWidth() - 2 - (hovered() === tab.sessionID ? 1 : 0)) const titleWidth = () => Math.max(1, width() - numberWidth() - 2 - (hovered() === tab.sessionID ? 1 : 0))
const title = () => tab.title ?? "Untitled session" const title = () => tab.title ?? "Untitled session"
const visibleTitle = createMemo(() => Locale.takeWidth(title(), titleWidth())) const visibleTitle = createMemo(() => Locale.takeWidth(title(), titleWidth()))
@@ -312,7 +311,7 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
selectable={false} selectable={false}
attributes={selected() ? TextAttributes.BOLD : undefined} attributes={selected() ? TextAttributes.BOLD : undefined}
> >
{sessionTabShortcutLabel(index())} {index() + 1}
</text> </text>
<text <text
width={titleWidth()} width={titleWidth()}
@@ -556,8 +555,8 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
const glows = () => !selected() && (status().attention || (!status().busy && status().unread !== undefined)) const glows = () => !selected() && (status().attention || (!status().busy && status().unread !== undefined))
const title = () => tab.title ?? "Untitled session" const title = () => tab.title ?? "Untitled session"
const tabNumber = createMemo(() => items().findIndex((item) => item.sessionID === tab.sessionID) + 1) const tabNumber = createMemo(() => items().findIndex((item) => item.sessionID === tab.sessionID) + 1)
// Shortcut labels stay one cell wide: 1-9, 0 for ten, then a neutral dot. // The number cell keeps one trailing space, even for double-digit tabs.
const numberWidth = () => 2 const numberWidth = () => String(tabNumber()).length + 1
// Hovering reveals the close mark, so the title's right bound shifts left of it. // Hovering reveals the close mark, so the title's right bound shifts left of it.
const availableTitleWidth = () => const availableTitleWidth = () =>
Math.max(1, width() - 1 - numberWidth() - (hovered() === tab.sessionID ? 2 : 0)) Math.max(1, width() - 1 - numberWidth() - (hovered() === tab.sessionID ? 2 : 0))
@@ -640,7 +639,7 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
{" "} {" "}
</text> </text>
<text width={numberWidth()} fg={numberColor()} selectable={false} attributes={bold()}> <text width={numberWidth()} fg={numberColor()} selectable={false} attributes={bold()}>
{sessionTabShortcutLabel(tabNumber() - 1)} {tabNumber()}
</text> </text>
<text <text
width={availableTitleWidth()} width={availableTitleWidth()}
-2
View File
@@ -126,7 +126,6 @@ export const Definitions = {
session_tab_select_7: keybind("<leader>7,ctrl+7", "Switch to tab 7"), session_tab_select_7: keybind("<leader>7,ctrl+7", "Switch to tab 7"),
session_tab_select_8: keybind("<leader>8,ctrl+8", "Switch to tab 8"), session_tab_select_8: keybind("<leader>8,ctrl+8", "Switch to tab 8"),
session_tab_select_9: keybind("<leader>9,ctrl+9", "Switch to tab 9"), session_tab_select_9: keybind("<leader>9,ctrl+9", "Switch to tab 9"),
session_tab_select_10: keybind("<leader>0,ctrl+0", "Switch to tab 10"),
stash_delete: keybind("ctrl+d", "Delete stash entry"), stash_delete: keybind("ctrl+d", "Delete stash entry"),
model_provider_list: keybind("ctrl+a", "Open provider list from model dialog"), model_provider_list: keybind("ctrl+a", "Open provider list from model dialog"),
@@ -330,7 +329,6 @@ export const CommandMap = {
session_tab_select_7: "session.tab.select.7", session_tab_select_7: "session.tab.select.7",
session_tab_select_8: "session.tab.select.8", session_tab_select_8: "session.tab.select.8",
session_tab_select_9: "session.tab.select.9", session_tab_select_9: "session.tab.select.9",
session_tab_select_10: "session.tab.select.10",
stash_delete: "stash.delete", stash_delete: "stash.delete",
model_provider_list: "model.dialog.provider", model_provider_list: "model.dialog.provider",
model_favorite_toggle: "model.dialog.favorite", model_favorite_toggle: "model.dialog.favorite",
@@ -7,12 +7,6 @@ export type SessionTabUnread = "activity" | "error"
export const NEW_SESSION_TAB_TITLE = "New session" export const NEW_SESSION_TAB_TITLE = "New session"
export function sessionTabShortcutLabel(index: number) {
if (index >= 0 && index < 9) return String(index + 1)
if (index === 9) return "0"
return "·"
}
export type SessionTabHistory = { export type SessionTabHistory = {
entries: readonly string[] entries: readonly string[]
index: number index: number
+23 -74
View File
@@ -21,7 +21,6 @@ import {
isExitCommand, isExitCommand,
isCompactCommand, isCompactCommand,
mentionTriggerIndex, mentionTriggerIndex,
slashTriggerIndex,
isNewCommand, isNewCommand,
movePromptHistory, movePromptHistory,
promptCopy, promptCopy,
@@ -51,7 +50,7 @@ export const TEXTAREA_MIN_ROWS = 1
const TEXTAREA_MAX_ROWS = 6 const TEXTAREA_MAX_ROWS = 6
export const PROMPT_MAX_ROWS = TEXTAREA_MAX_ROWS + AUTOCOMPLETE_ROWS - 1 + AUTOCOMPLETE_BOTTOM_ROWS export const PROMPT_MAX_ROWS = TEXTAREA_MAX_ROWS + AUTOCOMPLETE_ROWS - 1 + AUTOCOMPLETE_BOTTOM_ROWS
type Mention = Extract<RunPromptPart, { type: "file" | "agent" | "skill" }> type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
type Auto = RunFooterMenuItem & { type Auto = RunFooterMenuItem & {
kind: "mention" kind: "mention"
@@ -66,12 +65,7 @@ type SlashOption = RunFooterMenuItem & {
action?: "skill-menu" | "editor" | "settings" action?: "skill-menu" | "editor" | "settings"
} }
type SkillOption = RunFooterMenuItem & { type PromptOption = Auto | SlashOption
kind: "skill"
id: string
}
type PromptOption = Auto | SlashOption | SkillOption
type MenuMode = false | "mention" | "slash" type MenuMode = false | "mention" | "slash"
@@ -130,9 +124,12 @@ function emptyPrompt(shell: boolean): RunPrompt {
} }
function slashQuery(text: string, cursor: number) { function slashQuery(text: string, cursor: number) {
const at = slashTriggerIndex(text, cursor) const head = parseSlashHead(text.slice(0, cursor))
if (at === undefined) return if (!head || head.end !== cursor) {
return { at, value: displaySlice(text, at + 1, cursor) } return
}
return head.name
} }
function parseSlashCommand(text: string, commands: RunCommand[] | undefined) { function parseSlashCommand(text: string, commands: RunCommand[] | undefined) {
@@ -385,18 +382,10 @@ export function createPromptState(input: PromptInput): PromptState {
) )
const mentionOptions = createMemo(() => [...agents(), ...files(), ...references()]) const mentionOptions = createMemo(() => [...agents(), ...files(), ...references()])
const skillCommands = createMemo(() => (input.commands() ?? []).filter((item) => item.source === "skill")) const skillCommands = createMemo(() => (input.commands() ?? []).filter((item) => item.source === "skill"))
const skillOptions = createMemo<SkillOption[]>(() =>
skillCommands().map((item) => ({
kind: "skill",
id: item.name,
display: `/${item.name}`,
description: item.description,
})),
)
const hasSkillsCommand = createMemo(() => const hasSkillsCommand = createMemo(() =>
(input.commands() ?? []).some((item) => item.source !== "skill" && item.name === "skills"), (input.commands() ?? []).some((item) => item.source !== "skill" && item.name === "skills"),
) )
const slashOptions = createMemo<Array<SlashOption | SkillOption>>(() => { const slashOptions = createMemo<SlashOption[]>(() => {
const builtins = [ const builtins = [
{ {
kind: "slash", kind: "slash",
@@ -428,7 +417,6 @@ export function createPromptState(input: PromptInput): PromptState {
} }
return [ return [
...skillOptions(),
...(showSkillMenu ...(showSkillMenu
? [ ? [
{ {
@@ -455,7 +443,7 @@ export function createPromptState(input: PromptInput): PromptState {
].sort((a, b) => a.display.localeCompare(b.display)) ].sort((a, b) => a.display.localeCompare(b.display))
}) })
const options = createMemo<PromptOption[]>(() => { const options = createMemo<PromptOption[]>(() => {
const mixed: PromptOption[] = mode() === "slash" ? (at() === 0 ? slashOptions() : skillOptions()) : mentionOptions() const mixed: PromptOption[] = mode() === "slash" ? slashOptions() : mentionOptions()
if (!query()) { if (!query()) {
return mixed return mixed
} }
@@ -471,11 +459,7 @@ export function createPromptState(input: PromptInput): PromptState {
return fuzzysort return fuzzysort
.go(next, mixed, { .go(next, mixed, {
keys: [ keys: [(item) => (item.kind === "mention" ? item.value : item.name).trimEnd(), "display", "description"],
(item) => (item.kind === "mention" ? item.value : item.kind === "skill" ? item.id : item.name).trimEnd(),
"display",
"description",
],
}) })
.map((item) => item.obj) .map((item) => item.obj)
}) })
@@ -528,19 +512,17 @@ export function createPromptState(input: PromptInput): PromptState {
continue continue
} }
const text = displaySlice(area.plainText, item.start, item.end) const text = area.plainText.slice(item.start, item.end)
const prev = const prev =
part.type === "agent" part.type === "agent"
? (part.source?.value ?? "@" + part.name) ? (part.source?.value ?? "@" + part.name)
: part.type === "skill" : (part.source?.text.value ?? "@" + (part.filename ?? ""))
? (part.source?.value ?? "/" + part.id)
: (part.source?.text.value ?? "@" + (part.filename ?? ""))
if (text !== prev) { if (text !== prev) {
continue continue
} }
const copy = structuredClone(part) const copy = structuredClone(part)
if (copy.type === "agent" || copy.type === "skill") { if (copy.type === "agent") {
copy.source = { copy.source = {
start: item.start, start: item.start,
end: item.end, end: item.end,
@@ -576,7 +558,7 @@ export function createPromptState(input: PromptInput): PromptState {
const restoreParts = (value: RunPromptPart[]) => { const restoreParts = (value: RunPromptPart[]) => {
clearParts() clearParts()
parts = value parts = value
.filter((item): item is Mention => item.type === "file" || item.type === "agent" || item.type === "skill") .filter((item): item is Mention => item.type === "file" || item.type === "agent")
.map((item) => structuredClone(item)) .map((item) => structuredClone(item))
if (!area || area.isDestroyed || type === 0) { if (!area || area.isDestroyed || type === 0) {
return return
@@ -584,8 +566,8 @@ export function createPromptState(input: PromptInput): PromptState {
const box = area const box = area
parts.forEach((item, idx) => { parts.forEach((item, idx) => {
const start = item.type === "file" ? item.source?.text.start : item.source?.start const start = item.type === "agent" ? item.source?.start : item.source?.text.start
const end = item.type === "file" ? item.source?.text.end : item.source?.end const end = item.type === "agent" ? item.source?.end : item.source?.text.end
if (start === undefined || end === undefined) { if (start === undefined || end === undefined) {
return return
} }
@@ -645,16 +627,16 @@ export function createPromptState(input: PromptInput): PromptState {
return return
} }
setAt(slash.at) setAt(0)
setQuery(slash.value) setQuery(slash)
return return
} }
if (slash !== undefined) { if (slash !== undefined) {
setAt(slash.at) setAt(0)
menu.reset() menu.reset()
setMode("slash") setMode("slash")
setQuery(slash.value) setQuery(slash)
return return
} }
@@ -800,7 +782,7 @@ export function createPromptState(input: PromptInput): PromptState {
} }
const cursor = area.cursorOffset const cursor = area.cursorOffset
const startOffset = at() const startOffset = mode() === "slash" ? 0 : at()
area.cursorOffset = startOffset area.cursorOffset = startOffset
const start = area.logicalCursor const start = area.logicalCursor
area.cursorOffset = cursor area.cursorOffset = cursor
@@ -846,39 +828,6 @@ export function createPromptState(input: PromptInput): PromptState {
return return
} }
if (next.kind === "skill") {
if (parts.some((part) => part.type === "skill" && part.id === next.id)) {
cancelAutocomplete()
return
}
const cursor = area.cursorOffset
const tail = displayCharAt(area.plainText, cursor)
const append = `/${next.id}${tail === " " ? "" : " "}`
area.cursorOffset = at()
const start = area.logicalCursor
area.cursorOffset = cursor
const end = area.logicalCursor
area.deleteRange(start.row, start.col, end.row, end.col)
area.insertText(append)
const text = `/${next.id}`
const startOffset = at()
const endOffset = startOffset + stringWidth(text)
const part: Extract<RunPromptPart, { type: "skill" }> = {
type: "skill",
id: next.id,
source: { start: startOffset, end: endOffset, value: text },
}
const id = area.extmarks.create({ start: startOffset, end: endOffset, virtual: true, typeId: type })
marks.set(id, parts.length)
parts.push(part)
hide()
syncDraft()
scheduleRows()
area.focus()
return
}
if (next.kind === "slash") { if (next.kind === "slash") {
if (next.action === "editor") { if (next.action === "editor") {
void openEditor({ void openEditor({
@@ -1244,7 +1193,7 @@ export function createPromptState(input: PromptInput): PromptState {
} }
const parsed = const parsed =
command || next.parts.some((part) => part.type === "skill") || next.mode === "shell" || isNewCommand(next.text) command || next.mode === "shell" || isNewCommand(next.text)
? undefined ? undefined
: parseSlashCommand(next.text, input.commands()) : parseSlashCommand(next.text, input.commands())
if (parsed?.type === "pending") { if (parsed?.type === "pending") {
+5 -5
View File
@@ -2,7 +2,7 @@ import type { RunPromptPart } from "./types"
import { realignPromptMentions } from "../prompt/mention" import { realignPromptMentions } from "../prompt/mention"
import { parseSlashHead } from "../prompt/parse" import { parseSlashHead } from "../prompt/parse"
type Mention = Extract<RunPromptPart, { type: "file" | "agent" | "skill" }> type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
export function resolveEditorSlashValue(text: string) { export function resolveEditorSlashValue(text: string) {
const head = parseSlashHead(text) const head = parseSlashHead(text)
@@ -17,13 +17,13 @@ export function realignEditorPromptParts(content: string, parts: RunPromptPart[]
const matches = realignPromptMentions( const matches = realignPromptMentions(
content, content,
parts.map((part) => { parts.map((part) => {
if (part.type !== "file" && part.type !== "agent" && part.type !== "skill") return if (part.type !== "file" && part.type !== "agent") return
return promptPartMention(part) return promptPartMention(part)
}), }),
) )
return parts.flatMap((part, index) => { return parts.flatMap((part, index) => {
if (part.type !== "file" && part.type !== "agent" && part.type !== "skill") return [part] if (part.type !== "file" && part.type !== "agent") return [part]
const mention = promptPartMention(part) const mention = promptPartMention(part)
if (!mention?.text) return [part] if (!mention?.text) return [part]
const match = matches[index] const match = matches[index]
@@ -32,13 +32,13 @@ export function realignEditorPromptParts(content: string, parts: RunPromptPart[]
} }
function promptPartMention(part: Mention) { function promptPartMention(part: Mention) {
const source = part.type === "file" ? part.source?.text : part.source const source = part.type === "agent" ? part.source : part.source?.text
if (!source) return if (!source) return
return { start: source.start, end: source.end, text: source.value } return { start: source.start, end: source.end, text: source.value }
} }
function updatePromptPart(part: Mention, start: number, end: number, text: string): Mention { function updatePromptPart(part: Mention, start: number, end: number, text: string): Mention {
if (part.type === "agent" || part.type === "skill") { if (part.type === "agent") {
return { return {
...part, ...part,
source: { source: {
+1 -1
View File
@@ -7,7 +7,7 @@
// the current browse position. When the user arrows up at cursor offset 0, // the current browse position. When the user arrows up at cursor offset 0,
// the current draft is saved and history begins. Arrowing past the end // the current draft is saved and history begins. Arrowing past the end
// restores the draft. // restores the draft.
export { displayCharAt, displaySlice, mentionTriggerIndex, slashTriggerIndex } from "../prompt/display" export { displayCharAt, displaySlice, mentionTriggerIndex } from "../prompt/display"
import { stringWidth } from "../util/string-width" import { stringWidth } from "../util/string-width"
import type { RunPrompt } from "./types" import type { RunPrompt } from "./types"
+3 -24
View File
@@ -288,21 +288,6 @@ function promptAgents(next: SessionTurnInput) {
) )
} }
function promptSkills(next: SessionTurnInput) {
return next.prompt.parts.flatMap((part) =>
part.type === "skill"
? [
{
id: part.id,
mention: part.source
? { start: part.source.start, end: part.source.end, text: part.source.value }
: undefined,
},
]
: [],
)
}
function streamPartKey(messageID: string, partID: string) { function streamPartKey(messageID: string, partID: string) {
return `${messageID}\u0000${partID}` return `${messageID}\u0000${partID}`
} }
@@ -373,12 +358,12 @@ const catalogEvents = new Set([
// briefly so the output commit renders inside it. // briefly so the output commit renders inside it.
const SHELL_OUTPUT_GRACE_MS = 1500 const SHELL_OUTPUT_GRACE_MS = 1500
function skillCommit(messageID: string, name: string, skillID = messageID): StreamCommit { function skillCommit(messageID: string, name: string): StreamCommit {
return { return {
kind: "system", kind: "system",
source: "system", source: "system",
messageID, messageID,
partID: `skill:${skillID}`, partID: `skill:${messageID}`,
text: `→ Skill "${name}"`, text: `→ Skill "${name}"`,
phase: "start", phase: "start",
} }
@@ -652,10 +637,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
state.messageIDs.add(message.id) state.messageIDs.add(message.id)
if (!render) return if (!render) return
if (reuseVisibleWait && waiting) return if (reuseVisibleWait && waiting) return
write([ write([{ kind: "user", source: "system", text: message.text, phase: "start", messageID: message.id }])
...(message.skills ?? []).map((skill) => skillCommit(message.id, skill.name, skill.id)),
{ kind: "user", source: "system", text: message.text, phase: "start", messageID: message.id },
])
return return
} }
if (message.type === "skill") { if (message.type === "skill") {
@@ -1633,7 +1615,6 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
const command = next.prompt.command const command = next.prompt.command
const attachments = await prepareAttachments(next, command ? "command" : "prompt", input.readTextFile) const attachments = await prepareAttachments(next, command ? "command" : "prompt", input.readTextFile)
const agents = promptAgents(next) const agents = promptAgents(next)
const skills = promptSkills(next)
if (!command) { if (!command) {
input.trace?.write("send.prompt", { sessionID: input.sessionID, messageID, delivery }) input.trace?.write("send.prompt", { sessionID: input.sessionID, messageID, delivery })
return client.session.prompt( return client.session.prompt(
@@ -1643,7 +1624,6 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
text: [next.prompt.text, ...attachments.text].join("\n\n"), text: [next.prompt.text, ...attachments.text].join("\n\n"),
files: attachments.files.length ? attachments.files : undefined, files: attachments.files.length ? attachments.files : undefined,
agents: agents.length ? agents : undefined, agents: agents.length ? agents : undefined,
skills: skills.length ? skills : undefined,
delivery, delivery,
}, },
{ signal: next.signal }, { signal: next.signal },
@@ -1663,7 +1643,6 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
model: selected, model: selected,
files: attachments.files.length ? attachments.files : undefined, files: attachments.files.length ? attachments.files : undefined,
agents: agents.length ? agents : undefined, agents: agents.length ? agents : undefined,
skills: skills.length ? skills : undefined,
delivery, delivery,
}, },
{ signal: next.signal }, { signal: next.signal },
-1
View File
@@ -47,7 +47,6 @@ export type RunPromptPart =
} }
} }
| { type: "agent"; name: string; source?: { start: number; end: number; value: string } } | { type: "agent"; name: string; source?: { start: number; end: number; value: string } }
| { type: "skill"; id: string; source?: { start: number; end: number; value: string } }
export type RunCommand = { export type RunCommand = {
name: string name: string
+1 -10
View File
@@ -1,14 +1,9 @@
import type { Prompt, PromptInput } from "@opencode-ai/schema" import type { Prompt, PromptInput } from "@opencode-ai/schema"
import { Skill } from "@opencode-ai/schema/skill"
import type { Types } from "effect" import type { Types } from "effect"
export type EditablePromptInput = Types.DeepMutable<PromptInput.Prompt> export type EditablePromptInput = Types.DeepMutable<PromptInput.Prompt>
type ProjectedPrompt = Pick<Prompt, "text" | "files" | "agents"> & { export function projectedPromptInput(input: Pick<Prompt, "text" | "files" | "agents">): EditablePromptInput {
readonly skills?: ReadonlyArray<{ readonly id: string; readonly mention?: PromptInput.SkillAttachment["mention"] }>
}
export function projectedPromptInput(input: ProjectedPrompt): EditablePromptInput {
return { return {
text: input.text, text: input.text,
files: input.files?.map((file) => ({ files: input.files?.map((file) => ({
@@ -21,9 +16,5 @@ export function projectedPromptInput(input: ProjectedPrompt): EditablePromptInpu
name: agent.name, name: agent.name,
mention: agent.mention ? { ...agent.mention } : undefined, mention: agent.mention ? { ...agent.mention } : undefined,
})), })),
skills: input.skills?.map((skill) => ({
id: Skill.ID.make(skill.id),
mention: skill.mention ? { ...skill.mention } : undefined,
})),
} }
} }
-11
View File
@@ -48,14 +48,3 @@ export function mentionTriggerIndex(value: string, offset = promptOffsetWidth(va
return promptOffsetWidth(text.slice(0, index)) return promptOffsetWidth(text.slice(0, index))
} }
} }
export function slashTriggerIndex(value: string, offset = promptOffsetWidth(value)) {
const text = displaySlice(value, 0, offset)
for (let index = text.lastIndexOf("/"); index >= 0; index = text.lastIndexOf("/", index - 1)) {
const before = index === 0 ? undefined : text[index - 1]
const query = text.slice(index)
if (before !== undefined && !/\s/.test(before)) continue
if (/\s/.test(query) || query.slice(1).includes("/")) return
return promptOffsetWidth(text.slice(0, index))
}
}
+4 -4
View File
@@ -1,7 +1,7 @@
import path from "path" import path from "path"
import { onMount } from "solid-js" import { onMount } from "solid-js"
import { createStore, produce, unwrap } from "solid-js/store" import { createStore, produce, unwrap } from "solid-js/store"
import type { PromptInput } from "@opencode-ai/schema" import type { SessionPromptInput } from "@opencode-ai/client"
import type { Types } from "effect" import type { Types } from "effect"
import { createSimpleContext } from "../context/helper" import { createSimpleContext } from "../context/helper"
import { useTuiPaths } from "../context/runtime" import { useTuiPaths } from "../context/runtime"
@@ -16,17 +16,17 @@ export type PastedText = {
} }
} }
export type PromptInfo = Types.DeepMutable<Pick<PromptInput.Prompt, "text" | "files" | "agents" | "skills">> & { export type PromptInfo = Types.DeepMutable<Pick<SessionPromptInput, "text" | "files" | "agents">> & {
pasted: PastedText[] pasted: PastedText[]
mode?: "normal" | "shell" mode?: "normal" | "shell"
} }
export type PromptPartRef = { export type PromptPartRef = {
type: "file" | "agent" | "skill" | "pasted" type: "file" | "agent" | "pasted"
index: number index: number
} }
export const emptyPrompt = (): PromptInfo => ({ text: "", files: [], agents: [], skills: [], pasted: [] }) export const emptyPrompt = (): PromptInfo => ({ text: "", files: [], agents: [], pasted: [] })
export const MAX_HISTORY_ENTRIES = 50 export const MAX_HISTORY_ENTRIES = 50
-4
View File
@@ -52,11 +52,9 @@ export function realignPromptMentions(
export function realignPromptInputMentions(content: string, input: PromptInput.Prompt): EditablePromptInput { export function realignPromptInputMentions(content: string, input: PromptInput.Prompt): EditablePromptInput {
const files = input.files ?? [] const files = input.files ?? []
const agents = input.agents ?? [] const agents = input.agents ?? []
const skills = input.skills ?? []
const mentions = realignPromptMentions(content, [ const mentions = realignPromptMentions(content, [
...files.map((file) => file.mention), ...files.map((file) => file.mention),
...agents.map((agent) => agent.mention), ...agents.map((agent) => agent.mention),
...skills.map((skill) => skill.mention),
]) ])
const align = <T extends { mention?: PromptMention }>(items: readonly T[] | undefined, offset = 0) => const align = <T extends { mention?: PromptMention }>(items: readonly T[] | undefined, offset = 0) =>
items?.flatMap((item, index) => { items?.flatMap((item, index) => {
@@ -69,7 +67,6 @@ export function realignPromptInputMentions(content: string, input: PromptInput.P
text: content, text: content,
files: align(input.files), files: align(input.files),
agents: align(input.agents, files.length), agents: align(input.agents, files.length),
skills: align(input.skills, files.length + agents.length),
} }
} }
@@ -92,7 +89,6 @@ export function expandPromptInputPastedText(
text: expandTrackedPastedText(input.text, ranges), text: expandTrackedPastedText(input.text, ranges),
files: input.files?.map((file) => ({ ...file, mention: shift(file.mention) })), files: input.files?.map((file) => ({ ...file, mention: shift(file.mention) })),
agents: input.agents?.map((agent) => ({ ...agent, mention: shift(agent.mention) })), agents: input.agents?.map((agent) => ({ ...agent, mention: shift(agent.mention) })),
skills: input.skills?.map((skill) => ({ ...skill, mention: shift(skill.mention) })),
} }
} }
+1 -24
View File
@@ -1893,7 +1893,6 @@ function UserMessage(props: { message: SessionMessageUser }) {
const data = useData() const data = useData()
const local = useLocal() const local = useLocal()
const files = createMemo(() => props.message.files ?? []) const files = createMemo(() => props.message.files ?? [])
const skills = createMemo(() => props.message.skills ?? [])
const themes = useThemes() const themes = useThemes()
const theme = useTheme("elevated") const theme = useTheme("elevated")
const mode = themes.mode const mode = themes.mode
@@ -1909,7 +1908,7 @@ function UserMessage(props: { message: SessionMessageUser }) {
} }
return ( return (
<Show when={props.message.text.trim() || files().length || skills().length}> <Show when={props.message.text.trim() || files().length}>
<box <box
border={["left"]} border={["left"]}
borderColor={delivery() ? theme.border.default : color()} borderColor={delivery() ? theme.border.default : color()}
@@ -1954,28 +1953,6 @@ function UserMessage(props: { message: SessionMessageUser }) {
flexShrink={0} flexShrink={0}
> >
<text fg={theme.text.default}>{props.message.text}</text> <text fg={theme.text.default}>{props.message.text}</text>
<Show when={skills().length}>
<box flexDirection="row" paddingTop={1} gap={1} flexWrap="wrap">
<For each={skills()}>
{(skill) => (
<text fg={theme.text.default}>
<span
style={{
bg: theme.hue.accent[mode() === "light" ? 700 : 200],
fg: theme.background.default,
bold: true,
}}
>
{" skill "}
</span>
<span style={{ bg: theme.raise(theme.background.default), fg: theme.text.subdued }}>
{` ${skill.name} `}
</span>
</text>
)}
</For>
</box>
</Show>
<Show when={files().length}> <Show when={files().length}>
<box flexDirection="row" paddingTop={1} gap={1} flexWrap="wrap"> <box flexDirection="row" paddingTop={1} gap={1} flexWrap="wrap">
<For each={files()}> <For each={files()}>
+1
View File
@@ -38,6 +38,7 @@ export function permissionPresentation(
title: `Edit ${formatPath(file)}`, title: `Edit ${formatPath(file)}`,
lines: [], lines: [],
diff, diff,
patch: diff ? undefined : text(input.patchText) || undefined,
file, file,
} }
} }
+13 -5
View File
@@ -1,4 +1,4 @@
import { expect, test } from "bun:test" import { expect, mock, test } from "bun:test"
import { createTestRenderer } from "@opentui/core/testing" import { createTestRenderer } from "@opentui/core/testing"
import { Effect, FileSystem } from "effect" import { Effect, FileSystem } from "effect"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
@@ -7,6 +7,8 @@ import { createEventStream, createFetch, directory, json } from "./fixture/tui-c
test("SIGHUP clears title and disposes scoped resources once", async () => { test("SIGHUP clears title and disposes scoped resources once", async () => {
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false }) const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
const core = await import("@opentui/core")
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
const titles: string[] = [] const titles: string[] = []
let started!: () => void let started!: () => void
const ready = new Promise<void>((resolve) => { const ready = new Promise<void>((resolve) => {
@@ -30,7 +32,6 @@ test("SIGHUP clears title and disposes scoped resources once", async () => {
server: { endpoint: { url: server.url.toString() } }, server: { endpoint: { url: server.url.toString() } },
config: { get: async () => ({}), update: async () => ({}) }, config: { get: async () => ({}), update: async () => ({}) },
packages: { resolve: async () => undefined }, packages: { resolve: async () => undefined },
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
args: {}, args: {},
log: () => {}, log: () => {},
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))), }).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
@@ -45,11 +46,14 @@ test("SIGHUP clears title and disposes scoped resources once", async () => {
} finally { } finally {
if (!setup.renderer.isDestroyed) setup.renderer.destroy() if (!setup.renderer.isDestroyed) setup.renderer.destroy()
await server.stop() await server.stop()
mock.restore()
} }
}) })
test("session lifecycle updates the terminal title and prints the epilogue after cleanup", async () => { test("session lifecycle updates the terminal title and prints the epilogue after cleanup", async () => {
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false }) const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
const core = await import("@opentui/core")
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
let initialTitle!: () => void let initialTitle!: () => void
const initialTitleSet = new Promise<void>((resolve) => { const initialTitleSet = new Promise<void>((resolve) => {
initialTitle = resolve initialTitle = resolve
@@ -106,7 +110,6 @@ test("session lifecycle updates the terminal title and prints the epilogue after
server: { endpoint: { url: server.url.toString() } }, server: { endpoint: { url: server.url.toString() } },
config: { get: async () => ({}), update: async () => ({}) }, config: { get: async () => ({}), update: async () => ({}) },
packages: { resolve: async () => undefined }, packages: { resolve: async () => undefined },
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
args: { sessionID: "dummy" }, args: { sessionID: "dummy" },
log: () => {}, log: () => {},
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))), }).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
@@ -131,11 +134,14 @@ test("session lifecycle updates the terminal title and prints the epilogue after
process.stdout.write = originalWrite process.stdout.write = originalWrite
if (!setup.renderer.isDestroyed) setup.renderer.destroy() if (!setup.renderer.isDestroyed) setup.renderer.destroy()
await server.stop() await server.stop()
mock.restore()
} }
}) })
test("session title generated while an untitled session is loading remains visible", async () => { test("session title generated while an untitled session is loading remains visible", async () => {
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false }) const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
const core = await import("@opentui/core")
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
const titles: string[] = [] const titles: string[] = []
const setTitle = setup.renderer.setTerminalTitle.bind(setup.renderer) const setTitle = setup.renderer.setTerminalTitle.bind(setup.renderer)
const generatedTitle = Promise.withResolvers<void>() const generatedTitle = Promise.withResolvers<void>()
@@ -180,7 +186,6 @@ test("session title generated while an untitled session is loading remains visib
server: { endpoint: { url: server.url.toString() } }, server: { endpoint: { url: server.url.toString() } },
config: { get: async () => ({}), update: async () => ({}) }, config: { get: async () => ({}), update: async () => ({}) },
packages: { resolve: async () => undefined }, packages: { resolve: async () => undefined },
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
args: { sessionID: "dummy" }, args: { sessionID: "dummy" },
log: () => {}, log: () => {},
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))), }).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
@@ -217,11 +222,14 @@ test("session title generated while an untitled session is loading remains visib
} finally { } finally {
if (!setup.renderer.isDestroyed) setup.renderer.destroy() if (!setup.renderer.isDestroyed) setup.renderer.destroy()
await server.stop() await server.stop()
mock.restore()
} }
}) })
test("session startup prompt is submitted exactly once", async () => { test("session startup prompt is submitted exactly once", async () => {
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false }) const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
const core = await import("@opentui/core")
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
const events = createEventStream() const events = createEventStream()
const cwd = process.cwd() const cwd = process.cwd()
const location = { directory: cwd, project: { id: "project", directory: cwd } } const location = { directory: cwd, project: { id: "project", directory: cwd } }
@@ -271,7 +279,6 @@ test("session startup prompt is submitted exactly once", async () => {
server: { endpoint: { url: server.url.toString() } }, server: { endpoint: { url: server.url.toString() } },
config: { get: async () => ({}), update: async () => ({}) }, config: { get: async () => ({}), update: async () => ({}) },
packages: { resolve: async () => undefined }, packages: { resolve: async () => undefined },
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
args: { sessionID: "dummy", prompt: "RESUME_READY" }, args: { sessionID: "dummy", prompt: "RESUME_READY" },
log: () => {}, log: () => {},
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))), }).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
@@ -292,5 +299,6 @@ test("session startup prompt is submitted exactly once", async () => {
} finally { } finally {
if (!setup.renderer.isDestroyed) setup.renderer.destroy() if (!setup.renderer.isDestroyed) setup.renderer.destroy()
await server.stop() await server.stop()
mock.restore()
} }
}) })
@@ -86,7 +86,6 @@ test.each([
let themes: ReturnType<typeof useThemes> | undefined let themes: ReturnType<typeof useThemes> | undefined
let failure: ThemeError | undefined let failure: ThemeError | undefined
let unsubscribe: (() => void) | undefined let unsubscribe: (() => void) | undefined
const discovery = Promise.withResolvers<Record<string, unknown>>()
function Probe() { function Probe() {
const value = useThemes() const value = useThemes()
@@ -98,7 +97,7 @@ test.each([
const app = await testRender( const app = await testRender(
() => ( () => (
<ConfigProvider config={createTuiResolvedConfig({ theme: { name: "invalid" } })}> <ConfigProvider config={createTuiResolvedConfig({ theme: { name: "invalid" } })}>
<ThemeProvider mode="dark" source={{ discover: () => discovery.promise }}> <ThemeProvider mode="dark" source={{ discover: () => Promise.resolve({ invalid: source }) }}>
<Probe /> <Probe />
</ThemeProvider> </ThemeProvider>
</ConfigProvider> </ConfigProvider>
@@ -106,7 +105,6 @@ test.each([
{ width: 20, height: 2 }, { width: 20, height: 2 },
) )
app.renderer.start() app.renderer.start()
discovery.resolve({ invalid: source })
try { try {
await wait(() => themes?.ready === true) await wait(() => themes?.ready === true)
-1
View File
@@ -131,7 +131,6 @@ test("preserves pinned session bindings alongside tab bindings", () => {
expect(config.keybinds.get("session.pin.toggle")).toMatchObject([{ key: "ctrl+f" }]) expect(config.keybinds.get("session.pin.toggle")).toMatchObject([{ key: "ctrl+f" }])
expect(config.keybinds.get("session.quick_switch.1")).toMatchObject([{ key: "<leader>1" }]) expect(config.keybinds.get("session.quick_switch.1")).toMatchObject([{ key: "<leader>1" }])
expect(config.keybinds.get("session.tab.select.1")).toMatchObject([{ key: "<leader>1,ctrl+1" }]) expect(config.keybinds.get("session.tab.select.1")).toMatchObject([{ key: "<leader>1,ctrl+1" }])
expect(config.keybinds.get("session.tab.select.10")).toMatchObject([{ key: "<leader>0,ctrl+0" }])
}) })
test("disables suspend and assigns ctrl+z to undo when unsupported", () => { test("disables suspend and assigns ctrl+z to undo when unsupported", () => {
@@ -12,27 +12,9 @@ import {
seedSessionTabMotion, seedSessionTabMotion,
sessionTabComplete, sessionTabComplete,
sessionTabOverflowWidth, sessionTabOverflowWidth,
sessionTabShortcutLabel,
} from "../../src/context/session-tabs-model" } from "../../src/context/session-tabs-model"
describe("session tabs", () => { describe("session tabs", () => {
test("labels direct shortcut tabs and marks unbound tabs with a dot", () => {
expect(Array.from({ length: 12 }, (_, index) => sessionTabShortcutLabel(index))).toEqual([
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"·",
"·",
])
})
test("moves a tab to a clamped index and returns the same tabs for no-ops", () => { test("moves a tab to a clamped index and returns the same tabs for no-ops", () => {
const tabs = ["a", "b", "c"].map((sessionID) => ({ sessionID })) const tabs = ["a", "b", "c"].map((sessionID) => ({ sessionID }))
expect(moveSessionTab(tabs, "a", 2).map((tab) => tab.sessionID)).toEqual(["b", "c", "a"]) expect(moveSessionTab(tabs, "a", 2).map((tab) => tab.sessionID)).toEqual(["b", "c", "a"])
@@ -1262,75 +1262,6 @@ test("direct footer tags skill slash submissions with their catalog source", asy
} }
}) })
test("direct footer submits a selected leading skill as a prompt attachment", 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()
"/forma".split("").forEach((key) => app.mockInput.pressKey(key))
await app.renderOnce()
app.mockInput.pressEnter()
await app.renderOnce()
"src".split("").forEach((key) => app.mockInput.pressKey(key))
app.mockInput.pressEnter()
await app.renderOnce()
expect(submits).toEqual([
{
text: "/formatter src",
parts: [
{
type: "skill",
id: "formatter",
source: { start: 0, end: 10, value: "/formatter" },
},
],
delivery: "steer",
},
])
} finally {
app.cleanup()
}
})
test("direct footer preserves a selected skill after wide text", 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()
"中 /forma".split("").forEach((key) => app.mockInput.pressKey(key))
await app.renderOnce()
app.mockInput.pressEnter()
await app.renderOnce()
app.mockInput.pressEnter()
await app.renderOnce()
expect(submits[0]?.parts).toEqual([
{
type: "skill",
id: "formatter",
source: { start: 3, end: 13, value: "/formatter" },
},
])
} finally {
app.cleanup()
}
})
// OpenTUI currently segfaults Bun while tearing down this composer-to-skill-panel transition. // OpenTUI currently segfaults Bun while tearing down this composer-to-skill-panel transition.
// Re-enable after the upstream renderer teardown fix lands. // Re-enable after the upstream renderer teardown fix lands.
test.skip("direct footer skill picker inserts an editable bound skill command", async () => { test.skip("direct footer skill picker inserts an editable bound skill command", async () => {
@@ -152,7 +152,7 @@ describe("run permission shared", () => {
}) })
}) })
test("uses the resource display when an edit has no generated diff", () => { test("uses source patch text when an edit has no generated diff", () => {
const patch = '*** Begin Patch\n*** Update File: src/index.ts\n@@\n-old\n+const arrow = "→"\n*** End Patch' const patch = '*** Begin Patch\n*** Update File: src/index.ts\n@@\n-old\n+const arrow = "→"\n*** End Patch'
const request = req({ const request = req({
action: "edit", action: "edit",
@@ -171,11 +171,13 @@ describe("run permission shared", () => {
expect(permissionInfo(request)).toMatchObject({ expect(permissionInfo(request)).toMatchObject({
title: "Edit src/index.ts", title: "Edit src/index.ts",
diff: undefined, diff: undefined,
patch,
}) })
expect(permissionInfo(request, undefined, true)).toMatchObject({ expect(permissionInfo(request, undefined, true)).toMatchObject({
title: "Edit src/index.ts", title: "Edit src/index.ts",
lines: [], lines: [patch],
diff: undefined, diff: undefined,
patch: undefined,
}) })
}) })
@@ -2755,7 +2755,7 @@ describe("V2 mini transport", () => {
variant: undefined, variant: undefined,
prompt: { prompt: {
messageID: "msg_cmd", messageID: "msg_cmd",
text: "/deploy prod /api-design", text: "/deploy prod",
parts: [ parts: [
{ {
type: "file", type: "file",
@@ -2763,11 +2763,6 @@ describe("V2 mini transport", () => {
filename: "mentioned.txt", filename: "mentioned.txt",
source: { type: "file", text: { start: 8, end: 12, value: "prod" } }, source: { type: "file", text: { start: 8, end: 12, value: "prod" } },
}, },
{
type: "skill",
id: "api-design",
source: { start: 13, end: 24, value: "/api-design" },
},
], ],
command: { name: "deploy", arguments: "prod" }, command: { name: "deploy", arguments: "prod" },
}, },
@@ -2790,7 +2785,6 @@ describe("V2 mini transport", () => {
mention: { start: 8, end: 12, text: "prod" }, mention: { start: 8, end: 12, text: "prod" },
}, },
], ],
skills: [{ id: "api-design", mention: { start: 13, end: 24, text: "/api-design" } }],
delivery: "steer", delivery: "steer",
}) })
// Selection rides the command payload; no separate client-side switch. // Selection rides the command payload; no separate client-side switch.
@@ -2863,75 +2857,6 @@ describe("V2 mini transport", () => {
await transport.close() await transport.close()
}) })
test("sends inline skill attachments with a normal prompt", 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,
footer: ui.api,
})
let request: Parameters<OpenCodeClient["session"]["prompt"]>[0] | undefined
spyOn(client.session, "prompt").mockImplementation((input) => {
request = input
queueMicrotask(() => {
events.push({
id: "evt_prompted",
created: 0,
type: "session.input.promoted",
durable: durable("ses_1"),
data: { sessionID: "ses_1", inputID: "msg_skill_attachment" },
})
events.push({
id: "evt_settled",
created: 0,
type: "session.execution.succeeded",
durable: durable("ses_1"),
data: { sessionID: "ses_1" },
})
})
return ok({
id: input.id ?? "msg_skill_attachment",
sessionID: "ses_1",
type: "user" as const,
data: { text: input.text },
delivery: "steer" as const,
timeCreated: 2,
})
})
await transport.runPromptTurn({
agent: undefined,
model: undefined,
variant: undefined,
prompt: {
messageID: "msg_skill_attachment",
text: "Review this /api-design",
parts: [
{
type: "skill",
id: "api-design",
source: { start: 12, end: 23, value: "/api-design" },
},
],
},
files: [],
includeFiles: false,
})
expect(request).toMatchObject({
sessionID: "ses_1",
id: "msg_skill_attachment",
text: "Review this /api-design",
skills: [{ id: "api-design", mention: { start: 12, end: 23, text: "/api-design" } }],
delivery: "steer",
})
await transport.close()
})
test("refreshes catalogs on connection and location-scoped invalidations", async () => { test("refreshes catalogs on connection and location-scoped invalidations", async () => {
const events = feed() const events = feed()
events.push(connected()) events.push(connected())
+1 -11
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test" import { describe, expect, test } from "bun:test"
import { displayCharAt, displaySlice, mentionTriggerIndex, slashTriggerIndex } from "../../src/prompt/display" import { displayCharAt, displaySlice, mentionTriggerIndex } from "../../src/prompt/display"
describe("prompt display", () => { describe("prompt display", () => {
test("uses display-width offsets for mentions", () => { test("uses display-width offsets for mentions", () => {
@@ -30,14 +30,4 @@ describe("prompt display", () => {
expect(mentionTriggerIndex("foo@bar.com")).toBeUndefined() expect(mentionTriggerIndex("foo@bar.com")).toBeUndefined()
expect(mentionTriggerIndex("中文 @src file")).toBeUndefined() expect(mentionTriggerIndex("中文 @src file")).toBeUndefined()
}) })
test("finds slash attachments at token boundaries", () => {
expect(slashTriggerIndex("/")).toBe(0)
expect(slashTriggerIndex("Review this /api-design")).toBe(12)
expect(slashTriggerIndex("中文 /api-design")).toBe(5)
expect(slashTriggerIndex("Review /api design")).toBeUndefined()
expect(slashTriggerIndex("Review /tmp/file.ts")).toBeUndefined()
expect(slashTriggerIndex("https://opencode.ai/docs")).toBeUndefined()
expect(slashTriggerIndex("src/prompt/index.ts")).toBeUndefined()
})
}) })
+7 -1
View File
@@ -258,7 +258,13 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
const spawn = (command: ChildProcess.StandardCommand, opts: NodeChildProcess.SpawnOptions) => const spawn = (command: ChildProcess.StandardCommand, opts: NodeChildProcess.SpawnOptions) =>
Effect.callback<readonly [NodeChildProcess.ChildProcess, ExitSignal], PlatformError.PlatformError>((resume) => { Effect.callback<readonly [NodeChildProcess.ChildProcess, ExitSignal], PlatformError.PlatformError>((resume) => {
const signal = Deferred.makeUnsafe<readonly [code: number | null, signal: NodeJS.Signals | null]>() const signal = Deferred.makeUnsafe<readonly [code: number | null, signal: NodeJS.Signals | null]>()
const proc = launch(command.command, command.args, opts) let proc: NodeChildProcess.ChildProcess
try {
proc = launch(command.command, command.args, opts)
} catch (err) {
resume(Effect.fail(toPlatformError("spawn", toError(err), command)))
return Effect.void
}
let end = false let end = false
let exit: readonly [code: number | null, signal: NodeJS.Signals | null] | undefined let exit: readonly [code: number | null, signal: NodeJS.Signals | null] | undefined
proc.on("error", (err) => { proc.on("error", (err) => {
-62
View File
@@ -1809,12 +1809,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
}, },
@@ -2023,12 +2017,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
}
},
"delivery": { "delivery": {
"anyOf": [ "anyOf": [
{ {
@@ -12853,25 +12841,6 @@
"required": ["name"], "required": ["name"],
"additionalProperties": false "additionalProperties": false
}, },
"Prompt.SkillAttachment": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"text": {
"type": "string"
},
"mention": {
"$ref": "#/components/schemas/Prompt.Mention"
}
},
"required": ["id", "name", "text"],
"additionalProperties": false
},
"Session.Message.User": { "Session.Message.User": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -12911,12 +12880,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"type": { "type": {
"type": "string", "type": "string",
"enum": ["user"] "enum": ["user"]
@@ -13874,19 +13837,6 @@
"required": ["uri"], "required": ["uri"],
"additionalProperties": false "additionalProperties": false
}, },
"PromptInput.SkillAttachment": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"mention": {
"$ref": "#/components/schemas/Prompt.Mention"
}
},
"required": ["id"],
"additionalProperties": false
},
"SessionPending.UserData": { "SessionPending.UserData": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -13905,12 +13855,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
} }
@@ -14820,12 +14764,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
} }
-62
View File
@@ -1809,12 +1809,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
}, },
@@ -2023,12 +2017,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
}
},
"delivery": { "delivery": {
"anyOf": [ "anyOf": [
{ {
@@ -12853,25 +12841,6 @@
"required": ["name"], "required": ["name"],
"additionalProperties": false "additionalProperties": false
}, },
"Prompt.SkillAttachment": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"text": {
"type": "string"
},
"mention": {
"$ref": "#/components/schemas/Prompt.Mention"
}
},
"required": ["id", "name", "text"],
"additionalProperties": false
},
"Session.Message.User": { "Session.Message.User": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -12911,12 +12880,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"type": { "type": {
"type": "string", "type": "string",
"enum": ["user"] "enum": ["user"]
@@ -13874,19 +13837,6 @@
"required": ["uri"], "required": ["uri"],
"additionalProperties": false "additionalProperties": false
}, },
"PromptInput.SkillAttachment": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"mention": {
"$ref": "#/components/schemas/Prompt.Mention"
}
},
"required": ["id"],
"additionalProperties": false
},
"SessionPending.UserData": { "SessionPending.UserData": {
"type": "object", "type": "object",
"properties": { "properties": {
@@ -13905,12 +13855,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
} }
@@ -14820,12 +14764,6 @@
"$ref": "#/components/schemas/Prompt.AgentAttachment" "$ref": "#/components/schemas/Prompt.AgentAttachment"
} }
}, },
"skills": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Prompt.SkillAttachment"
}
},
"metadata": { "metadata": {
"type": "object" "type": "object"
} }