diff --git a/agent/package.json b/agent/package.json index 7b8df161..aa5a880c 100644 --- a/agent/package.json +++ b/agent/package.json @@ -1,6 +1,6 @@ { "name": "@forge-ui-official/agent", - "version": "0.4.0", + "version": "0.5.0", "description": "Forge Agent — an embeddable AI agent that understands your product, calls its tools and answers with Forge components", "license": "MIT", "private": false, @@ -37,7 +37,7 @@ "prepublishOnly": "pnpm build && pnpm typecheck && pnpm test" }, "peerDependencies": { - "@forge-ui-official/core": ">=0.8.3", + "@forge-ui-official/core": ">=0.9.0", "react": ">=19", "react-dom": ">=19" }, diff --git a/agent/src/catalog/blocks.ts b/agent/src/catalog/blocks.ts index c81a534f..5b720346 100644 --- a/agent/src/catalog/blocks.ts +++ b/agent/src/catalog/blocks.ts @@ -1,19 +1,11 @@ -import { uiSchemas, type UiToolName } from "./schema"; +import { BLOCK_OF, parseBlock, uiToolNames, type UiToolName } from "./schema"; /** * The model writes components inside its answer as fenced blocks (```forge:cards + JSON), so a whole * answer, components included, comes from one model step. Splitting the text turns each block into * a component; plain code fences become code or a copyable command. */ -export const BLOCK_NAMES: Record = { - "forge:cards": "show_cards", - "forge:steps": "show_steps", - "forge:table": "show_table", - "forge:metrics": "show_metrics", - "forge:chart": "show_chart", - "forge:choices": "show_choices", - "forge:followups": "suggest_followups", -}; +export const BLOCK_NAMES: Record = Object.fromEntries(uiToolNames.map(name => [BLOCK_OF[name], name])); export type Segment = | { kind: "text"; text: string } @@ -24,20 +16,46 @@ export type Segment = const SHELL = new Set(["bash", "sh", "shell", "zsh", "console", "terminal"]); const FENCE = /^ {0,3}(`{3,})[ \t]*([^\s`]*)[^\n]*$/; -function blockInput(name: UiToolName, body: string): unknown { - let value: unknown; +/** + * Models often quote words inside a string with plain double quotes (不是"接上就好"). A quote is + * structural only next to JSON punctuation; any other quote inside a string is escaped. + */ +export function repairQuotes(body: string) { + let out = ""; + let inString = false; + for (let index = 0; index < body.length; index++) { + const char = body[index]; + if (char === "\\" && inString) { out += char + (body[index + 1] ?? ""); index++; continue; } + if (char !== '"') { out += char; continue; } + if (!inString) { inString = true; out += char; continue; } + const next = body.slice(index + 1).trimStart()[0]; + if (next === undefined || next === ":" || next === "," || next === "}" || next === "]") { inString = false; out += char; } + else out += '\\"'; + } + return out; +} + +function parseJson(body: string): unknown { try { - value = JSON.parse(body); + return JSON.parse(body); } catch { - return undefined; + try { return JSON.parse(repairQuotes(body)); } catch { return undefined; } } +} + +function blockInput(name: UiToolName, body: string): unknown { + let value = parseJson(body); + if (value === undefined) return undefined; // A bare list is the obvious shorthand for follow-up questions. if (name === "suggest_followups" && Array.isArray(value)) value = { questions: value }; - const parsed = uiSchemas[name].safeParse(value); - return parsed.success ? parsed.data : undefined; + return parseBlock(name, value); } -function fenced(language: string, body: string): Segment | undefined { +function fenced(fenceLanguage: string, fenceBody: string): Segment | undefined { + // ```json with "forge:table" on the first line, or a bare ``` followed by it. + const named = fenceBody.match(/^\s*(forge:[a-z]+)\s*\n/); + const language = named && BLOCK_NAMES[named[1]] ? named[1] : fenceLanguage; + const body = named && BLOCK_NAMES[named[1]] ? fenceBody.slice(named[0].length) : fenceBody; const name = BLOCK_NAMES[language.toLowerCase()]; if (name) { const input = blockInput(name, body); @@ -64,19 +82,36 @@ export function splitBlocks(text: string, streaming = false): Segment[] { prose = []; }; for (let index = 0; index < lines.length; index++) { + // The whole block on one line: ```forge:tags {"tags": [...]}``` + const inline = lines[index].match(/^ {0,3}`{3,}\s*(forge:[a-z]+)\s+(\{.*\})\s*`{3,}\s*$/); + if (inline) { + flush(); + const segment = fenced(inline[1], inline[2]); + if (segment) segments.push(segment); + continue; + } const open = lines[index].match(FENCE); if (!open) { prose.push(lines[index]); continue; } - const close = lines.findIndex((line, at) => at > index && new RegExp(`^ {0,3}${open[1]}\`*[ \\t]*$`).test(line)); + let close = lines.findIndex((line, at) => at > index && new RegExp(`^ {0,3}${open[1]}\`*[ \\t]*$`).test(line)); + let body = lines.slice(index + 1, close).join("\n"); + // Models sometimes close a block on the JSON's last line: {"title": "…"}``` + if (close < 0 && BLOCK_NAMES[open[2].toLowerCase()]) { + const glued = lines.findIndex((line, at) => at > index && new RegExp(`${open[1]}\\s*$`).test(line)); + if (glued > 0) { + close = glued; + body = [...lines.slice(index + 1, glued), lines[glued].replace(new RegExp(`${open[1]}\\s*$`), "")].join("\n"); + } + } if (close < 0) { if (streaming) break; prose.push(...lines.slice(index)); break; } flush(); - const segment = fenced(open[2], lines.slice(index + 1, close).join("\n")); + const segment = fenced(open[2], body); if (segment) segments.push(segment); index = close; } diff --git a/agent/src/catalog/render.tsx b/agent/src/catalog/render.tsx index 4b90851b..2d48488d 100644 --- a/agent/src/catalog/render.tsx +++ b/agent/src/catalog/render.tsx @@ -1,10 +1,10 @@ "use client"; import { useEffect, useRef, useState, type ReactNode } from "react"; -import { BarChart, DataTable, PromptSuggestions, SmoothLineChart, StatCard, type ColumnDef } from "@forge-ui-official/core"; +import { AgentCodeBlock, ChoiceCard, DataTable, Panel, PromptSuggestions, StatCard, StatusBadge, type ColumnDef } from "@forge-ui-official/core"; import { CheckCircleLinear, CopyLinear } from "@forge-ui-official/core/icons"; -import { ChoiceCard } from "../interact"; -import { uiSchemas, type UiSpec, type UiToolName } from "./schema"; +import { parseBlock, type UiSpec, type UiToolName } from "./schema"; +import { Actions, Callout, Changes, Chart, Compare, Confirm, Flow, Form, Funnel, Images, ListBlock, Plan, Progress, Questions, RecordCard, Tags, Timeline } from "./widgets"; type Row = Record; @@ -27,27 +27,6 @@ export function Command({ text }: { text: string }) { ); } -// Code in the narrow panel: small type, a one-line header with the language and copy, no line numbers. -function CodeView({ language, code }: { language: string; code: string }) { - const [copied, setCopied] = useState(false); - return ( -
-
- {language} - -
-
{code}
-
- ); -} - const PREVIEW_WIDTH = 1024; /** @@ -105,36 +84,26 @@ function Cards({ title, items }: UiSpec<"show_cards">) { return (
{title &&

{title}

} -
- {items.map(item => { - const body = ( - <> - {/* eslint-disable-next-line @next/next/no-img-element -- the package does not depend on Next.js */} - {item.preview ? : item.image && { event.currentTarget.hidden = true; }} className="aspect-[16/10] w-full rounded-lg border border-fg-grey-200 object-cover object-top" loading="lazy" />} -
- {item.title} - {item.tag && {item.tag}} -
- {item.description &&

{item.description}

} - - ); - return ( -
- {item.href ? {body} : body} - {item.code && } -
- ); - })} -
+ {items.map(item => { + const heading = item.href ? {item.title} : item.title; + return ( + } gap="sm"> + {/* eslint-disable-next-line @next/next/no-img-element -- the package does not depend on Next.js */} + {item.preview ? : item.image && { event.currentTarget.hidden = true; }} className="aspect-[16/10] w-full rounded-2xl border border-fg-grey-200 object-cover object-top" loading="lazy" />} + {item.code && } + + ); + })}
); } function Table({ title, columns, rows }: UiSpec<"show_table">) { const defs: ColumnDef[] = columns.map(column => column.numeric - ? { key: column.key, header: column.header, valueKind: "number", render: row => String(row[column.key] ?? "") } - : { key: column.key, header: column.header, render: row => String(row[column.key] ?? "") }); - return index} />; + ? { key: column.key, header: column.header, valueKind: "number", render: row => (typeof row[column.key] === "number" ? (row[column.key] as number).toLocaleString("zh-CN") : String(row[column.key] ?? "—")) } + : { key: column.key, header: column.header, render: row => String(row[column.key] ?? "—") }); + // The panel is narrow: the table keeps readable columns and scrolls sideways instead of wrapping. + return index} tableMinWidth={`${Math.max(320, columns.length * 120)}px`} />; } function Metrics({ items }: UiSpec<"show_metrics">) { @@ -147,37 +116,22 @@ function Metrics({ items }: UiSpec<"show_metrics">) { ); } -function Chart({ title, type, labels, series }: UiSpec<"show_chart">) { - return ( -
- {title &&

{title}

} -
- {type === "bar" - ? ({ label, value: series[0]?.data[index] ?? 0 }))} ariaLabel={title} /> - : ({ label: item.label, data: item.data }))} ariaLabel={title} />} -
-
{labels[0]}{labels[labels.length - 1]}
-
- ); -} - function Steps({ title, steps }: UiSpec<"show_steps">) { return ( -
- {title &&

{title}

} -
    + +
      {steps.map((step, index) => (
    1. - {index + 1} + {index + 1}
      - {step.title} - {step.detail && {step.detail}} + {step.title} + {step.detail && {step.detail}} {step.code && }
    2. ))}
    -
+ ); } @@ -206,6 +160,8 @@ function groundCards(spec: UiSpec<"show_cards">, sources: Sources): UiSpec<"show function numbersOf(name: UiToolName, spec: unknown): (string | number)[] { if (name === "show_metrics") return (spec as UiSpec<"show_metrics">).items.map(item => item.value.replace(/[^0-9.\-]/g, "")).filter(Boolean); if (name === "show_chart") return (spec as UiSpec<"show_chart">).series.flatMap(item => item.data); + if (name === "show_progress") return (spec as UiSpec<"show_progress">).items.map(item => item.value); + if (name === "show_funnel") return (spec as UiSpec<"show_funnel">).stages.map(stage => stage.value); if (name === "show_table") { const table = spec as UiSpec<"show_table">; const numeric = table.columns.filter(column => column.numeric).map(column => column.key); @@ -214,15 +170,33 @@ function numbersOf(name: UiToolName, spec: unknown): (string | number)[] { return []; } +// Links and images must be this site's pages or appear in a tool result. +function ground(name: UiToolName, data: unknown, sources: Sources): unknown { + const href = (value?: string) => (value && (value.startsWith("/") || sources.has(value)) ? value : undefined); + switch (name) { + case "show_cards": return groundCards(data as UiSpec<"show_cards">, sources); + case "show_record": { const spec = data as UiSpec<"show_record">; return { ...spec, href: href(spec.href) }; } + case "show_list": { const spec = data as UiSpec<"show_list">; return { ...spec, items: spec.items.map(item => ({ ...item, href: href(item.href) })) }; } + case "show_actions": { const spec = data as UiSpec<"show_actions">; return { ...spec, items: spec.items.map(item => ({ ...item, href: href(item.href) })).filter(item => item.href || item.ask) }; } + case "show_images": { + const spec = data as UiSpec<"show_images">; + const items = spec.items.filter(item => sources.has(item.src)); + return items.length ? { items } : undefined; + } + default: return data; + } +} + /** * Renders one catalog tool call. Inputs are validated again here, so a part replayed from storage or a - * malformed call shows nothing rather than a broken component. Numbers in tables, metrics and charts - * must come from tool results in the same answer; otherwise a note replaces the figure. + * malformed call shows nothing rather than a broken component. Numbers in tables, metrics, charts, + * progress and funnels must come from tool results in the same answer; otherwise a note replaces them. */ export function renderCatalog(name: UiToolName, input: unknown, onAsk: (question: string) => void, sources: Sources, answer?: string): ReactNode { - const parsed = uiSchemas[name].safeParse(input); - if (!parsed.success) return null; - const data = name === "show_cards" ? groundCards(parsed.data as UiSpec<"show_cards">, sources) : parsed.data; + const parsed = parseBlock(name, input); + if (parsed === undefined) return null; + const data = ground(name, parsed, sources); + if (data === undefined) return null; if (numbersOf(name, data).some(value => !sources.has(value))) { return

