feat(core): add experimental artifacts with pluggable providers (#60351)

This commit is contained in:
Kit Langton
2026-10-30 06:19:18 -07:00
committed by GitHub
Unverified
parent 1e28374e48
commit 8f0fc21e71
35 changed files with 3263 additions and 1 deletions
+2
View File
@@ -8,6 +8,7 @@ import {
promiseOmitEndpoints,
} from "@opencode/protocol/client"
import { Agent } from "@opencode/schema/agent"
import { Artifact } from "@opencode/schema/artifact"
import { Command } from "@opencode/schema/command"
import { Config } from "@opencode/schema/config"
import { Credential } from "@opencode/schema/credential"
@@ -65,6 +66,7 @@ const effectContract = compile(ClientApi, {
})
const effectTypeReferences = [
...namespaceTypes("Agent", "@opencode/schema/agent", Agent),
...namespaceTypes("Artifact", "@opencode/schema/artifact", Artifact),
...namespaceTypes("Command", "@opencode/schema/command", Command),
...namespaceTypes("Config", "@opencode/schema/config", Config),
...namespaceTypes("Credential", "@opencode/schema/credential", Credential),
+78
View File
@@ -38,6 +38,7 @@ import type { Command } from "@opencode/schema/command"
import type { OpenCodeEvent } from "@opencode/protocol/groups/event"
import type { Pty } from "@opencode/schema/pty"
import type { Schedule } from "@opencode/schema/schedule"
import type { Artifact } from "@opencode/schema/artifact"
import type { Reference } from "@opencode/schema/reference"
import type { Worktree } from "@opencode/schema/worktree"
import type { Vcs } from "@opencode/schema/vcs"
@@ -2129,6 +2130,7 @@ export type EventSubscribeInput = {
| "form.replied"
| "form.cancelled"
| "websearch.updated"
| "artifact.updated"
| "session.status"
| "session.idle"
| "tui.prompt.append"
@@ -2415,6 +2417,74 @@ export type ExperimentalScheduleDeleteOperation<E = never> = (
input: ExperimentalScheduleDeleteInput,
) => Effect.Effect<ExperimentalScheduleDeleteOutput, E>
export type ExperimentalArtifactsProvidersInput = {
readonly location?: { readonly directory?: string | undefined } | undefined
}
export type ExperimentalArtifactsProvidersOutput = {
readonly location: Location.PublicRef
readonly data: ReadonlyArray<Artifact.Provider>
}
export type ExperimentalArtifactsProvidersOperation<E = never> = (
input?: ExperimentalArtifactsProvidersInput,
) => Effect.Effect<ExperimentalArtifactsProvidersOutput, E>
export type ExperimentalArtifactsListInput = {
readonly location?: { readonly directory?: string | undefined } | undefined
readonly sessionID?: Session.ID | undefined
readonly provider?: Artifact.ProviderID | undefined
}
export type ExperimentalArtifactsListOutput = {
readonly location: Location.PublicRef
readonly data: ReadonlyArray<Artifact.Info>
}
export type ExperimentalArtifactsListOperation<E = never> = (
input?: ExperimentalArtifactsListInput,
) => Effect.Effect<ExperimentalArtifactsListOutput, E>
export type ExperimentalArtifactsCreateInput = {
readonly location?: { readonly directory?: string | undefined } | undefined
readonly title: string
readonly files: { readonly [x: string]: string }
readonly entry?: string | undefined
readonly provider?: Artifact.ProviderID | undefined
readonly sessionID?: Session.ID | undefined
}
export type ExperimentalArtifactsCreateOutput = { readonly location: Location.PublicRef; readonly data: Artifact.Info }
export type ExperimentalArtifactsCreateOperation<E = never> = (
input: ExperimentalArtifactsCreateInput,
) => Effect.Effect<ExperimentalArtifactsCreateOutput, E>
export type ExperimentalArtifactsGetInput = {
readonly artifactID: Artifact.ID
readonly location?: { readonly directory?: string | undefined } | undefined
}
export type ExperimentalArtifactsGetOutput = { readonly location: Location.PublicRef; readonly data: Artifact.Content }
export type ExperimentalArtifactsGetOperation<E = never> = (
input: ExperimentalArtifactsGetInput,
) => Effect.Effect<ExperimentalArtifactsGetOutput, E>
export type ExperimentalArtifactsUpdateInput = {
readonly artifactID: Artifact.ID
readonly location?: { readonly directory?: string | undefined } | undefined
readonly title?: string | undefined
readonly files: { readonly [x: string]: string }
readonly entry?: string | undefined
readonly sessionID?: Session.ID | undefined
}
export type ExperimentalArtifactsUpdateOutput = { readonly location: Location.PublicRef; readonly data: Artifact.Info }
export type ExperimentalArtifactsUpdateOperation<E = never> = (
input: ExperimentalArtifactsUpdateInput,
) => Effect.Effect<ExperimentalArtifactsUpdateOutput, E>
export type ExperimentalArtifactsDeleteInput = {
readonly artifactID: Artifact.ID
readonly location?: { readonly directory?: string | undefined } | undefined
}
export type ExperimentalArtifactsDeleteOutput = void
export type ExperimentalArtifactsDeleteOperation<E = never> = (
input: ExperimentalArtifactsDeleteInput,
) => Effect.Effect<ExperimentalArtifactsDeleteOutput, E>
export interface ExperimentalApi<E = never> {
readonly persistentPty: {
readonly read: ExperimentalPersistentPtyReadOperation<E>
@@ -2436,6 +2506,14 @@ export interface ExperimentalApi<E = never> {
readonly resume: ExperimentalScheduleResumeOperation<E>
readonly delete: ExperimentalScheduleDeleteOperation<E>
}
readonly artifacts: {
readonly providers: ExperimentalArtifactsProvidersOperation<E>
readonly list: ExperimentalArtifactsListOperation<E>
readonly create: ExperimentalArtifactsCreateOperation<E>
readonly get: ExperimentalArtifactsGetOperation<E>
readonly update: ExperimentalArtifactsUpdateOperation<E>
readonly delete: ExperimentalArtifactsDeleteOperation<E>
}
}
export type ShellListInput = { readonly location?: { readonly directory?: string | undefined } | undefined }
+77
View File
@@ -255,6 +255,18 @@ import type {
ExperimentalScheduleResumeOutput,
ExperimentalScheduleDeleteInput,
ExperimentalScheduleDeleteOutput,
ExperimentalArtifactsProvidersInput,
ExperimentalArtifactsProvidersOutput,
ExperimentalArtifactsListInput,
ExperimentalArtifactsListOutput,
ExperimentalArtifactsCreateInput,
ExperimentalArtifactsCreateOutput,
ExperimentalArtifactsGetInput,
ExperimentalArtifactsGetOutput,
ExperimentalArtifactsUpdateInput,
ExperimentalArtifactsUpdateOutput,
ExperimentalArtifactsDeleteInput,
ExperimentalArtifactsDeleteOutput,
ShellListInput,
ShellListOutput,
ShellCreateInput,
@@ -1629,6 +1641,63 @@ const EndpointExperimentalScheduleDelete =
raw["schedule.delete"]({ params: { scheduleID: input["scheduleID"] } }).pipe(Effect.mapError(mapClientError)),
)
const EndpointExperimentalArtifactsProviders =
(raw: RawClient["server.experimental"]) => (input?: ExperimentalArtifactsProvidersInput) =>
preserveEffect<ExperimentalArtifactsProvidersOutput>()(
raw["artifacts.providers"]({ query: { location: input?.["location"] } }).pipe(Effect.mapError(mapClientError)),
)
const EndpointExperimentalArtifactsList =
(raw: RawClient["server.experimental"]) => (input?: ExperimentalArtifactsListInput) =>
preserveEffect<ExperimentalArtifactsListOutput>()(
raw["artifacts.list"]({
query: { location: input?.["location"], sessionID: input?.["sessionID"], provider: input?.["provider"] },
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointExperimentalArtifactsCreate =
(raw: RawClient["server.experimental"]) => (input: ExperimentalArtifactsCreateInput) =>
preserveEffect<ExperimentalArtifactsCreateOutput>()(
raw["artifacts.create"]({
query: { location: input["location"] },
payload: {
title: input["title"],
files: input["files"],
entry: input["entry"],
provider: input["provider"],
sessionID: input["sessionID"],
},
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointExperimentalArtifactsGet =
(raw: RawClient["server.experimental"]) => (input: ExperimentalArtifactsGetInput) =>
preserveEffect<ExperimentalArtifactsGetOutput>()(
raw["artifacts.get"]({
params: { artifactID: input["artifactID"] },
query: { location: input["location"] },
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointExperimentalArtifactsUpdate =
(raw: RawClient["server.experimental"]) => (input: ExperimentalArtifactsUpdateInput) =>
preserveEffect<ExperimentalArtifactsUpdateOutput>()(
raw["artifacts.update"]({
params: { artifactID: input["artifactID"] },
query: { location: input["location"] },
payload: { title: input["title"], files: input["files"], entry: input["entry"], sessionID: input["sessionID"] },
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointExperimentalArtifactsDelete =
(raw: RawClient["server.experimental"]) => (input: ExperimentalArtifactsDeleteInput) =>
preserveEffect<ExperimentalArtifactsDeleteOutput>()(
raw["artifacts.delete"]({
params: { artifactID: input["artifactID"] },
query: { location: input["location"] },
}).pipe(Effect.mapError(mapClientError)),
)
const adaptGroupExperimental = (raw: RawClient["server.experimental"]) => ({
persistentPty: {
read: EndpointExperimentalPersistentPtyRead(raw),
@@ -1650,6 +1719,14 @@ const adaptGroupExperimental = (raw: RawClient["server.experimental"]) => ({
resume: EndpointExperimentalScheduleResume(raw),
delete: EndpointExperimentalScheduleDelete(raw),
},
artifacts: {
providers: EndpointExperimentalArtifactsProviders(raw),
list: EndpointExperimentalArtifactsList(raw),
create: EndpointExperimentalArtifactsCreate(raw),
get: EndpointExperimentalArtifactsGet(raw),
update: EndpointExperimentalArtifactsUpdate(raw),
delete: EndpointExperimentalArtifactsDelete(raw),
},
})
const EndpointShellList = (raw: RawClient["server.shell"]) => (input?: ShellListInput) =>
+114
View File
@@ -255,6 +255,20 @@ import type {
ExperimentalScheduleResumeOutput,
ExperimentalScheduleDeleteInput,
ExperimentalScheduleDeleteOutput,
ExperimentalArtifactsProvidersInput,
ExperimentalArtifactsProvidersOutput,
ExperimentalArtifactsListInput,
ExperimentalArtifactsListOutput,
ExperimentalArtifactsCreateInput,
ExperimentalArtifactsCreateOutput,
ExperimentalArtifactsGetInput,
ExperimentalArtifactsGetOutput,
ExperimentalArtifactsUpdateInput,
ExperimentalArtifactsUpdateOutput,
ExperimentalArtifactsDeleteInput,
ExperimentalArtifactsDeleteOutput,
ExperimentalArtifactsViewInput,
ExperimentalArtifactsViewOutput,
ShellListInput,
ShellListOutput,
ShellCreateInput,
@@ -1567,6 +1581,106 @@ export function make(options: ClientOptions) {
requestOptions,
),
},
artifacts: {
providers: (input?: ExperimentalArtifactsProvidersInput, requestOptions?: RequestOptions) =>
request<ExperimentalArtifactsProvidersOutput>(
{
method: "GET",
path: `/api/experimental/artifacts/providers`,
query: { location: input?.["location"] },
successStatus: 200,
declaredStatuses: [400, 401, 403, 404, 503],
empty: false,
},
requestOptions,
),
list: (input?: ExperimentalArtifactsListInput, requestOptions?: RequestOptions) =>
request<ExperimentalArtifactsListOutput>(
{
method: "GET",
path: `/api/experimental/artifacts`,
query: { location: input?.["location"], sessionID: input?.["sessionID"], provider: input?.["provider"] },
successStatus: 200,
declaredStatuses: [400, 401, 403, 404, 503],
empty: false,
},
requestOptions,
),
create: (input: ExperimentalArtifactsCreateInput, requestOptions?: RequestOptions) =>
request<ExperimentalArtifactsCreateOutput>(
{
method: "POST",
path: `/api/experimental/artifacts`,
query: { location: input["location"] },
body: {
title: input["title"],
files: input["files"],
entry: input["entry"],
provider: input["provider"],
sessionID: input["sessionID"],
},
successStatus: 200,
declaredStatuses: [400, 401, 403, 404, 503],
empty: false,
},
requestOptions,
),
get: (input: ExperimentalArtifactsGetInput, requestOptions?: RequestOptions) =>
request<ExperimentalArtifactsGetOutput>(
{
method: "GET",
path: `/api/experimental/artifacts/${encodeURIComponent(input.artifactID)}`,
query: { location: input["location"] },
successStatus: 200,
declaredStatuses: [400, 401, 403, 404, 503],
empty: false,
},
requestOptions,
),
update: (input: ExperimentalArtifactsUpdateInput, requestOptions?: RequestOptions) =>
request<ExperimentalArtifactsUpdateOutput>(
{
method: "PATCH",
path: `/api/experimental/artifacts/${encodeURIComponent(input.artifactID)}`,
query: { location: input["location"] },
body: {
title: input["title"],
files: input["files"],
entry: input["entry"],
sessionID: input["sessionID"],
},
successStatus: 200,
declaredStatuses: [400, 401, 403, 404, 503],
empty: false,
},
requestOptions,
),
delete: (input: ExperimentalArtifactsDeleteInput, requestOptions?: RequestOptions) =>
request<ExperimentalArtifactsDeleteOutput>(
{
method: "DELETE",
path: `/api/experimental/artifacts/${encodeURIComponent(input.artifactID)}`,
query: { location: input["location"] },
successStatus: 204,
declaredStatuses: [400, 401, 403, 404, 503],
empty: true,
},
requestOptions,
),
view: (input: ExperimentalArtifactsViewInput, requestOptions?: RequestOptions) =>
request<ExperimentalArtifactsViewOutput>(
{
method: "GET",
path: `/api/experimental/artifacts/${encodeURIComponent(input.artifactID)}/view/${encodePath(input.path)}`,
query: { location: input["location"] },
successStatus: 200,
declaredStatuses: [400, 401, 403, 404, 503],
empty: false,
binary: true,
},
requestOptions,
),
},
migration: {
v1: {
status: (requestOptions?: RequestOptions) =>
+98
View File
@@ -337,6 +337,12 @@ export type ScheduleStatus = "active" | "paused" | "done"
export type ScheduleOutcome = "fired" | "late" | "checked" | "expired" | "skipped" | "disabled" | "failed"
export type ArtifactCapability = "static" | "server-code" | "sqlite" | "durable-objects"
export type ArtifactID = string
export type ArtifactTime = { created: number; updated: number }
export type ReferenceGitSource = { type: "git"; repository: string; branch?: string }
export type VcsBranch = { current?: string; default?: string }
@@ -913,6 +919,18 @@ export type ScheduleCondition = ScheduleConditionShell | ScheduleConditionCode
export type ScheduleAction = ScheduleActionPrompt
export type ArtifactProvider = { id: string; name: string; capabilities: Array<ArtifactCapability>; default: boolean }
export type ArtifactInfo = {
id: ArtifactID
provider: string
sessionID?: SessionID
title: string
entry: string
url: string
time: ArtifactTime
}
export type VcsInfo = { provider?: string; branch: VcsBranch }
export type WebSearchProvider = { id: WebSearchID; name: string }
@@ -1908,6 +1926,15 @@ export type WebsearchUpdated = {
data: {}
}
export type ArtifactUpdated = {
id: EventID
created: number
metadata?: { [x: string]: any }
type: "artifact.updated"
location?: LocationRef
data: {}
}
export type SessionStatusUpdated = {
id: EventID
created: number
@@ -2150,6 +2177,8 @@ export type FormReplied = {
export type ScheduleWhen = ScheduleWhenIn | ScheduleWhenAt | ScheduleWhenEvery | ScheduleWhenCron
export type ArtifactContent = { info: ArtifactInfo; files: { [x: string]: string } }
export type SessionInboxMove = {
id: SessionMessageID
sessionID: SessionID
@@ -2463,6 +2492,7 @@ export type ConfigEntry =
media_blob?: boolean
image_generate?: boolean | { model?: string | { providerID: string; model: string; variant?: string } }
schedules?: boolean
artifacts?: boolean
subagent_depth?: number
location_idle_timeout?: string | false
policies?: Array<{
@@ -2834,6 +2864,7 @@ export type V2Event =
| FormReplied
| FormCancelled
| WebsearchUpdated
| ArtifactUpdated
| SessionStatusUpdated
| SessionIdle
| TuiPromptAppend
@@ -3130,6 +3161,14 @@ export type ScheduleNotFoundError = {
export const isScheduleNotFoundError = (value: unknown): value is ScheduleNotFoundError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ScheduleNotFoundError"
export type ArtifactNotFoundError = {
readonly _tag: "ArtifactNotFoundError"
readonly artifactID: string
readonly message: string
}
export const isArtifactNotFoundError = (value: unknown): value is ArtifactNotFoundError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ArtifactNotFoundError"
export type ShellNotFoundError = { readonly _tag: "ShellNotFoundError"; readonly id: string; readonly message: string }
export const isShellNotFoundError = (value: unknown): value is ShellNotFoundError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ShellNotFoundError"
@@ -4306,6 +4345,7 @@ export type EventSubscribeInput = {
| "form.replied"
| "form.cancelled"
| "websearch.updated"
| "artifact.updated"
| "session.status"
| "session.idle"
| "tui.prompt.append"
@@ -4522,6 +4562,64 @@ export type ExperimentalScheduleDeleteInput = { readonly scheduleID: string }
export type ExperimentalScheduleDeleteOutput = void
export type ExperimentalArtifactsProvidersInput = {
readonly location?: { readonly directory?: string | undefined } | undefined
}
export type ExperimentalArtifactsProvidersOutput = { location: LocationPublicRef; data: Array<ArtifactProvider> }
export type ExperimentalArtifactsListInput = {
readonly location?: { readonly directory?: string | undefined } | undefined
readonly sessionID?: string | undefined
readonly provider?: string | undefined
}
export type ExperimentalArtifactsListOutput = { location: LocationPublicRef; data: Array<ArtifactInfo> }
export type ExperimentalArtifactsCreateInput = {
readonly location?: { readonly directory?: string | undefined } | undefined
readonly title: string
readonly files: { readonly [x: string]: string }
readonly entry?: string | undefined
readonly provider?: string | undefined
readonly sessionID?: string | undefined
}
export type ExperimentalArtifactsCreateOutput = { location: LocationPublicRef; data: ArtifactInfo }
export type ExperimentalArtifactsGetInput = {
readonly artifactID: string
readonly location?: { readonly directory?: string | undefined } | undefined
}
export type ExperimentalArtifactsGetOutput = { location: LocationPublicRef; data: ArtifactContent }
export type ExperimentalArtifactsUpdateInput = {
readonly artifactID: string
readonly location?: { readonly directory?: string | undefined } | undefined
readonly title?: string | undefined
readonly files: { readonly [x: string]: string }
readonly entry?: string | undefined
readonly sessionID?: string | undefined
}
export type ExperimentalArtifactsUpdateOutput = { location: LocationPublicRef; data: ArtifactInfo }
export type ExperimentalArtifactsDeleteInput = {
readonly artifactID: string
readonly location?: { readonly directory?: string | undefined } | undefined
}
export type ExperimentalArtifactsDeleteOutput = void
export type ExperimentalArtifactsViewInput = {
readonly artifactID: string
readonly location?: { readonly directory?: string | undefined } | undefined
readonly path: string
}
export type ExperimentalArtifactsViewOutput = globalThis.Uint8Array
export type ShellListInput = { readonly location?: { readonly directory?: string | undefined } | undefined }
export type ShellListOutput = { location: LocationPublicRef; data: Array<ShellInfo1> }
+1
View File
@@ -62,6 +62,7 @@ test("exposes every standard HTTP API group", () => {
"persistentPty",
"media",
"schedule",
"artifacts",
"migration",
"usage",
"config",
+615
View File
@@ -0,0 +1,615 @@
export * as Artifact from "./artifact.js"
import { randomUUID } from "node:crypto"
import fs from "node:fs/promises"
import path from "node:path"
import { lookup } from "mime-types"
import {
Capability,
Content,
CreateInput,
Event,
ID,
Info,
Provider,
ProviderID,
UpdateInput,
} from "@opencode/schema/artifact"
import type { SessionID } from "@opencode/schema/session-id"
import { Global } from "@opencode/util/global"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import { Clock, Context, Effect, Layer, Option, Schema } from "effect"
import { Bus } from "./bus.js"
import { Config } from "./config.js"
import { KV } from "./kv.js"
import { Location } from "./location.js"
import { Mime } from "./mime.js"
import { Session } from "./session.js"
import { State } from "./state.js"
export { Capability, Content, CreateInput, Event, ID, Info, Provider, ProviderID, UpdateInput }
export const LocalProviderID = ProviderID.make("local")
const ItemPrefix = "artifact:item:"
export interface ProviderCreateInput {
readonly id: ID
readonly title: string
readonly entry: string
readonly files: Readonly<Record<string, Uint8Array>>
readonly sessionID?: SessionID
}
export interface ProviderUpdateInput {
readonly title: string
readonly entry: string
readonly files: Readonly<Record<string, Uint8Array>>
readonly sessionID?: SessionID
}
export interface ProviderResult {
readonly url?: string
}
export interface ProviderImplementation {
readonly id: ProviderID
readonly name: string
readonly capabilities: readonly Capability[]
readonly prompt: string
readonly create: (input: ProviderCreateInput) => Effect.Effect<ProviderResult, unknown>
readonly read: (id: ID) => Effect.Effect<Readonly<Record<string, Uint8Array>>, unknown>
readonly update: (id: ID, input: ProviderUpdateInput) => Effect.Effect<ProviderResult, unknown>
readonly delete: (id: ID) => Effect.Effect<void, unknown>
}
export interface LocalFile {
readonly bytes: Uint8Array
readonly mime: string
}
export interface ProviderPrompts {
readonly defaultProvider: {
readonly id: ProviderID
readonly name: string
readonly capabilities: readonly Capability[]
readonly prompt: string
}
readonly others: readonly {
readonly id: ProviderID
readonly name: string
readonly capabilities: readonly Capability[]
}[]
}
export class DisabledError extends Schema.TaggedError<DisabledError>()("Artifact.DisabledError", {}) {
override get message() {
return "Artifacts are disabled; set experimental.artifacts in config"
}
}
export class NotFoundError extends Schema.TaggedError<NotFoundError>()("Artifact.NotFoundError", {
artifactID: ID,
}) {
override get message() {
return `Artifact not found: ${this.artifactID}`
}
}
export class FileMissingError extends Schema.TaggedError<FileMissingError>()("Artifact.FileMissingError", {
artifactID: ID,
path: Schema.String,
}) {
override get message() {
return `Artifact file not found: ${this.path}`
}
}
export class ProviderNotFoundError extends Schema.TaggedError<ProviderNotFoundError>()(
"Artifact.ProviderNotFoundError",
{
providerID: ProviderID,
},
) {
override get message() {
return `Artifact provider not found: ${this.providerID}`
}
}
export class InvalidError extends Schema.TaggedError<InvalidError>()("Artifact.InvalidError", {
reason: Schema.String,
field: Schema.optional(Schema.String),
}) {
override get message() {
return this.reason
}
}
export class ProviderError extends Schema.TaggedError<ProviderError>()("Artifact.ProviderError", {
providerID: ProviderID,
cause: Schema.Defect(),
}) {
override get message() {
return this.cause instanceof Error && this.cause.message
? `Artifact provider ${this.providerID} failed: ${this.cause.message}`
: `Artifact provider ${this.providerID} failed`
}
}
export type Error =
| DisabledError
| NotFoundError
| FileMissingError
| ProviderNotFoundError
| InvalidError
| ProviderError
| Session.NotFoundError
export type Editor = {
add: (provider: ProviderImplementation) => void
remove: (id: ProviderID) => void
default: {
get: () => ProviderID | undefined
set: (providerID: ProviderID | undefined) => void
}
}
type Data = {
readonly providers: Map<ProviderID, ProviderImplementation>
selection?: ProviderID
}
export interface Interface extends State.Transformable<Editor> {
readonly enabled: () => Effect.Effect<boolean>
readonly providers: () => Effect.Effect<readonly Provider[], DisabledError>
readonly prompts: () => Effect.Effect<ProviderPrompts>
readonly list: (filter?: {
readonly sessionID?: SessionID
readonly provider?: ProviderID
}) => Effect.Effect<readonly Info[], DisabledError | Session.NotFoundError>
readonly create: (input: CreateInput) => Effect.Effect<Info, Error>
readonly get: (id: ID) => Effect.Effect<Content, DisabledError | NotFoundError | ProviderNotFoundError | ProviderError>
readonly info: (id: ID) => Effect.Effect<Info, DisabledError | NotFoundError>
readonly update: (id: ID, input: UpdateInput) => Effect.Effect<Info, Error>
readonly remove: (id: ID) => Effect.Effect<void, DisabledError | NotFoundError | ProviderError>
readonly readLocalFile: (
id: ID,
subpath?: string,
) => Effect.Effect<LocalFile, DisabledError | NotFoundError | FileMissingError | InvalidError>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Artifact") {}
const StoredRecord = Schema.Struct({
info: Info,
directory: Schema.String,
projectID: Schema.String,
})
type StoredRecord = typeof StoredRecord.Type
const decodeStoredRecord = Schema.decodeUnknownOption(StoredRecord)
const encodeStoredRecord = Schema.encodeSync(StoredRecord)
const encoder = new TextEncoder()
/** Resolves the stored directory of an artifact for HTTP routes without an explicit location query. */
export const locate = (kv: KV.Interface, id: ID) =>
kv.get(ItemPrefix + id).pipe(
Effect.map((stored) => {
if (stored === undefined) return undefined
const decoded = decodeStoredRecord(stored)
return Option.isSome(decoded) ? decoded.value.directory : undefined
}),
)
const layer = Layer.effect(
Service,
Effect.gen(function* () {
const bus = yield* Bus.Service
const config = yield* Config.Service
const global = yield* Global.Service
const kv = yield* KV.Service
const location = yield* Location.Service
const sessions = yield* Session.Service
const rootDir = path.join(global.data, "artifacts")
const itemDir = (id: ID) => path.join(rootDir, id)
const localProvider: ProviderImplementation = {
id: LocalProviderID,
name: "Local",
capabilities: ["static"],
prompt:
"Artifacts are served as HTML by this OpenCode server. Only people who can reach this server can open them.",
create: (input) =>
replaceDirectoryFiles(itemDir(input.id), input.files).pipe(
Effect.as({ url: `/api/experimental/artifacts/${encodeURIComponent(input.id)}/view/` }),
),
read: (id) => readDirectoryFiles(itemDir(id)),
update: (id, input) =>
replaceDirectoryFiles(itemDir(id), input.files).pipe(
Effect.as({ url: `/api/experimental/artifacts/${encodeURIComponent(id)}/view/` }),
),
delete: (id) => Effect.promise(() => fs.rm(itemDir(id), { recursive: true, force: true })),
}
const snapshotProviders = (data: Data) =>
Array.from(data.providers.values(), (provider) => ({
id: provider.id,
name: provider.name,
capabilities: provider.capabilities,
selection: data.selection,
})).toSorted((a, b) => a.id.localeCompare(b.id))
const state = State.create<Data, Editor>({
initial: () => ({
providers: new Map([[LocalProviderID, localProvider]]),
}),
editor: (draft) => ({
add: (provider) => {
draft.providers.set(provider.id, provider)
},
remove: (id) => {
if (id === LocalProviderID) return
draft.providers.delete(id)
if (draft.selection === id) draft.selection = undefined
},
default: {
get: () => draft.selection,
set: (providerID) => {
draft.selection = providerID
},
},
}),
notify: State.changes(snapshotProviders, () => bus.publish(Event.Updated, {}).pipe(Effect.asVoid)),
})
const isEnabled = Effect.fn("Artifact.enabled")(function* () {
const entries = yield* config.entries()
return Config.latest(entries, "experimental")?.artifacts === true
})
const requireEnabled = () =>
isEnabled().pipe(Effect.flatMap((on) => (on ? Effect.void : Effect.fail(new DisabledError()))))
const activeDefaultID = () => {
const data = state.get()
return data.selection && data.providers.has(data.selection) ? data.selection : LocalProviderID
}
const resolveProvider = (requested?: ProviderID) => {
const data = state.get()
const target = requested ?? activeDefaultID()
const found = data.providers.get(target)
return found ? Effect.succeed(found) : Effect.fail(new ProviderNotFoundError({ providerID: target }))
}
const checkSession = (sessionID?: SessionID) =>
sessionID === undefined ? Effect.void : sessions.get(sessionID).pipe(Effect.asVoid)
return Service.of({
transform: state.transform,
reload: state.reload,
enabled: isEnabled,
providers: Effect.fn("Artifact.providers")(function* () {
yield* requireEnabled()
const defaultID = activeDefaultID()
return Array.from(state.get().providers.values(), (provider) =>
Provider.make({
id: provider.id,
name: provider.name,
capabilities: [...provider.capabilities],
default: provider.id === defaultID,
}),
).toSorted((a, b) => Number(b.default) - Number(a.default) || a.name.localeCompare(b.name))
}),
prompts: Effect.fn("Artifact.prompts")(function* () {
const defaultID = activeDefaultID()
const defaultProvider = state.get().providers.get(defaultID) ?? localProvider
const others = Array.from(state.get().providers.values())
.filter((item) => item.id !== defaultProvider.id)
.toSorted((a, b) => a.name.localeCompare(b.name))
.map((item) => ({ id: item.id, name: item.name, capabilities: item.capabilities }))
return {
defaultProvider: {
id: defaultProvider.id,
name: defaultProvider.name,
capabilities: defaultProvider.capabilities,
prompt: defaultProvider.prompt,
},
others,
}
}),
list: Effect.fn("Artifact.list")(function* (filter) {
yield* requireEnabled()
if (filter?.sessionID !== undefined) yield* checkSession(filter.sessionID)
const items = yield* scanProjectInfos(kv, location.project.id)
return items
.filter(
(item) =>
(filter?.sessionID === undefined || item.sessionID === filter.sessionID) &&
(filter?.provider === undefined || item.provider === filter.provider),
)
.toSorted((a, b) => b.time.updated - a.time.updated || b.id.localeCompare(a.id))
}),
create: Effect.fn("Artifact.create")(function* (input) {
yield* requireEnabled()
yield* checkSession(input.sessionID)
const title = input.title.trim()
if (!title) return yield* new InvalidError({ reason: "Artifact title must not be empty", field: "title" })
const files = yield* normalizeFiles(encodeStringFiles(input.files))
const entry = yield* resolveEntry(files, input.entry)
const provider = yield* resolveProvider(input.provider)
const id = ID.create()
const now = yield* Clock.currentTimeMillis
const created = yield* provider
.create({ id, title, entry, files, sessionID: input.sessionID })
.pipe(Effect.mapError((cause) => new ProviderError({ providerID: provider.id, cause })))
const info = Info.make({
id,
provider: provider.id,
...(input.sessionID === undefined ? {} : { sessionID: input.sessionID }),
title,
entry,
url: created.url ?? `/api/experimental/artifacts/${encodeURIComponent(id)}/view/`,
time: { created: now, updated: now },
})
yield* kv.set(
ItemPrefix + id,
encodeStoredRecord({
info,
directory: location.directory,
projectID: location.project.id,
}),
)
return info
}),
info: Effect.fn("Artifact.info")(function* (id) {
yield* requireEnabled()
const existing = yield* loadProjectRecord(kv, id, location.project.id)
if (!existing) return yield* new NotFoundError({ artifactID: id })
return existing.info
}),
get: Effect.fn("Artifact.get")(function* (id) {
yield* requireEnabled()
const existing = yield* loadProjectRecord(kv, id, location.project.id)
if (!existing) return yield* new NotFoundError({ artifactID: id })
const provider = yield* resolveProvider(existing.info.provider)
const raw = yield* provider
.read(id)
.pipe(Effect.mapError((cause) => new ProviderError({ providerID: provider.id, cause })))
return Content.make({
info: existing.info,
files: decodeReadFiles(raw),
})
}),
update: Effect.fn("Artifact.update")(function* (id, input) {
yield* requireEnabled()
yield* checkSession(input.sessionID)
const existing = yield* loadProjectRecord(kv, id, location.project.id)
if (!existing) return yield* new NotFoundError({ artifactID: id })
const title = input.title === undefined ? existing.info.title : input.title.trim()
if (!title) return yield* new InvalidError({ reason: "Artifact title must not be empty", field: "title" })
const files = yield* normalizeFiles(encodeStringFiles(input.files))
const entry = yield* resolveEntry(
files,
input.entry ?? (files[existing.info.entry] ? existing.info.entry : undefined),
)
const provider = yield* resolveProvider(existing.info.provider)
const now = yield* Clock.currentTimeMillis
const sessionID = input.sessionID ?? existing.info.sessionID
const updated = yield* provider
.update(id, { title, entry, files, sessionID })
.pipe(Effect.mapError((cause) => new ProviderError({ providerID: provider.id, cause })))
const info = Info.make({
id,
provider: existing.info.provider,
...(sessionID === undefined ? {} : { sessionID }),
title,
entry,
url: updated.url ?? existing.info.url,
time: { created: existing.info.time.created, updated: now },
})
yield* kv.set(
ItemPrefix + id,
encodeStoredRecord({
info,
directory: existing.directory,
projectID: existing.projectID,
}),
)
return info
}),
remove: Effect.fn("Artifact.remove")(function* (id) {
yield* requireEnabled()
const existing = yield* loadProjectRecord(kv, id, location.project.id)
if (!existing) return yield* new NotFoundError({ artifactID: id })
const provider = state.get().providers.get(existing.info.provider)
if (provider) {
yield* provider
.delete(id)
.pipe(Effect.mapError((cause) => new ProviderError({ providerID: provider.id, cause })))
}
yield* kv.remove(ItemPrefix + id)
}),
readLocalFile: Effect.fn("Artifact.readLocalFile")(function* (id, subpath) {
yield* requireEnabled()
const existing = yield* loadProjectRecord(kv, id, location.project.id)
if (!existing) return yield* new NotFoundError({ artifactID: id })
if (existing.info.provider !== LocalProviderID) {
return yield* new InvalidError({
reason: `Artifact ${id} is hosted by provider "${existing.info.provider}", not the local server`,
field: "artifactID",
})
}
const requested = subpath?.trim() ? yield* normalizePath(subpath) : existing.info.entry
const target = path.join(itemDir(id), ...requested.split("/"))
const exists = yield* Effect.promise(() =>
fs
.stat(target)
.then((stat) => stat.isFile())
.catch(() => false),
)
if (!exists) return yield* new FileMissingError({ artifactID: id, path: requested })
const bytes = yield* Effect.promise(() => fs.readFile(target).then((buf) => new Uint8Array(buf)))
return { bytes, mime: detectFileMime(requested, bytes) }
}),
})
}),
)
export const node = makeLocationNode({
service: Service,
layer,
deps: [Bus.node, Config.node, Global.node, KV.node, Location.node, Session.node],
})
function encodeStringFiles(files: Readonly<Record<string, string>>) {
return Object.fromEntries(Object.entries(files).map(([filePath, content]) => [filePath, encoder.encode(content)]))
}
function decodeReadFiles(files: Readonly<Record<string, Uint8Array>>) {
const decoder = new TextDecoder()
return Object.fromEntries(Object.entries(files).map(([filePath, bytes]) => [filePath, decoder.decode(bytes)]))
}
function detectFileMime(filePath: string, bytes: Uint8Array) {
const byName = lookup(filePath)
if (typeof byName === "string") {
return byName.startsWith("text/") || byName === "application/javascript" || byName === "application/json"
? `${byName}; charset=utf-8`
: byName
}
return Mime.detect(bytes)
}
function normalizePath(raw: string): Effect.Effect<string, InvalidError> {
const trimmed = raw.replaceAll("\\", "/").replace(/^(?:\.\/)+/u, "").replace(/^\/+/u, "")
if (!trimmed || trimmed.includes("\0")) {
return Effect.fail(new InvalidError({ reason: `Invalid artifact file path: ${JSON.stringify(raw)}`, field: "files" }))
}
const segments = trimmed.split("/")
if (segments.some((part) => !part || part === "." || part === "..")) {
return Effect.fail(
new InvalidError({ reason: `Artifact file path must stay relative: ${JSON.stringify(raw)}`, field: "files" }),
)
}
return Effect.succeed(segments.join("/"))
}
function normalizeFiles(files: Readonly<Record<string, Uint8Array>>) {
return Effect.gen(function* () {
const entries = Object.entries(files)
if (entries.length === 0) {
return yield* new InvalidError({ reason: "Artifact must include at least one file", field: "files" })
}
const normalized = new Map<string, Uint8Array>()
for (const [rawPath, content] of entries) {
const clean = yield* normalizePath(rawPath)
normalized.set(clean, content)
}
return Object.fromEntries(normalized)
})
}
function resolveEntry(files: Readonly<Record<string, Uint8Array>>, requested?: string) {
if (requested !== undefined) {
return normalizePath(requested).pipe(
Effect.flatMap((clean) =>
files[clean] !== undefined
? Effect.succeed(clean)
: Effect.fail(new InvalidError({ reason: `Entry file not found in files: ${clean}`, field: "entry" })),
),
)
}
if (files["index.html"] !== undefined) return Effect.succeed("index.html")
if (files["index.md"] !== undefined) return Effect.succeed("index.md")
const keys = Object.keys(files)
if (keys.length === 1 && keys[0] !== undefined) return Effect.succeed(keys[0])
return Effect.fail(
new InvalidError({
reason: 'Include "index.html" or "index.md", or specify "entry" when publishing multiple files',
field: "entry",
}),
)
}
function loadProjectRecord(kv: KV.Interface, id: ID, projectID: string) {
return kv.get(ItemPrefix + id).pipe(
Effect.map((stored) => {
if (stored === undefined) return undefined
const decoded = Option.getOrUndefined(decodeStoredRecord(stored))
return decoded?.projectID === projectID ? decoded : undefined
}),
)
}
function scanProjectInfos(kv: KV.Interface, projectID: string) {
return Effect.gen(function* () {
const results: Info[] = []
let after: string | undefined
while (true) {
const page = yield* kv.scan({ prefix: ItemPrefix, after, limit: 500 })
results.push(
...page.entries.flatMap((entry) => {
const decoded = decodeStoredRecord(entry.value)
return Option.isSome(decoded) && decoded.value.projectID === projectID ? [decoded.value.info] : []
}),
)
if (!page.next) return results
after = page.next
}
})
}
function replaceDirectoryFiles(baseDir: string, files: Readonly<Record<string, Uint8Array>>) {
return Effect.tryPromise(async () => {
const parent = path.dirname(baseDir)
await fs.mkdir(parent, { recursive: true })
const nonce = randomUUID()
const staging = `${baseDir}.staging-${nonce}`
const backup = `${baseDir}.backup-${nonce}`
try {
await fs.mkdir(staging, { recursive: true })
await Promise.all(
Object.entries(files).map(async ([rel, bytes]) => {
const dest = path.join(staging, ...rel.split("/"))
await fs.mkdir(path.dirname(dest), { recursive: true })
await fs.writeFile(dest, bytes)
}),
)
const hadExisting = await fs
.stat(baseDir)
.then(() => true)
.catch(() => false)
if (hadExisting) await fs.rename(baseDir, backup)
try {
await fs.rename(staging, baseDir)
} catch (err) {
if (hadExisting) await fs.rename(backup, baseDir).catch(() => undefined)
throw err
}
if (hadExisting) await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined)
} catch (err) {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
throw err
}
})
}
function readDirectoryFiles(baseDir: string) {
return Effect.promise(async () => {
const out: Record<string, Uint8Array> = {}
const walk = async (current: string, prefix: string): Promise<void> => {
const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => [])
await Promise.all(
entries.map(async (entry) => {
const rel = prefix ? `${prefix}/${entry.name}` : entry.name
const full = path.join(current, entry.name)
if (entry.isDirectory()) return walk(full, rel)
if (entry.isFile()) out[rel] = new Uint8Array(await fs.readFile(full))
}),
)
}
await walk(baseDir, "")
return out
})
}
+9
View File
@@ -513,6 +513,15 @@ function normalizeExperimental(
)
if (value !== undefined) result.schedules = value
}
if (own(experimental, "artifacts")) {
const value = decodeEncoded(
ConfigExperimental.Info.fields.artifacts,
experimental.artifacts,
["experimental", "artifacts"],
diagnostics,
)
if (value !== undefined) result.artifacts = value
}
if (own(experimental, "subagent_depth")) {
const value = decodeEncoded(
ConfigExperimental.Info.fields.subagent_depth,
+2
View File
@@ -1,5 +1,6 @@
import { Context, Effect, Layer } from "effect"
import { Agent } from "./agent.js"
import { Artifact } from "./artifact.js"
import { AISDK } from "./aisdk.js"
import { Model } from "./model.js"
import { Provider } from "./provider.js"
@@ -63,6 +64,7 @@ const nodes = [
Environment.node,
Config.node,
Agent.node,
Artifact.node,
Command.node,
Reference.node,
Rpc.node,
+28
View File
@@ -8,6 +8,7 @@ import { ServerConfig } from "@opencode/schema/mcp"
import { App } from "../app.js"
import { Effect, Schema, Stream } from "effect"
import { Agent } from "../agent.js"
import { Artifact } from "../artifact.js"
import { AISDK } from "../aisdk.js"
import { Command } from "../command.js"
import { Credential } from "../credential.js"
@@ -54,6 +55,7 @@ export const make = Effect.fn("PluginHost.make")(function* (
) {
const app = yield* App.Metadata
const agents = yield* Agent.Service
const artifacts = yield* Artifact.Service
const aisdk = yield* AISDK.Service
const providers = yield* Provider.Service
const models = yield* Model.Service
@@ -288,6 +290,31 @@ export const make = Effect.fn("PluginHost.make")(function* (
image: generate.image,
decisions: generate.decisions,
},
artifact: {
reload: artifacts.reload,
transform: (callback) =>
artifacts.transform((editor) => {
callback({
add: (definition) =>
editor.add({
id: Artifact.ProviderID.make(definition.id),
name: definition.name,
capabilities: definition.capabilities,
prompt: definition.prompt,
create: definition.create,
read: definition.read,
update: definition.update,
delete: definition.delete,
}),
remove: (id) => editor.remove(Artifact.ProviderID.make(id)),
default: {
get: () => editor.default.get(),
set: (providerID) =>
editor.default.set(providerID === undefined ? undefined : Artifact.ProviderID.make(providerID)),
},
})
}),
},
},
generate: {
text: generateText,
@@ -631,6 +658,7 @@ export const make = Effect.fn("PluginHost.make")(function* (
export const requirements = LayerNode.group([
App.node,
Agent.node,
Artifact.node,
AISDK.node,
Provider.node,
Model.node,
+5
View File
@@ -8,6 +8,7 @@ import { AppProcess } from "@opencode/util/process"
import { Context, Effect, Scope } from "effect"
import { HttpClient } from "effect/http"
import { Agent } from "../agent.js"
import { Artifact } from "../artifact.js"
import { Model } from "../model.js"
import { Provider } from "../provider.js"
import { Command } from "../command.js"
@@ -79,6 +80,7 @@ import { OpenCodeTools } from "../tool/plugin/opencode.js"
import { QuestionTool } from "../tool/plugin/question.js"
import { ReadToolFileSystem } from "../tool/read-filesystem.js"
import { ReadTool } from "../tool/plugin/read.js"
import { ArtifactTools } from "../tool/plugin/artifact.js"
import { ScheduleTools } from "../tool/plugin/schedule.js"
import { ShellTool } from "../tool/plugin/shell.js"
import { SkillTool } from "../tool/plugin/skill.js"
@@ -113,6 +115,7 @@ import { WellKnownPlugin } from "../wellknown/plugin.js"
const services = [
Agent.Service,
Artifact.Service,
AppProcess.Service,
Provider.Service,
Model.Service,
@@ -168,6 +171,7 @@ export type Requirements = Context.Service.Identifier<(typeof services)[number]>
export const requirements = LayerNode.group([
Agent.node,
Artifact.node,
AppProcess.node,
Provider.node,
Model.node,
@@ -250,6 +254,7 @@ const pre = [
McpResourceTools.Plugin,
QuestionTool.Plugin,
ReadTool.Plugin,
ArtifactTools.Plugin,
ScheduleTools.Plugin,
ShellTool.Plugin,
SkillTool.Plugin,
+169
View File
@@ -0,0 +1,169 @@
export * as ArtifactTools from "./artifact.js"
import { ToolFailure } from "@opencode/ai/effect"
import type { Context } from "@opencode/plugin/effect/plugin"
import { optional } from "@opencode/schema/schema"
import { Effect, Schema, Stream } from "effect"
import { Artifact } from "../../artifact.js"
import { Config } from "../../config.js"
import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js"
export const CreateToolInput = Schema.Struct({
title: Schema.String.annotate({ description: "Human-readable artifact title." }),
files: Schema.Record(Schema.String, Schema.String).annotate({
description: "UTF-8 file map keyed by relative path (for example index.html and assets/app.js).",
}),
entry: Schema.String.pipe(optional).annotate({
description: "Entry file path relative to the artifact root. Defaults to index.html, index.md, or the sole file.",
}),
provider: Schema.String.pipe(optional).annotate({
description: "Artifact provider ID to override the default provider for this request.",
}),
})
export const ReadToolInput = Schema.Struct({
id: Artifact.ID.annotate({ description: "Artifact ID (art_...) to read." }),
})
export const UpdateToolInput = Schema.Struct({
id: Artifact.ID.annotate({ description: "Artifact ID (art_...) to update." }),
title: Schema.String.pipe(optional).annotate({ description: "Updated title, or omit to keep the current title." }),
files: Schema.Record(Schema.String, Schema.String).annotate({
description: "Replacement UTF-8 file map keyed by relative path.",
}),
entry: Schema.String.pipe(optional).annotate({ description: "Updated entry file path." }),
})
export const DeleteToolInput = Schema.Struct({
id: Artifact.ID.annotate({ description: "Artifact ID (art_...) to delete." }),
})
const DeleteToolOutput = Schema.Struct({
id: Artifact.ID,
deleted: Schema.Boolean,
})
export const Plugin = {
id: "opencode.tool.artifact",
effect: Effect.fn("ArtifactTools.Plugin")(function* (ctx: Context) {
const config = yield* Config.Service
const artifacts = yield* Artifact.Service
const promptSnapshot = { text: yield* renderCreateDescription(artifacts) }
const refreshTools = Effect.gen(function* () {
promptSnapshot.text = yield* renderCreateDescription(artifacts)
yield* ctx.tool.reload()
})
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, refreshTools)
yield* ctx.event.subscribe({ types: [Artifact.Event.Updated.type] }).pipe(
Stream.runForEach(() => refreshTools),
Effect.forkScoped({ startImmediately: true }),
)
const enabled = () => Config.latest(loaded.entries, "experimental")?.artifacts === true
const failure = (error: { readonly message: string }) => new ToolFailure({ message: error.message, error })
yield* ctx.tool
.transform((editor) => {
if (!enabled()) return
editor.add({
name: "artifact_create",
description: promptSnapshot.text,
input: CreateToolInput,
output: Artifact.Info,
options: { namespace: "opencode", codemode: true },
execute: (input, context) =>
artifacts
.create({
title: input.title,
files: input.files,
entry: input.entry,
provider: input.provider === undefined ? undefined : Artifact.ProviderID.make(input.provider),
sessionID: context.sessionID,
})
.pipe(
Effect.map((info) => ({
output: info,
content: `Published ${info.title} (${info.id} via ${info.provider}): ${info.url}`,
})),
Effect.mapError(failure),
),
})
editor.add({
name: "artifact_read",
description: "Read an artifact's metadata and file contents so you can inspect or update it.",
input: ReadToolInput,
output: Artifact.Content,
options: { namespace: "opencode", codemode: true },
execute: (input) =>
artifacts.get(input.id).pipe(
Effect.map((content) => ({
output: content,
content: `${content.info.title} (${content.info.id} · ${Object.keys(content.files).length} files)`,
})),
Effect.mapError(failure),
),
})
editor.add({
name: "artifact_update",
description: "Replace an existing artifact's files at the same ID and URL.",
input: UpdateToolInput,
output: Artifact.Info,
options: { namespace: "opencode", codemode: true },
execute: (input, context) =>
artifacts
.update(input.id, {
title: input.title,
files: input.files,
entry: input.entry,
sessionID: context.sessionID,
})
.pipe(
Effect.map((info) => ({
output: info,
content: `Updated ${info.title} (${info.id}): ${info.url}`,
})),
Effect.mapError(failure),
),
})
editor.add({
name: "artifact_delete",
description: "Delete an artifact and remove its stored copy.",
input: DeleteToolInput,
output: DeleteToolOutput,
options: { namespace: "opencode", codemode: true },
execute: (input) =>
artifacts.remove(input.id).pipe(
Effect.map(() => ({
output: { id: input.id, deleted: true },
content: `Deleted ${input.id}`,
})),
Effect.mapError(failure),
),
})
})
.pipe(Effect.orDie)
}),
}
function renderCreateDescription(artifacts: Artifact.Interface) {
return artifacts.prompts().pipe(
Effect.map(({ defaultProvider, others }) => {
const lines = [
"Publish a new artifact to the default artifact provider or a named override.",
`Default provider (${defaultProvider.id} [${defaultProvider.capabilities.join(", ")}]): ${defaultProvider.prompt}`,
]
if (others.length > 0) {
lines.push(
`Other active providers (pass provider to override): ${others.map((item) => `${item.id} [${item.capabilities.join(", ")}]`).join(", ")}.`,
)
}
return lines.join("\n")
}),
)
}
+206
View File
@@ -0,0 +1,206 @@
import path from "node:path"
import { describe, expect } from "bun:test"
import { Effect, Layer, Stream } from "effect"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { Artifact } from "@opencode/core/artifact"
import { Config } from "@opencode/core/config"
import { Image } from "@opencode/core/image"
import { Location } from "@opencode/core/location"
import { Permission } from "@opencode/core/permission"
import { Session } from "@opencode/core/session"
import { Tool } from "@opencode/core/tool"
import { ArtifactTools } from "@opencode/core/tool/plugin/artifact"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { Global } from "@opencode/util/global"
import { Document, Info } from "@opencode/schema/config"
import { ConfigExperimental } from "@opencode/schema/config/experimental"
import { AbsolutePath } from "@opencode/schema/schema"
import { tmpdirScoped } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
import { imagePassthrough } from "./lib/image"
import { permissionLayer } from "./lib/permission"
import { codeModeListings, executeTool, registerToolPlugin, toolIdentity } from "./lib/tool"
const toolPaths = [
"opencode.artifact_create",
"opencode.artifact_read",
"opencode.artifact_update",
"opencode.artifact_delete",
]
const buildLayer = (artifactsEnabled: boolean, dir: string) => {
const entries = artifactsEnabled
? [
new Document({
type: "document",
info: new Info({
experimental: new ConfigExperimental.Info({ artifacts: true }),
}),
}),
]
: []
const ref = Location.Ref.make({ directory: AbsolutePath.make(dir) })
return AppNodeBuilder.build(
LayerNode.group([Artifact.node, Config.node, Global.node, Location.node, Permission.node, Session.node, Tool.node]),
[
Config.node.replace(Config.testLayer(entries)),
Global.node.replace(Global.layerWith({ data: path.join(dir, ".data") })),
Image.node.replace(imagePassthrough),
Location.node.replace(Location.boundNode(ref)),
Permission.node.replace(permissionLayer({ assert: () => Effect.void })),
],
)
}
const callCodeMode = (registry: Tool.Interface, sessionID: Session.ID, name: string, input: unknown) =>
executeTool(registry, {
sessionID,
...toolIdentity,
call: {
type: "tool-call",
id: `call-${name}`,
name: "execute",
input: { code: `return await tools.opencode.${name}(${JSON.stringify(input)})` },
},
}).pipe(
Effect.map((result) => {
if (result.status !== "completed") {
throw new Error(`Tool ${name} failed: ${JSON.stringify(result.error)}`)
}
return JSON.parse(result.content?.[0]?.type === "text" ? result.content[0].text : "")
}),
)
const it = testEffect(Layer.empty)
describe("experimental.artifacts service and tools", () => {
it.live("stays disabled and hides artifact tools when experimental.artifacts is unset", () =>
Effect.gen(function* () {
const dir = (yield* tmpdirScoped("opencode-artifact-off-")).path
yield* Effect.gen(function* () {
const artifacts = yield* Artifact.Service
const registry = yield* Tool.Service
expect(yield* artifacts.enabled()).toBe(false)
expect(
yield* artifacts
.create({ title: "Draft", files: { "index.html": "<h1>hi</h1>" } })
.pipe(Effect.flip),
).toBeInstanceOf(Artifact.DisabledError)
yield* registerToolPlugin(ArtifactTools.Plugin, {
event: { subscribe: () => Stream.never },
})
const snap = yield* registry.snapshot()
const listed = snap.codeModeCatalog ? codeModeListings(snap.codeModeCatalog).map((item) => item.path) : []
for (const name of toolPaths) {
expect(listed).not.toContain(name)
}
}).pipe(Effect.provide(buildLayer(false, dir)))
}),
)
it.live("registers custom providers, routes overrides, and runs the 4 CRUD tools", () =>
Effect.gen(function* () {
const dir = (yield* tmpdirScoped("opencode-artifact-on-")).path
yield* Effect.gen(function* () {
const artifacts = yield* Artifact.Service
const registry = yield* Tool.Service
const sessions = yield* Session.Service
const session = yield* sessions.create({
location: Location.Ref.make({ directory: AbsolutePath.make(dir) }),
})
const remoteStore = new Map<Artifact.ID, Record<string, Uint8Array>>()
yield* artifacts.transform((editor) => {
editor.add({
id: Artifact.ProviderID.make("cloudflare"),
name: "Cloudflare",
capabilities: ["static", "server-code", "sqlite", "durable-objects"],
prompt: "Artifacts deploy to Cloudflare with SQLite and Durable Objects.",
create: (input) =>
Effect.sync(() => {
remoteStore.set(input.id, { ...input.files })
return { url: `https://cf.example.test/${input.id}/` }
}),
read: (id) => Effect.sync(() => remoteStore.get(id) ?? {}),
update: (id, input) =>
Effect.sync(() => {
remoteStore.set(id, { ...input.files })
return { url: `https://cf.example.test/${id}/` }
}),
delete: (id) =>
Effect.sync(() => {
remoteStore.delete(id)
}),
})
editor.default.set(Artifact.ProviderID.make("cloudflare"))
})
yield* registerToolPlugin(ArtifactTools.Plugin, {
event: { subscribe: () => Stream.never },
})
const snap = yield* registry.snapshot()
const listings = snap.codeModeCatalog ? codeModeListings(snap.codeModeCatalog) : []
expect(listings.map((item) => item.path)).toEqual(expect.arrayContaining(toolPaths))
const rawTools = yield* registry.list()
const createTool = rawTools.find((item) => item.id === "opencode_artifact_create")
expect(createTool?.description).toContain(
"Default provider (cloudflare [static, server-code, sqlite, durable-objects]): Artifacts deploy to Cloudflare with SQLite and Durable Objects.",
)
expect(createTool?.description).toContain(
"Other active providers (pass provider to override): local [static].",
)
const createdInfo = (yield* callCodeMode(registry, session.id, "artifact_create", {
title: "Flamegraph report",
files: {
"index.html": "<!doctype html><script src='./assets/app.js'></script>",
"assets/app.js": "console.log('v1')",
},
})) as Artifact.Info
expect(createdInfo).toMatchObject({
provider: "cloudflare",
sessionID: session.id,
title: "Flamegraph report",
entry: "index.html",
url: `https://cf.example.test/${createdInfo.id}/`,
})
const content = (yield* callCodeMode(registry, session.id, "artifact_read", {
id: createdInfo.id,
})) as Artifact.Content
expect(Object.keys(content.files).toSorted()).toEqual(["assets/app.js", "index.html"])
expect(content.files["assets/app.js"]).toBe("console.log('v1')")
// Per-request provider override ("local") stores independently of default ("cloudflare")
const localInfo = (yield* callCodeMode(registry, session.id, "artifact_create", {
title: "Local scratch",
files: { "index.html": "<h1>Notes</h1>" },
provider: "local",
})) as Artifact.Info
expect(localInfo.provider).toBe(Artifact.LocalProviderID)
// Update replaces files at the same ID and URL
const updatedInfo = (yield* callCodeMode(registry, session.id, "artifact_update", {
id: createdInfo.id,
files: { "index.html": "<h1>v2</h1>" },
})) as Artifact.Info
expect(updatedInfo.url).toBe(createdInfo.url)
yield* callCodeMode(registry, session.id, "artifact_delete", { id: createdInfo.id })
expect(yield* artifacts.get(createdInfo.id).pipe(Effect.flip)).toBeInstanceOf(Artifact.NotFoundError)
// Reject path traversal
const traversal = yield* artifacts
.create({
title: "Bad path",
files: { "../escape.html": "nope" },
})
.pipe(Effect.flip)
expect(traversal).toBeInstanceOf(Artifact.InvalidError)
}).pipe(Effect.provide(buildLayer(true, dir)))
}),
)
})
+2
View File
@@ -1,4 +1,5 @@
import { Agent } from "@opencode/core/agent"
import { Artifact } from "@opencode/core/artifact"
import { AISDK } from "@opencode/core/aisdk"
import { Command } from "@opencode/core/command"
import { Config } from "@opencode/core/config"
@@ -102,6 +103,7 @@ export const makePluginTestLayer = (permission = permissionLayer, generate = gen
LayerNodePlatform.httpClient,
Plugin.node,
Agent.node,
Artifact.node,
AISDK.node,
Provider.node,
Model.node,
+4
View File
@@ -77,6 +77,10 @@ export function host(overrides: Overrides = {}): Plugin.Context {
image: () => Effect.die("unused experimental.generate.image"),
decisions: () => Effect.die("unused experimental.generate.decisions"),
},
artifact: {
transform: () => Effect.die("unused experimental.artifact.transform"),
reload: () => Effect.die("unused experimental.artifact.reload"),
},
},
generate: overrides.generate ?? {
text: () => Effect.die("unused generate.text"),
+51
View File
@@ -0,0 +1,51 @@
import type { Artifact } from "@opencode/schema/artifact"
import type { Session } from "@opencode/schema/session"
import type { Effect } from "effect"
import type { Transform } from "./registration.js"
export interface ArtifactProviderCreateInput {
readonly id: Artifact.ID
readonly title: string
readonly entry: string
readonly files: Readonly<Record<string, Uint8Array>>
readonly sessionID?: Session.ID
}
export interface ArtifactProviderUpdateInput {
readonly title: string
readonly entry: string
readonly files: Readonly<Record<string, Uint8Array>>
readonly sessionID?: Session.ID
}
export interface ArtifactProviderResult {
readonly url?: string
}
export interface ArtifactProviderDefinition {
readonly id: string
readonly name: string
readonly capabilities: readonly Artifact.Capability[]
readonly prompt: string
readonly create: (input: ArtifactProviderCreateInput) => Effect.Effect<ArtifactProviderResult, unknown>
readonly read: (id: Artifact.ID) => Effect.Effect<Readonly<Record<string, Uint8Array>>, unknown>
readonly update: (
id: Artifact.ID,
input: ArtifactProviderUpdateInput,
) => Effect.Effect<ArtifactProviderResult, unknown>
readonly delete: (id: Artifact.ID) => Effect.Effect<void, unknown>
}
export interface ArtifactEditor {
add(definition: ArtifactProviderDefinition): void
remove(id: string): void
readonly default: {
get(): string | undefined
set(providerID: string | undefined): void
}
}
export interface ExperimentalArtifactDomain {
readonly transform: Transform<ArtifactEditor>
readonly reload: () => Effect.Effect<void>
}
+1
View File
@@ -2,6 +2,7 @@ export * as Plugin from "./plugin.js"
export type { StorageEntry, StorageScanOptions, StorageScanResult } from "../storage.js"
export { Agent } from "@opencode/schema/agent"
export { Artifact } from "@opencode/schema/artifact"
export { Command } from "@opencode/schema/command"
export { Connection } from "@opencode/schema/connection"
export { Credential } from "@opencode/schema/credential"
+2
View File
@@ -4,6 +4,7 @@ import type { Effect, Scope } from "effect"
import type { PluginOptions } from "../options.js"
import type { App } from "../app.js"
import type { AgentDomain } from "./agent.js"
import type { ExperimentalArtifactDomain } from "./artifact.js"
import type { AISDKDomain } from "./aisdk.js"
import type { CommandDomain } from "./command.js"
import type { EventDomain } from "./event.js"
@@ -36,6 +37,7 @@ export interface Context {
readonly terminal: Pick<ExperimentalApi<unknown>["persistentPty"], "read">
/** Stateless generation with a model and a prompt: no session, history or tools. */
readonly generate: ExperimentalGenerateApi<unknown>
readonly artifact: ExperimentalArtifactDomain
}
readonly integration: IntegrationDomain
readonly mcp: MCPDomain
+23
View File
@@ -349,6 +349,29 @@ export function fromPromise(plugin: Plugin) {
image: adaptApiMethod(GenerateEndpoints["generate.image"], host.experimental.generate.image),
decisions: adaptApiMethod(GenerateEndpoints["generate.decisions"], host.experimental.generate.decisions),
},
artifact: {
reload: () => run(host.experimental.artifact.reload()),
transform: (callback) =>
register(
host.experimental.artifact.transform((editor) => {
callback({
add: (definition) =>
editor.add({
id: definition.id,
name: definition.name,
capabilities: definition.capabilities,
prompt: definition.prompt,
create: (input) => attempt((signal) => definition.create(input, { signal })),
read: (id) => attempt((signal) => definition.read(id, { signal })),
update: (id, input) => attempt((signal) => definition.update(id, input, { signal })),
delete: (id) => attempt((signal) => definition.delete(id, { signal })),
}),
remove: editor.remove,
default: editor.default,
})
}),
),
},
},
generate: {
text: adaptApiMethod(GenerateEndpoints["generate.text"], host.generate.text),
+57
View File
@@ -0,0 +1,57 @@
import type { Artifact } from "@opencode/schema/artifact"
import type { Session } from "@opencode/schema/session"
import type { Transform } from "./registration.js"
export interface ArtifactProviderCreateInput {
readonly id: Artifact.ID
readonly title: string
readonly entry: string
readonly files: Readonly<Record<string, Uint8Array>>
readonly sessionID?: Session.ID
}
export interface ArtifactProviderUpdateInput {
readonly title: string
readonly entry: string
readonly files: Readonly<Record<string, Uint8Array>>
readonly sessionID?: Session.ID
}
export interface ArtifactProviderResult {
readonly url?: string
}
export interface ArtifactProviderDefinition {
readonly id: string
readonly name: string
readonly capabilities: readonly Artifact.Capability[]
readonly prompt: string
readonly create: (
input: ArtifactProviderCreateInput,
context: { readonly signal: AbortSignal },
) => Promise<ArtifactProviderResult>
readonly read: (
id: Artifact.ID,
context: { readonly signal: AbortSignal },
) => Promise<Readonly<Record<string, Uint8Array>>>
readonly update: (
id: Artifact.ID,
input: ArtifactProviderUpdateInput,
context: { readonly signal: AbortSignal },
) => Promise<ArtifactProviderResult>
readonly delete: (id: Artifact.ID, context: { readonly signal: AbortSignal }) => Promise<void>
}
export interface ArtifactEditor {
add(definition: ArtifactProviderDefinition): void
remove(id: string): void
readonly default: {
get(): string | undefined
set(providerID: string | undefined): void
}
}
export interface ExperimentalArtifactDomain {
readonly transform: Transform<ArtifactEditor>
readonly reload: () => Promise<void>
}
+1
View File
@@ -3,6 +3,7 @@ export type { StorageEntry, StorageScanOptions, StorageScanResult } from "../sto
export * as Plugin from "./plugin.js"
export { Agent } from "@opencode/schema/agent"
export { Artifact } from "@opencode/schema/artifact"
export { Command } from "@opencode/schema/command"
export { Connection } from "@opencode/schema/connection"
export { Credential } from "@opencode/schema/credential"
+2
View File
@@ -4,6 +4,7 @@ import type { Location } from "@opencode/schema/location"
import type { PluginOptions } from "../options.js"
import type { App } from "../app.js"
import type { AgentDomain } from "./agent.js"
import type { ExperimentalArtifactDomain } from "./artifact.js"
import type { AISDKDomain } from "./aisdk.js"
import type { CommandDomain } from "./command.js"
import type { EventDomain } from "./event.js"
@@ -36,6 +37,7 @@ export interface Context {
readonly terminal: Pick<OpenCodeClient["experimental"]["persistentPty"], "read">
/** Stateless generation with a model and a prompt: no session, history or tools. */
readonly generate: ExperimentalGenerateApi
readonly artifact: ExperimentalArtifactDomain
}
readonly integration: IntegrationDomain
readonly mcp: MCPDomain
+1043
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -84,6 +84,7 @@ export const effectOmitEndpoints = new Set([
"fs.read",
"fs.write",
"media.get",
"artifacts.view",
"pty.connect",
"persistentPty.connect",
"mcp.client",
+9
View File
@@ -333,3 +333,12 @@ export class ScheduleNotFoundError extends Schema.TaggedError<ScheduleNotFoundEr
},
{ httpApiStatus: 404 },
) {}
export class ArtifactNotFoundError extends Schema.TaggedError<ArtifactNotFoundError>()(
"ArtifactNotFoundError",
{
artifactID: Schema.String,
message: Schema.String,
},
{ httpApiStatus: 404 },
) {}
+103
View File
@@ -0,0 +1,103 @@
import { Artifact } from "@opencode/schema/artifact"
import { Location } from "@opencode/schema/location"
import { Session } from "@opencode/schema/session"
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api"
import {
ArtifactNotFoundError,
FileNotFoundError,
ForbiddenError,
InvalidRequestError,
LocationNotFoundError,
ProviderNotFoundError,
ServiceUnavailableError,
SessionNotFoundError,
} from "../errors.js"
import { LocationQuery, locationQueryOpenApi } from "./location.js"
const EXPERIMENTAL =
"Experimental: needs experimental.artifacts in the Location's config and may change without notice."
const params = { artifactID: Artifact.ID }
const ListQuery = Schema.Struct({
...LocationQuery.fields,
sessionID: Schema.optional(Session.ID),
provider: Schema.optional(Artifact.ProviderID),
})
const annotations = (identifier: string, summary: string, description: string) =>
OpenApi.annotations({
identifier: `experimental.artifacts.${identifier}`,
summary,
description: `${description} ${EXPERIMENTAL}`,
transform: (operation) => ({ ...operation, tags: ["experimental"] }),
})
const commonErrors = [ForbiddenError, LocationNotFoundError, ServiceUnavailableError] as const
const itemErrors = [ArtifactNotFoundError, ...commonErrors] as const
/** Lives in the `server.experimental` group (see `groups/experimental.ts`). */
export const ArtifactEndpoints = [
HttpApiEndpoint.get("artifacts.providers", "/api/experimental/artifacts/providers", {
query: LocationQuery,
success: Location.response(Schema.Array(Artifact.Provider)),
error: commonErrors,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(annotations("providers", "List artifact providers", "Return active artifact providers and default.")),
HttpApiEndpoint.get("artifacts.list", "/api/experimental/artifacts", {
query: ListQuery,
success: Location.response(Schema.Array(Artifact.Info)),
error: [SessionNotFoundError, ...commonErrors],
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(annotations("list", "List artifacts", "List published artifacts, newest update first.")),
HttpApiEndpoint.post("artifacts.create", "/api/experimental/artifacts", {
query: LocationQuery,
payload: Artifact.CreateInput,
success: Location.response(Artifact.Info),
error: [InvalidRequestError, ProviderNotFoundError, SessionNotFoundError, ...commonErrors],
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
annotations(
"create",
"Create artifact",
"Publish a new artifact through the selected or default artifact provider.",
),
),
HttpApiEndpoint.get("artifacts.get", "/api/experimental/artifacts/:artifactID", {
params,
query: LocationQuery,
success: Location.response(Artifact.Content),
error: itemErrors,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(annotations("get", "Read artifact", "Read an artifact's metadata and file contents.")),
HttpApiEndpoint.patch("artifacts.update", "/api/experimental/artifacts/:artifactID", {
params,
query: LocationQuery,
payload: Artifact.UpdateInput,
success: Location.response(Artifact.Info),
error: [InvalidRequestError, SessionNotFoundError, ...itemErrors],
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(annotations("update", "Update artifact", "Replace an artifact's files at the same ID and URL.")),
HttpApiEndpoint.delete("artifacts.delete", "/api/experimental/artifacts/:artifactID", {
params,
query: LocationQuery,
success: HttpApiSchema.NoContent,
error: itemErrors,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(annotations("delete", "Delete artifact", "Remove an artifact and its stored files.")),
HttpApiEndpoint.get("artifacts.view", "/api/experimental/artifacts/:artifactID/view/*", {
params,
query: LocationQuery,
success: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()),
error: [FileNotFoundError, InvalidRequestError, ...itemErrors],
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(annotations("view", "View local artifact", "Serve HTML and static files from the local provider.")),
] as const
+2 -1
View File
@@ -1,6 +1,7 @@
import { ArtifactEndpoints } from "./artifact.js"
import { MediaGetEndpoint } from "./media.js"
import { PersistentPtyGroup } from "./persistent-pty.js"
import { ScheduleEndpoints } from "./schedule.js"
/** `server.experimental`: routes under /api/experimental, without compatibility guarantees. */
export const ExperimentalGroup = PersistentPtyGroup.add(MediaGetEndpoint, ...ScheduleEndpoints)
export const ExperimentalGroup = PersistentPtyGroup.add(MediaGetEndpoint, ...ScheduleEndpoints, ...ArtifactEndpoints)
+81
View File
@@ -0,0 +1,81 @@
export * as Artifact from "./artifact.js"
import { Schema } from "effect"
import { ephemeral, inventory } from "./event.js"
import { ascending } from "./identifier.js"
import { optional, statics } from "./schema.js"
import { SessionID } from "./session-id.js"
export const ID = Schema.String.check(Schema.isStartingWith("art_")).pipe(
Schema.brand("Artifact.ID"),
Schema.annotate({ identifier: "Artifact.ID" }),
statics((schema) => ({
create: () => schema.make("art_" + ascending()),
})),
)
export type ID = typeof ID.Type
export const ProviderID = Schema.Trim.check(Schema.isNonEmpty()).pipe(
Schema.brand("Artifact.ProviderID"),
Schema.annotate({ identifier: "Artifact.ProviderID" }),
)
export type ProviderID = typeof ProviderID.Type
export const Capability = Schema.Literals(["static", "server-code", "sqlite", "durable-objects"]).annotate({
identifier: "Artifact.Capability",
})
export type Capability = typeof Capability.Type
export interface Provider extends Schema.Schema.Type<typeof Provider> {}
export const Provider = Schema.Struct({
id: ProviderID,
name: Schema.String,
capabilities: Schema.Array(Capability),
default: Schema.Boolean,
}).annotate({ identifier: "Artifact.Provider" })
export interface Time extends Schema.Schema.Type<typeof Time> {}
export const Time = Schema.Struct({
created: Schema.Finite,
updated: Schema.Finite,
}).annotate({ identifier: "Artifact.Time" })
export interface Info extends Schema.Schema.Type<typeof Info> {}
export const Info = Schema.Struct({
id: ID,
provider: ProviderID,
sessionID: SessionID.pipe(optional),
title: Schema.String,
entry: Schema.String,
url: Schema.String,
time: Time,
}).annotate({ identifier: "Artifact.Info" })
export interface Content extends Schema.Schema.Type<typeof Content> {}
export const Content = Schema.Struct({
info: Info,
files: Schema.Record(Schema.String, Schema.String),
}).annotate({ identifier: "Artifact.Content" })
export interface CreateInput extends Schema.Schema.Type<typeof CreateInput> {}
export const CreateInput = Schema.Struct({
title: Schema.String,
files: Schema.Record(Schema.String, Schema.String),
entry: Schema.String.pipe(optional),
provider: ProviderID.pipe(optional),
sessionID: SessionID.pipe(optional),
}).annotate({ identifier: "Artifact.CreateInput" })
export interface UpdateInput extends Schema.Schema.Type<typeof UpdateInput> {}
export const UpdateInput = Schema.Struct({
title: Schema.String.pipe(optional),
files: Schema.Record(Schema.String, Schema.String),
entry: Schema.String.pipe(optional),
sessionID: SessionID.pipe(optional),
}).annotate({ identifier: "Artifact.UpdateInput" })
const Updated = ephemeral({
type: "artifact.updated",
schema: {},
})
export const Event = { Updated, Definitions: inventory(Updated) }
@@ -37,6 +37,9 @@ export class Info extends Schema.Class<Info>("ConfigExperimental.Info")({
schedules: Schema.Boolean.pipe(optional).annotate({
description: "Enable experimental scheduled tasks that wake a session with a prompt. Defaults to false.",
}),
artifacts: Schema.Boolean.pipe(optional).annotate({
description: "Enable experimental artifacts backed by pluggable providers. Defaults to false.",
}),
subagent_depth: NonNegativeInt.pipe(optional).annotate({
description: "Maximum subagent nesting depth. Defaults to 1.",
}),
+2
View File
@@ -2,6 +2,7 @@ export * as EventManifest from "./event-manifest.js"
import { Schema } from "effect"
import { Agent } from "./agent.js"
import { Artifact } from "./artifact.js"
import { Command } from "./command.js"
import { Config } from "./config.js"
import { Credential } from "./credential.js"
@@ -65,6 +66,7 @@ const featureDefinitions = Event.inventory(
...Shell.Event.Definitions,
...Form.Event.Definitions,
...WebSearch.Event.Definitions,
...Artifact.Event.Definitions,
)
export const ServerDefinitions = Event.inventory(
+1
View File
@@ -1,4 +1,5 @@
export { Agent } from "./agent.js"
export { Artifact } from "./artifact.js"
export { Command } from "./command.js"
export { Config } from "./config.js"
export { Connection } from "./connection.js"
+242
View File
@@ -0,0 +1,242 @@
import { Artifact } from "@opencode/core/artifact"
import { KV } from "@opencode/core/kv"
import { Location } from "@opencode/core/location"
import { LocationServiceMap } from "@opencode/core/location-service-map"
import { AbsolutePath } from "@opencode/core/schema"
import { Session } from "@opencode/core/session"
import {
ArtifactNotFoundError,
FileNotFoundError,
ForbiddenError,
InvalidRequestError,
ProviderNotFoundError,
ServiceUnavailableError,
} from "@opencode/protocol/errors"
import { Effect } from "effect"
import { type HttpServerRequest, HttpServerResponse } from "effect/http"
import { HttpApiSchema } from "effect/http-api"
import { awaitPlugins, locationErrors, requestRef, response } from "../location"
import { missingSession } from "./session-error"
/** `artifacts.*` in the `server.experimental` group. Every route needs experimental.artifacts in the resolved Location. */
export const makeArtifact = Effect.gen(function* () {
const locations = yield* LocationServiceMap.Service
const sessions = yield* Session.Service
const kv = yield* KV.Service
const explicitDirectory = (
request: HttpServerRequest.HttpServerRequest,
location?: { readonly directory?: string; readonly workspace?: string },
) => {
if (location?.directory !== undefined) return location.directory
const query = new URL(request.url, "http://localhost").searchParams.get("location[directory]")
if (query) return query
const header = request.headers["x-opencode-directory"]
if (!header) return undefined
try {
return decodeURIComponent(header)
} catch {
return header
}
}
const resolveLocation = (
request: HttpServerRequest.HttpServerRequest,
options: {
readonly location?: { readonly directory?: string; readonly workspace?: string }
readonly sessionID?: Session.ID
readonly artifactID?: Artifact.ID
},
) =>
Effect.gen(function* () {
const requestedDir = explicitDirectory(request, options.location)
if (requestedDir !== undefined) {
return Location.Ref.make({ directory: AbsolutePath.make(requestedDir) })
}
if (options.sessionID !== undefined) {
const session = yield* sessions.get(options.sessionID).pipe(Effect.mapError(missingSession))
return session.location
}
if (options.artifactID !== undefined) {
const directory = yield* Artifact.locate(kv, options.artifactID)
if (directory !== undefined) {
return Location.Ref.make({ directory: AbsolutePath.make(directory) })
}
}
return requestRef(request)
})
const inLocation = <A, E>(
request: HttpServerRequest.HttpServerRequest,
options: {
readonly location?: { readonly directory?: string; readonly workspace?: string }
readonly sessionID?: Session.ID
readonly artifactID?: Artifact.ID
},
effect: Effect.Effect<A, E, Artifact.Service | Location.Service>,
) =>
Effect.gen(function* () {
const ref = yield* resolveLocation(request, options)
return yield* awaitPlugins.pipe(Effect.andThen(effect), Effect.provide(locations.get(ref)), locationErrors)
})
const mapCommon = <A, E>(effect: Effect.Effect<A, E>) =>
effect.pipe(
Effect.catchTags({
"Artifact.DisabledError": (error: Artifact.DisabledError) =>
Effect.fail(new ForbiddenError({ message: error.message })),
"Artifact.NotFoundError": (error: Artifact.NotFoundError) =>
Effect.fail(new ArtifactNotFoundError({ artifactID: error.artifactID, message: error.message })),
"Artifact.ProviderNotFoundError": (error: Artifact.ProviderNotFoundError) =>
Effect.fail(new ProviderNotFoundError({ providerID: error.providerID, message: error.message })),
"Artifact.InvalidError": (error: Artifact.InvalidError) =>
Effect.fail(
new InvalidRequestError({ message: error.message, kind: "artifact_invalid", field: error.field }),
),
"Artifact.ProviderError": (error: Artifact.ProviderError) =>
Effect.fail(new ServiceUnavailableError({ message: error.message, service: error.providerID })),
"Session.NotFoundError": (error: Session.NotFoundError) => Effect.fail(missingSession(error)),
} as never),
)
return {
providers: (
query: { readonly location?: { readonly directory?: string } },
request: HttpServerRequest.HttpServerRequest,
) =>
inLocation(
request,
{ location: query.location },
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
return yield* response(artifacts.providers())
}),
).pipe(mapCommon),
list: (
query: {
readonly location?: { readonly directory?: string }
readonly sessionID?: Session.ID
readonly provider?: Artifact.ProviderID
},
request: HttpServerRequest.HttpServerRequest,
) =>
inLocation(
request,
{ location: query.location, sessionID: query.sessionID },
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
return yield* response(artifacts.list({ sessionID: query.sessionID, provider: query.provider }))
}),
).pipe(mapCommon),
create: (
query: { readonly location?: { readonly directory?: string } },
payload: Artifact.CreateInput,
request: HttpServerRequest.HttpServerRequest,
) =>
inLocation(
request,
{ location: query.location, sessionID: payload.sessionID },
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
return yield* response(artifacts.create(payload))
}),
).pipe(mapCommon),
get: (
artifactID: Artifact.ID,
query: { readonly location?: { readonly directory?: string } },
request: HttpServerRequest.HttpServerRequest,
) =>
inLocation(
request,
{ location: query.location, artifactID },
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
return yield* response(artifacts.get(artifactID))
}),
).pipe(mapCommon),
update: (
artifactID: Artifact.ID,
query: { readonly location?: { readonly directory?: string } },
payload: Artifact.UpdateInput,
request: HttpServerRequest.HttpServerRequest,
) =>
inLocation(
request,
{ location: query.location, sessionID: payload.sessionID, artifactID },
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
return yield* response(artifacts.update(artifactID, payload))
}),
).pipe(mapCommon),
remove: (
artifactID: Artifact.ID,
query: { readonly location?: { readonly directory?: string } },
request: HttpServerRequest.HttpServerRequest,
) =>
inLocation(
request,
{ location: query.location, artifactID },
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
yield* artifacts.remove(artifactID)
return HttpApiSchema.NoContent.make()
}),
).pipe(mapCommon),
view: (
artifactID: Artifact.ID,
query: { readonly location?: { readonly directory?: string } },
request: HttpServerRequest.HttpServerRequest,
) =>
inLocation(
request,
{ location: query.location, artifactID },
Effect.gen(function* () {
const artifacts = yield* Artifact.Service
const parsed = new URL(request.url, "http://localhost")
const prefix = `/api/experimental/artifacts/${encodeURIComponent(artifactID)}/view`
if (parsed.pathname === prefix) {
yield* artifacts.info(artifactID)
return HttpServerResponse.empty({
status: 308,
headers: { location: `${prefix}/${parsed.search}` },
})
}
const subpath = extractViewSubpath(request.url, artifactID)
const file = yield* artifacts.readLocalFile(artifactID, subpath).pipe(
Effect.catchTag("Artifact.FileMissingError", (error) =>
Effect.fail(new FileNotFoundError({ path: error.path, message: error.message })),
),
)
return HttpServerResponse.uint8Array(file.bytes, {
status: 200,
contentType: file.mime,
headers: {
"access-control-allow-origin": "*",
"cache-control": "private, no-cache",
"content-security-policy": "sandbox allow-scripts",
"x-content-type-options": "nosniff",
},
})
}),
).pipe(mapCommon),
}
})
function extractViewSubpath(url: string, artifactID: Artifact.ID) {
const pathname = new URL(url, "http://localhost").pathname
const prefix = `/api/experimental/artifacts/${encodeURIComponent(artifactID)}/view/`
if (!pathname.startsWith(prefix)) return undefined
const raw = pathname.slice(prefix.length)
if (!raw) return undefined
try {
return decodeURIComponent(raw)
} catch {
return raw
}
}
@@ -17,6 +17,7 @@ import { HttpApiBuilder, HttpApiSchema } from "effect/http-api"
import { Socket } from "effect/socket"
import { Api } from "../api"
import { CorsConfig, isAllowedRequestOrigin } from "../cors"
import { makeArtifact } from "./artifact"
import { makeMediaGet } from "./media"
import { type Outbound, runPtySocket } from "./pty-socket"
import { makeSchedule } from "./schedule"
@@ -26,11 +27,19 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment
const tickets = yield* PtyTicket.Service
const cors = yield* CorsConfig
const pty = yield* PersistentPty.Service
const artifact = yield* makeArtifact
const mediaGet = yield* makeMediaGet
const schedule = yield* makeSchedule
return handlers
.handleRaw("media.get", (ctx) => mediaGet(ctx.params.hash, ctx.request))
.handle("artifacts.providers", (ctx) => artifact.providers(ctx.query, ctx.request))
.handle("artifacts.list", (ctx) => artifact.list(ctx.query, ctx.request))
.handle("artifacts.create", (ctx) => artifact.create(ctx.query, ctx.payload, ctx.request))
.handle("artifacts.get", (ctx) => artifact.get(ctx.params.artifactID, ctx.query, ctx.request))
.handle("artifacts.update", (ctx) => artifact.update(ctx.params.artifactID, ctx.query, ctx.payload, ctx.request))
.handle("artifacts.delete", (ctx) => artifact.remove(ctx.params.artifactID, ctx.query, ctx.request))
.handleRaw("artifacts.view", (ctx) => artifact.view(ctx.params.artifactID, ctx.query, ctx.request))
.handle("schedule.create", (ctx) => schedule.create(ctx.payload))
.handle("schedule.list", (ctx) => schedule.list(ctx.query.sessionID))
.handle("schedule.get", (ctx) => schedule.get(ctx.params.scheduleID))
+2
View File
@@ -21,6 +21,7 @@ import { SessionTransfer } from "@opencode/core/session/transfer"
import { InstructionEntry } from "@opencode/core/session/instruction-entry"
import { ShellSelect } from "@opencode/core/shell/select"
import { Job } from "@opencode/core/job"
import { KV } from "@opencode/core/kv"
import { Mcp } from "@opencode/core/mcp/index"
import { Global } from "@opencode/util/global"
import { FSUtil } from "@opencode/util/fs-util"
@@ -56,6 +57,7 @@ const applicationServiceNodes = [
Global.node,
FSUtil.node,
Database.node,
KV.node,
Bus.node,
EventLogger.node,
httpClient,
+218
View File
@@ -0,0 +1,218 @@
import fs from "node:fs/promises"
import path from "node:path"
import { expect } from "bun:test"
import { OpenCode } from "@opencode/client"
import { Effect } from "effect"
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
import { it } from "../../core/test/lib/effect"
import { ServerFetch } from "../src/fetch"
const client = (handler: (request: Request) => Promise<Response>) =>
OpenCode.make({
baseUrl: "http://opencode.local",
fetch: Object.assign((input: string | URL | Request, init?: RequestInit) => handler(new Request(input, init)), {
preconnect: fetch.preconnect,
}),
})
it.live("manages local and plugin-backed artifacts through /api/experimental/artifacts when enabled", () =>
Effect.gen(function* () {
const dir = (yield* tmpdirScoped("opencode-artifact-api-")).path
const global = path.join(dir, "global")
const enabled = path.join(dir, "enabled")
const enabledOther = path.join(dir, "enabled-other")
const disabled = path.join(dir, "disabled")
const pluginDir = path.join(dir, "custom-artifact-plugin")
yield* Effect.promise(async () => {
await Promise.all([global, enabled, enabledOther, disabled, pluginDir].map((item) => fs.mkdir(item, { recursive: true })))
await fs.writeFile(
path.join(pluginDir, "package.json"),
JSON.stringify({ name: "custom-artifact-plugin", type: "module", exports: "./index.js" }),
)
await fs.writeFile(
path.join(pluginDir, "index.js"),
`
const store = new Map()
const decoder = new TextDecoder()
const encoder = new TextEncoder()
export default {
id: "test-s3-artifacts",
async setup(ctx) {
await ctx.experimental.artifact.transform((editor) => {
editor.add({
id: "s3",
name: "S3 Static",
capabilities: ["static"],
prompt: "Artifacts go to a static S3 bucket.",
async create(input) {
store.set(input.id, Object.fromEntries(Object.entries(input.files).map(([k, v]) => [k, decoder.decode(v)])))
return { url: "https://artifacts.example.test/" + input.id + "/" }
},
async read(id) {
const item = store.get(id) ?? {}
return Object.fromEntries(Object.entries(item).map(([k, v]) => [k, encoder.encode(v)]))
},
async update(id, input) {
store.set(id, Object.fromEntries(Object.entries(input.files).map(([k, v]) => [k, decoder.decode(v)])))
return { url: "https://artifacts.example.test/" + id + "/" }
},
async delete(id) {
store.delete(id)
},
})
})
},
}
`,
)
await fs.writeFile(
path.join(enabled, "opencode.json"),
JSON.stringify({
plugins: [{ package: pluginDir }],
experimental: { artifacts: true },
}),
)
await fs.writeFile(
path.join(enabledOther, "opencode.json"),
JSON.stringify({
experimental: { artifacts: true },
}),
)
})
const handler = yield* ServerFetch.make({
app: { version: "test" },
database: { path: path.join(dir, "opencode.db") },
config: { directory: global, project: true, claude: false },
models: { fetch: false },
fs: { filewatcher: false },
})
const api = client(handler)
yield* Effect.promise(async () => {
// Disabled location returns ForbiddenError
await expect(
api.experimental.artifacts.list({ location: { directory: disabled } }),
).rejects.toMatchObject({ _tag: "ForbiddenError" })
// Providers list includes built-in local (default) and plugin-registered s3
const providers = await api.experimental.artifacts.providers({ location: { directory: enabled } })
expect(providers.data).toEqual([
{ id: "local", name: "Local", capabilities: ["static"], default: true },
{ id: "s3", name: "S3 Static", capabilities: ["static"], default: false },
])
const session = await api.session.create({ location: { directory: enabled } })
// Create local multi-file artifact linked to session
const created = await api.experimental.artifacts.create({
location: { directory: enabled },
sessionID: session.id,
title: "Wait stats",
files: {
"index.html": "<!doctype html><h1>v1</h1><script src='./assets/app.js'></script>",
"assets/app.js": "window.VERSION = 1",
},
})
expect(created.data).toMatchObject({
provider: "local",
sessionID: session.id,
title: "Wait stats",
entry: "index.html",
url: `/api/experimental/artifacts/${encodeURIComponent(created.data.id)}/view/`,
})
// Redirects /view -> /view/ with 308 so relative "./assets/*" resolves
const redirect = await handler(
new Request(`http://opencode.local/api/experimental/artifacts/${created.data.id}/view`),
)
expect(redirect.status).toBe(308)
expect(redirect.headers.get("location")).toBe(`/api/experimental/artifacts/${created.data.id}/view/`)
// Serves entry HTML and relative JS in a sandboxed opaque origin without requiring location query
const v1Html = await handler(
new Request(`http://opencode.local/api/experimental/artifacts/${created.data.id}/view/`),
)
expect(v1Html.status).toBe(200)
expect(v1Html.headers.get("content-type")).toContain("text/html")
expect(v1Html.headers.get("content-security-policy")).toBe("sandbox allow-scripts")
expect(await v1Html.text()).toContain("<h1>v1</h1>")
// Sessionless SDK artifact also resolves its stored directory at /view/
const sessionless = await api.experimental.artifacts.create({
location: { directory: enabled },
title: "Standalone report",
files: { "index.html": "<h1>no-session</h1>" },
})
const sessionlessHtml = await handler(
new Request(`http://opencode.local${sessionless.data.url}`),
)
expect(sessionlessHtml.status).toBe(200)
expect(await sessionlessHtml.text()).toContain("<h1>no-session</h1>")
// Another enabled project cannot list, read, update, or delete this project's artifacts
const otherList = await api.experimental.artifacts.list({ location: { directory: enabledOther } })
expect(otherList.data).toEqual([])
await expect(
api.experimental.artifacts.get({ artifactID: created.data.id, location: { directory: enabledOther } }),
).rejects.toMatchObject({ _tag: "ArtifactNotFoundError" })
await expect(
api.experimental.artifacts.delete({ artifactID: created.data.id, location: { directory: enabledOther } }),
).rejects.toMatchObject({ _tag: "ArtifactNotFoundError" })
const v1Js = await handler(
new Request(`http://opencode.local/api/experimental/artifacts/${created.data.id}/view/assets/app.js`),
)
expect(v1Js.status).toBe(200)
expect(await v1Js.text()).toBe("window.VERSION = 1")
// Update replaces files at the same ID and URL
const updated = await api.experimental.artifacts.update({
artifactID: created.data.id,
files: {
"index.html": "<!doctype html><h1>v2</h1>",
},
})
expect(updated.data.url).toBe(created.data.url)
const latestHtml = await handler(
new Request(`http://opencode.local/api/experimental/artifacts/${created.data.id}/view/`),
)
expect(await latestHtml.text()).toContain("<h1>v2</h1>")
// Per-request override to plugin-registered "s3" provider
const remote = await api.experimental.artifacts.create({
location: { directory: enabled },
sessionID: session.id,
provider: "s3",
title: "Shared bundle",
files: { "index.html": "<p>remote</p>" },
})
expect(remote.data).toMatchObject({
provider: "s3",
url: `https://artifacts.example.test/${remote.data.id}/`,
})
const fetchedRemote = await api.experimental.artifacts.get({
artifactID: remote.data.id,
location: { directory: enabled },
})
expect(fetchedRemote.data.files).toEqual({ "index.html": "<p>remote</p>" })
const listedS3 = await api.experimental.artifacts.list({
sessionID: session.id,
provider: "s3",
})
expect(listedS3.data.map((item) => item.id)).toEqual([remote.data.id])
// Delete removes record and returns 404 thereafter
await api.experimental.artifacts.delete({ artifactID: created.data.id, location: { directory: enabled } })
await expect(
api.experimental.artifacts.get({ artifactID: created.data.id, location: { directory: enabled } }),
).rejects.toMatchObject({
_tag: "ArtifactNotFoundError",
})
})
}),
)