feat(core): store and validate live widget template capabilities

This commit is contained in:
OpenCode Agent 2026-11-20 21:33:14 +00:00
parent 87adbecebe
commit 61ec2cefc7
6 changed files with 120 additions and 3 deletions

View file

@ -262,6 +262,7 @@ export default Plugin.define({
...(input.title === undefined ? {} : { title: input.title }),
status: "open",
wait: input.wait === true,
...(template.capabilities === undefined ? {} : { capabilities: template.capabilities }),
time: { created: yield* Clock.currentTimeMillis },
}
if (!state.wait) {
@ -306,6 +307,7 @@ export default Plugin.define({
data: yield* required("data", input.data),
source: yield* required("source", input.source),
...(input.mode === undefined ? {} : { mode: input.mode }),
...(input.capabilities === undefined ? {} : { capabilities: input.capabilities }),
example: yield* required("example", input.example),
})
.pipe(Effect.mapError(toolError))

View file

@ -164,6 +164,17 @@ ui.shader(wgsl, { id, height, width, values, fps, alt, poster }) a WGSL fragme
Children may contain `null` or `false` (for `cond && node`) and nested arrays.
## Live templates and capabilities
Save a template with `mode: "live"` for games, timers, animations and live dashboards: it defines
`async function main(data)` instead of `init`/`view`/`update`, and runs until it calls `widget.submit` or
`widget.dismiss` (see the spec's `widgets-live.md`). The server only checks that it compiles.
A live template that calls `widget.fetch` declares the hosts it needs, as narrowly as it can:
`capabilities: { https: { hosts: ["api.github.com"] } }` (exact hosts, `*.example.com`, or `["*"]` only if it truly
needs any host). Step templates can't declare capabilities. Fetching from the widget is for live dashboards that must
refresh while open; for anything else, fetch the data yourself and pass it in `data`.
## Canvas and shader
Use a **canvas** for custom 2D graphics driven by data and state: charts, diagrams, gauges, small games, anything that

View file

@ -45,6 +45,8 @@ export interface SaveInput {
readonly source: string
/** `step` (default) or `live` (widgets-live.md). */
readonly mode?: Widget.Mode
/** Live templates only. */
readonly capabilities?: Widget.Capabilities
/**
* Data checked against `data` and, for a step template, run through `init` (which renders the first view) before the
* template is stored. A live template is only compiled.
@ -64,14 +66,41 @@ const builtin = new Map(builtins.map((template) => [template.name, decode({ mode
* A template's content address. Step templates use `@opencode/widget`'s `version`; a live template's also covers its
* mode, so the same source and schema in the other mode is another version.
*/
export const versionOf = (source: string, data: Widget.DataSchema, mode: Widget.Mode) =>
export const versionOf = (
source: string,
data: Widget.DataSchema,
mode: Widget.Mode,
capabilities?: Widget.Capabilities,
) =>
mode === "step"
? version(source, data)
: createHash("sha256")
.update(program(source) + "\n" + JSON.stringify(data) + "\nlive")
.update(
program(source) +
"\n" +
JSON.stringify(data) +
"\nlive" +
(capabilities === undefined ? "" : "\n" + JSON.stringify(capabilities)),
)
.digest("hex")
.slice(0, 16)
// An exact host name, or `*.` and a host name for any subdomain of it.
const HOST = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/
/** Why `capabilities` can't be stored on a template of `mode`, if they can't. */
export function capabilitiesProblem(mode: Widget.Mode, capabilities: Widget.Capabilities | undefined) {
if (capabilities === undefined) return
if (mode !== "live") return "only live templates can declare capabilities"
const hosts = capabilities.https?.hosts
if (hosts === undefined) return
if (hosts.length === 0) return "https.hosts lists no hosts; leave https out instead"
if (hosts.length > 32) return "https.hosts lists more than 32 hosts"
const bad = hosts.find((host) => host !== "*" && !HOST.test(host))
if (bad !== undefined)
return `https.hosts entry ${JSON.stringify(bad)} is not a host name like "api.example.com", "*.example.com" or "*"`
}
// A version lives under its content address and never changes; `latest:<name>` names the newest saved one.
const versionKey = (name: string, version: string) => `template:${name}:${version}`
const latestKey = (name: string) => `latest:${name}`
@ -154,10 +183,13 @@ export const make = (storage: StorageDomain) => {
if (input.description.trim() === "") return yield* invalid("description is empty")
if (input.data.type !== "object") return yield* invalid('the data schema must have type "object"')
const mode = input.mode ?? "step"
const problem = capabilitiesProblem(mode, input.capabilities)
if (problem) return yield* invalid(problem)
const template = decode({
name: input.name,
version: versionOf(input.source, input.data, mode),
version: versionOf(input.source, input.data, mode, input.capabilities),
mode,
...(input.capabilities === undefined ? {} : { capabilities: input.capabilities }),
description: input.description.trim(),
data: input.data,
source: input.source,

View file

@ -62,6 +62,10 @@ export const TemplateInput = Schema.Struct({
description:
'For save: "step" (default) for init/view/update templates, "live" for a long-running async main(data) (games, timers, animations)',
}),
capabilities: Widget.Capabilities.pipe(optional).annotate({
description:
'For save, live templates only: what the widget may use, e.g. { https: { hosts: ["api.github.com"] } } for widget.fetch. Declare the fewest hosts it needs',
}),
example: Schema.Record(Schema.String, Schema.Json)
.pipe(optional)
.annotate({ description: "Example data (a JSON object) to test the template with, for save" }),

View file

@ -193,6 +193,61 @@ describe("live templates", () => {
))
})
describe("capabilities", () => {
const source = `async function main(data) {
const response = await widget.fetch("https://api.github.com/zen")
widget.render(ui.text(await response.text()))
}`
const save = (fake: Effect.Success<typeof make>, input: Record<string, unknown>) =>
execute(fake, "widget_template", {
action: "save",
name: "zen",
description: "GitHub zen",
data: pickerSchema,
source,
example: { items: ["a"] },
mode: "live",
...input,
})
test("stores a live template's capabilities in its version, summary, program and widget states", () =>
run((fake) =>
Effect.gen(function* () {
const capabilities = { https: { hosts: ["api.github.com", "*.githubusercontent.com"] } }
yield* save(fake, {})
const bare = yield* fake.call<Widget.Program>("program", { name: "zen" })
yield* save(fake, { capabilities })
const granted = yield* fake.call<Widget.Program>("program", { name: "zen" })
expect(bare.capabilities).toBeUndefined()
expect(granted).toMatchObject({ capabilities })
expect(granted.version).not.toBe(bare.version)
expect(
(yield* fake.call<ReadonlyArray<Widget.Summary>>("templates", {})).find((item) => item.name === "zen"),
).toMatchObject({ capabilities })
yield* execute(fake, "widget", { template: "zen", data: { items: ["x"] } })
expect((yield* states(fake))[0]).toMatchObject({ capabilities })
}),
))
test("rejects capabilities on step templates and host lists that are not host names", () =>
run((fake) =>
Effect.gen(function* () {
const reason = (input: Record<string, unknown>) =>
save(fake, input).pipe(Effect.map((exit) => String(failure(exit))))
expect(
yield* reason({ mode: "step", source: pickerSource, capabilities: { https: { hosts: ["api.github.com"] } } }),
).toContain("only live templates can declare capabilities")
expect(yield* reason({ capabilities: { https: { hosts: ["https://api.github.com/"] } } })).toContain(
"is not a host name",
)
expect(yield* reason({ capabilities: { https: { hosts: [] } } })).toContain("lists no hosts")
expect(Exit.isSuccess(yield* save(fake, { capabilities: { https: { hosts: ["*"] } } }))).toBe(true)
}),
))
})
describe("widget answers", () => {
const show = (fake: Effect.Success<typeof make>) =>
Effect.gen(function* () {

View file

@ -30,6 +30,15 @@ export type DataSchema = typeof DataSchema.Type
export const Mode = Schema.Literals(["step", "live"]).annotate({ identifier: "Widget.Mode" })
export type Mode = typeof Mode.Type
/**
* What a live template may use beyond rendering (widgets-live.md, Capabilities). `https.hosts` entries are exact host
* names or `*.` suffix wildcards; `["*"]` is any host.
*/
export interface Capabilities extends Schema.Schema.Type<typeof Capabilities> {}
export const Capabilities = Schema.Struct({
https: optional(Schema.Struct({ hosts: Schema.Array(Schema.String) })),
}).annotate({ identifier: "Widget.Capabilities" })
/** A template version without its source, as listed. */
export interface Summary extends Schema.Schema.Type<typeof Summary> {}
export const Summary = Schema.Struct({
@ -39,6 +48,8 @@ export const Summary = Schema.Struct({
description: Schema.String,
data: DataSchema,
mode: Mode,
/** Live templates only. */
capabilities: optional(Capabilities),
builtin: Schema.Boolean,
}).annotate({ identifier: "Widget.Summary" })
@ -85,6 +96,8 @@ export const State = Schema.Struct({
response: optional(Schema.Json),
/** The tool call waits for the answer and returns it as its result. */
wait: Schema.Boolean,
/** The template's capabilities, so clients can show what the widget is granted. */
capabilities: optional(Capabilities),
/** Epoch milliseconds. */
time: Schema.Struct({ created: Schema.Number, responded: optional(Schema.Number) }),
}).annotate({ identifier: "Widget.State" })