这组数字没能和查询结果核对上,已省略。

; } @@ -231,23 +205,38 @@ export function renderCatalog(name: UiToolName, input: unknown, onAsk: (question } function catalogContent(name: UiToolName, data: unknown, onAsk: (question: string) => void, answer?: string): ReactNode { - const parsed = { data }; switch (name) { - case "show_cards": return )} />; + case "show_cards": return )} />; case "show_code": { - const spec = parsed.data as UiSpec<"show_code">; - return ; + const code = data as UiSpec<"show_code">; + return ; } - case "show_table": return )} />; - case "show_metrics": return )} />; - case "show_chart": return )} />; - case "show_steps": return )} />; + case "show_steps": return )} />; + case "show_callout": return )} />; + case "show_record": return )} />; + case "show_list": return )} />; + case "show_timeline": return )} />; + case "show_tags": return )} />; + case "show_compare": return )} />; + case "show_changes": return )} />; + case "show_flow": return )} />; + case "show_images": return )} />; + case "show_table": return
)} />; + case "show_metrics": return )} />; + case "show_chart": return )} />; + case "show_progress": return )} />; + case "show_funnel": return )} />; case "show_choices": { // A pick is sent as the user's next message; once answered the card shows the answer. - const spec = parsed.data as UiSpec<"show_choices">; - const options = spec.options.map(option => ({ id: option.label, ...option })); - return { if ("optionId" in picked) onAsk(picked.optionId); }} />; + const choices = data as UiSpec<"show_choices">; + const options = choices.options.map(option => ({ id: option.label, ...option })); + return { if ("optionId" in picked) onAsk(picked.optionId); }} />; } - case "suggest_followups": return ).questions} onSelect={onAsk} />; + case "show_questions": return )} answer={answer} onAsk={onAsk} />; + case "show_form": return
)} answer={answer} onAsk={onAsk} />; + case "show_confirm": return )} answer={answer} onAsk={onAsk} />; + case "show_plan": return )} answer={answer} onAsk={onAsk} />; + case "show_actions": return )} onAsk={onAsk} />; + case "suggest_followups": return ).questions} onSelect={onAsk} />; } } diff --git a/agent/src/catalog/schema.ts b/agent/src/catalog/schema.ts index bff045cf..1bbce830 100644 --- a/agent/src/catalog/schema.ts +++ b/agent/src/catalog/schema.ts @@ -4,8 +4,10 @@ import { z } from "zod"; // before anything renders, and the client draws them with Forge components. const text = (max: number) => z.string().trim().min(1).max(max); +const tone = z.enum(["info", "success", "warning", "danger"]); export const uiSchemas = { + /* ── Display ── */ show_cards: z.object({ title: text(60).optional(), items: z.array(z.object({ @@ -22,6 +24,51 @@ export const uiSchemas = { filename: text(80).optional(), code: z.string().min(1).max(6000), }), + show_steps: z.object({ + title: text(60).optional(), + steps: z.array(z.object({ title: text(80), detail: text(400).optional(), code: z.string().max(2000).optional() })).min(1).max(10), + }), + show_callout: z.object({ + tone, + title: text(60).optional(), + text: text(400), + }), + show_record: z.object({ + title: text(60), + subtitle: text(80).optional(), + status: text(20).optional(), + fields: z.array(z.object({ label: text(20), value: text(120) })).min(1).max(12), + href: z.string().max(300).optional(), + }), + show_list: z.object({ + title: text(60).optional(), + items: z.array(z.object({ title: text(80), description: text(160).optional(), meta: text(30).optional(), tag: text(20).optional(), href: z.string().max(300).optional() })).min(1).max(12), + }), + show_timeline: z.object({ + title: text(60).optional(), + events: z.array(z.object({ time: text(30), title: text(80), detail: text(200).optional(), tone: tone.optional() })).min(1).max(12), + }), + show_tags: z.object({ + title: text(60).optional(), + tags: z.array(text(24)).min(1).max(20), + }), + show_compare: z.object({ + title: text(60).optional(), + items: z.array(z.object({ title: text(40), tag: text(20).optional(), points: z.array(text(120)).min(1).max(8), recommended: z.boolean().optional() })).min(2).max(4), + }), + show_changes: z.object({ + title: text(60).optional(), + fields: z.array(z.object({ label: text(30), before: z.string().max(120), after: z.string().max(120) })).min(1).max(12), + }), + show_flow: z.object({ + title: text(60).optional(), + nodes: z.array(z.object({ id: text(20), label: text(40), kind: z.enum(["start", "step", "decision", "end"]).optional() })).min(2).max(12), + edges: z.array(z.object({ from: text(20), to: text(20), label: text(20).optional() })).max(16), + }), + show_images: z.object({ + items: z.array(z.object({ src: z.string().max(300), caption: text(60).optional() })).min(1).max(8), + }), + /* ── Data ── */ show_table: z.object({ title: text(60).optional(), columns: z.array(z.object({ key: text(40), header: text(30), numeric: z.boolean().optional() })).min(1).max(8), @@ -37,18 +84,58 @@ export const uiSchemas = { }), show_chart: z.object({ title: text(60).optional(), - type: z.enum(["line", "bar"]), + type: z.enum(["line", "area", "bar", "hbar", "donut"]), labels: z.array(text(20)).min(2).max(60), series: z.array(z.object({ label: text(30), data: z.array(z.number()) })).min(1).max(4), }), - show_steps: z.object({ + show_progress: z.object({ title: text(60).optional(), - steps: z.array(z.object({ title: text(80), detail: text(400).optional(), code: z.string().max(2000).optional() })).min(1).max(10), + items: z.array(z.object({ label: text(30), value: z.number().min(0).max(100), note: text(40).optional() })).min(1).max(8), }), + show_funnel: z.object({ + title: text(60).optional(), + stages: z.array(z.object({ label: text(20), value: z.number().min(0) })).min(2).max(8), + }), + /* ── Asking and acting ── */ show_choices: z.object({ title: text(80), options: z.array(z.object({ label: text(60), description: text(120).optional() })).min(2).max(8), }), + show_questions: z.object({ + questions: z.array(z.object({ + title: text(80), + options: z.array(z.object({ label: text(60), description: text(120).optional() })).max(8), + multiple: z.boolean().optional(), + allowText: z.boolean().optional(), + })).min(1).max(4), + }), + show_form: z.object({ + title: text(60), + submitLabel: text(12).optional(), + fields: z.array(z.object({ + name: text(30), + label: text(30), + type: z.enum(["text", "textarea", "number", "date", "select", "multiselect", "switch"]), + options: z.array(text(40)).max(12).optional(), + required: z.boolean().optional(), + placeholder: text(60).optional(), + default: z.union([z.string().max(200), z.number(), z.boolean(), z.array(z.string().max(40))]).optional(), + })).min(1).max(10), + }), + show_confirm: z.object({ + title: text(80), + description: text(300).optional(), + risk: z.enum(["low", "medium", "high"]).optional(), + fields: z.array(z.object({ label: text(30), before: z.string().max(120).optional(), after: z.string().max(120).optional(), value: z.string().max(120).optional() })).max(10).optional(), + confirmLabel: text(12).optional(), + }), + show_plan: z.object({ + title: text(60).optional(), + steps: z.array(z.object({ title: text(80), detail: text(200).optional() })).min(2).max(10), + }), + show_actions: z.object({ + items: z.array(z.object({ label: text(20), ask: text(80).optional(), href: z.string().max(300).optional(), primary: z.boolean().optional() })).min(1).max(4), + }), suggest_followups: z.object({ questions: z.array(text(40)).min(1).max(4), }), @@ -58,3 +145,104 @@ export type UiToolName = keyof typeof uiSchemas; export type UiSpec = z.infer<(typeof uiSchemas)[Name]>; export const uiToolNames = Object.keys(uiSchemas) as UiToolName[]; + +/** The fenced block name the model writes for each component: ```forge:table … ```. */ +export const BLOCK_OF: Record = { + show_cards: "forge:cards", + show_code: "forge:code", + show_steps: "forge:steps", + show_callout: "forge:callout", + show_record: "forge:record", + show_list: "forge:list", + show_timeline: "forge:timeline", + show_tags: "forge:tags", + show_compare: "forge:compare", + show_changes: "forge:changes", + show_flow: "forge:flow", + show_images: "forge:images", + show_table: "forge:table", + show_metrics: "forge:metrics", + show_chart: "forge:chart", + show_progress: "forge:progress", + show_funnel: "forge:funnel", + show_choices: "forge:choices", + show_questions: "forge:questions", + show_form: "forge:form", + show_confirm: "forge:confirm", + show_plan: "forge:plan", + show_actions: "forge:actions", + suggest_followups: "forge:followups", +}; + +/** One line per component for the system prompt: shape first, then when to use it. */ +export const BLOCK_GUIDE: Record = { + show_cards: `卡片:{"title"?, "items": [{"title", "description"?, "tag"?, "href"?, "preview"?, "code"?, "image"?}]},最多 8 项。preview 是能嵌入预览的站内页面路径,会显示成缩略图;code 是一行可复制的命令。`, + show_code: `代码:{"filename"?, "code"}。一般代码用普通 Markdown 代码块即可,要给文件名时用它。`, + show_steps: `步骤:{"title"?, "steps": [{"title", "detail"?, "code"?}]},教用户怎么做时用。`, + show_callout: `提示框:{"tone": "info"|"success"|"warning"|"danger", "title"?, "text"},只用于真正要提醒的一件事。`, + show_record: `单条记录:{"title", "subtitle"?, "status"?, "fields": [{"label", "value"}], "href"?},展示一个订单、账号、合同等的详情。`, + show_list: `列表:{"title"?, "items": [{"title", "description"?, "meta"?, "tag"?, "href"?}]},多条记录的摘要。`, + show_timeline: `时间线:{"title"?, "events": [{"time", "title", "detail"?, "tone"?}]},按时间排的经过、日志、进度。`, + show_tags: `标签:{"title"?, "tags": [...]}`, + show_compare: `方案对比:{"title"?, "items": [{"title", "tag"?, "points": [...], "recommended"?}]},2 到 4 个方案并排比较。`, + show_changes: `改动前后:{"title"?, "fields": [{"label", "before", "after"}]},说明改了什么。`, + show_flow: `流程图:{"title"?, "nodes": [{"id", "label", "kind"?: "start"|"step"|"decision"|"end"}], "edges": [{"from", "to", "label"?}]},讲审批流、业务流程时用。`, + show_images: `图片:{"items": [{"src", "caption"?}]},src 只用工具结果里的图片地址。`, + show_table: `表格:{"title"?, "columns": [{"key", "header", "numeric"?}], "rows": [{列 key: 值}]}`, + show_metrics: `指标:{"items": [{"label", "value", "change"?, "direction"?: "up"|"down"}]}`, + show_chart: `图表:{"title"?, "type": "line"|"area"|"bar"|"hbar"|"donut", "labels": [...], "series": [{"label", "data": [数字]}]}。趋势用 line/area,比较用 bar,排名用 hbar,占比用 donut(只取第一组数据)。`, + show_progress: `进度:{"title"?, "items": [{"label", "value": 0 到 100, "note"?}]},完成率、额度用量。`, + show_funnel: `漏斗:{"title"?, "stages": [{"label", "value"}]},转化各环节的数量。`, + show_choices: `让用户选:{"title", "options": [{"label", "description"?}]},2 到 8 项。要用户在几个明确方案里挑一个时用,用户点选后会作为下一条消息发来;问开放问题时直接用文字问。`, + show_questions: `一次问几件事:{"questions": [{"title", "options": [{"label", "description"?}], "multiple"?, "allowText"?}]},最多 4 题;缺好几项信息才能继续时用,答案会作为下一条消息发来。`, + show_form: `表单:{"title", "submitLabel"?, "fields": [{"name", "label", "type": "text"|"textarea"|"number"|"date"|"select"|"multiselect"|"switch", "options"?, "required"?, "placeholder"?, "default"?}]},让用户填一组结构化信息(例如新建记录);提交内容会作为下一条消息发来。`, + show_confirm: `请用户确认:{"title", "description"?, "risk"?: "low"|"medium"|"high", "fields"?: [{"label", "before"?, "after"}], "confirmLabel"?}。用户要你改数据、删除、发送时,先用它列出改动请用户确认,确认后再执行;用户的确认或取消会作为下一条消息发来。`, + show_plan: `执行计划:{"title"?, "steps": [{"title", "detail"?}]},多步任务开始前给用户看,用户可以增删改步骤,确认后计划会作为下一条消息发来。`, + show_actions: `操作按钮:{"items": [{"label", "ask"?, "href"?, "primary"?}]},最多 4 个;ask 是点了之后发出的消息,href 是要打开的链接。`, + suggest_followups: `后续问题:{"questions": [1 到 4 个短问题]},放在回答最后,正文里不要再列一遍。`, +}; + +/** The prompt lines for the enabled components. */ +export function catalogGuide(names: readonly UiToolName[] = uiToolNames) { + return names.map(name => ` - ${BLOCK_OF[name]} ${BLOCK_GUIDE[name]}`).join("\n"); +} + +// One worked example keeps the fence format exact; the first enabled component that has one is used. +const EXAMPLES: Partial> = { + show_cards: `{"items": [{"title": "订单列表", "tag": "页面", "description": "搜索、筛选、分页都已接好", "href": "/orders"}]}`, + show_table: `{"columns": [{"key": "name", "header": "客户"}, {"key": "amount", "header": "金额", "numeric": true}], "rows": [{"name": "华东分公司", "amount": 1280}]}`, + show_confirm: `{"title": "把张三的角色改为管理员", "risk": "medium", "fields": [{"label": "角色", "before": "成员", "after": "管理员"}]}`, +}; + +/** The prompt's example line for the enabled components, or nothing. */ +export function catalogExample(names: readonly UiToolName[]) { + const name = names.find(item => EXAMPLES[item]); + return name ? `- 例:\n\`\`\`${BLOCK_OF[name]}\n${EXAMPLES[name]}\n\`\`\`\n` : ""; +} + +type Issue = { code: string; path: PropertyKey[]; maximum?: number | bigint; origin?: string }; + +/** + * Models overshoot limits: one point too many, a label a few characters long. Instead of dropping the + * whole component, cut lists and strings to the limit the schema reports, and parse again. + */ +export function parseBlock(name: Name, value: unknown): UiSpec | undefined { + let current = value; + for (let round = 0; round < 4; round++) { + const parsed = uiSchemas[name].safeParse(current); + if (parsed.success) return parsed.data as UiSpec; + const fixable = (parsed.error.issues as Issue[]).filter(issue => issue.code === "too_big" && typeof issue.maximum === "number" && (issue.origin === "array" || issue.origin === "string")); + if (!fixable.length) return undefined; + current = structuredClone(current); + for (const issue of fixable) { + const parent = issue.path.slice(0, -1).reduce((node, key) => (node as Record | undefined)?.[key], current) as Record | undefined; + const key = issue.path.at(-1); + const target = key === undefined ? current : parent?.[key]; + const max = Number(issue.maximum); + const cut = Array.isArray(target) ? target.slice(0, max) : typeof target === "string" ? `${target.slice(0, Math.max(1, max - 1))}…` : target; + if (key === undefined) current = cut; + else if (parent) parent[key] = cut; + } + } + return undefined; +} diff --git a/agent/src/catalog/widgets.tsx b/agent/src/catalog/widgets.tsx new file mode 100644 index 00000000..81d96b4a --- /dev/null +++ b/agent/src/catalog/widgets.tsx @@ -0,0 +1,397 @@ +"use client"; + +import { useState, type ReactNode } from "react"; +import { + AgentFlowchart, + AgentPlan, + Approval, + BarChart, + Button, + DescriptionItem, + DonutChart, + HistoryGrouped, + ImageGrid, + Label, + ListGroup, + ListItem, + Panel, + ProgressBar, + Question, + SelectOption, + SmoothLineChart, + StatusBadge, + TextArea, + TextField, + Toggle, + cn, + type AgentFlowKind, + type PlanStep, +} from "@forge-ui-official/core"; +import { AltArrowRightLinear, CheckCircleLinear, DangerTriangleLinear, InfoCircleLinear } from "@forge-ui-official/core/icons"; +import type { UiSpec } from "./schema"; + +/** + * Components the model writes into its answer, drawn with the same Forge components the pages use: + * Panel, StatCard, the charts, ListGroup, HistoryGrouped, DescriptionItem, AgentFlowchart and the + * form fields. Cards, tables and metrics live in render.tsx. + */ + +const Answered = ({ children }: { children: ReactNode }) => ( +

{children}

+); +const safeHref = (href?: string) => (href && (/^\/(?!\/)/.test(href) || /^https:\/\//.test(href)) ? href : undefined); +export const formatNumber = (value: number) => value.toLocaleString("zh-CN"); + +/* ── Display ── */ + +const TONE = { + info: { icon: InfoCircleLinear, style: "bg-fg-blue-50 text-fg-blue-800 outline-fg-blue-200", color: "var(--fg-blue-500)" }, + success: { icon: CheckCircleLinear, style: "bg-fg-green-50 text-fg-green-700 outline-fg-green-200", color: "var(--fg-green-500)" }, + warning: { icon: DangerTriangleLinear, style: "bg-fg-yellow-50 text-fg-yellow-900 outline-fg-yellow-200", color: "var(--fg-yellow-700)" }, + danger: { icon: DangerTriangleLinear, style: "bg-fg-red-50 text-fg-red-700 outline-fg-red-200", color: "var(--fg-red)" }, +} as const; + +export function Callout({ tone, title, text }: UiSpec<"show_callout">) { + const { icon: Icon, style, color } = TONE[tone]; + return ( +
+ +
{title && {title}}{text}
+
+ ); +} + +const STATUS_TONE: { test: RegExp; color: "green" | "yellow" | "red" | "blue" | "grey" }[] = [ + { test: /完成|成功|通过|已退款|已付|正常|启用/, color: "green" }, + { test: /失败|拒绝|驳回|逾期|异常|超/, color: "red" }, + { test: /待|审核|处理中|进行|退款中|中$/, color: "yellow" }, +]; +const statusColor = (status: string) => STATUS_TONE.find(rule => rule.test.test(status))?.color ?? "grey"; + +export function RecordCard({ title, subtitle, status, fields, href }: UiSpec<"show_record">) { + const link = safeHref(href); + return ( + } + footer={link && 查看详情} + gap="sm" + > +
+ {fields.map(field => )} +
+
+ ); +} + +export function ListBlock({ title, items }: UiSpec<"show_list">) { + return ( + { + const link = safeHref(item.href); + const row = : undefined} />; + return link ? {row} : row; + })} + /> + ); +} + +const HISTORY_COLOR = { info: "blue", success: "green", warning: "yellow", danger: "red" } as const; + +export function Timeline({ title, events }: UiSpec<"show_timeline">) { + return ( + ({ title: event.title, description: event.detail, datetime: event.time, color: HISTORY_COLOR[event.tone ?? "info"], showConnector: index < events.length - 1 }))} + /> + ); +} + +export function Tags({ title, tags }: UiSpec<"show_tags">) { + return ( + +
{tags.map(tag => )}
+
+ ); +} + +export function Compare({ title, items }: UiSpec<"show_compare">) { + return ( + +
+ {items.map(item => ( +
+
+ {item.title} + {item.recommended ? : item.tag && } +
+
    + {item.points.map(point =>
  • {point}
  • )} +
+
+ ))} +
+
+ ); +} + +export function Changes({ title, fields }: UiSpec<"show_changes">) { + return ( + +
+ {fields.map(field => ( + {field.before || "空"}{field.after || "空"}} + /> + ))} +
+
+ ); +} + +const FLOW_KIND: Record = { start: "trigger", step: "action", decision: "condition", end: "action" }; + +export function Flow({ title, nodes, edges }: UiSpec<"show_flow">) { + return ( + ({ id: node.id, kind: FLOW_KIND[node.kind ?? "step"], title: node.label }))} + edges={edges.map(edge => ({ from: edge.from, to: edge.to, label: edge.label }))} + kindLabels={{ trigger: "开始", action: "步骤", condition: "判断" }} + /> + ); +} + +export function Images({ items }: UiSpec<"show_images">) { + return ( + + item.src)} size="md" /> + {items.some(item => item.caption) &&

{items.map(item => item.caption).filter(Boolean).join(" · ")}

} +
+ ); +} + +/* ── Data ── */ + +// The latest value of a single series leads the chart, as on Forge's chart cards. +function Headline({ label, value, previous }: { label: string; value: number; previous?: number }) { + const change = previous ? ((value - previous) / previous) * 100 : undefined; + return ( +
+

