mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 05:01:03 +03:00
feat(core): support in-memory skill:// URIs (#60921)
This commit is contained in:
committed by
GitHub
Unverified
parent
f4ec1532f0
commit
69269e4ebe
@@ -684,7 +684,7 @@ test("Extensions lists open config files and skills in a side tab and start setu
|
||||
mcp: [{ name: "atlas-search", status: { status: "connected" } }],
|
||||
plugins: [],
|
||||
skills: [
|
||||
{ id: "opencode", name: "OpenCode", path: "/builtin/opencode.md", content: "# Built-in OpenCode guide" },
|
||||
{ id: "opencode", name: "OpenCode", path: "skill://opencode/SKILL.md", content: "# Built-in OpenCode guide" },
|
||||
{ id: "release-notes", name: "release-notes", path: skill, content: "Release notes" },
|
||||
],
|
||||
configEntries: [
|
||||
@@ -699,12 +699,12 @@ test("Extensions lists open config files and skills in a side tab and start setu
|
||||
fileContent: (path) => ({ type: "text", content: `contents:${path}` }),
|
||||
})
|
||||
|
||||
await page.route(/\/api\/fs\/read\/opencode\.md(\?|$)/, (route) => {
|
||||
await page.route(/\/api\/fs\/read\/SKILL\.md(\?|$)/, (route) => {
|
||||
builtinReads += 1
|
||||
|
||||
return route.fulfill({
|
||||
status: 404,
|
||||
json: { message: "Location not found: /builtin" },
|
||||
json: { message: "Location not found: skill://opencode" },
|
||||
headers: cors,
|
||||
})
|
||||
})
|
||||
@@ -728,7 +728,7 @@ test("Extensions lists open config files and skills in a side tab and start setu
|
||||
await row("Skills").hover()
|
||||
await list("Skills").getByRole("button", { name: "OpenCode", exact: true }).click()
|
||||
await expect(summary).toBeHidden()
|
||||
await expect(page.getByRole("tab", { name: "opencode.md", exact: true })).toHaveAttribute("aria-selected", "true")
|
||||
await expect(page.getByRole("tab", { name: "SKILL.md", exact: true })).toHaveAttribute("aria-selected", "true")
|
||||
await expect(page.getByRole("heading", { name: "Built-in OpenCode guide", exact: true })).toBeVisible()
|
||||
await expect(page.getByText("Failed to load file", { exact: true })).toHaveCount(0)
|
||||
expect(builtinReads).toBe(0)
|
||||
@@ -737,7 +737,8 @@ test("Extensions lists open config files and skills in a side tab and start setu
|
||||
await row("Skills").hover()
|
||||
await list("Skills").getByRole("button", { name: "release-notes", exact: true }).click()
|
||||
await expect(summary).toBeHidden()
|
||||
await expect(page.getByRole("tab", { name: "SKILL.md", exact: true })).toHaveAttribute("aria-selected", "true")
|
||||
await expect(page.getByRole("tab", { name: "SKILL.md", selected: true, exact: true })).toBeVisible()
|
||||
await expect(page.getByText("contents:.opencode/skills/release-notes/SKILL.md", { exact: true })).toBeVisible()
|
||||
|
||||
// An empty list offers a draft session in the global configuration's directory, its prompt filled in.
|
||||
await trigger.click()
|
||||
|
||||
@@ -180,7 +180,9 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
|
||||
)
|
||||
}
|
||||
|
||||
// Built-in skills register virtual `/builtin/*.md` paths whose content is inline in `/api/skill`.
|
||||
// Built-in and virtual skills register `skill://` (or legacy `/builtin/`) paths whose content is inline in `/api/skill`.
|
||||
const isVirtualSkill = (file: string) => file.startsWith("skill://") || file.startsWith("/builtin/")
|
||||
|
||||
const builtinSkill = async (file: string, directory: string) => {
|
||||
if (data.location.skill.list({ directory }) === undefined) {
|
||||
await data.location.skill.sync({ directory })
|
||||
@@ -225,7 +227,7 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
|
||||
|
||||
// Files outside the workspace are read from their own directory, like markdown images.
|
||||
// The trailing separator from getDirectory keeps "/" and "C:/" valid, like readLocalImage.
|
||||
const source = file.startsWith("/builtin/")
|
||||
const source = isVirtualSkill(file)
|
||||
? readBuiltin(file, directory)
|
||||
: read(
|
||||
file,
|
||||
@@ -272,7 +274,7 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
|
||||
|
||||
if (!file) return Promise.resolve(false)
|
||||
|
||||
if (file.startsWith("/builtin/")) {
|
||||
if (isVirtualSkill(file)) {
|
||||
return builtinSkill(file, scope()).then(Boolean, () => false)
|
||||
}
|
||||
|
||||
|
||||
@@ -121,7 +121,8 @@ export function createPathHelpers(scope: () => string) {
|
||||
}
|
||||
|
||||
/** Whether a normalized path points outside the workspace root. */
|
||||
const absolute = (path: string) => /^[A-Za-z]:[/\\]/.test(path) || path.startsWith("/") || path.startsWith("\\\\")
|
||||
const absolute = (path: string) =>
|
||||
path.startsWith("skill://") || /^[A-Za-z]:[/\\]/.test(path) || path.startsWith("/") || path.startsWith("\\\\")
|
||||
|
||||
const normalizeDir = (input: string) => {
|
||||
const path = normalize(input)
|
||||
|
||||
@@ -30,7 +30,7 @@ export const Plugin = define({
|
||||
id: Skill.ID.make("opencode"),
|
||||
name: Skill.Name.make("OpenCode"),
|
||||
description: OpencodeDescription,
|
||||
path: AbsolutePath.make("/builtin/opencode.md"),
|
||||
path: AbsolutePath.make("skill://opencode/SKILL.md"),
|
||||
content: OpencodeContent,
|
||||
}),
|
||||
)
|
||||
@@ -39,7 +39,7 @@ export const Plugin = define({
|
||||
id: Skill.ID.make("report"),
|
||||
name: Skill.Name.make("Report"),
|
||||
description: REPORT_DESCRIPTION,
|
||||
path: AbsolutePath.make("/builtin/report.md"),
|
||||
path: AbsolutePath.make("skill://report/SKILL.md"),
|
||||
content: reportContent,
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -67,10 +67,11 @@ export const prepare = Effect.fn("SessionPrompt.prepare")(function* (request: {
|
||||
const skill = yield* skillService.get(attachment.id)
|
||||
if (!skill) return yield* new SkillNotFoundError({ skill: attachment.id })
|
||||
prepared.set(skill.id, skill.name)
|
||||
const files = yield* skillService.files(skill.id)
|
||||
return {
|
||||
id: skill.id,
|
||||
name: skill.name,
|
||||
text: (yield* Skill.prepare(fs, skill).pipe(Effect.orDie)).output,
|
||||
text: (yield* Skill.prepare(fs, skill, files).pipe(Effect.orDie)).output,
|
||||
mention: attachment.mention,
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -33,8 +33,12 @@ export { Event } from "@opencode/schema/skill"
|
||||
export const available = (skills: ReadonlyArray<Info>, permissions: Permission.Ruleset) =>
|
||||
skills.filter((skill) => Permission.evaluate("skill", skill.id, permissions).effect !== "deny")
|
||||
|
||||
export const uri = (id: string, file?: string) => (file ? `skill://${id}/${file}` : `skill://${id}`)
|
||||
|
||||
export const isUri = (value: string) => value.startsWith("skill://")
|
||||
|
||||
export const toModelOutput = (skill: Info, files: ReadonlyArray<string>) => {
|
||||
const directory = path.dirname(skill.path)
|
||||
const directory = isUri(skill.path) ? uri(skill.id) : path.dirname(skill.path)
|
||||
return [
|
||||
`<skill_content name="${skill.name}">`,
|
||||
`# Skill: ${skill.name}`,
|
||||
@@ -52,7 +56,23 @@ export const toModelOutput = (skill: Info, files: ReadonlyArray<string>) => {
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
export const prepare = Effect.fn("Skill.prepare")(function* (fs: FSUtil.Interface, skill: Info) {
|
||||
export const prepare = Effect.fn("Skill.prepare")(function* (
|
||||
fs: FSUtil.Interface,
|
||||
skill: Info,
|
||||
virtualFiles?: ReadonlyMap<string, string>,
|
||||
) {
|
||||
if (isUri(skill.path)) {
|
||||
const directory = uri(skill.id)
|
||||
const files = Array.from(virtualFiles?.keys() ?? [])
|
||||
.filter((file) => file !== "SKILL.md")
|
||||
.toSorted()
|
||||
.slice(0, 10)
|
||||
.map((file) => uri(skill.id, file))
|
||||
return {
|
||||
directory,
|
||||
output: toModelOutput(skill, files),
|
||||
}
|
||||
}
|
||||
const directory = path.dirname(skill.path)
|
||||
const files =
|
||||
path.basename(skill.path) === "SKILL.md"
|
||||
@@ -75,18 +95,20 @@ export const prepare = Effect.fn("Skill.prepare")(function* (fs: FSUtil.Interfac
|
||||
|
||||
export type Data = {
|
||||
skills: Map<ID, Types.DeepMutable<Info>>
|
||||
files: Map<ID, ReadonlyMap<string, string>>
|
||||
}
|
||||
|
||||
export type Editor = {
|
||||
list: () => readonly Types.DeepMutable<Info>[]
|
||||
get: (id: string) => Types.DeepMutable<Info> | undefined
|
||||
add: (skill: Info) => void
|
||||
add: (skill: Info, files?: Readonly<Record<string, string>>) => void
|
||||
update: (id: string, update: (skill: Types.DeepMutable<Info>) => void) => void
|
||||
remove: (id: string) => void
|
||||
}
|
||||
|
||||
export interface Interface extends State.Transformable<Editor> {
|
||||
readonly get: (id: ID) => Effect.Effect<Info | undefined>
|
||||
readonly files: (id: ID) => Effect.Effect<ReadonlyMap<string, string> | undefined>
|
||||
readonly list: () => Effect.Effect<Info[]>
|
||||
}
|
||||
|
||||
@@ -99,12 +121,22 @@ const layer = Layer.effect(
|
||||
|
||||
const state = State.create<Data, Editor>({
|
||||
name: "skill",
|
||||
initial: () => ({ skills: new Map() }),
|
||||
initial: () => ({ skills: new Map(), files: new Map() }),
|
||||
editor: (editor) => ({
|
||||
list: () => Array.from(editor.skills.values()),
|
||||
get: (id) => editor.skills.get(ID.make(id)),
|
||||
add: (skill) => {
|
||||
add: (skill, files) => {
|
||||
editor.skills.set(skill.id, { ...skill })
|
||||
const entries = files
|
||||
? Object.entries(files)
|
||||
.filter(([file]) => file !== "SKILL.md")
|
||||
.toSorted(([a], [b]) => a.localeCompare(b))
|
||||
: []
|
||||
if (entries.length === 0) {
|
||||
editor.files.delete(skill.id)
|
||||
return
|
||||
}
|
||||
editor.files.set(skill.id, new Map(entries))
|
||||
},
|
||||
update: (id, update) => {
|
||||
const key = ID.make(id)
|
||||
@@ -114,11 +146,16 @@ const layer = Layer.effect(
|
||||
current.id = key
|
||||
},
|
||||
remove: (id) => {
|
||||
editor.skills.delete(ID.make(id))
|
||||
const key = ID.make(id)
|
||||
editor.skills.delete(key)
|
||||
editor.files.delete(key)
|
||||
},
|
||||
}),
|
||||
notify: State.changes(
|
||||
(data) => Array.from(data.skills.values()),
|
||||
(data) => [
|
||||
Array.from(data.skills.values()),
|
||||
Array.from(data.files, ([id, entries]) => [id, Array.from(entries)]),
|
||||
],
|
||||
() => bus.publish(Skill.Event.Updated, {}).pipe(Effect.asVoid),
|
||||
),
|
||||
})
|
||||
@@ -129,6 +166,10 @@ const layer = Layer.effect(
|
||||
get: Effect.fn("Skill.get")(function* (id) {
|
||||
return state.get().skills.get(id)
|
||||
}),
|
||||
files: Effect.fn("Skill.files")(function* (id) {
|
||||
const current = state.get()
|
||||
return current.skills.has(id) ? current.files.get(id) : undefined
|
||||
}),
|
||||
list: Effect.fn("Skill.list")(function* () {
|
||||
return Array.from(state.get().skills.values())
|
||||
}),
|
||||
|
||||
@@ -13,7 +13,7 @@ import { Hash } from "@opencode/util/hash"
|
||||
const skillConcurrency = 4
|
||||
const fileConcurrency = 8
|
||||
|
||||
function isSafeSegment(value: string) {
|
||||
export function isSafeSegment(value: string) {
|
||||
return (
|
||||
value.length > 0 &&
|
||||
value !== "." &&
|
||||
@@ -24,7 +24,7 @@ function isSafeSegment(value: string) {
|
||||
)
|
||||
}
|
||||
|
||||
function isSafeRelativePath(value: string) {
|
||||
export function isSafeRelativePath(value: string) {
|
||||
const segments = value.split("/")
|
||||
return (
|
||||
value.length > 0 &&
|
||||
|
||||
@@ -7,8 +7,11 @@ import { Effect, Schema } from "effect"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { Location } from "../../location.js"
|
||||
import { FileAccess } from "../../file-access.js"
|
||||
import { Permission } from "../../permission.js"
|
||||
import { SessionInstructions } from "../../session/instructions.js"
|
||||
import { AbsolutePath } from "../../schema.js"
|
||||
import { Skill } from "../../skill.js"
|
||||
import { SkillDiscovery } from "../../skill/discovery.js"
|
||||
import { ReadToolFileSystem } from "../read-filesystem.js"
|
||||
import { Environment } from "../../environment/index.js"
|
||||
|
||||
@@ -31,6 +34,8 @@ export const Plugin = {
|
||||
effect: Effect.fn("ReadTool.Plugin")(function* (ctx: Context) {
|
||||
const reader = yield* ReadToolFileSystem.Service
|
||||
const access = yield* FileAccess.Service
|
||||
const permission = yield* Permission.Service
|
||||
const skills = yield* Skill.Service
|
||||
const sessionInstructions = yield* SessionInstructions.Service
|
||||
const fs = yield* FSUtil.Service
|
||||
const location = yield* Location.Service
|
||||
@@ -46,6 +51,51 @@ export const Plugin = {
|
||||
output: Output,
|
||||
execute: (input, context) => {
|
||||
return Effect.gen(function* () {
|
||||
if (Skill.isUri(input.path)) {
|
||||
const parsed = parseSkillUri(input.path)
|
||||
if (!parsed) return yield* new ToolFailure({ message: `File not found: ${input.path}` })
|
||||
const id = Skill.ID.make(parsed.id)
|
||||
const skill = yield* skills.get(id)
|
||||
if (!skill || !Skill.isUri(skill.path))
|
||||
return yield* new ToolFailure({ message: `File not found: ${input.path}` })
|
||||
const extra = yield* skills.files(id)
|
||||
const source = { type: "tool" as const, messageID: context.messageID, id: context.id }
|
||||
yield* permission.assert({
|
||||
action: "skill",
|
||||
resources: [skill.id],
|
||||
save: [skill.id],
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
source,
|
||||
})
|
||||
yield* permission.assert({
|
||||
action: "read",
|
||||
resources: [parsed.uri],
|
||||
save: ["*"],
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
source,
|
||||
})
|
||||
const virtualFs = Environment.makeFiles(Environment.makeMemoryDriver())
|
||||
const encoder = new TextEncoder()
|
||||
yield* virtualFs.write(AbsolutePath.make("/SKILL.md"), encoder.encode(skill.content))
|
||||
yield* Effect.forEach(
|
||||
extra ? Array.from(extra) : [],
|
||||
([rel, text]) => virtualFs.write(AbsolutePath.make(`/${rel}`), encoder.encode(text)),
|
||||
{ discard: true },
|
||||
)
|
||||
const output = yield* ReadToolFileSystem.read(virtualFs, AbsolutePath.make(parsed.target), input.path, {
|
||||
offset: input.offset,
|
||||
limit: input.limit,
|
||||
}).pipe(
|
||||
Effect.catchIf(
|
||||
(error) => error instanceof Environment.NotFound,
|
||||
() => Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })),
|
||||
),
|
||||
)
|
||||
return { output, path: input.path }
|
||||
}
|
||||
|
||||
const read = (target: FileAccess.Target) =>
|
||||
reader.read(target.absolute, target.resource, {
|
||||
offset: input.offset,
|
||||
@@ -199,6 +249,17 @@ export const Plugin = {
|
||||
}),
|
||||
}
|
||||
|
||||
function parseSkillUri(value: string) {
|
||||
const trimmed = value.slice("skill://".length).replace(/\/+$/, "")
|
||||
const slash = trimmed.indexOf("/")
|
||||
const id = slash === -1 ? trimmed : trimmed.slice(0, slash)
|
||||
const rest = slash === -1 ? "" : trimmed.slice(slash + 1)
|
||||
if (!SkillDiscovery.isSafeSegment(id)) return undefined
|
||||
if (rest !== "" && !rest.split("/").every(SkillDiscovery.isSafeSegment)) return undefined
|
||||
// Permission checks use the canonical URI, so `skill://id/file/` can't slip past a rule for `skill://id/file`.
|
||||
return { id, target: rest === "" ? "/" : `/${rest}`, uri: Skill.uri(id, rest || undefined) }
|
||||
}
|
||||
|
||||
export const toModelContent = (path: string, offset: number | undefined, output: typeof Output.Type) => {
|
||||
if (output.type === "file" && output.encoding === "base64")
|
||||
return [
|
||||
|
||||
@@ -56,7 +56,8 @@ export const Plugin = {
|
||||
agent: context.agent,
|
||||
source: { type: "tool", messageID: context.messageID, id: context.id },
|
||||
})
|
||||
return { name: skill.name, ...(yield* Skill.prepare(fs, skill)) }
|
||||
const files = yield* skills.files(skill.id)
|
||||
return { name: skill.name, ...(yield* Skill.prepare(fs, skill, files)) }
|
||||
}).pipe(Effect.mapError((error) => unableToLoad(input.id, error)))
|
||||
}).pipe(
|
||||
Effect.map((output) => ({
|
||||
|
||||
@@ -119,12 +119,13 @@ export const read = Effect.fn("ReadTool.read")(function* (
|
||||
resource: string,
|
||||
page: PageInput = {},
|
||||
) {
|
||||
const virtual = resource.startsWith("skill://")
|
||||
const first = yield* files.read(input, { offset: 0, length: FIRST_CHUNK }).pipe(
|
||||
Effect.catchTag("Environment.WrongKind", (error) => {
|
||||
if (error.actual !== "directory")
|
||||
return Effect.fail(new PathKindError({ resource, expected: "a file or directory" }))
|
||||
return files.list(input).pipe(
|
||||
Effect.map((entries) => list(entries, page)),
|
||||
Effect.map((entries) => list(entries, page, virtual ? "/" : path.sep)),
|
||||
Effect.catchTag("Environment.WrongKind", () =>
|
||||
Effect.fail(new PathKindError({ resource, expected: "a file or directory" })),
|
||||
),
|
||||
@@ -140,8 +141,8 @@ export const read = Effect.fn("ReadTool.read")(function* (
|
||||
const whole = yield* readFile(files, input, resource)
|
||||
return {
|
||||
type: "file" as const,
|
||||
uri: pathToFileURL(input).href,
|
||||
name: path.basename(input),
|
||||
uri: virtual ? resource : pathToFileURL(input).href,
|
||||
name: virtual ? path.posix.basename(input) : path.basename(input),
|
||||
content: Buffer.from(whole.bytes).toString("base64"),
|
||||
encoding: "base64" as const,
|
||||
mime: media,
|
||||
@@ -153,8 +154,8 @@ export const read = Effect.fn("ReadTool.read")(function* (
|
||||
if (first.bytes.includes(0)) return yield* new BinaryFileError({ resource })
|
||||
return {
|
||||
type: "file" as const,
|
||||
uri: pathToFileURL(input).href,
|
||||
name: path.basename(input),
|
||||
uri: virtual ? resource : pathToFileURL(input).href,
|
||||
name: virtual ? path.posix.basename(input) : path.basename(input),
|
||||
content: new TextDecoder().decode(first.bytes).split("\n").map(clampLine).join("\n"),
|
||||
encoding: "utf8" as const,
|
||||
mime: mimeType(input),
|
||||
@@ -255,7 +256,7 @@ const makeTextPage = Effect.fnUntraced(function* (
|
||||
})
|
||||
})
|
||||
|
||||
const list = (items: ReadonlyArray<Environment.DirEntry>, page: PageInput) => {
|
||||
const list = (items: ReadonlyArray<Environment.DirEntry>, page: PageInput, sep = path.sep) => {
|
||||
const offset = page.offset || 1
|
||||
const limit = Math.min(page.limit || MAX_READ_LINES, MAX_READ_LINES)
|
||||
const visible = items
|
||||
@@ -264,7 +265,7 @@ const list = (items: ReadonlyArray<Environment.DirEntry>, page: PageInput) => {
|
||||
? []
|
||||
: [
|
||||
ListEntry.make({
|
||||
path: RelativePath.make(item.name + (item.type === "directory" ? path.sep : "")),
|
||||
path: RelativePath.make(item.name + (item.type === "directory" ? sep : "")),
|
||||
type: item.type,
|
||||
}),
|
||||
],
|
||||
|
||||
@@ -39,6 +39,7 @@ describe("SkillPlugin.Plugin", () => {
|
||||
expect.objectContaining({
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
path: "skill://opencode/SKILL.md",
|
||||
description: expect.stringContaining("any question about OpenCode itself"),
|
||||
}),
|
||||
)
|
||||
@@ -46,6 +47,7 @@ describe("SkillPlugin.Plugin", () => {
|
||||
expect.objectContaining({
|
||||
id: "report",
|
||||
name: "Report",
|
||||
path: "skill://report/SKILL.md",
|
||||
description: expect.stringContaining("opencode issue"),
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -27,6 +27,7 @@ import { SessionMessage } from "@opencode/core/session/message"
|
||||
import { SessionProjector } from "@opencode/core/session/projector"
|
||||
import { SessionStore } from "@opencode/core/session/store"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { toLLMMessages } from "@opencode/core/session/runner/to-llm-message"
|
||||
import { PluginHooks } from "@opencode/core/plugin/hooks"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
@@ -47,6 +48,7 @@ const readToolNode = makeLocationNode({
|
||||
Image.node,
|
||||
Permission.node,
|
||||
SessionInstructions.node,
|
||||
Skill.node,
|
||||
FSUtil.node,
|
||||
Location.node,
|
||||
],
|
||||
@@ -71,6 +73,7 @@ const testLayer = AppNodeBuilder.build(
|
||||
Tool.node,
|
||||
PluginHooks.node,
|
||||
SessionInstructions.node,
|
||||
Skill.node,
|
||||
Global.node,
|
||||
Image.node,
|
||||
]),
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Deferred, Effect, Fiber, Layer, Schedule, Stream } from "effect"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { Bus } from "@opencode/core/bus"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { Document, Event } from "@opencode/schema/config"
|
||||
@@ -15,10 +16,9 @@ import { registerIntegrationPolicy, setOrganizationPolicy } from "./fixture/poli
|
||||
|
||||
const configLayer = Config.testLayer()
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Skill.node, SkillInstructions.node, Agent.node, Bus.node]),
|
||||
[Config.node.replace(configLayer)],
|
||||
).pipe(Layer.provideMerge(configLayer)),
|
||||
AppNodeBuilder.build(LayerNode.group([Skill.node, SkillInstructions.node, Agent.node, Bus.node, FSUtil.node]), [
|
||||
Config.node.replace(configLayer),
|
||||
]).pipe(Layer.provideMerge(configLayer)),
|
||||
)
|
||||
|
||||
const info = (id: string, description: string) =>
|
||||
@@ -220,6 +220,55 @@ describe("Skill", () => {
|
||||
expect(Skill.available([info("deploy", "Deploy")], agent!.permissions)).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect(
|
||||
"stores virtual skill files, notifies when they change, and prepares skill:// output without disk scans",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const skill = yield* Skill.Service
|
||||
const bus = yield* Bus.Service
|
||||
const virtual = Skill.Info.make({
|
||||
...info("review", "Review"),
|
||||
path: AbsolutePath.make(Skill.uri("review", "SKILL.md")),
|
||||
})
|
||||
let extra: Record<string, string> = { "SKILL.md": "ignored", "references/b.md": "B", "references/a.md": "A" }
|
||||
yield* skill.transform((editor) => {
|
||||
editor.add(virtual, extra)
|
||||
editor.update("review", (draft) => {
|
||||
draft.description = "Updated"
|
||||
})
|
||||
})
|
||||
|
||||
const files = yield* skill.files(Skill.ID.make("review"))
|
||||
expect(Array.from(files ?? [])).toEqual([
|
||||
["references/a.md", "A"],
|
||||
["references/b.md", "B"],
|
||||
])
|
||||
const fs = yield* FSUtil.Service
|
||||
const prepared = yield* Skill.prepare(
|
||||
{ ...fs, scan: () => Effect.die(new Error("unexpected disk scan")) },
|
||||
virtual,
|
||||
files,
|
||||
)
|
||||
expect(prepared).toEqual({
|
||||
directory: "skill://review",
|
||||
output: Skill.toModelOutput(virtual, ["skill://review/references/a.md", "skill://review/references/b.md"]),
|
||||
})
|
||||
|
||||
let updates = 0
|
||||
yield* bus.listen((event) =>
|
||||
Effect.sync(() => {
|
||||
if (event.type === Skill.Event.Updated.type) updates++
|
||||
}),
|
||||
)
|
||||
extra = { "references/a.md": "Changed" }
|
||||
yield* skill.reload()
|
||||
expect(updates).toBe(1)
|
||||
|
||||
yield* skill.transform((editor) => editor.remove("review"))
|
||||
expect(yield* skill.files(Skill.ID.make("review"))).toBeUndefined()
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
const waitUntil = (condition: Effect.Effect<boolean>) =>
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Location } from "@opencode/core/location"
|
||||
import { Image } from "@opencode/core/image"
|
||||
import { Permission } from "@opencode/core/permission"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { AbsolutePath, RelativePath } from "@opencode/core/schema"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { FileAccess } from "@opencode/core/file-access"
|
||||
@@ -34,6 +35,7 @@ const readToolNode = makeLocationNode({
|
||||
Image.node,
|
||||
Permission.node,
|
||||
SessionInstructions.node,
|
||||
Skill.node,
|
||||
FSUtil.node,
|
||||
Location.node,
|
||||
],
|
||||
@@ -108,7 +110,7 @@ const unavailableImage = Layer.mock(Image.Service, {
|
||||
})
|
||||
const readLayer = (imageLayer: Layer.Layer<Image.Service>) =>
|
||||
Layer.mergeAll(
|
||||
AppNodeBuilder.build(LayerNode.group([Tool.node, readToolNode]), [
|
||||
AppNodeBuilder.build(LayerNode.group([Tool.node, readToolNode, Skill.node]), [
|
||||
ReadToolFileSystem.node.replace(reader),
|
||||
Permission.node.replace(permission),
|
||||
Config.node.replace(config),
|
||||
@@ -1056,4 +1058,123 @@ describe("ReadTool", () => {
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("reads virtual skill:// files and directories from Skill.Service without external_directory approval", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const registry = yield* Tool.Service
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* skills.transform((editor) =>
|
||||
editor.add(
|
||||
Skill.Info.make({
|
||||
id: Skill.ID.make("guide"),
|
||||
name: Skill.Name.make("Guide"),
|
||||
description: "Guide",
|
||||
path: AbsolutePath.make("skill://guide/SKILL.md"),
|
||||
content: "# Guide\nRead references/style.md",
|
||||
}),
|
||||
{
|
||||
"references/style.md": "Line 1\nLine 2",
|
||||
},
|
||||
),
|
||||
)
|
||||
yield* skills.transform((editor) =>
|
||||
editor.add(
|
||||
Skill.Info.make({
|
||||
id: Skill.ID.make("disk"),
|
||||
name: Skill.Name.make("Disk"),
|
||||
path: AbsolutePath.make("/somewhere/disk/SKILL.md"),
|
||||
content: "Disk",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
const file = yield* executeTool(registry, {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
call: {
|
||||
type: "tool-call",
|
||||
id: "call-skill-file",
|
||||
name: "read",
|
||||
input: { path: "skill://guide/references/style.md", offset: 2, limit: 1 },
|
||||
},
|
||||
})
|
||||
expect(file).toMatchObject({
|
||||
status: "completed",
|
||||
content: [{ type: "text", text: "Read file skill://guide/references/style.md, lines 2-2\n2: Line 2" }],
|
||||
})
|
||||
|
||||
const root = yield* executeTool(registry, {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
call: { type: "tool-call", id: "call-skill-dir", name: "read", input: { path: "skill://guide/" } },
|
||||
})
|
||||
expect(root).toMatchObject({
|
||||
status: "completed",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Read directory skill://guide/, entries 1-2\nreferences/\nSKILL.md",
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
for (const bad of [
|
||||
"skill://",
|
||||
"skill://guide/../SKILL.md",
|
||||
"skill://guide/missing.md",
|
||||
"skill://unknown",
|
||||
"skill://disk/SKILL.md",
|
||||
]) {
|
||||
expect(
|
||||
yield* executeTool(registry, {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
call: { type: "tool-call", id: `call-${bad}`, name: "read", input: { path: bad } },
|
||||
}),
|
||||
).toEqual({
|
||||
status: "error",
|
||||
error: { type: "tool.execution", message: `File not found: ${bad}` },
|
||||
})
|
||||
}
|
||||
|
||||
expect(assertions).toMatchObject([
|
||||
{ sessionID, action: "skill", resources: ["guide"], save: ["guide"] },
|
||||
{ sessionID, action: "read", resources: ["skill://guide/references/style.md"], save: ["*"] },
|
||||
{ sessionID, action: "skill", resources: ["guide"], save: ["guide"] },
|
||||
{ sessionID, action: "read", resources: ["skill://guide"], save: ["*"] },
|
||||
{ sessionID, action: "skill", resources: ["guide"], save: ["guide"] },
|
||||
{ sessionID, action: "read", resources: ["skill://guide/missing.md"], save: ["*"] },
|
||||
])
|
||||
expect(readCalls).toEqual([])
|
||||
|
||||
deniedResource = "guide"
|
||||
expect(
|
||||
yield* executeTool(registry, {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
call: {
|
||||
type: "tool-call",
|
||||
id: "call-skill-denied",
|
||||
name: "read",
|
||||
input: { path: "skill://guide/SKILL.md" },
|
||||
},
|
||||
}),
|
||||
).toEqual({ status: "error", error: { type: "permission.rejected", message: "Permission denied: skill" } })
|
||||
|
||||
deniedResource = "skill://guide/SKILL.md"
|
||||
for (const path of ["skill://guide/SKILL.md", "skill://guide/SKILL.md/"]) {
|
||||
expect(
|
||||
yield* executeTool(registry, {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
call: { type: "tool-call", id: `call-skill-read-denied-${path}`, name: "read", input: { path } },
|
||||
}),
|
||||
).toEqual({ status: "error", error: { type: "permission.rejected", message: "Permission denied: read" } })
|
||||
}
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -109,6 +109,7 @@ describe("SkillTool", () => {
|
||||
})
|
||||
const skills = Layer.mock(Skill.Service, {
|
||||
get: (id) => Effect.succeed(current.find((skill) => skill.id === id)),
|
||||
files: () => Effect.undefined,
|
||||
list: () => Effect.succeed(current),
|
||||
})
|
||||
const skillToolLayer = AppNodeBuilder.build(LayerNode.group([Tool.node, skillToolNode]), [
|
||||
|
||||
@@ -121,7 +121,13 @@ export function useOpenInApp(input: { session: MountedSession; path: () => strin
|
||||
|
||||
const request = input.request ?? { app: () => local.app, set: (app: OpenApp | undefined) => setLocal("app", app) }
|
||||
|
||||
const canOpen = createMemo(() => !!desktop && input.session.server.local)
|
||||
const canOpen = createMemo(
|
||||
() =>
|
||||
!!desktop &&
|
||||
input.session.server.local &&
|
||||
!input.path().startsWith("skill://") &&
|
||||
!input.path().startsWith("/builtin/"),
|
||||
)
|
||||
|
||||
const current = createMemo(
|
||||
() =>
|
||||
|
||||
@@ -13,6 +13,10 @@ describe("resolveOpenInAppPath", () => {
|
||||
expect(resolveOpenInAppPath("C:/workspace", "\\\\server\\share\\file.ts")).toBe("\\\\server\\share\\file.ts")
|
||||
expect(resolveOpenInAppPath("C:/workspace", "\\src\\file.ts")).toBe("\\src\\file.ts")
|
||||
})
|
||||
|
||||
test("keeps in-memory skill URIs out of the workspace", () => {
|
||||
expect(resolveOpenInAppPath("/workspace", "skill://report/SKILL.md")).toBe("skill://report/SKILL.md")
|
||||
})
|
||||
})
|
||||
|
||||
describe("openInAppParentPath", () => {
|
||||
|
||||
@@ -18,6 +18,9 @@ export const workspaceFileUrl = (root: string, path: string) =>
|
||||
|
||||
export function resolveOpenInAppPath(root: string, path: string) {
|
||||
if (!path) return root
|
||||
|
||||
if (path.startsWith("skill://")) return path
|
||||
|
||||
const windowsRoot = root.startsWith("\\\\") || /^[A-Za-z]:[\\/]/.test(root)
|
||||
|
||||
if (path.startsWith("/") || (windowsRoot && path.startsWith("\\")) || /^[A-Za-z]:[\\/]/.test(path)) return path
|
||||
|
||||
@@ -528,7 +528,7 @@ const setup: Plugin.Setup<typeof File> = (ctx) => {
|
||||
const resolve = (files: Files, value: string, base?: string) => {
|
||||
const root = files.root.replaceAll("\\", "/").replace(/\/+$/, "")
|
||||
|
||||
if (/^[a-z]:\//i.test(value) || value.startsWith("/")) return files.resolve(value)
|
||||
if (/^skill:\/\//i.test(value) || /^[a-z]:\//i.test(value) || value.startsWith("/")) return files.resolve(value)
|
||||
|
||||
const relative = resolveArtifactPath(base ?? "", value)
|
||||
|
||||
|
||||
@@ -58,6 +58,8 @@ describe("parseFileLink", () => {
|
||||
["a%2520b.ts", "a%2520b.ts", undefined],
|
||||
["C:/foo/../../x.ts", "C:/x.ts", undefined],
|
||||
["file:///C:/tmp/demo%20file.ts:12", "C:/tmp/demo file.ts", { start: 12, end: 12 }],
|
||||
["skill://opencode/SKILL.md", "skill://opencode/SKILL.md", undefined],
|
||||
["skill://guide/references/style.md:12", "skill://guide/references/style.md", { start: 12, end: 12 }],
|
||||
])("parses %s", (href, expectedPath, expectedSelection) => {
|
||||
const parsed = parseFileLink(href)
|
||||
expect(parsed.path).toBe(expectedPath)
|
||||
|
||||
@@ -25,7 +25,7 @@ export function parseFileLink(href: string): ParsedFileLink {
|
||||
}
|
||||
|
||||
export function isAbsoluteLink(path: string) {
|
||||
return /^[a-z]:\//i.test(path) || path.startsWith("/")
|
||||
return /^skill:\/\//i.test(path) || /^[a-z]:\//i.test(path) || path.startsWith("/")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,10 +101,20 @@ function normalizeRelativeSegments(input: string, decode: boolean): string {
|
||||
|
||||
if (!trimmed) return ""
|
||||
|
||||
const unc = trimmed.startsWith("//")
|
||||
const skill = /^skill:\/\//i.test(trimmed)
|
||||
const unc = !skill && trimmed.startsWith("//")
|
||||
const driveMatch = trimmed.match(/^([a-z]:)\/(.*)$/i)
|
||||
const prefix = unc ? "//" : driveMatch ? `${driveMatch[1]}/` : trimmed.startsWith("/") ? "/" : ""
|
||||
const rest = unc ? trimmed.slice(2) : driveMatch ? (driveMatch[2] ?? "") : prefix ? trimmed.slice(1) : trimmed
|
||||
const prefix = skill ? "skill://" : unc ? "//" : driveMatch ? `${driveMatch[1]}/` : trimmed.startsWith("/") ? "/" : ""
|
||||
|
||||
const rest = skill
|
||||
? trimmed.slice("skill://".length)
|
||||
: unc
|
||||
? trimmed.slice(2)
|
||||
: driveMatch
|
||||
? (driveMatch[2] ?? "")
|
||||
: prefix
|
||||
? trimmed.slice(1)
|
||||
: trimmed
|
||||
|
||||
const out = rest.split("/").reduce<string[]>((acc, part) => {
|
||||
if (!part || part === ".") return acc
|
||||
|
||||
@@ -12,7 +12,7 @@ export const info = Skill.Info.make({
|
||||
name: Skill.Name.make("Browser"),
|
||||
description:
|
||||
"Use the in-app browser: open and read pages, click and fill forms, take screenshots, check console and network logs, and profile performance and memory. Load it before your first browser tool call.",
|
||||
path: AbsolutePath.make("/builtin/browser.md"),
|
||||
path: AbsolutePath.make("skill://browser/SKILL.md"),
|
||||
content: [
|
||||
"# In-app browser",
|
||||
"",
|
||||
|
||||
@@ -4,11 +4,16 @@ import { basename, dirname } from "node:path"
|
||||
import { Effect } from "effect"
|
||||
import { Browser } from "../src/rpc.js"
|
||||
import { BrowserFiles } from "../src/files.js"
|
||||
import { BrowserSkill } from "../src/skill.js"
|
||||
import { BrowserTools } from "../src/tools.js"
|
||||
|
||||
const tabID = Browser.TabID.make(`tab_${crypto.randomUUID()}`)
|
||||
const navigate = (url: string) => BrowserTools.normalizeAction({ type: "navigate", tabID, url })
|
||||
|
||||
test("built-in browser skill uses a virtual skill:// URI", () => {
|
||||
expect(String(BrowserSkill.info.path)).toBe("skill://browser/SKILL.md")
|
||||
})
|
||||
|
||||
test("URL normalization rejects filesystem paths instead of treating them as hostnames", () => {
|
||||
for (const path of ["/tmp/page.html", "./page.html", "../page.html", "C:\\Users\\me\\page.html", "D:/page.html"])
|
||||
expect(() => navigate(path)).toThrow("Unsupported browser URL")
|
||||
|
||||
Reference in New Issue
Block a user