From a6b7c546cfbb8563619f7f860a4c81eb667923b1 Mon Sep 17 00:00:00 2001 From: Artur Veres Date: Wed, 2 Dec 2026 10:46:03 +0100 Subject: [PATCH 1/7] Fill a tool-call label from the call's arguments A tool schema's x-summary-template, or the catalog's summary_template, labels the card head and the step-group row with its placeholders filled from the call's top-level scalar arguments. Any placeholder that cannot be filled falls back to the static label chain unchanged. The fixture is django-spec-agents 0.31.0's own build_tool_catalog output. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + demo/app/scenarios.js | 2 + demo/mock-server.mjs | 34 +++ docs/api.md | 1 + docs/quickstart.md | 6 +- docs/tool-calls.md | 17 ++ scripts/record_summary_template_fixture.py | 52 +++++ src/constants.ts | 7 + src/core/ag_ui_chat.ts | 1 + src/index.ts | 1 + src/tools/parse_tool_catalog.ts | 18 +- src/tools/tool_catalog.ts | 5 + src/ui/progress/fill_summary_template.ts | 47 ++++ src/ui/transcript/transcript.ts | 47 +++- tests/ag_ui_chat_summary_template.test.ts | 209 ++++++++++++++++++ .../browser/summary_template.browser.test.ts | 80 +++++++ tests/fill_summary_template.test.ts | 55 +++++ tests/fixtures/summary_template.json | 75 +++++++ tests/parse_tool_catalog.test.ts | 19 ++ 19 files changed, 671 insertions(+), 16 deletions(-) create mode 100644 scripts/record_summary_template_fixture.py create mode 100644 src/ui/progress/fill_summary_template.ts create mode 100644 tests/ag_ui_chat_summary_template.test.ts create mode 100644 tests/browser/summary_template.browser.test.ts create mode 100644 tests/fill_summary_template.test.ts create mode 100644 tests/fixtures/summary_template.json diff --git a/CHANGELOG.md b/CHANGELOG.md index efee5b6..e73ae3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### 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. 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. + ## [0.18.0] — 2026-11-25 ### Added diff --git a/demo/app/scenarios.js b/demo/app/scenarios.js index 43afe41..58fbd6b 100644 --- a/demo/app/scenarios.js +++ b/demo/app/scenarios.js @@ -195,7 +195,9 @@ export const SCENARIOS = [ ["A failing tool", "break something"], ["Nothing to open", "ping"], ["Sub-agents", "delegate this"], + ["Labels from arguments (0.19.0)", "search orders"], ], + attrs: { "data-tools-url": "/tools/" }, }, { slug: "approvals", diff --git a/demo/mock-server.mjs b/demo/mock-server.mjs index d7d5102..d374263 100644 --- a/demo/mock-server.mjs +++ b/demo/mock-server.mjs @@ -201,6 +201,15 @@ 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}", + }, + { 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) }); @@ -965,6 +974,24 @@ 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. + const parent = id("msg"); + await streamText(res, parent, ["Looking those up…"]); + const calls = [ + ["search_orders", { query: "acme", status: "late" }], + ["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 @@ -1637,6 +1664,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..0e93ad1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -234,5 +234,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 6ea7075..c5c8298 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? }]`), fetched with the element's headers and cookie policy; labels tool-call cards for server-side tools. | | `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 8c8ce09..265bb7b 100644 --- a/docs/tool-calls.md +++ b/docs/tool-calls.md @@ -175,6 +175,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/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/src/constants.ts b/src/constants.ts index 3430de1..d914646 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 839e508..a8fe3dd 100644 --- a/src/core/ag_ui_chat.ts +++ b/src/core/ag_ui_chat.ts @@ -1119,6 +1119,7 @@ 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), 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..28f2dc9 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"; diff --git a/src/tools/parse_tool_catalog.ts b/src/tools/parse_tool_catalog.ts index e55c280..e870976 100644 --- a/src/tools/parse_tool_catalog.ts +++ b/src/tools/parse_tool_catalog.ts @@ -7,6 +7,12 @@ 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; } @@ -16,7 +22,8 @@ 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` and + * `summaryTemplate` (read off the wire's `summary_template`). */ export function parseToolCatalog(data: unknown): Record { const out: Record = {}; @@ -31,10 +38,15 @@ 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/transcript/transcript.ts b/src/ui/transcript/transcript.ts index 83c01fb..2391f8d 100644 --- a/src/ui/transcript/transcript.ts +++ b/src/ui/transcript/transcript.ts @@ -1,10 +1,16 @@ -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 { 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 +45,8 @@ 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; /** 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,16 +503,7 @@ 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 card = new ToolCallCard(call.name, call.args, summary, this.#host.strings(), { // 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 @@ -522,6 +521,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/tests/ag_ui_chat_summary_template.test.ts b/tests/ag_ui_chat_summary_template.test.ts new file mode 100644 index 0000000..10d423e --- /dev/null +++ b/tests/ag_ui_chat_summary_template.test.ts @@ -0,0 +1,209 @@ +/** + * 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