{label}

+

{formatNumber(value)}

+ {change !== undefined && Number.isFinite(change) &&

{change >= 0 ? "+" : ""}{change.toFixed(1)}% 较上一期

} +
+ ); +} + +// As in Forge's spending case: the ring and its rows point at each other on hover. +function Donut({ title, points, total }: { title?: string; points: { label: string; value: number }[]; total: number }) { + const [active, setActive] = useState(); + const shown = active === undefined ? total : points[active].value; + return ( + +
+ +
+ +
+ ); +} + +function ValueRows({ rows, total, active, onActive }: { rows: { label: string; value: number }[]; total?: number; active?: number; onActive?: (index?: number) => void }) { + return ( +
onActive?.(undefined)}> + {rows.map((row, index) => ( +
onActive?.(index)} className={cn("flex min-h-9 items-center justify-between gap-3 rounded-lg px-2 text-sm text-fg-black hover:bg-fg-grey-50", active === index && "bg-fg-grey-50")}> + {row.label} + {formatNumber(row.value)}{total ? {Math.round((row.value / total) * 100)}% : null} +
+ ))} +
+ ); +} + +export function Chart({ title, type, labels, series }: UiSpec<"show_chart">) { + const first = series[0]?.data ?? []; + const points = labels.map((label, index) => ({ label, value: first[index] ?? 0 })); + const total = points.reduce((sum, point) => sum + point.value, 0); + if (type === "donut") return ; + if (type === "hbar" || (type === "bar" && points.length > 8)) { + const top = Math.max(1, ...points.map(point => point.value)); + return ( + +
+ {points.map(point => ( +
+
{point.label}{formatNumber(point.value)}
+ +
+ ))} +
+
+ ); + } + if (type === "bar") { + return ( + + + + + ); + } + const single = series.length === 1; + return ( + + {single && first.length > 0 && } + ({ label: item.label, data: item.data, fillArea: single || type === "area" }))} height="h-40" ariaLabel={title} /> +
{(labels.length > 4 ? [labels[0], labels[Math.floor((labels.length - 1) / 2)], labels[labels.length - 1]] : labels).map((label, index) => {label})}
+ {!single && ({ label: `${item.label}(最新)`, value: item.data[item.data.length - 1] ?? 0 }))} />} +
+ ); +} + +export function Progress({ title, items }: UiSpec<"show_progress">) { + return ( + +
+ {items.map(item => ( + = 90 ? "red" : item.value >= 75 ? "yellow" : "blue"} size="sm" /> + ))} +
+
+ ); +} + +export function Funnel({ title, stages }: UiSpec<"show_funnel">) { + const top = Math.max(1, stages[0]?.value ?? 1); + return ( + +
+ {stages.map((stage, index) => ( +
+
+ {stage.label} + {index > 0 && 转化 {stages[index - 1].value ? `${Math.round((stage.value / stages[index - 1].value) * 100)}%` : "—"}} + {formatNumber(stage.value)} +
+ +
+ ))} +
+
+ ); +} + +/* ── Asking and acting: what the user does goes back as their next message ── */ + +export function Questions({ questions, answer, onAsk }: UiSpec<"show_questions"> & { answer?: string; onAsk: (text: string) => void }) { + if (answer) return {answer}; + const items = questions.map((question, index) => ({ id: String(index), title: question.title, multiple: question.multiple, allowText: question.allowText, options: question.options.map(option => ({ id: option.label, ...option })) })); + return ( + onAsk(items.map(item => `${item.title}:${[...(answers[item.id]?.optionIds ?? []), answers[item.id]?.text?.trim()].filter(Boolean).join("、") || "不限"}`).join(";"))} + /> + ); +} + +type FieldValue = string | number | boolean | string[]; + +export function Form({ title, submitLabel, fields, answer, onAsk }: UiSpec<"show_form"> & { answer?: string; onAsk: (text: string) => void }) { + const [values, setValues] = useState>(() => Object.fromEntries(fields.map(field => [field.name, field.default ?? (field.type === "switch" ? false : field.type === "multiselect" ? [] : "")]))); + if (answer) return {answer}; + const set = (name: string, value: FieldValue) => setValues(current => ({ ...current, [name]: value })); + const missing = fields.filter(field => field.required && (values[field.name] === "" || (Array.isArray(values[field.name]) && !(values[field.name] as string[]).length))); + const describe = (value: FieldValue) => (Array.isArray(value) ? value.join("、") : typeof value === "boolean" ? (value ? "是" : "否") : String(value)); + const label = (field: (typeof fields)[number]) => `${field.label}${field.required ? " *" : ""}`; + return ( + { + event.preventDefault(); + if (missing.length) return; + onAsk(`提交「${title}」:${fields.filter(field => describe(values[field.name]) !== "").map(field => `${field.label}:${describe(values[field.name])}`).join(";")}`); + }} + > + 0} className="self-end">{submitLabel ?? "提交"}}> +
+ {fields.map(field => { + const value = values[field.name]; + const options = (field.options ?? []).map(option => ({ value: option, label: option })); + if (field.type === "textarea") return