mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
refactor(core): keep one entry per skill and parse skill paths at the edge (#66285)
This commit is contained in:
parent
fcc2732693
commit
8ec08f4913
7 changed files with 216 additions and 99 deletions
|
|
@ -99,10 +99,10 @@ export const Plugin = define({
|
|||
state.registered.set(key(skill.server, skill.entry.uri), id)
|
||||
const root = skill.entry.uri.slice(0, skill.entry.uri.lastIndexOf("/") + 1)
|
||||
const files = skill.entry.resources.flatMap((resource) => {
|
||||
const file = resource.uri.startsWith(root) ? resource.uri.slice(root.length) : ""
|
||||
return SkillDiscovery.isSafeRelativePath(file) ? [{ file, digest: resource.digest }] : []
|
||||
const file = resource.uri.startsWith(root) ? Skill.parseFilePath(resource.uri.slice(root.length)) : undefined
|
||||
return file ? [{ file, digest: resource.digest }] : []
|
||||
})
|
||||
const digest = files.find((item) => item.file === "SKILL.md")?.digest ?? ""
|
||||
const digest = files.find((item) => item.file === Skill.manifest)?.digest ?? ""
|
||||
editor.add(
|
||||
{
|
||||
id,
|
||||
|
|
|
|||
|
|
@ -3,11 +3,12 @@ export * as Skill from "./skill.js"
|
|||
import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import path from "path"
|
||||
import { Context, Effect, Layer, Schema, Types } from "effect"
|
||||
import { Brand, Context, Effect, Layer, Schema, Types } from "effect"
|
||||
import { Skill } from "@opencode/schema/skill"
|
||||
import { Bus } from "./bus.js"
|
||||
import { PermissionPolicy } from "./permission/policy.js"
|
||||
import { State } from "./state.js"
|
||||
import { SkillDiscovery } from "./skill/discovery.js"
|
||||
|
||||
export const DirectorySource = Skill.DirectorySource
|
||||
export type DirectorySource = Skill.DirectorySource
|
||||
|
|
@ -63,8 +64,43 @@ export const uri = (id: string, file?: string) => (file ? `skill://${id}/${file}
|
|||
|
||||
export const isUri = (value: string) => value.startsWith("skill://")
|
||||
|
||||
/** Where a skill's files live: a folder on disk, or only in the registry under `skill://<id>/`. */
|
||||
export type Location = { readonly _tag: "disk"; readonly directory: string } | { readonly _tag: "virtual" }
|
||||
|
||||
export const locate = (skill: Pick<Info, "path">): Location =>
|
||||
isUri(skill.path) ? { _tag: "virtual" } : { _tag: "disk", directory: path.dirname(skill.path) }
|
||||
|
||||
/** A safe path relative to a skill's folder, such as `references/FORMS.md`. Only the parsers below produce one. */
|
||||
export type FilePath = string & Brand.Brand<"Skill.FilePath">
|
||||
const FilePath = Brand.nominal<FilePath>()
|
||||
|
||||
export const manifest = FilePath("SKILL.md")
|
||||
|
||||
export const parseFilePath = (value: string): FilePath | undefined =>
|
||||
SkillDiscovery.isSafeRelativePath(value) ? FilePath(value) : undefined
|
||||
|
||||
/** A `skill://<id>/<file>` path, parsed. `file` is absent for the skill's folder. */
|
||||
export interface Address {
|
||||
readonly id: ID
|
||||
readonly file?: FilePath
|
||||
/** The canonical form, so `skill://id/file/` can't slip past a rule for `skill://id/file`. */
|
||||
readonly uri: string
|
||||
}
|
||||
|
||||
export const parseAddress = (value: string): Address | undefined => {
|
||||
if (!isUri(value)) return undefined
|
||||
const trimmed = value.slice("skill://".length).replace(/\/+$/, "")
|
||||
const slash = trimmed.indexOf("/")
|
||||
const id = slash === -1 ? trimmed : trimmed.slice(0, slash)
|
||||
if (!SkillDiscovery.isSafeSegment(id)) return undefined
|
||||
if (slash === -1) return { id: ID.make(id), uri: uri(id) }
|
||||
const file = parseFilePath(trimmed.slice(slash + 1))
|
||||
return file && { id: ID.make(id), file, uri: uri(id, file) }
|
||||
}
|
||||
|
||||
export const toModelOutput = (skill: Info, files: ReadonlyArray<string>) => {
|
||||
const directory = isUri(skill.path) ? uri(skill.id) : path.dirname(skill.path)
|
||||
const location = locate(skill)
|
||||
const directory = location._tag === "virtual" ? uri(skill.id) : location.directory
|
||||
return [
|
||||
`<skill_content name="${skill.name}">`,
|
||||
`# Skill: ${skill.name}`,
|
||||
|
|
@ -85,12 +121,13 @@ export const toModelOutput = (skill: Info, files: ReadonlyArray<string>) => {
|
|||
export const prepare = Effect.fn("Skill.prepare")(function* (
|
||||
fs: FSUtil.Interface,
|
||||
skill: Info,
|
||||
virtualFiles?: ReadonlyArray<string>,
|
||||
virtualFiles?: ReadonlyArray<FilePath>,
|
||||
) {
|
||||
if (isUri(skill.path)) {
|
||||
const location = locate(skill)
|
||||
if (location._tag === "virtual") {
|
||||
const directory = uri(skill.id)
|
||||
const files = (virtualFiles ?? [])
|
||||
.filter((file) => file !== "SKILL.md")
|
||||
.filter((file) => file !== manifest)
|
||||
.toSorted()
|
||||
.slice(0, 10)
|
||||
.map((file) => uri(skill.id, file))
|
||||
|
|
@ -99,7 +136,7 @@ export const prepare = Effect.fn("Skill.prepare")(function* (
|
|||
output: toModelOutput(skill, files),
|
||||
}
|
||||
}
|
||||
const directory = path.dirname(skill.path)
|
||||
const directory = location.directory
|
||||
const files =
|
||||
path.basename(skill.path) === "SKILL.md"
|
||||
? (yield* fs.scan("**/*", {
|
||||
|
|
@ -119,11 +156,17 @@ export const prepare = Effect.fn("Skill.prepare")(function* (
|
|||
}
|
||||
})
|
||||
|
||||
type Entry = {
|
||||
readonly info: Types.DeepMutable<Info>
|
||||
/** Loads the SKILL.md body on first use while `info.content` is empty. */
|
||||
readonly load?: Effect.Effect<string, LoadError>
|
||||
/** Virtual files besides SKILL.md. */
|
||||
readonly files: ReadonlyMap<FilePath, File>
|
||||
readonly origin?: Origin
|
||||
}
|
||||
|
||||
export type Data = {
|
||||
skills: Map<ID, Types.DeepMutable<Info>>
|
||||
files: Map<ID, ReadonlyMap<string, File>>
|
||||
loaders: Map<ID, Effect.Effect<string, LoadError>>
|
||||
origins: Map<ID, Origin>
|
||||
entries: Map<ID, Entry>
|
||||
resolvers: Resolver[]
|
||||
}
|
||||
|
||||
|
|
@ -146,12 +189,12 @@ export interface Interface extends State.Transformable<Editor> {
|
|||
/** The skill's SKILL.md body, loaded when the skill doesn't have it inline. */
|
||||
readonly content: (id: ID) => Effect.Effect<string, LoadError>
|
||||
/** Paths of the skill's virtual files besides SKILL.md. */
|
||||
readonly files: (id: ID) => Effect.Effect<ReadonlyArray<string> | undefined>
|
||||
readonly files: (id: ID) => Effect.Effect<ReadonlyArray<FilePath> | undefined>
|
||||
/**
|
||||
* One file of a skill by its path relative to the skill's folder, loaded when it isn't inline. `SKILL.md` is the
|
||||
* body without frontmatter. Any path that isn't one of the skill's files, unsafe ones included, is not found.
|
||||
* body without frontmatter. Any path that isn't one of the skill's files is not found.
|
||||
*/
|
||||
readonly read: (id: ID, file: string) => Effect.Effect<Uint8Array, NotFoundError | FileNotFoundError | LoadError>
|
||||
readonly read: (id: ID, file: FilePath) => Effect.Effect<Uint8Array, NotFoundError | FileNotFoundError | LoadError>
|
||||
readonly list: () => Effect.Effect<Info[]>
|
||||
/** The skill with this ID, or the one a resolver finds for it. */
|
||||
readonly resolve: (id: string) => Effect.Effect<Info | undefined, LoadError>
|
||||
|
|
@ -168,101 +211,93 @@ const layer = Layer.effect(
|
|||
|
||||
const state = State.create<Data, Editor>({
|
||||
name: "skill",
|
||||
initial: () => ({ skills: new Map(), files: new Map(), loaders: new Map(), origins: new Map(), resolvers: [] }),
|
||||
initial: () => ({ entries: new Map(), resolvers: [] }),
|
||||
editor: (editor) => ({
|
||||
list: () => Array.from(editor.skills.values()),
|
||||
get: (id) => editor.skills.get(ID.make(id)),
|
||||
list: () => Array.from(editor.entries.values(), (entry) => entry.info),
|
||||
get: (id) => editor.entries.get(ID.make(id))?.info,
|
||||
add: (skill, files, origin) => {
|
||||
const content = skill.content
|
||||
editor.skills.set(skill.id, { ...skill, content: typeof content === "string" ? content : "" })
|
||||
editor.loaders.delete(skill.id)
|
||||
if (typeof content !== "string") editor.loaders.set(skill.id, content)
|
||||
editor.origins.delete(skill.id)
|
||||
if (origin) editor.origins.set(skill.id, origin)
|
||||
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))
|
||||
editor.entries.set(skill.id, {
|
||||
info: { ...skill, content: typeof content === "string" ? content : "" },
|
||||
...(typeof content === "string" ? {} : { load: content }),
|
||||
// Files are named by whoever adds the skill, so unsafe paths are dropped here.
|
||||
files: new Map(
|
||||
Object.entries(files ?? {})
|
||||
.flatMap(([file, value]) => {
|
||||
const parsed = parseFilePath(file)
|
||||
return parsed && parsed !== manifest ? [[parsed, value] as const] : []
|
||||
})
|
||||
.toSorted(([a], [b]) => a.localeCompare(b)),
|
||||
),
|
||||
origin,
|
||||
})
|
||||
},
|
||||
update: (id, update) => {
|
||||
const key = ID.make(id)
|
||||
const current = editor.skills.get(key)
|
||||
if (!current) return
|
||||
update(current)
|
||||
current.id = key
|
||||
const entry = editor.entries.get(key)
|
||||
if (!entry) return
|
||||
update(entry.info)
|
||||
entry.info.id = key
|
||||
},
|
||||
remove: (id) => {
|
||||
const key = ID.make(id)
|
||||
editor.skills.delete(key)
|
||||
editor.files.delete(key)
|
||||
editor.loaders.delete(key)
|
||||
editor.origins.delete(key)
|
||||
editor.entries.delete(ID.make(id))
|
||||
},
|
||||
resolve: (resolver) => {
|
||||
editor.resolvers.push(resolver)
|
||||
},
|
||||
}),
|
||||
notify: State.changes(
|
||||
(data) => [
|
||||
Array.from(data.skills.values()),
|
||||
Array.from(data.files, ([id, entries]) => [
|
||||
id,
|
||||
Array.from(entries, ([file, value]) => [file, Effect.isEffect(value) ? null : value]),
|
||||
(data) =>
|
||||
Array.from(data.entries.values(), (entry) => [
|
||||
entry.info,
|
||||
Array.from(entry.files, ([file, value]) => [file, Effect.isEffect(value) ? null : value]),
|
||||
]),
|
||||
],
|
||||
() => bus.publish(Skill.Event.Updated, {}).pipe(Effect.asVoid),
|
||||
),
|
||||
})
|
||||
|
||||
const content = Effect.fn("Skill.content")(function* (id: ID) {
|
||||
const current = state.get()
|
||||
const loader = current.loaders.get(id)
|
||||
const inline = current.skills.get(id)?.content ?? ""
|
||||
if (inline || !loader) return inline
|
||||
return yield* loader
|
||||
const entry = state.get().entries.get(id)
|
||||
if (!entry) return ""
|
||||
// A plugin can set `content` on a lazy skill, and what it set wins.
|
||||
if (!entry.load || entry.info.content) return entry.info.content
|
||||
return yield* entry.load
|
||||
})
|
||||
|
||||
return Service.of({
|
||||
transform: state.transform,
|
||||
reload: state.reload,
|
||||
get: Effect.fn("Skill.get")(function* (id) {
|
||||
return state.get().skills.get(id)
|
||||
return state.get().entries.get(id)?.info
|
||||
}),
|
||||
content,
|
||||
files: Effect.fn("Skill.files")(function* (id) {
|
||||
const current = state.get()
|
||||
if (!current.skills.has(id)) return undefined
|
||||
return Array.from(current.files.get(id)?.keys() ?? [])
|
||||
const entry = state.get().entries.get(id)
|
||||
return entry && Array.from(entry.files.keys())
|
||||
}),
|
||||
read: Effect.fn("Skill.read")(function* (id, file) {
|
||||
const current = state.get()
|
||||
if (!current.skills.has(id)) return yield* new NotFoundError({ skill: id })
|
||||
const value = file === "SKILL.md" ? yield* content(id) : current.files.get(id)?.get(file)
|
||||
const entry = state.get().entries.get(id)
|
||||
if (!entry) return yield* new NotFoundError({ skill: id })
|
||||
const value = file === manifest ? yield* content(id) : entry.files.get(file)
|
||||
if (value === undefined) return yield* new FileNotFoundError({ skill: id, file })
|
||||
const loaded = typeof value === "string" || value instanceof Uint8Array ? value : yield* value
|
||||
return typeof loaded === "string" ? new TextEncoder().encode(loaded) : loaded
|
||||
}),
|
||||
list: Effect.fn("Skill.list")(function* () {
|
||||
return Array.from(state.get().skills.values())
|
||||
return Array.from(state.get().entries.values(), (entry) => entry.info)
|
||||
}),
|
||||
resolve: Effect.fn("Skill.resolve")(function* (id) {
|
||||
const known = state.get().skills.get(ID.make(id))
|
||||
if (known) return known
|
||||
const known = state.get().entries.get(ID.make(id))
|
||||
if (known) return known.info
|
||||
for (const resolver of state.get().resolvers) {
|
||||
const found = yield* resolver(id)
|
||||
if (found) return state.get().skills.get(found)
|
||||
if (found) return state.get().entries.get(found)?.info
|
||||
}
|
||||
return undefined
|
||||
}),
|
||||
instructions: Effect.fn("Skill.instructions")(function* (id) {
|
||||
const body = yield* content(id)
|
||||
const origin = state.get().origins.get(id)
|
||||
const origin = state.get().entries.get(id)?.origin
|
||||
if (!origin) return body
|
||||
return `This skill comes from MCP server "${origin.server}", not from this machine.\n\n${body}`
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ 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"
|
||||
|
||||
|
|
@ -74,13 +73,13 @@ export const Plugin = {
|
|||
const workingDirectory = yield* currentWorkingDirectory
|
||||
if (input.limit === 0) return yield* new ToolFailure({ message: "Limit must be a positive integer" })
|
||||
if (Skill.isUri(input.path)) {
|
||||
const parsed = parseSkillUri(input.path)
|
||||
const parsed = Skill.parseAddress(input.path)
|
||||
if (!parsed) return yield* new ToolFailure({ message: `File not found: ${input.path}` })
|
||||
const id = Skill.ID.make(parsed.id)
|
||||
const id = parsed.id
|
||||
const skill = yield* skills.get(id)
|
||||
if (!skill || !Skill.isUri(skill.path))
|
||||
if (!skill || Skill.locate(skill)._tag !== "virtual")
|
||||
return yield* new ToolFailure({ message: `File not found: ${input.path}` })
|
||||
const files = ["SKILL.md", ...((yield* skills.files(id)) ?? [])]
|
||||
const files = [Skill.manifest, ...((yield* skills.files(id)) ?? [])]
|
||||
yield* permission.assert({
|
||||
action: "skill",
|
||||
resources: [skill.id],
|
||||
|
|
@ -98,7 +97,7 @@ export const Plugin = {
|
|||
yield* Effect.forEach(
|
||||
files,
|
||||
(file) =>
|
||||
(file === parsed.target.slice(1) ? skills.read(id, file) : Effect.succeed(new Uint8Array())).pipe(
|
||||
(file === parsed.file ? skills.read(id, file) : Effect.succeed(new Uint8Array())).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ToolFailure({
|
||||
|
|
@ -112,10 +111,15 @@ export const Plugin = {
|
|||
),
|
||||
{ discard: true },
|
||||
)
|
||||
const output = yield* ReadToolFileSystem.read(virtualFs, AbsolutePath.make(parsed.target), input.path, {
|
||||
offset: input.offset,
|
||||
limit: input.limit,
|
||||
}).pipe(
|
||||
const output = yield* ReadToolFileSystem.read(
|
||||
virtualFs,
|
||||
AbsolutePath.make(`/${parsed.file ?? ""}`),
|
||||
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}` })),
|
||||
|
|
@ -348,17 +352,6 @@ const editDistance = (a: string, b: string) => {
|
|||
return previous[b.length]
|
||||
}
|
||||
|
||||
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) }
|
||||
}
|
||||
|
||||
const toOutput = (
|
||||
output: ReadToolFileSystem.TextPage | ReadToolFileSystem.DirectoryContent | ReadToolFileSystem.Media,
|
||||
): ReadToolFileSystem.Output => {
|
||||
|
|
|
|||
|
|
@ -69,6 +69,11 @@ const it = testEffect(
|
|||
const DEPLOY = "---\nname: deploy\ndescription: Deploy the app\n---\n# Deploy\n\nRun scripts/run.sh.\n"
|
||||
const deploy = { "SKILL.md": DEPLOY, "scripts/run.sh": "echo run" }
|
||||
const id = Skill.ID.make("team:deploy")
|
||||
const script = (() => {
|
||||
const parsed = Skill.parseFilePath("scripts/run.sh")
|
||||
if (!parsed) throw new Error("scripts/run.sh should be a safe skill file path")
|
||||
return parsed
|
||||
})()
|
||||
|
||||
/**
|
||||
* A Streamable HTTP MCP server publishing skills through the SDK's skills extension. Keys are skill folders below
|
||||
|
|
@ -172,7 +177,7 @@ describe("MCP skills", () => {
|
|||
},
|
||||
])
|
||||
const skills = yield* Skill.Service
|
||||
expect(yield* skills.files(id)).toEqual(["scripts/run.sh"])
|
||||
expect((yield* skills.files(id))?.map(String)).toEqual(["scripts/run.sh"])
|
||||
expect(server.state.reads).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
|
@ -222,11 +227,11 @@ describe("MCP skills", () => {
|
|||
expect(yield* skills.instructions(id)).toBe(
|
||||
'This skill comes from MCP server "team", not from this machine.\n\n# Deploy\n\nRun scripts/run.sh.\n',
|
||||
)
|
||||
expect(new TextDecoder().decode(yield* skills.read(id, "scripts/run.sh"))).toBe("echo run")
|
||||
expect(new TextDecoder().decode(yield* skills.read(id, script))).toBe("echo run")
|
||||
// Once loaded, the content is listed and nothing is read again.
|
||||
yield* eventually(skills.get(id), (skill) => skill?.content === "# Deploy\n\nRun scripts/run.sh.\n")
|
||||
yield* skills.content(id)
|
||||
yield* skills.read(id, "scripts/run.sh")
|
||||
yield* skills.read(id, script)
|
||||
expect(server.state.reads).toEqual(["skill://deploy/SKILL.md", "skill://deploy/scripts/run.sh"])
|
||||
}),
|
||||
)
|
||||
|
|
@ -243,7 +248,7 @@ describe("MCP skills", () => {
|
|||
expect(content).toBeInstanceOf(Skill.LoadError)
|
||||
expect(content.message).toStartWith("Failed to load SKILL.md of MCP skill team:deploy: ")
|
||||
expect(content.message).toContain("digest")
|
||||
const file = yield* skills.read(id, "scripts/run.sh").pipe(Effect.flip)
|
||||
const file = yield* skills.read(id, script).pipe(Effect.flip)
|
||||
expect(file.message).toContain("digest")
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { describe, expect } from "bun:test"
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Deferred, Effect, Fiber, Layer, Stream } from "effect"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { PermissionPolicy } from "@opencode/core/permission/policy"
|
||||
|
|
@ -32,6 +32,57 @@ const info = (id: string, description: string) =>
|
|||
content: `# ${id}`,
|
||||
})
|
||||
|
||||
const file = (value: string) => {
|
||||
const parsed = Skill.parseFilePath(value)
|
||||
if (!parsed) throw new Error(`unsafe test path: ${value}`)
|
||||
return parsed
|
||||
}
|
||||
|
||||
describe("Skill.parseAddress", () => {
|
||||
test("parses skill:// paths into an ID, a file and the canonical URI", () => {
|
||||
const address = Skill.parseAddress("skill://docs:pdf/references/FORMS.md")
|
||||
expect(address?.id).toBe(Skill.ID.make("docs:pdf"))
|
||||
expect(String(address?.file)).toBe("references/FORMS.md")
|
||||
expect(address?.uri).toBe("skill://docs:pdf/references/FORMS.md")
|
||||
expect(Skill.parseAddress("skill://docs:pdf/references/")?.uri).toBe("skill://docs:pdf/references")
|
||||
expect(Skill.parseAddress("skill://docs:pdf/")?.uri).toBe("skill://docs:pdf")
|
||||
const folder = Skill.parseAddress("skill://docs:pdf")
|
||||
expect(folder?.file).toBeUndefined()
|
||||
expect(folder?.uri).toBe("skill://docs:pdf")
|
||||
})
|
||||
|
||||
test("refuses anything that isn't a safe skill:// path", () => {
|
||||
for (const value of [
|
||||
"/skills/pdf/SKILL.md",
|
||||
"skill://",
|
||||
"skill://../x",
|
||||
"skill://pdf/../secret",
|
||||
"skill://pdf/a\\b",
|
||||
])
|
||||
expect(Skill.parseAddress(value)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe("Skill.parseFilePath", () => {
|
||||
test("accepts paths inside a skill's folder and nothing else", () => {
|
||||
expect(String(Skill.parseFilePath("references/FORMS.md"))).toBe("references/FORMS.md")
|
||||
for (const value of [
|
||||
"",
|
||||
".",
|
||||
"../secret",
|
||||
"a/../../b",
|
||||
"%2e%2e/x",
|
||||
"a#b",
|
||||
"a?b",
|
||||
"/etc/passwd",
|
||||
"C:\\x",
|
||||
"https://x/y",
|
||||
"a\\b",
|
||||
])
|
||||
expect(Skill.parseFilePath(value)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe("Skill", () => {
|
||||
it.live("hides and refuses denied skills while organization policy overrides local allows", () =>
|
||||
Effect.gen(function* () {
|
||||
|
|
@ -224,14 +275,40 @@ describe("Skill", () => {
|
|||
const id = Skill.ID.make("remote")
|
||||
|
||||
expect((yield* skill.list()).map((item) => item.content)).toEqual([""])
|
||||
expect(yield* skill.files(id)).toEqual(["references/a.md", "references/b.md"])
|
||||
expect((yield* skill.files(id))?.map(String)).toEqual(["references/a.md", "references/b.md"])
|
||||
expect(loaded).toEqual([])
|
||||
expect(yield* skill.content(id)).toBe("# remote")
|
||||
expect(new TextDecoder().decode(yield* skill.read(id, "references/a.md"))).toBe("A")
|
||||
expect(new TextDecoder().decode(yield* skill.read(id, file("references/a.md")))).toBe("A")
|
||||
expect(loaded).toEqual(["SKILL.md", "references/a.md"])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("drops file names that aren't safe paths when a skill is added", () =>
|
||||
Effect.gen(function* () {
|
||||
const skill = yield* Skill.Service
|
||||
yield* skill.transform((editor) =>
|
||||
editor.add(
|
||||
{ ...info("bundle", "Bundle"), path: AbsolutePath.make(Skill.uri("bundle", "SKILL.md")) },
|
||||
{ "references/a.md": "A", "../secret": "no", "/etc/passwd": "no", "a?b": "no" },
|
||||
),
|
||||
)
|
||||
expect((yield* skill.files(Skill.ID.make("bundle")))?.map(String)).toEqual(["references/a.md"])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("uses content a plugin sets on a lazy skill instead of loading it", () =>
|
||||
Effect.gen(function* () {
|
||||
const skill = yield* Skill.Service
|
||||
yield* skill.transform((editor) => {
|
||||
editor.add({ ...info("remote", "Remote"), content: Effect.die("loaded") })
|
||||
editor.update("remote", (draft) => {
|
||||
draft.content = "# Set by a plugin"
|
||||
})
|
||||
})
|
||||
expect(yield* skill.content(Skill.ID.make("remote"))).toBe("# Set by a plugin")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("filters values by agent permissions", () =>
|
||||
Effect.gen(function* () {
|
||||
const agents = yield* Agent.Service
|
||||
|
|
@ -264,9 +341,9 @@ describe("Skill", () => {
|
|||
})
|
||||
|
||||
const files = yield* skill.files(Skill.ID.make("review"))
|
||||
expect(files).toEqual(["references/a.md", "references/b.md"])
|
||||
expect(new TextDecoder().decode(yield* skill.read(Skill.ID.make("review"), "references/a.md"))).toBe("A")
|
||||
expect((yield* skill.read(Skill.ID.make("review"), "../secret").pipe(Effect.flip))._tag).toBe(
|
||||
expect(files?.map(String)).toEqual(["references/a.md", "references/b.md"])
|
||||
expect(new TextDecoder().decode(yield* skill.read(Skill.ID.make("review"), file("references/a.md")))).toBe("A")
|
||||
expect((yield* skill.read(Skill.ID.make("review"), file("missing.md")).pipe(Effect.flip))._tag).toBe(
|
||||
"Skill.FileNotFoundError",
|
||||
)
|
||||
const fs = yield* FSUtil.Service
|
||||
|
|
|
|||
|
|
@ -13,10 +13,12 @@ export const SkillHandler = HttpApiBuilder.group(Api, "server.skill", (handlers)
|
|||
const skills = yield* Skill.Service
|
||||
// The path after /api/experimental/skill/<id>/file/.
|
||||
const raw = new URL(ctx.request.url, "http://localhost").pathname.split("/").slice(6).join("/")
|
||||
const notFound = new FileNotFoundError({ path: raw, message: `File not found: ${raw}` })
|
||||
const file = yield* Effect.try({
|
||||
try: () => decodeURIComponent(raw),
|
||||
catch: () => new FileNotFoundError({ path: raw, message: `File not found: ${raw}` }),
|
||||
try: () => Skill.parseFilePath(decodeURIComponent(raw)),
|
||||
catch: () => notFound,
|
||||
})
|
||||
if (!file) return yield* notFound
|
||||
return yield* skills.read(ctx.params.skillID, file).pipe(
|
||||
Effect.catchTags({
|
||||
"Skill.NotFoundError": (error) =>
|
||||
|
|
|
|||
|
|
@ -46,6 +46,11 @@ it.live("lists configured skills and reads their files", () =>
|
|||
const missingFile = yield* file("demo", "other.md")
|
||||
expect(missingFile.status).toBe(404)
|
||||
expect(yield* Effect.promise(() => missingFile.json())).toMatchObject({ _tag: "FileNotFoundError" })
|
||||
const unsafe = yield* file("demo", "..%2Fsecret")
|
||||
expect(unsafe.status).toBe(404)
|
||||
expect(yield* Effect.promise(() => unsafe.json())).toMatchObject({ _tag: "FileNotFoundError" })
|
||||
// The router itself refuses a path that isn't valid percent-encoding.
|
||||
expect((yield* file("demo", "%ZZ")).status).toBe(404)
|
||||
const missingSkill = yield* file("missing", "SKILL.md")
|
||||
expect(missingSkill.status).toBe(404)
|
||||
expect(yield* Effect.promise(() => missingSkill.json())).toMatchObject({ _tag: "SkillNotFoundError" })
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue