Public: anyone can read this; the crew can change it.
Talk API: an agent turn's cards as data, with exact values #18008
Merged 14h 29m ago, live in production
torque/forge:torque/18005-talk-api-an-agent-turn-s-cards-as-data-w → main 0 commits fork
9 files
changed +201
−7
docs/features/talk-voice.md +1 −1
| @@ -73,7 +73,7 @@ In Talk a widget is drawn as a shown card is, bare under a hairline on its start | ||
| 73 | 73 | |
| 74 | 74 | ### In the terminal |
| 75 | 75 | |
| 76 | `forge talk` and the terminal's Talk screen print a placed widget from the same data, through the parser every door uses: a chart as one line of block characters a series (one scale for all, its total after it) over the days it spans. `GET /api/v1/conversation/turns` carries the printed reply as `plain` when it places a card or a widget. | |
| 76 | `forge talk` and the terminal's Talk screen print a placed widget from the same data, through the parser every door uses: a chart as one line of block characters a series (one scale for all, its total after it) over the days it spans. `GET /api/v1/conversation/turns` carries the printed reply as `plain` when it places a card or a widget, and every agent turn carries `cards` (#18005): each result its text places, as data a native client can draw itself (`src/core/talk_cards.ts`). A card is `{ ref, kind, title, source, tool, at }` where `ref` is the `cN` of the `::show cN` line. A chart (`kind` is `line`, `bar` or `area`) adds `series: [{ label, unit?, tone?, points: [{ t?, v }] }]`, the very values the page draws and `widgetLines` prints (copied from the kept data, never read back from a drawing), and `levels: true` when a value is a level to read as the last one, not a sum. Any other kind (a card of rows, a receipt) adds `status` and `rows: [{ label, value, link?, depth? }]`. A bearer token of either scope reads them; each shape is in `/api/v1/openapi.json` as `TurnCard`. | |
| 77 | 77 | |
| 78 | 78 | ### Limits |
| 79 | 79 |
src/cli/api.ts +1 −1
| @@ -531,7 +531,7 @@ export class ForgeApi { | ||
| 531 | 531 | } |
| 532 | 532 | |
| 533 | 533 | /** The latest turns of the person's conversation (`GET /api/v1/conversation/turns`). */ |
| 534 | async conversation(): Promise<ApiResult<{ running: boolean; turns: { id: string; role: string; text: string; plain?: string; work?: { steps: string; links: { href: string; label: string }[] } | null }[] }>> { | |
| 534 | async conversation(): Promise<ApiResult<{ running: boolean; turns: { id: string; role: string; text: string; plain?: string; cards?: { ref: string; kind: string; title: string }[]; work?: { steps: string; links: { href: string; label: string }[] } | null }[] }>> { | |
| 535 | 535 | return this.call("/api/v1/conversation/turns?limit=20"); |
| 536 | 536 | } |
| 537 | 537 |
src/contract/openapi/routes/getApiV1ConversationTurns.ts +3 −2
| @@ -1,3 +1,4 @@ | ||
| 1 | import { ref } from "../schema_kit.ts"; | |
| 1 | 2 | import { type Route, limitTo } from "../shared.ts"; |
| 2 | 3 | import { MAX_PAGE } from "../../../core/conversations.ts"; |
| 3 | 4 | |
| @@ -5,10 +6,10 @@ export const route: Route = { | ||
| 5 | 6 | method: "get", |
| 6 | 7 | path: "/api/v1/conversation/turns", |
| 7 | 8 | summary: "The signed-in person's conversation with the forge's agent", |
| 8 | detail: "The signed-in person's conversation with the forge's agent: the latest turns, oldest first, and whether an answer is being written now; stoppedAt is \"limit\" when the latest turn ended because it reached its turn or token limit (cut off, not finished; send a short message to go on), else null", | |
| 9 | detail: "The signed-in person's conversation with the forge's agent: the latest turns, oldest first, and whether an answer is being written now; stoppedAt is \"limit\" when the latest turn ended because it reached its turn or token limit (cut off, not finished; send a short message to go on), else null. An agent turn carries `cards`: each result its text places with a `::show cN` line, as { ref: \"cN\", kind, title, source, tool, at } and, for a chart (kind line, bar or area), series: [{ label, unit?, tone?, points: [{ t?, v }] }] (the exact values the page draws from; levels: true when a value is a level, so read the last), and for any other kind (rows, a receipt) status and rows: [{ label, value, link?, depth? }]; a handle that names no kept result is left out", | |
| 9 | 10 | auth: true, |
| 10 | 11 | role: "member", |
| 11 | 12 | query: { limit: limitTo(MAX_PAGE), before: "string", conversation: "string" }, |
| 12 | reply: { running: "boolean", stoppedAt: "string|null", turns: "array" }, | |
| 13 | response: ref("ConversationTurns"), | |
| 13 | 14 | refuses: [401], |
| 14 | 15 | }; |
src/contract/openapi/schema_kit.ts +1
| @@ -10,6 +10,7 @@ export type Schema = Readonly<Record<string, unknown>>; | ||
| 10 | 10 | |
| 11 | 11 | export const str: Schema = { type: "string" }; |
| 12 | 12 | export const int: Schema = { type: "integer" }; |
| 13 | export const num: Schema = { type: "number" }; | |
| 13 | 14 | export const bool: Schema = { type: "boolean" }; |
| 14 | 15 | |
| 15 | 16 | /** A value that may also be null (OpenAPI 3.1: a type array, or `anyOf` with null for a `$ref`). */ |
src/contract/openapi/schemas/conversation.ts +63 −1
| @@ -3,7 +3,9 @@ | ||
| 3 | 3 | * conversation. |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | import { bool, int, list, obj, orNull, ref, str, words, type Schema } from "../schema_kit.ts"; | |
| 6 | import { bool, int, list, num, obj, orNull, ref, str, words, type Schema } from "../schema_kit.ts"; | |
| 7 | import { TURN_ROLES } from "../../../core/conversations.ts"; | |
| 8 | import { CARD_KINDS } from "../../../web/studio/cards.ts"; | |
| 7 | 9 | |
| 8 | 10 | const MESSAGE_REQUEST: Schema = obj( |
| 9 | 11 | { text: str, conversation: str, files: list(str), during: words("queue", "steer"), about: str, model: str }, |
| @@ -42,6 +44,60 @@ const CONVERSATION: Schema = obj({ | ||
| 42 | 44 | pinnedAt: orNull(str), |
| 43 | 45 | }); |
| 44 | 46 | |
| 47 | /** One point of a chart: `t` is its x label (a day, an hour or a name), `v` the exact value. */ | |
| 48 | const CARD_POINT: Schema = obj({ t: str, v: num }, ["t"]); | |
| 49 | ||
| 50 | const CARD_SERIES: Schema = obj({ label: str, unit: str, tone: words("good", "bad"), points: list(ref("TurnCardPoint")) }, ["unit", "tone"]); | |
| 51 | ||
| 52 | const CARD_FIELD: Schema = obj({ label: str, value: str, link: str, depth: int }, ["link", "depth"]); | |
| 53 | ||
| 54 | /** | |
| 55 | * A result a reply places with `::show cN`. A chart (`line`, `bar`, `area`) carries `series`; any | |
| 56 | * other kind (a card of rows) carries `status` and `rows`. | |
| 57 | */ | |
| 58 | const TURN_CARD: Schema = obj( | |
| 59 | { | |
| 60 | ref: { type: "string", pattern: "^c[1-9][0-9]*$" }, | |
| 61 | kind: words("line", "bar", "area", ...CARD_KINDS), | |
| 62 | title: str, | |
| 63 | source: str, | |
| 64 | tool: str, | |
| 65 | at: str, | |
| 66 | series: list(ref("TurnCardSeries")), | |
| 67 | levels: bool, | |
| 68 | status: str, | |
| 69 | rows: list(ref("TurnCardField")), | |
| 70 | }, | |
| 71 | ["series", "levels", "status", "rows"], | |
| 72 | ); | |
| 73 | ||
| 74 | /** | |
| 75 | * A turn: agent turns also carry `cards`, the results their text places, in the order it places | |
| 76 | * them. | |
| 77 | */ | |
| 78 | const TURN: Schema = obj( | |
| 79 | { | |
| 80 | id: str, | |
| 81 | conversationId: str, | |
| 82 | role: words(...TURN_ROLES), | |
| 83 | text: str, | |
| 84 | createdAt: str, | |
| 85 | replaced: bool, | |
| 86 | failed: bool, | |
| 87 | limited: bool, | |
| 88 | stoppedAt: str, | |
| 89 | work: orNull(obj({ steps: str, links: list(obj({ href: str, label: str })) })), | |
| 90 | costUsd: orNull(num), | |
| 91 | plain: str, | |
| 92 | cards: list(ref("TurnCard")), | |
| 93 | }, | |
| 94 | ["limited", "stoppedAt", "work", "costUsd", "plain", "cards"], | |
| 95 | ); | |
| 96 | ||
| 97 | const TURNS: Schema = obj( | |
| 98 | { running: bool, stoppedAt: orNull(str), conversation: str, totalUsd: orNull(num), queued: list(obj({ id: str, text: str })), turns: list(ref("ConversationTurn")) }, | |
| 99 | ); | |
| 100 | ||
| 45 | 101 | const CONVERSATION_REQUEST: Schema = obj({ title: str, archived: bool }, ["title", "archived"]); |
| 46 | 102 | |
| 47 | 103 | export const CONVERSATION_SCHEMAS: Readonly<Record<string, Schema>> = { |
| @@ -51,4 +107,10 @@ export const CONVERSATION_SCHEMAS: Readonly<Record<string, Schema>> = { | ||
| 51 | 107 | ConversationEnvelope: obj({ conversation: ref("Conversation") }), |
| 52 | 108 | ConversationList: obj({ conversations: list(ref("Conversation")) }), |
| 53 | 109 | ConversationRequest: CONVERSATION_REQUEST, |
| 110 | TurnCardPoint: CARD_POINT, | |
| 111 | TurnCardSeries: CARD_SERIES, | |
| 112 | TurnCardField: CARD_FIELD, | |
| 113 | TurnCard: TURN_CARD, | |
| 114 | ConversationTurn: TURN, | |
| 115 | ConversationTurns: TURNS, | |
| 54 | 116 | }; |
src/core/talk_cards.ts added +99
| @@ -0,0 +1,99 @@ | ||
| 1 | /** | |
| 2 | * An agent turn's placed results as data (#18005), for a client that draws its own: each | |
| 3 | * `::show cN` a reply places becomes `{ ref, kind, title, source, ... }`. A chart's series are the | |
| 4 | * exact numbers the page's SVG is drawn from (`widgetHtml` reads the same `ChartData` kept in | |
| 5 | * `ShownCard.widget`) and the terminal prints (`widgetLines`), copied and never re-derived from a | |
| 6 | * drawing; a card with no series (rows, a receipt) carries its typed fields. Plain data in, plain | |
| 7 | * data out; no access check of its own: the caller read the cards through `cardsPlaced`, which | |
| 8 | * checks the person. | |
| 9 | */ | |
| 10 | ||
| 11 | import { shownIn, voiceParts, type ShownCard } from "./talk_voice.ts"; | |
| 12 | ||
| 13 | /** | |
| 14 | * One point of a series: `t` is its label on the x axis (a day, an hour, a name), `v` its value. | |
| 15 | */ | |
| 16 | export interface CardPoint { | |
| 17 | readonly t?: string; | |
| 18 | readonly v: number; | |
| 19 | } | |
| 20 | ||
| 21 | /** One series: its label, what a value counts (`$`, `%`, "checks") and its points, in order. */ | |
| 22 | export interface CardSeries { | |
| 23 | readonly label: string; | |
| 24 | readonly unit?: string; | |
| 25 | /** Good or bad news, as the page colours it. */ | |
| 26 | readonly tone?: "good" | "bad"; | |
| 27 | readonly points: readonly CardPoint[]; | |
| 28 | } | |
| 29 | ||
| 30 | /** One row of a card, as kept: the label and the value as the card says them. */ | |
| 31 | export interface CardField { | |
| 32 | readonly label: string; | |
| 33 | readonly value: string; | |
| 34 | readonly link?: string; | |
| 35 | readonly depth?: number; | |
| 36 | } | |
| 37 | ||
| 38 | export interface TurnCard { | |
| 39 | /** `c3`: the handle in the reply's `::show c3` line. */ | |
| 40 | readonly ref: string; | |
| 41 | /** | |
| 42 | * The web's own: `line`, `bar` or `area` for a chart; a card's kind (`crew`, `issues`...) else. | |
| 43 | */ | |
| 44 | readonly kind: string; | |
| 45 | readonly title: string; | |
| 46 | /** Where it came from: the call in plain words. */ | |
| 47 | readonly source: string; | |
| 48 | /** The tool that drew it, and when (ISO). */ | |
| 49 | readonly tool: string; | |
| 50 | readonly at: string; | |
| 51 | /** A chart only: the series, and whether its values are levels (read the last, not the sum). */ | |
| 52 | readonly series?: readonly CardSeries[]; | |
| 53 | readonly levels?: boolean; | |
| 54 | /** A card of rows only: its status line and its rows. */ | |
| 55 | readonly status?: string; | |
| 56 | readonly rows?: readonly CardField[]; | |
| 57 | } | |
| 58 | ||
| 59 | /** One kept result as data; the same fields whichever door asks. */ | |
| 60 | export function cardData(shown: ShownCard): TurnCard { | |
| 61 | const head = { ref: `c${shown.n}`, title: shown.title, source: shown.said, tool: shown.tool, at: shown.createdAt }; | |
| 62 | const w = shown.widget; | |
| 63 | if (w !== undefined) { | |
| 64 | const d = w.data; | |
| 65 | return { | |
| 66 | ref: head.ref, | |
| 67 | kind: d.kind, | |
| 68 | title: head.title, | |
| 69 | source: head.source, | |
| 70 | tool: head.tool, | |
| 71 | at: head.at, | |
| 72 | series: d.series.map((s) => ({ | |
| 73 | label: s.name, | |
| 74 | ...(d.unit === undefined ? {} : { unit: d.unit }), | |
| 75 | ...(s.tone === undefined ? {} : { tone: s.tone }), | |
| 76 | points: s.values.map((v, i) => (d.x[i] === undefined ? { v } : { t: d.x[i]!, v })), | |
| 77 | })), | |
| 78 | ...(d.levels === true ? { levels: true } : {}), | |
| 79 | }; | |
| 80 | } | |
| 81 | const card = shown.card!; | |
| 82 | return { | |
| 83 | ...head, | |
| 84 | kind: card.kind, | |
| 85 | status: card.status, | |
| 86 | rows: card.rows.map((r) => ({ label: r.label, value: r.value, ...(r.link === undefined ? {} : { link: r.link }), ...(r.depth === undefined ? {} : { depth: r.depth }) })), | |
| 87 | }; | |
| 88 | } | |
| 89 | ||
| 90 | /** | |
| 91 | * The results a reply places, in the order its text first places them; a handle that names none | |
| 92 | * kept is left out. | |
| 93 | */ | |
| 94 | export function cardsOfReply(text: string, kept: ReadonlyMap<number, ShownCard>): TurnCard[] { | |
| 95 | return shownIn(voiceParts(text)).flatMap((n) => { | |
| 96 | const shown = kept.get(n); | |
| 97 | return shown === undefined ? [] : [cardData(shown)]; | |
| 98 | }); | |
| 99 | } |
src/http/api/conversation_talk.ts +2 −1
| @@ -38,6 +38,7 @@ import { scopeAllows } from "../../core/tokens.ts"; | ||
| 38 | 38 | import type { User } from "../../core/users.ts"; |
| 39 | 39 | import { worksOf } from "../../core/talk_work.ts"; |
| 40 | 40 | import { cardsPlaced, plainVoice } from "../../core/talk_voice.ts"; |
| 41 | import { cardsOfReply } from "../../core/talk_cards.ts"; | |
| 41 | 42 | import { fileQueued, queuedOf, turnRunning } from "../../crew/conversation.ts"; |
| 42 | 43 | import { crossOrigin, type Handler } from "../context.ts"; |
| 43 | 44 | import { holds, weakEtag } from "../etag.ts"; |
| @@ -236,7 +237,7 @@ export function conversationTalkRoutes(router: Router<Handler>): void { | ||
| 236 | 237 | // parser every door uses (`core/talk_voice.ts`); a reply that places none is its own text. |
| 237 | 238 | const kept = cardsPlaced(ctx.app.db, user.id, conversation.id, all); |
| 238 | 239 | const plainOf = (text: string) => ((p) => (p === text ? {} : { plain: p }))(plainVoice(text, kept)); |
| 239 | const shown = all.map((t) => (t.role === "agent" ? { ...t, ...(t.limited === true ? { stoppedAt: "limit" } : {}), work: works.get(t.id) ?? null, costUsd: costs.get(t.id) ?? null, ...plainOf(t.text) } : t)); | |
| 240 | const shown = all.map((t) => (t.role === "agent" ? { ...t, ...(t.limited === true ? { stoppedAt: "limit" } : {}), work: works.get(t.id) ?? null, costUsd: costs.get(t.id) ?? null, ...plainOf(t.text), cards: t.failed === true ? [] : cardsOfReply(t.text, kept) } : t)); | |
| 240 | 241 | // The tag is of the exact bytes sent (so `before` and `limit` give their own), made after the |
| 241 | 242 | // person's own access was settled above. |
| 242 | 243 | const text = JSON.stringify({ running: turnRunning(ctx.app, user.id, conversation.id), stoppedAt: stoppedAt(all, ctx.url.searchParams.has("before")), conversation: conversation.id, totalUsd: conversationTotal(ctx.app.db, conversation.id) ?? null, queued: queuedOf(ctx.app, user.id, conversation.id).map((q) => ({ id: q.id, text: q.text })), turns: shown }); |
test/openapi-schemas.test.ts +11
| @@ -13,6 +13,8 @@ import { openPull } from "../src/actions/pulls.ts"; | ||
| 13 | 13 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; |
| 14 | 14 | import { createApp, type App } from "../src/app.ts"; |
| 15 | 15 | import { openapi } from "../src/contract/openapi.ts"; |
| 16 | import { appendTurn } from "../src/core/conversations.ts"; | |
| 17 | import { recordCard, recordWidget } from "../src/core/talk_voice.ts"; | |
| 16 | 18 | import { createToken } from "../src/core/tokens.ts"; |
| 17 | 19 | import { repoDir } from "../src/git/repos.ts"; |
| 18 | 20 | import { createUser } from "../src/core/users.ts"; |
| @@ -178,4 +180,13 @@ test("conversations and a message to the forge's agent answer their schemas", as | ||
| 178 | 180 | expect([renamed.status, renamed.problems]).toEqual([200, []]); |
| 179 | 181 | const sent = await check("post", "/api/v1/conversation/messages", "/api/v1/conversation/messages", { text: "hello", conversation: id }); |
| 180 | 182 | expect([sent.status, sent.problems]).toEqual([202, []]); |
| 183 | // An agent turn that places a chart and a card of rows carries both as data, held to the schema. | |
| 184 | const via = `conversation:${id}`; | |
| 185 | const owner = (app.db.query("SELECT id FROM user WHERE username = 'alice'").get() as { id: string }).id; | |
| 186 | recordWidget(app.db, via, owner, "Checks", { name: "checks", renderer: "chart", title: "Checks", data: { kind: "bar", x: ["2026-11-22", "2026-11-23"], unit: "checks", series: [{ name: "Passed", values: [1, 2], tone: "good" }] } }); | |
| 187 | recordCard(app.db, via, owner, "Now", "Now", { kind: "crew", title: "Working now", status: "1 going", rows: [{ label: "smith", value: "running", depth: 1 }], actions: [] }, "http://forge.test"); | |
| 188 | appendTurn(app.db, owner, id, { role: "agent", text: "Here.\n\n::show c1\n\n::show c2" }); | |
| 189 | const read = await check("get", "/api/v1/conversation/turns", `/api/v1/conversation/turns?conversation=${id}`); | |
| 190 | expect([read.status, read.problems]).toEqual([200, []]); | |
| 191 | expect(JSON.stringify(read.json)).toContain('"ref":"c2"'); | |
| 181 | 192 | }); |
test/widgets.test.ts +20 −1
| @@ -18,7 +18,7 @@ import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | ||
| 18 | 18 | import { appendTurn, createConversation } from "../src/core/conversations.ts"; |
| 19 | 19 | import { canRead, getRepo, type Repo } from "../src/core/repos.ts"; |
| 20 | 20 | import { createSession } from "../src/core/sessions.ts"; |
| 21 | import { cardsOf, plainVoice, recordWidget, widgetLines } from "../src/core/talk_voice.ts"; | |
| 21 | import { cardsOf, plainVoice, recordCard, recordWidget, widgetLines } from "../src/core/talk_voice.ts"; | |
| 22 | 22 | import { createToken } from "../src/core/tokens.ts"; |
| 23 | 23 | import { createUser, type User } from "../src/core/users.ts"; |
| 24 | 24 | import { mintViaToken } from "../src/core/via_token.ts"; |
| @@ -396,6 +396,25 @@ describe("the terminal", () => { | ||
| 396 | 396 | expect(turns.find((t) => t.text === "Nothing placed here.")!.plain).toBeUndefined(); |
| 397 | 397 | }); |
| 398 | 398 | |
| 399 | test("the API carries a placed chart's exact values as cards, and a card of rows its typed fields (#18005)", async () => { | |
| 400 | const c = createConversation(app.db, alice.id); | |
| 401 | const via = `conversation:${c.value.id}`; | |
| 402 | const data: ChartData = { kind: "line", x: ["2026-11-22", "2026-11-23", "2026-11-24"], unit: "$", levels: true, series: [{ name: "Spend", values: [0.5, 3.25, 1e-3], tone: "bad" }] }; | |
| 403 | expect(recordWidget(app.db, via, alice.id, "Spend per day", { name: "compute", renderer: "chart", title: "Spend per day", data })).toBe(1); | |
| 404 | expect(recordCard(app.db, via, alice.id, "Now", "Now", { kind: "crew", title: "Working now", status: "1 going", rows: [{ label: "smith", value: "running", link: "https://x.test/a", depth: 2 }], actions: [] }, servers.url)).toBe(2); | |
| 405 | appendTurn(app.db, alice.id, c.value.id, { role: "agent", text: "See:\n\n::show c1\n\n::show c2\n\n::show c1\n\n::show c9" }); | |
| 406 | appendTurn(app.db, alice.id, c.value.id, { role: "agent", text: "No cards." }); | |
| 407 | const res = await fetch(`${servers.url}/api/v1/conversation/turns?conversation=${c.value.id}`, { headers: { authorization: `Bearer ${createToken(app.db, alice.id, "t", "ro").token}` } }); | |
| 408 | const turns = ((await res.json()) as { turns: { text: string; cards?: Record<string, unknown>[] }[] }).turns; | |
| 409 | const cards = turns.find((t) => t.text.startsWith("See"))!.cards!; | |
| 410 | // Each handle once, in order; c9 names nothing kept and is left out. | |
| 411 | expect(cards.map((x) => x["ref"])).toEqual(["c1", "c2"]); | |
| 412 | expect(cards[0]).toMatchObject({ kind: "line", title: "Spend per day", levels: true, series: [{ label: "Spend", unit: "$", tone: "bad", points: [{ t: "2026-11-22", v: 0.5 }, { t: "2026-11-23", v: 3.25 }, { t: "2026-11-24", v: 1e-3 }] }] }); | |
| 413 | expect(cards[1]).toMatchObject({ kind: "crew", status: "1 going", rows: [{ label: "smith", value: "running", link: "https://x.test/a", depth: 2 }] }); | |
| 414 | expect(cards[1]!["series"]).toBeUndefined(); | |
| 415 | expect(turns.find((t) => t.text === "No cards.")!.cards).toEqual([]); | |
| 416 | }); | |
| 417 | ||
| 399 | 418 | test("the Conversations screen prints the chart a conversation holds, and b finds no button on it", async () => { |
| 400 | 419 | // A person of their own, so the conversation Enter opens is this one whatever ran before. |
| 401 | 420 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" }); |
new above
offline