diff --git a/packages/client/script/generate.ts b/packages/client/script/generate.ts index d828797d473..2aa8604988c 100644 --- a/packages/client/script/generate.ts +++ b/packages/client/script/generate.ts @@ -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), diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 68ae125a3c4..2e2a0b9651d 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -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 = ( input: ExperimentalScheduleDeleteInput, ) => Effect.Effect +export type ExperimentalArtifactsProvidersInput = { + readonly location?: { readonly directory?: string | undefined } | undefined +} +export type ExperimentalArtifactsProvidersOutput = { + readonly location: Location.PublicRef + readonly data: ReadonlyArray +} +export type ExperimentalArtifactsProvidersOperation = ( + input?: ExperimentalArtifactsProvidersInput, +) => Effect.Effect + +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 +} +export type ExperimentalArtifactsListOperation = ( + input?: ExperimentalArtifactsListInput, +) => Effect.Effect + +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 = ( + input: ExperimentalArtifactsCreateInput, +) => Effect.Effect + +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 = ( + input: ExperimentalArtifactsGetInput, +) => Effect.Effect + +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 = ( + input: ExperimentalArtifactsUpdateInput, +) => Effect.Effect + +export type ExperimentalArtifactsDeleteInput = { + readonly artifactID: Artifact.ID + readonly location?: { readonly directory?: string | undefined } | undefined +} +export type ExperimentalArtifactsDeleteOutput = void +export type ExperimentalArtifactsDeleteOperation = ( + input: ExperimentalArtifactsDeleteInput, +) => Effect.Effect + export interface ExperimentalApi { readonly persistentPty: { readonly read: ExperimentalPersistentPtyReadOperation @@ -2436,6 +2506,14 @@ export interface ExperimentalApi { readonly resume: ExperimentalScheduleResumeOperation readonly delete: ExperimentalScheduleDeleteOperation } + readonly artifacts: { + readonly providers: ExperimentalArtifactsProvidersOperation + readonly list: ExperimentalArtifactsListOperation + readonly create: ExperimentalArtifactsCreateOperation + readonly get: ExperimentalArtifactsGetOperation + readonly update: ExperimentalArtifactsUpdateOperation + readonly delete: ExperimentalArtifactsDeleteOperation + } } export type ShellListInput = { readonly location?: { readonly directory?: string | undefined } | undefined } diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index b57d2c379aa..a129b28e93e 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -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()( + raw["artifacts.providers"]({ query: { location: input?.["location"] } }).pipe(Effect.mapError(mapClientError)), + ) + +const EndpointExperimentalArtifactsList = + (raw: RawClient["server.experimental"]) => (input?: ExperimentalArtifactsListInput) => + preserveEffect()( + 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()( + 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()( + raw["artifacts.get"]({ + params: { artifactID: input["artifactID"] }, + query: { location: input["location"] }, + }).pipe(Effect.mapError(mapClientError)), + ) + +const EndpointExperimentalArtifactsUpdate = + (raw: RawClient["server.experimental"]) => (input: ExperimentalArtifactsUpdateInput) => + preserveEffect()( + 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()( + 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) => diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index cadaa8b85a3..42b961eacc7 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -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( + { + 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( + { + 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( + { + 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( + { + 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( + { + 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( + { + 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( + { + 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) => diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index d9b299ebbd7..ac80fd23e80 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -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; 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 } + +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 } + +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 } diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index b27962332d7..a3ad7ec2593 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -62,6 +62,7 @@ test("exposes every standard HTTP API group", () => { "persistentPty", "media", "schedule", + "artifacts", "migration", "usage", "config", diff --git a/packages/core/src/artifact.ts b/packages/core/src/artifact.ts new file mode 100644 index 00000000000..ed09984ec0c --- /dev/null +++ b/packages/core/src/artifact.ts @@ -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> + readonly sessionID?: SessionID +} + +export interface ProviderUpdateInput { + readonly title: string + readonly entry: string + readonly files: Readonly> + 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 + readonly read: (id: ID) => Effect.Effect>, unknown> + readonly update: (id: ID, input: ProviderUpdateInput) => Effect.Effect + readonly delete: (id: ID) => Effect.Effect +} + +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()("Artifact.DisabledError", {}) { + override get message() { + return "Artifacts are disabled; set experimental.artifacts in config" + } +} + +export class NotFoundError extends Schema.TaggedError()("Artifact.NotFoundError", { + artifactID: ID, +}) { + override get message() { + return `Artifact not found: ${this.artifactID}` + } +} + +export class FileMissingError extends Schema.TaggedError()("Artifact.FileMissingError", { + artifactID: ID, + path: Schema.String, +}) { + override get message() { + return `Artifact file not found: ${this.path}` + } +} + +export class ProviderNotFoundError extends Schema.TaggedError()( + "Artifact.ProviderNotFoundError", + { + providerID: ProviderID, + }, +) { + override get message() { + return `Artifact provider not found: ${this.providerID}` + } +} + +export class InvalidError extends Schema.TaggedError()("Artifact.InvalidError", { + reason: Schema.String, + field: Schema.optional(Schema.String), +}) { + override get message() { + return this.reason + } +} + +export class ProviderError extends Schema.TaggedError()("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 + selection?: ProviderID +} + +export interface Interface extends State.Transformable { + readonly enabled: () => Effect.Effect + readonly providers: () => Effect.Effect + readonly prompts: () => Effect.Effect + readonly list: (filter?: { + readonly sessionID?: SessionID + readonly provider?: ProviderID + }) => Effect.Effect + readonly create: (input: CreateInput) => Effect.Effect + readonly get: (id: ID) => Effect.Effect + readonly info: (id: ID) => Effect.Effect + readonly update: (id: ID, input: UpdateInput) => Effect.Effect + readonly remove: (id: ID) => Effect.Effect + readonly readLocalFile: ( + id: ID, + subpath?: string, + ) => Effect.Effect +} + +export class Service extends Context.Service()("@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({ + 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>) { + return Object.fromEntries(Object.entries(files).map(([filePath, content]) => [filePath, encoder.encode(content)])) +} + +function decodeReadFiles(files: Readonly>) { + 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 { + 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>) { + 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() + for (const [rawPath, content] of entries) { + const clean = yield* normalizePath(rawPath) + normalized.set(clean, content) + } + return Object.fromEntries(normalized) + }) +} + +function resolveEntry(files: Readonly>, 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>) { + 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 = {} + const walk = async (current: string, prefix: string): Promise => { + 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 + }) +} diff --git a/packages/core/src/config/normalize.ts b/packages/core/src/config/normalize.ts index 1ab9ffe1e0b..1ef08471294 100644 --- a/packages/core/src/config/normalize.ts +++ b/packages/core/src/config/normalize.ts @@ -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, diff --git a/packages/core/src/instance.ts b/packages/core/src/instance.ts index 6368c95a64c..0691d633215 100644 --- a/packages/core/src/instance.ts +++ b/packages/core/src/instance.ts @@ -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, diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index 4485a0ab773..56a6a027f63 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -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, diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index 6ee27e4aeb9..7db8143c246 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -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, diff --git a/packages/core/src/tool/plugin/artifact.ts b/packages/core/src/tool/plugin/artifact.ts new file mode 100644 index 00000000000..52875543289 --- /dev/null +++ b/packages/core/src/tool/plugin/artifact.ts @@ -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") + }), + ) +} diff --git a/packages/core/test/artifact.test.ts b/packages/core/test/artifact.test.ts new file mode 100644 index 00000000000..5cbc5a4b2a0 --- /dev/null +++ b/packages/core/test/artifact.test.ts @@ -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": "

hi

" } }) + .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>() + 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": "", + "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": "

Notes

" }, + 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": "

v2

" }, + })) 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))) + }), + ) +}) diff --git a/packages/core/test/plugin/fixture.ts b/packages/core/test/plugin/fixture.ts index c8f3a06a727..d3d3fcea05c 100644 --- a/packages/core/test/plugin/fixture.ts +++ b/packages/core/test/plugin/fixture.ts @@ -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, diff --git a/packages/core/test/plugin/host.ts b/packages/core/test/plugin/host.ts index 74d2899d058..bc436ab7d24 100644 --- a/packages/core/test/plugin/host.ts +++ b/packages/core/test/plugin/host.ts @@ -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"), diff --git a/packages/plugin/src/effect/artifact.ts b/packages/plugin/src/effect/artifact.ts new file mode 100644 index 00000000000..4330d6df9a0 --- /dev/null +++ b/packages/plugin/src/effect/artifact.ts @@ -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> + readonly sessionID?: Session.ID +} + +export interface ArtifactProviderUpdateInput { + readonly title: string + readonly entry: string + readonly files: Readonly> + 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 + readonly read: (id: Artifact.ID) => Effect.Effect>, unknown> + readonly update: ( + id: Artifact.ID, + input: ArtifactProviderUpdateInput, + ) => Effect.Effect + readonly delete: (id: Artifact.ID) => Effect.Effect +} + +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 + readonly reload: () => Effect.Effect +} diff --git a/packages/plugin/src/effect/index.ts b/packages/plugin/src/effect/index.ts index 9f4047f075d..952ce71d24b 100644 --- a/packages/plugin/src/effect/index.ts +++ b/packages/plugin/src/effect/index.ts @@ -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" diff --git a/packages/plugin/src/effect/plugin.ts b/packages/plugin/src/effect/plugin.ts index 9902197bfa4..32004d4d7d8 100644 --- a/packages/plugin/src/effect/plugin.ts +++ b/packages/plugin/src/effect/plugin.ts @@ -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["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 diff --git a/packages/plugin/src/promise/adapter.ts b/packages/plugin/src/promise/adapter.ts index d3932b50a5c..62387459a66 100644 --- a/packages/plugin/src/promise/adapter.ts +++ b/packages/plugin/src/promise/adapter.ts @@ -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), diff --git a/packages/plugin/src/promise/artifact.ts b/packages/plugin/src/promise/artifact.ts new file mode 100644 index 00000000000..a93daafd850 --- /dev/null +++ b/packages/plugin/src/promise/artifact.ts @@ -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> + readonly sessionID?: Session.ID +} + +export interface ArtifactProviderUpdateInput { + readonly title: string + readonly entry: string + readonly files: Readonly> + 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 + readonly read: ( + id: Artifact.ID, + context: { readonly signal: AbortSignal }, + ) => Promise>> + readonly update: ( + id: Artifact.ID, + input: ArtifactProviderUpdateInput, + context: { readonly signal: AbortSignal }, + ) => Promise + readonly delete: (id: Artifact.ID, context: { readonly signal: AbortSignal }) => Promise +} + +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 + readonly reload: () => Promise +} diff --git a/packages/plugin/src/promise/index.ts b/packages/plugin/src/promise/index.ts index 1a8b1bb1e4d..332e507ba53 100644 --- a/packages/plugin/src/promise/index.ts +++ b/packages/plugin/src/promise/index.ts @@ -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" diff --git a/packages/plugin/src/promise/plugin.ts b/packages/plugin/src/promise/plugin.ts index d12eaeefb75..6e22d0547e8 100644 --- a/packages/plugin/src/promise/plugin.ts +++ b/packages/plugin/src/promise/plugin.ts @@ -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 /** 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 diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 3fc515d3710..93984c663db 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -10675,6 +10675,7 @@ "form.replied", "form.cancelled", "websearch.updated", + "artifact.updated", "session.status", "session.idle", "tui.prompt.append", @@ -10782,6 +10783,7 @@ "form.replied", "form.cancelled", "websearch.updated", + "artifact.updated", "session.status", "session.idle", "tui.prompt.append", @@ -13096,6 +13098,890 @@ "summary": "Resume schedule" } }, + "/api/experimental/artifacts/providers": { + "get": { + "tags": ["experimental"], + "operationId": "experimental.artifacts.providers", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.PublicRef" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Artifact.Provider" + } + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "Return active artifact providers and default. Experimental: needs experimental.artifacts in the Location's config and may change without notice.", + "summary": "List artifact providers" + } + }, + "/api/experimental/artifacts": { + "get": { + "tags": ["experimental"], + "operationId": "experimental.artifacts.list", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false + }, + { + "name": "sessionID", + "in": "query", + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/Session.ID" + }, + { + "type": "null" + } + ] + }, + "required": false + }, + { + "name": "provider", + "in": "query", + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/Artifact.ProviderIDEncoded" + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.PublicRef" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Artifact.Info" + } + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "List published artifacts, newest update first. Experimental: needs experimental.artifacts in the Location's config and may change without notice.", + "summary": "List artifacts" + }, + "post": { + "tags": ["experimental"], + "operationId": "experimental.artifacts.create", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.PublicRef" + }, + "data": { + "$ref": "#/components/schemas/Artifact.Info" + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "ProviderNotFoundError | SessionNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ProviderNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/SessionNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "Publish a new artifact through the selected or default artifact provider. Experimental: needs experimental.artifacts in the Location's config and may change without notice.", + "summary": "Create artifact", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Artifact.CreateInput" + } + } + }, + "required": true + } + } + }, + "/api/experimental/artifacts/{artifactID}": { + "get": { + "tags": ["experimental"], + "operationId": "experimental.artifacts.get", + "parameters": [ + { + "name": "artifactID", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Artifact.ID" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.PublicRef" + }, + "data": { + "$ref": "#/components/schemas/Artifact.Content" + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "ArtifactNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ArtifactNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "Read an artifact's metadata and file contents. Experimental: needs experimental.artifacts in the Location's config and may change without notice.", + "summary": "Read artifact" + }, + "patch": { + "tags": ["experimental"], + "operationId": "experimental.artifacts.update", + "parameters": [ + { + "name": "artifactID", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Artifact.ID" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.PublicRef" + }, + "data": { + "$ref": "#/components/schemas/Artifact.Info" + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "SessionNotFoundError | ArtifactNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/ArtifactNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "Replace an artifact's files at the same ID and URL. Experimental: needs experimental.artifacts in the Location's config and may change without notice.", + "summary": "Update artifact", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Artifact.UpdateInput" + } + } + }, + "required": true + } + }, + "delete": { + "tags": ["experimental"], + "operationId": "experimental.artifacts.delete", + "parameters": [ + { + "name": "artifactID", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Artifact.ID" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "ArtifactNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ArtifactNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "Remove an artifact and its stored files. Experimental: needs experimental.artifacts in the Location's config and may change without notice.", + "summary": "Delete artifact" + } + }, + "/api/experimental/artifacts/{artifactID}/view/*": { + "get": { + "tags": ["experimental"], + "operationId": "experimental.artifacts.view", + "parameters": [ + { + "name": "artifactID", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Artifact.ID" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "FileNotFoundError | ArtifactNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/FileNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/ArtifactNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "Serve HTML and static files from the local provider. Experimental: needs experimental.artifacts in the Location's config and may change without notice.", + "summary": "View local artifact" + } + }, "/api/shell": { "get": { "tags": ["shell"], @@ -15661,6 +16547,160 @@ "required": ["_tag", "agentID", "message"], "additionalProperties": false }, + "Artifact.Capability": { + "type": "string", + "enum": ["static", "server-code", "sqlite", "durable-objects"] + }, + "Artifact.Content": { + "type": "object", + "properties": { + "info": { + "$ref": "#/components/schemas/Artifact.Info" + }, + "files": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": ["info", "files"], + "additionalProperties": false + }, + "Artifact.CreateInput": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "files": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "entry": { + "type": "string" + }, + "provider": { + "type": "string" + }, + "sessionID": { + "$ref": "#/components/schemas/Session.ID" + } + }, + "required": ["title", "files"], + "additionalProperties": false + }, + "Artifact.ID": { + "type": "string", + "pattern": "^art_" + }, + "Artifact.Info": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Artifact.ID" + }, + "provider": { + "$ref": "#/components/schemas/Artifact.ProviderIDEncoded" + }, + "sessionID": { + "$ref": "#/components/schemas/Session.ID" + }, + "title": { + "type": "string" + }, + "entry": { + "type": "string" + }, + "url": { + "type": "string" + }, + "time": { + "$ref": "#/components/schemas/Artifact.Time" + } + }, + "required": ["id", "provider", "title", "entry", "url", "time"], + "additionalProperties": false + }, + "Artifact.Provider": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Artifact.ProviderIDEncoded" + }, + "name": { + "type": "string" + }, + "capabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Artifact.Capability" + } + }, + "default": { + "type": "boolean" + } + }, + "required": ["id", "name", "capabilities", "default"], + "additionalProperties": false + }, + "Artifact.ProviderIDEncoded": { + "type": "string" + }, + "Artifact.Time": { + "type": "object", + "properties": { + "created": { + "type": "number" + }, + "updated": { + "type": "number" + } + }, + "required": ["created", "updated"], + "additionalProperties": false + }, + "Artifact.UpdateInput": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "files": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "entry": { + "type": "string" + }, + "sessionID": { + "$ref": "#/components/schemas/Session.ID" + } + }, + "required": ["files"], + "additionalProperties": false + }, + "ArtifactNotFoundErrorEncoded": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": ["ArtifactNotFoundError"] + }, + "artifactID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": ["_tag", "artifactID", "message"], + "additionalProperties": false + }, "Command.Info": { "type": "object", "properties": { @@ -16304,6 +17344,9 @@ "schedules": { "type": "boolean" }, + "artifacts": { + "type": "boolean" + }, "subagent_depth": { "type": "integer", "minimum": 0, diff --git a/packages/protocol/src/client.ts b/packages/protocol/src/client.ts index 40ae172abb4..b46ff3d9056 100644 --- a/packages/protocol/src/client.ts +++ b/packages/protocol/src/client.ts @@ -84,6 +84,7 @@ export const effectOmitEndpoints = new Set([ "fs.read", "fs.write", "media.get", + "artifacts.view", "pty.connect", "persistentPty.connect", "mcp.client", diff --git a/packages/protocol/src/errors.ts b/packages/protocol/src/errors.ts index 951db21b3d9..c9f8fa5c3d5 100644 --- a/packages/protocol/src/errors.ts +++ b/packages/protocol/src/errors.ts @@ -333,3 +333,12 @@ export class ScheduleNotFoundError extends Schema.TaggedError()( + "ArtifactNotFoundError", + { + artifactID: Schema.String, + message: Schema.String, + }, + { httpApiStatus: 404 }, +) {} diff --git a/packages/protocol/src/groups/artifact.ts b/packages/protocol/src/groups/artifact.ts new file mode 100644 index 00000000000..0d679828708 --- /dev/null +++ b/packages/protocol/src/groups/artifact.ts @@ -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 diff --git a/packages/protocol/src/groups/experimental.ts b/packages/protocol/src/groups/experimental.ts index c1513517a6c..3f3cd006e83 100644 --- a/packages/protocol/src/groups/experimental.ts +++ b/packages/protocol/src/groups/experimental.ts @@ -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) diff --git a/packages/schema/src/artifact.ts b/packages/schema/src/artifact.ts new file mode 100644 index 00000000000..86b1e3ef870 --- /dev/null +++ b/packages/schema/src/artifact.ts @@ -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 {} +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 {} +export const Time = Schema.Struct({ + created: Schema.Finite, + updated: Schema.Finite, +}).annotate({ identifier: "Artifact.Time" }) + +export interface Info extends Schema.Schema.Type {} +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 {} +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 {} +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 {} +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) } diff --git a/packages/schema/src/config/experimental.ts b/packages/schema/src/config/experimental.ts index 83ad0a9d212..123e24fd3c2 100644 --- a/packages/schema/src/config/experimental.ts +++ b/packages/schema/src/config/experimental.ts @@ -37,6 +37,9 @@ export class Info extends Schema.Class("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.", }), diff --git a/packages/schema/src/event-manifest.ts b/packages/schema/src/event-manifest.ts index c0ff5825066..f0c5bd30e01 100644 --- a/packages/schema/src/event-manifest.ts +++ b/packages/schema/src/event-manifest.ts @@ -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( diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts index c7718c9f568..8d61a45d0dc 100644 --- a/packages/schema/src/index.ts +++ b/packages/schema/src/index.ts @@ -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" diff --git a/packages/server/src/handlers/artifact.ts b/packages/server/src/handlers/artifact.ts new file mode 100644 index 00000000000..1a217107f20 --- /dev/null +++ b/packages/server/src/handlers/artifact.ts @@ -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 = ( + request: HttpServerRequest.HttpServerRequest, + options: { + readonly location?: { readonly directory?: string; readonly workspace?: string } + readonly sessionID?: Session.ID + readonly artifactID?: Artifact.ID + }, + effect: Effect.Effect, + ) => + Effect.gen(function* () { + const ref = yield* resolveLocation(request, options) + return yield* awaitPlugins.pipe(Effect.andThen(effect), Effect.provide(locations.get(ref)), locationErrors) + }) + + const mapCommon = (effect: Effect.Effect) => + 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 + } +} diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index b3a2d0802b0..b8c918c9bc4 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -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)) diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index e3ae6830b19..0c065bc2b79 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -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, diff --git a/packages/server/test/artifact.test.ts b/packages/server/test/artifact.test.ts new file mode 100644 index 00000000000..3ee6047e0c0 --- /dev/null +++ b/packages/server/test/artifact.test.ts @@ -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) => + 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": "

v1

", + "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("

v1

") + + // 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": "

no-session

" }, + }) + const sessionlessHtml = await handler( + new Request(`http://opencode.local${sessionless.data.url}`), + ) + expect(sessionlessHtml.status).toBe(200) + expect(await sessionlessHtml.text()).toContain("

no-session

") + + // 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": "

v2

", + }, + }) + 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("

v2

") + + // 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": "

remote

" }, + }) + 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": "

remote

" }) + + 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", + }) + }) + }), +)