diff --git a/CHANGELOG.md b/CHANGELOG.md index 19d0cfa..1f15d71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.20.0] — 2026-12-02 + +### Added + +- **A tool-call label can be filled from the call's arguments.** A tool schema's + `x-summary-template` (`X_SUMMARY_TEMPLATE_KEY`), or the `data-tools-url` catalog's + `summary_template` that django-spec-agents 0.31.0 emits, such as + `"Search orders for {query}"`, labels the card head and the step-group row with the filled + sentence. Placeholders fill from top-level string, number and boolean arguments; if any + cannot be filled the label is the static one, as before. A filled template outranks every + static label, a host's `toolSummaries` entry included. Values are set as text. + `ToolCatalogEntry` gains `summaryTemplate`. No opt-in: the server or tool supplies the + template, and a tool without one labels exactly as before. +- **A tool card's arguments read by what the server says about each one.** The + `data-tools-url` catalog's `arguments` projection (django-spec-agents 0.31.0 and later), or a + client tool's own `parameters.properties`, labels an argument by its `title`, draws an enum + constant as its `oneOf` label, draws a `date` or `date-time` string through `Intl` in the + browser's locale, and leaves an `x-hidden` argument out of the list. View raw still shows the + exact JSON, constants and hidden arguments included. `ToolCatalogEntry` gains `arguments`, and + `ToolCallCardOptions` gains `display` (a `PayloadDisplay`, the arguments region only), with + `ArgumentDisplays`, `ArgumentDisplay`, `ArgumentChoice` and `PayloadDisplay` exported as types; + a malformed projection costs that field, never the entry. No opt-in: a catalog or schema + without these keys draws exactly as before. + ## [0.19.0] — 2026-12-02 ### Added @@ -1103,7 +1127,8 @@ move page walks a host over. Each entry below says whether a host opts in. kept offering the moon under `theme="dark"`. Only the toggle's own click redrew it before. A host opts in to nothing. -[Unreleased]: https://github.com/Artui/agents-web-components/compare/v0.19.0...HEAD +[Unreleased]: https://github.com/Artui/agents-web-components/compare/v0.20.0...HEAD +[0.20.0]: https://github.com/Artui/agents-web-components/compare/v0.19.0...v0.20.0 [0.19.0]: https://github.com/Artui/agents-web-components/compare/v0.18.0...v0.19.0 [0.18.0]: https://github.com/Artui/agents-web-components/compare/v0.17.0...v0.18.0 [0.17.0]: https://github.com/Artui/agents-web-components/compare/v0.16.0...v0.17.0 diff --git a/demo/app/scenarios.js b/demo/app/scenarios.js index 39a53a8..cb7b12b 100644 --- a/demo/app/scenarios.js +++ b/demo/app/scenarios.js @@ -206,7 +206,9 @@ export const SCENARIOS = [ ["Nothing to open", "ping"], ["Readable arguments", "look up an invoice"], ["Sub-agents", "delegate this"], + ["Labels from arguments", "search orders"], ], + attrs: { "data-tools-url": "/tools/" }, }, { slug: "approvals", diff --git a/demo/mock-server.mjs b/demo/mock-server.mjs index 17236f9..3f8cc11 100644 --- a/demo/mock-server.mjs +++ b/demo/mock-server.mjs @@ -205,6 +205,28 @@ async function streamText(res, messageId, chunks) { emit(res, { type: "TEXT_MESSAGE_END", messageId }); } +const TOOL_CATALOG = [ + { + name: "search_orders", + summary: "Search orders", + summary_template: "Search orders for {query} in {status}", + // How each argument reads in the card's list: a title, enum labels, a date + // format and a hidden key, as django-spec-agents projects them. + arguments: { + query: { title: "Customer" }, + status: { + oneOf: [ + { const: "late", title: "Running late" }, + { const: "open", title: "Awaiting reply" }, + ], + }, + since: { format: "date" }, + trace_id: { "x-hidden": true }, + }, + }, + { name: "tag_record", summary: "Tag a record", summary_template: "Tag {record} with {tags}" }, +]; + function emitToolCall(res, id, name, args, parentMessageId) { emit(res, { type: "TOOL_CALL_START", toolCallId: id, toolCallName: name, parentMessageId }); emit(res, { type: "TOOL_CALL_ARGS", toolCallId: id, delta: JSON.stringify(args) }); @@ -969,6 +991,25 @@ async function handleAgent(res, body) { const parent = id("msg"); await streamText(res, parent, ["Trying the flaky one…"]); emitToolCall(res, id("call"), "break_something", {}, parent); + } else if (/\bsearch orders\b/i.test(prompt)) { + // Labels filled from the call's arguments: the /tools/ catalog gives these + // tools a summary_template. The first fills; the second lacks an argument + // and the third's is a list, so both show the static summary instead. The + // catalog's arguments projection labels the first card's arguments list. + const parent = id("msg"); + await streamText(res, parent, ["Looking those up…"]); + const calls = [ + ["search_orders", { query: "acme", status: "late", since: "2026-11-01", trace_id: "req-81f2" }], + ["search_orders", { query: "globex" }], + ["tag_record", { record: "order-17", tags: ["urgent", "vip"] }], + ]; + for (const [name, args] of calls) { + const call = id("call"); + emitToolCall(res, call, name, args, parent); + await sleep(400); + emitToolResult(res, call, JSON.stringify({ ok: true })); + } + await streamText(res, id("msg"), ["Done."]); } else if (/\bthink silently\b/i.test(prompt)) { // Reasoning that carries no text, the way a provider sends redacted // thinking or reasoning with its summaries off: a start and an end and @@ -1668,6 +1709,13 @@ const server = createServer((req, res) => { editorRoute(req, res, path); return; } + if (req.method === "GET" && req.url === "/tools/") { + // The tool-label catalog, entries as django-spec-agents' build_tool_catalog + // writes them (tests/fixtures/summary_template.json is the recorded output). + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(TOOL_CATALOG)); + return; + } if (req.method === "GET" && req.url === "/runs/") { // The run index behind the header's checkpoint control. Without this route // the button is not built at all — the element only offers it when a host diff --git a/docs/api.md b/docs/api.md index fd37ea1..0ebb5fc 100644 --- a/docs/api.md +++ b/docs/api.md @@ -74,6 +74,9 @@ paths. | `X_DESTRUCTIVE_KEY` / `X_NAVIGATES_KEY` | const | The JSON-Schema extension keys. | | `parseToolCatalog(data)` | function | Parse a fetched `data-tools-url` catalog into a `Record` — whole entries, not bare summaries, so a caller can reach `description` too. Malformed input yields an empty map rather than throwing. | | `ToolCatalogEntry` | type | One row of that catalog. | +| `ArgumentDisplays` | type | A catalog entry's `arguments` projection, read: argument name to its `ArgumentDisplay` (a `Map`). | +| `ArgumentDisplay` | type | How one argument reads: `{ title?, format?, choices?, hidden? }`. | +| `ArgumentChoice` | type | One choice of an enumerated argument: `{ const, title? }`. | | `prettifyToolName(name)` | function | Last fallback of the tool-card label chain (`delete_record` reads as *Delete record*). | ## Host seams @@ -157,7 +160,8 @@ paths. | `ToolGroupDisplayMode` | type | How an opened step group draws its calls (`TOOL_GROUP_DISPLAY`'s values). | | `ToolPayloadFormatter` | type | Draws one region of a card's body (`AgUiChat.formatToolPayload`); `null` falls through to the built-in pretty-print. | | `ToolPayload` | type | The region being drawn: `arguments` (the parsed record) or `result` (the raw string and its outcome). | -| `ToolCallCardOptions` | type | Per-card wiring beyond name / args / label / strings — currently `formatPayload`. | +| `ToolCallCardOptions` | type | Per-card wiring beyond name / args / label / strings: `formatPayload` and `display` (a `PayloadDisplay`, read by the arguments region only). | +| `PayloadDisplay` | type | How a card's arguments read: `{ arguments?, locale? }`, an `ArgumentDisplays` map and the `Intl` locale dates draw in. | | `requestConfirmation(host, request, options?)` | function | Append the inline confirmation card to the transcript. | | `ConfirmationRequest` | type | What the card displays. | | `ConfirmationOptions` | type | `{ signal?, strings?, onAlwaysAllow? }` — abort resolves the card as declined; `strings` localizes it; passing `onAlwaysAllow` is what adds the third button. | @@ -234,5 +238,6 @@ paths. | `TOOL_OUTCOME` | How a tool call ended, as a server states it on `TOOL_CALL_RESULT` (`success` / `failed` / `denied`). | | `X_CONFIRM_KEY` | Confirmation-prompt key: on a tool's JSON Schema for a client-side confirmation, and in an AG-UI interrupt's `metadata` for a server-side approval. | | `X_SUMMARY_KEY` | JSON-Schema key carrying a short tool-card label. | +| `X_SUMMARY_TEMPLATE_KEY` | JSON-Schema key carrying a tool-card label with `{name}` placeholders filled from the call's arguments. | | `MAX_TOOL_ROUNDS` | Upper bound on tool-call → re-run rounds per send. | | `VERSION` | The package version string. | diff --git a/docs/quickstart.md b/docs/quickstart.md index 31233ce..c70d666 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -90,7 +90,7 @@ another origin, add `credentials="include"` too; see | `data-routine-minute-step` | `5` | The minute step of the routine form's time field, a whole number from 1 to 30; anything else keeps 5. Read each time the form opens. A routine saved at a minute off the step still shows that minute. See [The time and timezone fields](skills.md#the-time-and-timezone-fields). | | `data-skill-editor-button` | absent | With `data-skill-editor-url`, also puts a Skills button in the header. Off by default. On a narrow panel it moves into the header's [More menu](header-and-panel.md#the-header-row-and-its-more-menu) like the other optional controls. | | `data-editors` | absent | `external` hands the skill editor and routines to the page: the Skills and Routines buttons, Make this a routine and the palette's Manage skills fire `ag-ui-open-editor` instead of opening the view in the panel, for an [editor element](editors.md#the-editors-on-a-page-of-their-own) to answer. Read at each click. The methods still open the panel. | -| `data-tools-url` | — | URL of a server tool-label catalog (`[{ name, summary, description? }]`), fetched with the element's headers and cookie policy; labels tool-call cards for server-side tools. | +| `data-tools-url` | — | URL of a server tool-label catalog (`[{ name, summary, summary_template?, description?, arguments? }]`), fetched with the element's headers and cookie policy; labels tool-call cards for server-side tools and [their arguments](tool-calls.md#what-the-server-says-about-each-argument). | | `user-key` | `userKey` | Who the stored conversation belongs to — any string identifying the signed-in principal. Joins the storage namespace, and **changing it purges what the previous principal left behind**. Live (not connect-time): a logout is the host's to announce. See [Who the stored conversation belongs to](durability.md#who-the-stored-conversation-belongs-to-user-key). | | `user-name` | `userName` | The signed-in user's display name, for the [greeting](theming.md#the-greeting-on-an-empty-page) an empty conversation shows under `placement="page"`. Presentation only: unlike `user-key` it scopes nothing and is never sent. Absent or blank gives the nameless greeting. Live. | | `data-threads-url` | — | URL of a server thread index (django-ag-ui's `ThreadsView`, or any server that keeps to [the threads contract](threads-contract.md)); enables durable, cross-device chat history. | @@ -222,7 +222,9 @@ the django-ag-ui `@tool` registry), whose schema never reaches the browser — e `chat.toolSummaries = { list_projects: "Search projects" }`. Or point `data-tools-url` at a server catalog endpoint (django-ag-ui's `tools/`) and the labels are fetched automatically — per card, `x-summary` → an explicit -`toolSummaries` entry → the fetched catalog → the raw name. +`toolSummaries` entry → the fetched catalog → the raw name. A +[summary template](tool-calls.md#a-label-filled-from-the-calls-arguments) the call's +arguments can fill comes before all of them. `sharedState` is AG-UI shared state, documented under [the run loop](concepts.md#the-run-loop-and-the-ag-ui-client); `unread` and `unhandledActivityTypes` are diff --git a/docs/tool-calls.md b/docs/tool-calls.md index cfe6725..5c3de38 100644 --- a/docs/tool-calls.md +++ b/docs/tool-calls.md @@ -140,6 +140,23 @@ this list too. Parts: `tool-card-section-head` (the heading row), `tool-card-raw `tool-card-field-value`; a value the card worded itself carries `data-kind` (`boolean`, `empty` or `count`, else `text`). +#### What the server says about each argument + +The arguments list reads more of the tool's schema when it has it: a client tool's own +`parameters.properties`, else the `arguments` projection on the `data-tools-url` catalog's +entry, which django-spec-agents 0.31.0 and later emit, translated, for the request's locale. +Per argument: + +- `title` replaces the prettified key; +- `oneOf: [{const, title}]` draws a value equal to a `const` as its `title` (the View raw JSON + keeps the constant); +- `format: "date"` and `"date-time"` draw a string through `Intl.DateTimeFormat` in the + browser's locale (a date as its calendar day), and fall back to the text if it does not parse; +- `x-hidden: true` leaves the argument out of the list; View raw still shows it. + +A malformed `arguments` costs only itself: the entry keeps its label. The result region never +reads them, since a result's keys are not arguments. + ### Drawing a card's body yourself A thirty-field result is a wall of JSON where a host wanted a table, or a @@ -201,6 +218,23 @@ is the authority. If a tool's schema carries an `x-summary` string (use `X_SUMMARY_KEY`), the card shows it on the label instead of the raw tool name. +### A label filled from the call's arguments + +A tool can name what this call does rather than what the tool is. An `x-summary-template` +string at the schema root (use `X_SUMMARY_TEMPLATE_KEY`), or a `summary_template` on the +tool's entry in the `data-tools-url` catalog, holds `{name}` placeholders that the call's +top-level arguments fill: `"Search orders for {query}"` called with `{ "query": "acme" }` +labels the card head, and the step-group row, *Search orders for acme*. django-spec-agents +0.31.0 and later emit both from `@tool(summary_template=...)`. + +The schema's template comes first, then the catalog's. Each placeholder fills from an +argument that is a non-empty string, a finite number or a boolean. If any placeholder +cannot be filled (the argument is missing, empty, nested or an array or object; the name is +dotted; or the template has a stray brace), the label is the static one, through the chain +above, never a half-filled sentence or literal braces. A filled value is set as text, so +markup in an argument shows as the characters it is. A tool without a template labels +exactly as before. + Every card leads with a **status icon** drawn entirely in CSS — a spinning ring while the call runs, then a check / cross / slash / dotted ring on success / error / decline / not finished. Re-theme it via custom properties (or the `tool-card-icon` part): `--ag-ui-tool-icon-done`, diff --git a/package.json b/package.json index 4ffe416..99124bf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@artooi/agents-web-components", - "version": "0.19.0", + "version": "0.20.0", "description": "Framework-free Web Component over the AG-UI protocol. Drop-in chat sidebar with a pluggable client-side tool registry, DOM driver primitives, animations, and destructive-action confirmation modal.", "type": "module", "main": "./dist/index.js", diff --git a/scripts/record_summary_template_fixture.py b/scripts/record_summary_template_fixture.py new file mode 100644 index 0000000..1275da5 --- /dev/null +++ b/scripts/record_summary_template_fixture.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +from __future__ import annotations + +import json +import sys +from importlib.metadata import version +from pathlib import Path + +import django +from django.conf import settings + +settings.configure(INSTALLED_APPS=[], USE_I18N=False) +django.setup() + +from django_spec_agents import ToolRegistry, build_tool_catalog, tool # noqa: E402 + +OUT = Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "summary_template.json" + +registry = ToolRegistry() + + +@tool(registry, summary="Search orders", summary_template="Search orders for {query} in {status}") +def search_orders(query: str, status: str = "open", limit: int = 10) -> list[str]: + """Find orders matching a query.""" + return [] + + +@tool(registry, summary="Tag a record", summary_template="Tag {record} with {tags}") +def tag_record(record: str, tags: list[str]) -> str: + """Tag a record.""" + return record + + +@tool(registry, summary="Ping") +def ping() -> str: + """Check the server is up.""" + return "pong" + + +def record() -> dict[str, object]: + """The catalog and the client-tool schemas, both as django-spec-agents builds them.""" + return { + "generator": "scripts/record_summary_template_fixture.py", + "djangoSpecAgents": version("django-spec-agents"), + "catalog": build_tool_catalog(registry), + "schemas": {binding.spec.name: binding.input_schema for binding in registry}, + } + + +if __name__ == "__main__": + OUT.write_text(json.dumps(record(), indent=2) + "\n") + sys.stdout.write(f"wrote {OUT.name}\n") diff --git a/scripts/record_tool_arguments_fixture.py b/scripts/record_tool_arguments_fixture.py new file mode 100644 index 0000000..6547942 --- /dev/null +++ b/scripts/record_tool_arguments_fixture.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +from __future__ import annotations + +import datetime +import json +import sys +from importlib.metadata import version +from pathlib import Path +from typing import Annotated, Literal + +import django +from django.conf import settings + +settings.configure(INSTALLED_APPS=[], USE_I18N=False) +django.setup() + +from django.db import models # noqa: E402 +from pydantic import Field # noqa: E402 + +from django_spec_agents import ToolRegistry, build_tool_catalog, tool # noqa: E402 + +OUT = Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "tool_arguments.json" + +registry = ToolRegistry() + + +class Status(models.TextChoices): + OPEN = "open", "Awaiting reply" + DONE = "done", "Closed" + + +@tool(registry, summary="File a ticket") +def file_ticket( + due_date: datetime.date, + status: Status, + customer_ref: Annotated[str, Field(title="Customer")], + mode: Literal["fast", "slow"] = "fast", + trace_id: Annotated[str, Field(json_schema_extra={"x-hidden": True})] = "", + reminder_at: datetime.datetime | None = None, + follow_up: Status | None = None, + query: str = "", +) -> str: + """File a support ticket.""" + return "filed" + + +@tool(registry, summary="Ping") +def ping(note: str = "") -> str: + """Check the server is up.""" + return "pong" + + +def record() -> dict[str, object]: + """The catalog and the client-tool schemas, both as django-spec-agents builds them.""" + return { + "generator": "scripts/record_tool_arguments_fixture.py", + "djangoSpecAgents": version("django-spec-agents"), + "catalog": build_tool_catalog(registry), + "schemas": {binding.spec.name: binding.input_schema for binding in registry}, + } + + +if __name__ == "__main__": + OUT.write_text(json.dumps(record(), indent=2) + "\n") + sys.stdout.write(f"wrote {OUT.name}\n") diff --git a/src/constants.ts b/src/constants.ts index f2f3f48..35e822f 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -303,6 +303,13 @@ export const X_CONFIRM_KEY = "x-confirm"; */ export const X_SUMMARY_KEY = "x-summary"; +/** + * Schema-root key holding a label with `{name}` placeholders (e.g. + * `"Search orders for {query}"`), filled from the call's top-level arguments. + * A placeholder the arguments cannot fill shows the static label instead. + */ +export const X_SUMMARY_TEMPLATE_KEY = "x-summary-template"; + /** * Schema-root key marking a tool as navigating — its handler triggers a full * page reload. The element checkpoints the call before the reload and resumes diff --git a/src/core/ag_ui_chat.ts b/src/core/ag_ui_chat.ts index 6261205..ce57f00 100644 --- a/src/core/ag_ui_chat.ts +++ b/src/core/ag_ui_chat.ts @@ -1119,6 +1119,8 @@ export class AgUiChat extends HTMLElement { resolveTool: (name) => this.#tools.resolve(name), toolSummaries: () => this.toolSummaries, serverSummary: (name) => this.#tools.summary(name), + serverSummaryTemplate: (name) => this.#tools.summaryTemplate(name), + argumentDisplays: (name) => this.#tools.argumentDisplays(name), toolDisplay: () => this.toolDisplay, toolGroupDisplay: () => this.toolGroupDisplay, // A thunk over the live property, not the property itself: the card keeps diff --git a/src/index.ts b/src/index.ts index cda4a73..410d438 100644 --- a/src/index.ts +++ b/src/index.ts @@ -57,6 +57,7 @@ export { X_DESTRUCTIVE_KEY, X_NAVIGATES_KEY, X_SUMMARY_KEY, + X_SUMMARY_TEMPLATE_KEY, } from "./constants.js"; export type { ActivityRegistration } from "./core/activity_registration.js"; export type { ActivityRenderContext } from "./core/activity_render_context.js"; @@ -181,6 +182,11 @@ export { export { createPageMapContext, type PageMap } from "./tools/page_map.js"; export { type PageMapFromOptions, type PageMapKind, pageMapFrom } from "./tools/page_map_from.js"; export { createPageStateTools, type PageState } from "./tools/page_state.js"; +export type { + ArgumentChoice, + ArgumentDisplay, + ArgumentDisplays, +} from "./tools/parse_argument_displays.js"; export { parseToolCatalog, type ToolCatalogEntry } from "./tools/parse_tool_catalog.js"; export { resolvePageMapHandle } from "./tools/resolve_page_map_handle.js"; export { @@ -234,6 +240,7 @@ export { } from "./ui/interrupts/question_card.js"; export type { Place } from "./ui/place/place.js"; export { prettifyToolName } from "./ui/progress/prettify_tool_name.js"; +export type { PayloadDisplay } from "./ui/progress/readable_payload.js"; export { type SettledStatus, ToolCallCard, diff --git a/src/tools/parse_argument_displays.ts b/src/tools/parse_argument_displays.ts new file mode 100644 index 0000000..bfd4782 --- /dev/null +++ b/src/tools/parse_argument_displays.ts @@ -0,0 +1,88 @@ +/** The property key django-spec-agents stamps on an argument a readable view leaves out. */ +const X_HIDDEN_KEY = "x-hidden"; + +/** One choice of an enumerated argument: the value on the wire and, if the server named it, its label. */ +export interface ArgumentChoice { + readonly const: unknown; + readonly title?: string; +} + +/** + * How one top-level argument reads to a person: the JSON Schema keys + * django-spec-agents projects into a catalog entry's `arguments`, and that a + * client tool's own `parameters.properties` carries under the same names. + */ +export interface ArgumentDisplay { + /** The label, in place of the prettified key. */ + readonly title?: string; + /** A JSON Schema `format`; `date` and `date-time` draw through `Intl`. */ + readonly format?: string; + /** The `oneOf: [{const, title}]` choices, a constant drawn as its title. */ + readonly choices?: readonly ArgumentChoice[]; + /** `x-hidden`: left out of the readable list, kept in the raw view. */ + readonly hidden?: boolean; +} + +/** Argument name to its display, a `Map` so a key such as "constructor" finds nothing inherited. */ +export type ArgumentDisplays = ReadonlyMap; + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +/** The well-formed `{const, title?}` choices, or none when `oneOf` is not a list of them. */ +function parseChoices(oneOf: unknown): ArgumentChoice[] { + if (!Array.isArray(oneOf)) { + return []; + } + const choices: ArgumentChoice[] = []; + for (const option of oneOf) { + if (!isRecord(option) || !Object.hasOwn(option, "const")) { + continue; + } + const title = option["title"]; + choices.push( + typeof title === "string" ? { const: option["const"], title } : { const: option["const"] }, + ); + } + return choices; +} + +/** One property's display, or null when it says nothing a reader would see. */ +function parseOne(property: unknown): ArgumentDisplay | null { + if (!isRecord(property)) { + return null; + } + const title = property["title"]; + const format = property["format"]; + const choices = parseChoices(property["oneOf"]); + const display: ArgumentDisplay = { + ...(typeof title === "string" ? { title } : {}), + ...(typeof format === "string" ? { format } : {}), + ...(choices.length > 0 ? { choices } : {}), + ...(property[X_HIDDEN_KEY] === true ? { hidden: true } : {}), + }; + return Object.keys(display).length > 0 ? display : null; +} + +/** + * Read argument displays off a `name -> property` record: a catalog entry's + * `arguments` or a client tool's `parameters.properties`. + * + * Tolerant per key: a malformed value costs that key, a malformed property + * costs that property, and anything but a record yields undefined, so the + * caller keeps the entry it came with. + */ +export function parseArgumentDisplays(data: unknown): ArgumentDisplays | undefined { + if (!isRecord(data)) { + return undefined; + } + const out = new Map(); + for (const [key, property] of Object.entries(data)) { + const display = parseOne(property); + if (display !== null) { + out.set(key, display); + } + } + return out.size > 0 ? out : undefined; +} diff --git a/src/tools/parse_tool_catalog.ts b/src/tools/parse_tool_catalog.ts index e55c280..830e50f 100644 --- a/src/tools/parse_tool_catalog.ts +++ b/src/tools/parse_tool_catalog.ts @@ -1,3 +1,5 @@ +import { type ArgumentDisplays, parseArgumentDisplays } from "./parse_argument_displays.js"; + /** * One entry in the server-tool catalog served by django-ag-ui's `tools/` * endpoint and fetched via the `data-tools-url` attribute. @@ -7,8 +9,19 @@ export interface ToolCatalogEntry { readonly name: string; /** A friendly card label for the tool. */ readonly summary: string; + /** + * A label with `{name}` placeholders, filled from the call's top-level + * arguments (the wire's `summary_template`). The card shows `summary` when + * any placeholder cannot be filled. + */ + readonly summaryTemplate?: string; /** Optional longer blurb (e.g. for a tooltip). */ readonly description?: string; + /** + * How each argument reads to a person (the wire's `arguments` projection): + * its title, format, enum labels and hidden flag. + */ + readonly arguments?: ArgumentDisplays; } /** @@ -16,7 +29,9 @@ export interface ToolCatalogEntry { * that isn't a `{ name: string, summary: string }` object. Tolerant by design: * a malformed payload yields an empty map rather than throwing, and an * optional field of the wrong type costs that field rather than the entry. - * Whole entries are kept, so a consumer can reach `description`. + * Whole entries are kept, so a consumer can reach `description`, + * `summaryTemplate` (read off the wire's `summary_template`) and `arguments`, + * whose malformed properties cost only themselves. */ export function parseToolCatalog(data: unknown): Record { const out: Record = {}; @@ -31,10 +46,17 @@ export function parseToolCatalog(data: unknown): Record { const url = this.#host.element.getAttribute("data-tools-url"); diff --git a/src/ui/progress/fill_summary_template.ts b/src/ui/progress/fill_summary_template.ts new file mode 100644 index 0000000..ac27def --- /dev/null +++ b/src/ui/progress/fill_summary_template.ts @@ -0,0 +1,47 @@ +/** A placeholder as django-spec-agents reads one: anything between a brace pair, no brace inside. */ +const PLACEHOLDER = /\{([^{}]*)\}/g; + +/** + * Fill a tool's `{name}` summary template from the call's top-level arguments, + * or `null` when any placeholder cannot be filled. + * + * A placeholder fills only from an own argument that is a non-empty string, a + * finite number or a boolean; a missing, empty, nested or non-scalar argument + * makes the whole template unfillable, so a caller falls back to its static + * label rather than showing a half-filled sentence. A stray brace outside a + * placeholder is unfillable too, so literal braces never reach the label. The + * result is plain text: a caller sets it as `textContent`, never as markup. + */ +export function fillSummaryTemplate( + template: string, + args: Readonly>, +): string | null { + let unfillable = false; + // The function form of replace: a string replacement would expand $& in a value. + const filled = template.replace(PLACEHOLDER, (_match, name: string) => { + const value = Object.hasOwn(args, name) ? args[name] : undefined; + const text = scalarText(value); + if (text === null) { + unfillable = true; + return ""; + } + return text; + }); + if (unfillable || /[{}]/.test(template.replace(PLACEHOLDER, ""))) { + return null; + } + return filled; +} + +function scalarText(value: unknown): string | null { + if (typeof value === "string") { + return value.trim() === "" ? null : value; + } + if (typeof value === "number") { + return Number.isFinite(value) ? String(value) : null; + } + if (typeof value === "boolean") { + return String(value); + } + return null; +} diff --git a/src/ui/progress/readable_payload.ts b/src/ui/progress/readable_payload.ts index 24dfaff..0c30092 100644 --- a/src/ui/progress/readable_payload.ts +++ b/src/ui/progress/readable_payload.ts @@ -1,3 +1,4 @@ +import type { ArgumentDisplay, ArgumentDisplays } from "../../tools/parse_argument_displays.js"; import type { UiStrings } from "../ui_strings.js"; import { prettifyToolName } from "./prettify_tool_name.js"; @@ -25,6 +26,50 @@ function describeValue(value: unknown, strings: UiStrings): { text: string; kind return { text: String(value), kind: "text" }; } +/** What a caller knows about the payload's keys beyond the payload itself. */ +export interface PayloadDisplay { + /** Per-key titles, formats, enum labels and hidden flags; only an arguments region has them. */ + readonly arguments?: ArgumentDisplays; + /** The `Intl` locale dates draw in; the browser's own when absent. */ + readonly locale?: string; +} + +/** The `Intl` options a JSON Schema `format` draws with; a date-only value is a UTC calendar day. */ +const DATE_FORMATS: ReadonlyMap = new Map([ + ["date", { dateStyle: "medium", timeZone: "UTC" }], + ["date-time", { dateStyle: "medium", timeStyle: "short" }], +]); + +/** A string in a date `format` drawn through `Intl`, or null for any value that is not one. */ +function formatDate(value: unknown, format: string, locale: string | undefined): string | null { + const options = DATE_FORMATS.get(format); + if (options === undefined || typeof value !== "string") { + return null; + } + const date = new Date(value); + if (Number.isNaN(date.getTime())) { + return null; + } + try { + return new Intl.DateTimeFormat(locale, options).format(date); + } catch { + return null; + } +} + +/** The words a value draws as under its argument's display, or null to draw it as RENDER does. */ +function describeArgument( + value: unknown, + display: ArgumentDisplay, + locale: string | undefined, +): string | null { + const label = display.choices?.find((choice) => choice.const === value)?.title; + if (label !== undefined) { + return label; + } + return display.format === undefined ? null : formatDate(value, display.format, locale); +} + /** * Draw a tool payload as a label/value list a person can read, or return null * when it is not a record with at least one key, so the caller keeps its text. @@ -34,8 +79,17 @@ function describeValue(value: unknown, strings: UiStrings): { text: string; kind * another shape. Keys are labelled by the rule {@link prettifyToolName} applies * to a tool's name. Every word lands as a text node, so a key or value that * looks like markup is shown as written and never parsed. + * + * With `display.arguments`, a key's title replaces its prettified label, an + * enum constant draws as its label, a `date` or `date-time` string draws + * through `Intl`, and a hidden key is left out (the raw view keeps it), so a + * payload whose every key is hidden draws as an empty list, not as raw text. */ -export function renderReadablePayload(value: unknown, strings: UiStrings): HTMLElement | null { +export function renderReadablePayload( + value: unknown, + strings: UiStrings, + display: PayloadDisplay = {}, +): HTMLElement | null { if (value === null || typeof value !== "object" || Array.isArray(value)) { return null; } @@ -47,6 +101,10 @@ export function renderReadablePayload(value: unknown, strings: UiStrings): HTMLE list.className = "tool-call-fields"; list.setAttribute("part", "tool-card-fields"); for (const [key, entry] of entries) { + const argument = display.arguments?.get(key) ?? {}; + if (argument.hidden === true) { + continue; + } const row = document.createElement("div"); row.className = "tool-call-field"; row.setAttribute("part", "tool-card-field"); @@ -55,9 +113,11 @@ export function renderReadablePayload(value: unknown, strings: UiStrings): HTMLE const label = document.createElement("dt"); label.className = "tool-call-field-label"; label.setAttribute("part", "tool-card-field-label"); - label.textContent = prettifyToolName(key); + label.textContent = argument.title ?? prettifyToolName(key); - const { text, kind } = describeValue(entry, strings); + const drawn = describeArgument(entry, argument, display.locale); + const { text, kind } = + drawn === null ? describeValue(entry, strings) : { text: drawn, kind: "text" as const }; const cell = document.createElement("dd"); cell.className = "tool-call-field-value"; cell.setAttribute("part", "tool-card-field-value"); diff --git a/src/ui/progress/tool_call_card.ts b/src/ui/progress/tool_call_card.ts index eaecc4e..e3d3947 100644 --- a/src/ui/progress/tool_call_card.ts +++ b/src/ui/progress/tool_call_card.ts @@ -1,6 +1,6 @@ import { TOOL_CALL_STATUS, type TOOL_DISPLAY } from "../../constants.js"; import { DEFAULT_UI_STRINGS, type UiStrings } from "../ui_strings.js"; -import { renderReadablePayload } from "./readable_payload.js"; +import { type PayloadDisplay, renderReadablePayload } from "./readable_payload.js"; /** Any state a tool-call card can be in. */ export type ToolCallStatus = (typeof TOOL_CALL_STATUS)[keyof typeof TOOL_CALL_STATUS]; @@ -128,6 +128,8 @@ interface Section { export interface ToolCallCardOptions { /** Host presentation hook for both body regions. See {@link ToolPayloadFormatter}. */ readonly formatPayload?: ToolPayloadFormatter; + /** How the arguments read: their titles, formats, enum labels and hidden keys. Never the result. */ + readonly display?: PayloadDisplay; } /** @@ -265,6 +267,7 @@ export class ToolCallCard { { kind: "arguments", toolName: name, args }, args, JSON.stringify(args, null, 2), + options.display, ); // Drop the region rather than frame an empty object. The marker is what // the shadow CSS reads to tell whether the toggle has anything to open: @@ -443,7 +446,13 @@ export class ToolCallCard { * the host's to draw, and a region already showing raw text has nothing else * to show. */ - #renderPayload(section: Section, payload: ToolPayload, value: unknown, raw: string): void { + #renderPayload( + section: Section, + payload: ToolPayload, + value: unknown, + raw: string, + display: PayloadDisplay = {}, + ): void { const { body } = section; const rendered = this.#formatPayload === null ? null : this.#formatPayload(payload); if (rendered !== null) { @@ -455,7 +464,7 @@ export class ToolCallCard { body.replaceChildren(rendered); return; } - const list = renderReadablePayload(value, this.#strings); + const list = renderReadablePayload(value, this.#strings, display); if (list === null) { body.textContent = raw; return; diff --git a/src/ui/transcript/transcript.ts b/src/ui/transcript/transcript.ts index 83c01fb..9f10ea2 100644 --- a/src/ui/transcript/transcript.ts +++ b/src/ui/transcript/transcript.ts @@ -1,10 +1,17 @@ -import { MESSAGE_ROLE, type ToolGroupDisplayMode, X_SUMMARY_KEY } from "../../constants.js"; +import { + MESSAGE_ROLE, + type ToolGroupDisplayMode, + X_SUMMARY_KEY, + X_SUMMARY_TEMPLATE_KEY, +} from "../../constants.js"; import type { AgUiToolCall } from "../../core/agui_client.js"; import type { MessageRole } from "../../core/message_role.js"; import { skillNameFrom } from "../../skills/skill_name_from.js"; import type { ChartRenderer, ClientTool } from "../../tools/client_tool_registry.js"; +import type { ArgumentDisplays } from "../../tools/parse_argument_displays.js"; import { attachCopyButtons } from "../excerpts/attach_copy_buttons.js"; import { fillUiString } from "../fill_ui_string.js"; +import { fillSummaryTemplate } from "../progress/fill_summary_template.js"; import { prettifyToolName } from "../progress/prettify_tool_name.js"; import { renderRunNotice } from "../progress/run_notice.js"; import { ThoughtsBlock } from "../progress/thoughts_block.js"; @@ -39,6 +46,10 @@ export interface TranscriptHost { readonly toolSummaries: () => Record; /** The server catalog's label for a tool, if it sent one. */ readonly serverSummary: (name: string) => string | undefined; + /** The server catalog's `{name}` label template for a tool, if it sent one. */ + readonly serverSummaryTemplate: (name: string) => string | undefined; + /** How a tool's arguments read: its own schema's, else the server catalog's. */ + readonly argumentDisplays: (name: string) => ArgumentDisplays | undefined; /** The element's `formatToolPayload`, asked per region of a card. */ readonly formatToolPayload: (payload: ToolPayload) => Node | string | null; /** The element's `toolDisplay`, read per card: it decides whether calls fold into a step group. */ @@ -495,17 +506,10 @@ export class Transcript { if (existing !== undefined) { return existing; } - // Prefer the tool's own `x-summary`; then an explicit `toolSummaries` - // entry; then the fetched server catalog (`data-tools-url`). All cover - // server-side tools whose schema never reached the browser. - const labelled = this.#host.resolveTool(call.name)?.parameters[X_SUMMARY_KEY]; - const summary = - typeof labelled === "string" - ? labelled - : (this.#host.toolSummaries()[call.name] ?? - this.#host.serverSummary(call.name) ?? - prettifyToolName(call.name)); + const summary = this.#labelFor(call); + const displays = this.#host.argumentDisplays(call.name); const card = new ToolCallCard(call.name, call.args, summary, this.#host.strings(), { + ...(displays === undefined ? {} : { display: { arguments: displays } }), // A thunk over the live property, not the property itself: the card keeps // this for the life of the call, and the result region is filled when the // tool settles -- which can be long after a host set the hook. @@ -522,6 +526,32 @@ export class Transcript { return card; } + /** + * The label a call's card and step row show. + * + * A template filled from the call's arguments comes first: the tool's own + * `x-summary-template`, else the server catalog's `summary_template`. One the + * arguments cannot fill falls through, whole, to the static chain: the tool's + * own `x-summary`; then an explicit `toolSummaries` entry; then the fetched + * server catalog (`data-tools-url`), which covers server-side tools whose + * schema never reached the browser; then the prettified name. + */ + #labelFor(call: AgUiToolCall): string { + const parameters = this.#host.resolveTool(call.name)?.parameters; + const own = parameters?.[X_SUMMARY_TEMPLATE_KEY]; + const template = typeof own === "string" ? own : this.#host.serverSummaryTemplate(call.name); + const filled = template === undefined ? null : fillSummaryTemplate(template, call.args); + if (filled !== null) { + return filled; + } + const labelled = parameters?.[X_SUMMARY_KEY]; + return typeof labelled === "string" + ? labelled + : (this.#host.toolSummaries()[call.name] ?? + this.#host.serverSummary(call.name) ?? + prettifyToolName(call.name)); + } + /** Redraw every step group's row, for a change of the inner display, which no card announces. */ refreshStepGroups(): void { for (const element of this.#host.messages.querySelectorAll(".tool-group")) { diff --git a/src/version.ts b/src/version.ts index 25ae14a..0c5ec8d 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION: string = "0.19.0"; +export const VERSION: string = "0.20.0"; diff --git a/tests/ag_ui_chat_argument_displays.test.ts b/tests/ag_ui_chat_argument_displays.test.ts new file mode 100644 index 0000000..8894b63 --- /dev/null +++ b/tests/ag_ui_chat_argument_displays.test.ts @@ -0,0 +1,78 @@ +/** + * A tool card's arguments drawn by the catalog's `arguments` projection, recorded from + * django-spec-agents' `build_tool_catalog` by `scripts/record_tool_arguments_fixture.py`. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ELEMENT_TAG } from "../src/constants.js"; +import type { AgUiChat } from "../src/core/ag_ui_chat.js"; +import { defineChat } from "../src/core/define_chat.js"; +import fixture from "./fixtures/tool_arguments.json"; +import { type Emit, makeFakeAgent } from "./helpers/fake_agent.js"; + +defineChat(); + +beforeEach(() => { + document.body.innerHTML = ""; + sessionStorage.clear(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +async function flush(): Promise { + for (let i = 0; i < 5; i += 1) { + await Promise.resolve(); + } +} + +async function run(calls: (emit: Emit) => void): Promise { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ json: () => Promise.resolve(fixture.catalog) }), + ); + const el = document.createElement(ELEMENT_TAG) as AgUiChat; + el.setAttribute("endpoint", "/agent/"); + el.setAttribute("data-start-open", ""); + el.setAttribute("data-tool-display", "full"); + el.setAttribute("data-tools-url", "/agent/tools/"); + el.agentFactory = () => + makeFakeAgent({ + script: (emit) => { + emit.runStart(); + calls(emit); + emit.runEnd(); + }, + }).agent; + document.body.appendChild(el); + await flush(); + const root = el.shadowRoot as ShadowRoot; + const input = root.querySelector(".input") as HTMLTextAreaElement; + input.value = "go"; + root.querySelector(".send")?.click(); + await flush(); + return root; +} + +function labels(root: ShadowRoot): (string | null)[] { + return [...root.querySelectorAll(".tool-call-args .tool-call-field-label")].map( + (label) => label.textContent, + ); +} + +describe("a server tool's catalog arguments", () => { + it("label the card's arguments and leave the hidden one out", async () => { + const root = await run((emit) => + emit.toolCall("tc1", "file_ticket", { customer_ref: "C-9", status: "done", trace_id: "t" }), + ); + expect(labels(root)).toEqual(["Customer", "Status"]); + expect(root.querySelector(".tool-call-args")?.textContent).toContain("Closed"); + }); + + it("leave a tool the catalog says nothing about drawn as before", async () => { + const root = await run((emit) => emit.toolCall("tc1", "ping", { note: "hi" })); + expect(labels(root)).toEqual(["Note"]); + }); +}); diff --git a/tests/ag_ui_chat_summary_template.test.ts b/tests/ag_ui_chat_summary_template.test.ts new file mode 100644 index 0000000..7d6fb52 --- /dev/null +++ b/tests/ag_ui_chat_summary_template.test.ts @@ -0,0 +1,245 @@ +/** + * A tool call labelled by its summary template, filled from the call's arguments. + * + * The catalog and the schemas are django-spec-agents' own output, recorded by + * `scripts/record_summary_template_fixture.py` (run it with + * `uv run --no-project --with django-spec-agents==0.31.0 python