@cerebro-labs/agentnava-sdk 0.47.1 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/react.js ADDED
@@ -0,0 +1,196 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ // Ready-made React views for the widgets an agent draws in its replies.
3
+ //
4
+ // import { ReplyView } from '@cerebro-labs/agentnava-sdk/react'
5
+ // import '@cerebro-labs/agentnava-sdk/react/styles.css'
6
+ //
7
+ // <ReplyView text={reply} widgets={widgets} onAsk={send} />
8
+ //
9
+ // React is optional for the SDK: only this entry needs it, and the rest of the
10
+ // package never imports it. Every kind of part has a default look (styles.css,
11
+ // themed through CSS variables), and any kind can be swapped for your own
12
+ // component with `parts`.
13
+ //
14
+ // A widget is written by the model, so it is drawn defensively: a kind this
15
+ // does not know, or a part missing a field, is skipped; each part is drawn
16
+ // once, even if two containers name it; links and pictures open only over
17
+ // https:// (narrow it further with `allowUrl`); and a widget that throws while
18
+ // drawing is left out rather than breaking the screen around it.
19
+ import { Component, Fragment } from 'react';
20
+ import { placeWidgets } from "./widgets.js";
21
+ export { placeWidgets } from "./widgets.js";
22
+ const str = (v) => (typeof v === 'string' || typeof v === 'number' ? String(v) : '');
23
+ const list = (v) => (Array.isArray(v) ? v : []);
24
+ const TONES = new Set(['high', 'medium', 'low', 'good', 'info']);
25
+ const toneOf = (v) => (typeof v === 'string' && TONES.has(v) ? v : 'info');
26
+ const httpsOnly = (url) => /^https:\/\//i.test(url);
27
+ /** A widget that throws while drawing is left out, never a crash of the screen. */
28
+ class Boundary extends Component {
29
+ state = { failed: false };
30
+ static getDerivedStateFromError() {
31
+ return { failed: true };
32
+ }
33
+ render() {
34
+ return this.state.failed ? null : this.props.children;
35
+ }
36
+ }
37
+ function Chart({ part, ctx }) {
38
+ const series = list(part.series)
39
+ .map((s) => ({
40
+ name: str(s?.name),
41
+ points: list(s?.points).filter((p) => typeof p?.y === 'number' && Number.isFinite(p.y)),
42
+ }))
43
+ .filter((s) => s.points.length > 0);
44
+ if (series.length === 0)
45
+ return null;
46
+ const xs = series[0].points.map((p) => str(p.x));
47
+ const ref = part.reference;
48
+ const refY = typeof ref?.y === 'number' && Number.isFinite(ref.y) ? ref.y : undefined;
49
+ const ys = [...series.flatMap((s) => s.points.map((p) => p.y)), ...(refY === undefined ? [] : [refY])];
50
+ const max = Math.max(...ys, 0) || 1;
51
+ const W = 320;
52
+ const H = 140;
53
+ const step = W / Math.max(xs.length, 1);
54
+ const fmt = (n) => (part.unit === 'currency' ? ctx.money(n) : part.unit === 'percent' ? `${ctx.number(n)}%` : ctx.number(n));
55
+ const yOf = (y) => H - (Math.max(y, 0) / max) * (H - 18);
56
+ const labelled = series.length === 1 && xs.length <= 6;
57
+ return (_jsxs("figure", { className: "an-w-chart", children: [str(part.title) && _jsx("figcaption", { children: str(part.title) }), _jsxs("svg", { viewBox: `0 0 ${W} ${H + 18}`, role: "img", "aria-label": str(part.title) || 'Chart', children: [series.map((s, si) => part.type === 'bar' ? (s.points.map((p, i) => {
58
+ const bw = (step * 0.7) / series.length;
59
+ const x = i * step + step * 0.15 + si * bw;
60
+ const y = yOf(p.y);
61
+ return (_jsxs("g", { children: [_jsx("rect", { className: `an-w-s${si % 4}`, x: x, y: y, width: bw, height: H - y, rx: 2, children: _jsx("title", { children: `${str(p.x)}: ${fmt(p.y)}` }) }), labelled && (_jsx("text", { x: x + bw / 2, y: y - 4, textAnchor: "middle", children: fmt(p.y) }))] }, `${si}-${i}`));
62
+ })) : (_jsxs("g", { children: [_jsx("polyline", { className: `an-w-line an-w-s${si % 4}${part.type === 'area' ? ' is-area' : ''}`, points: s.points.map((p, i) => `${i * step + step / 2},${yOf(p.y)}`).join(' ') }), s.points.map((p, i) => (_jsxs("g", { children: [_jsx("circle", { className: `an-w-s${si % 4}`, cx: i * step + step / 2, cy: yOf(p.y), r: 3, children: _jsx("title", { children: `${str(p.x)}: ${fmt(p.y)}` }) }), labelled && (_jsx("text", { x: i * step + step / 2, y: yOf(p.y) - 7, textAnchor: "middle", children: fmt(p.y) }))] }, i)))] }, si))), refY !== undefined && (_jsxs("g", { className: "an-w-ref", children: [_jsx("line", { x1: 0, x2: W, y1: yOf(refY), y2: yOf(refY) }), str(ref?.label) && (_jsx("text", { x: W, y: yOf(refY) - 4, textAnchor: "end", children: str(ref?.label) }))] })), xs.map((x, i) => (_jsx("text", { x: i * step + step / 2, y: H + 14, textAnchor: "middle", children: x }, i)))] }), series.length > 1 && (_jsx("div", { className: "an-w-legend", children: series.map((s, si) => (_jsxs("span", { children: [_jsx("i", { className: `an-w-s${si % 4}` }), s.name] }, si))) }))] }));
63
+ }
64
+ /** The default look of one part. `kids` is its children, already drawn. */
65
+ function defaultPart(part, kids, ctx) {
66
+ const onAsk = ctx.props.onAsk;
67
+ switch (part.component) {
68
+ case 'Column':
69
+ return _jsx("div", { className: `an-w-col an-w-gap-${['small', 'large'].includes(str(part.gap)) ? str(part.gap) : 'medium'}`, children: kids });
70
+ case 'Row':
71
+ return _jsx("div", { className: `an-w-row${part.scroll === true ? ' is-scroll' : ''}`, children: kids });
72
+ case 'Card': {
73
+ const image = ctx.url(part.image, 'image');
74
+ const href = ctx.url(part.href, 'link');
75
+ const body = (_jsxs("div", { className: "an-w-card", children: [image && _jsx("img", { src: image, alt: str(part.imageAlt), referrerPolicy: "no-referrer", loading: "lazy" }), _jsx("div", { className: "an-w-card-body", children: kids })] }));
76
+ return href ? (_jsx("a", { className: "an-w-card-link", href: href, target: "_blank", rel: "noreferrer noopener", children: body })) : (body);
77
+ }
78
+ case 'Text': {
79
+ if (!str(part.text))
80
+ return null;
81
+ const v = ['title', 'heading', 'caption'].includes(str(part.variant)) ? str(part.variant) : 'body';
82
+ return _jsx("p", { className: `an-w-text is-${v}`, children: str(part.text) });
83
+ }
84
+ case 'Stat':
85
+ if (!str(part.value))
86
+ return null;
87
+ return (_jsxs("div", { className: "an-w-stat", children: [_jsx("strong", { children: str(part.value) }), str(part.label) && _jsx("span", { children: str(part.label) }), str(part.caption) && _jsx("small", { children: str(part.caption) })] }));
88
+ case 'KeyValue': {
89
+ const rows = list(part.rows).filter((r) => str(r?.label) || str(r?.value));
90
+ if (rows.length === 0)
91
+ return null;
92
+ return (_jsxs("div", { className: "an-w-kv", children: [str(part.title) && _jsx("div", { className: "an-w-title", children: str(part.title) }), _jsx("dl", { children: rows.map((r, i) => (_jsxs("div", { className: r?.emphasis ? 'is-total' : undefined, children: [_jsx("dt", { children: str(r?.label) }), _jsx("dd", { children: str(r?.value) })] }, i))) })] }));
93
+ }
94
+ case 'Table': {
95
+ const cols = list(part.columns).map(str);
96
+ const rows = list(part.rows).filter(Array.isArray);
97
+ if (cols.length === 0 && rows.length === 0)
98
+ return null;
99
+ return (_jsxs("div", { className: "an-w-table", children: [str(part.title) && _jsx("div", { className: "an-w-title", children: str(part.title) }), _jsxs("table", { children: [cols.length > 0 && (_jsx("thead", { children: _jsx("tr", { children: cols.map((c, j) => (_jsx("th", { children: c }, j))) }) })), _jsx("tbody", { children: rows.map((r, i) => (_jsx("tr", { children: r.map((c, j) => (_jsx("td", { className: typeof c === 'number' ? 'is-num' : undefined, children: typeof c === 'number' ? ctx.number(c) : str(c) }, j))) }, i))) })] })] }));
100
+ }
101
+ case 'Chart':
102
+ return _jsx(Chart, { part: part, ctx: ctx });
103
+ case 'Image': {
104
+ const url = ctx.url(part.url, 'image');
105
+ return url ? (_jsxs("figure", { className: "an-w-image", children: [_jsx("img", { src: url, alt: str(part.alt), referrerPolicy: "no-referrer", loading: "lazy" }), str(part.caption) && _jsx("figcaption", { children: str(part.caption) })] })) : null;
106
+ }
107
+ case 'List': {
108
+ const items = list(part.items).filter((it) => str(it?.title));
109
+ if (items.length === 0)
110
+ return null;
111
+ const Tag = part.ordered === true ? 'ol' : 'ul';
112
+ return (_jsxs("div", { className: "an-w-list", children: [str(part.title) && _jsx("div", { className: "an-w-title", children: str(part.title) }), _jsx(Tag, { children: items.map((it, i) => (_jsxs("li", { children: [_jsx("i", { className: `an-w-dot is-${toneOf(it?.tone)}`, "aria-hidden": "true" }), _jsxs("div", { children: [_jsx("strong", { children: str(it?.title) }), str(it?.detail) && _jsx("span", { children: str(it?.detail) })] }), str(it?.meta) && _jsx("small", { children: str(it?.meta) })] }, i))) })] }));
113
+ }
114
+ case 'Note':
115
+ if (!str(part.text))
116
+ return null;
117
+ return (_jsxs("div", { className: "an-w-note", children: [str(part.title) && _jsx("strong", { children: str(part.title) }), _jsx("span", { children: str(part.text) })] }));
118
+ case 'Badge':
119
+ return str(part.text) ? _jsx("span", { className: `an-w-badge is-${toneOf(part.tone)}`, children: str(part.text) }) : null;
120
+ case 'Link': {
121
+ const url = ctx.url(part.url, 'link');
122
+ return url && str(part.label) ? (_jsx("a", { className: "an-w-link", href: url, target: "_blank", rel: "noreferrer noopener", children: str(part.label) })) : null;
123
+ }
124
+ case 'Button':
125
+ if (!str(part.label))
126
+ return null;
127
+ return (_jsx("button", { type: "button", className: `an-w-button is-${part.variant === 'secondary' ? 'secondary' : 'primary'}`, disabled: !onAsk, onClick: () => onAsk?.(str(part.label)), children: str(part.label) }));
128
+ case 'Suggestions': {
129
+ const options = list(part.options).map(str).filter(Boolean);
130
+ if (options.length === 0)
131
+ return null;
132
+ return (_jsx("div", { className: "an-w-suggest", children: options.map((o, i) => (_jsx("button", { type: "button", disabled: !onAsk, onClick: () => onAsk?.(o), children: o }, i))) }));
133
+ }
134
+ case 'Divider':
135
+ return _jsx("hr", { className: "an-w-divider" });
136
+ default:
137
+ return null;
138
+ }
139
+ }
140
+ const CONTAINERS = new Set(['Column', 'Row', 'Card']);
141
+ // A plain function, not a component: the set of parts already drawn lives for
142
+ // one render of the widget. As a component, React's development mode would draw
143
+ // each part twice and find every one "already drawn" on its second pass.
144
+ function draw(id, ctx) {
145
+ const part = ctx.byId.get(id);
146
+ // A part listed twice, or a loop of containers, is drawn once.
147
+ if (!part || ctx.seen.has(id))
148
+ return null;
149
+ ctx.seen.add(id);
150
+ const kids = CONTAINERS.has(part.component)
151
+ ? list(part.children)
152
+ .filter((k) => typeof k === 'string')
153
+ .map((k) => _jsx(Fragment, { children: draw(k, ctx) }, k))
154
+ : undefined;
155
+ const own = ctx.props.parts?.[part.component];
156
+ return own ? own({ part, children: kids, onAsk: ctx.props.onAsk }) : defaultPart(part, kids, ctx);
157
+ }
158
+ /** One widget, drawn from its root part. Draws nothing when there is no root yet. */
159
+ export function WidgetView(props) {
160
+ const { widget, currency = 'USD', locale, allowUrl } = props;
161
+ const byId = new Map();
162
+ for (const p of Array.isArray(widget?.components) ? widget.components : []) {
163
+ if (p && typeof p === 'object' && typeof p.id === 'string' && typeof p.component === 'string' && !byId.has(p.id))
164
+ byId.set(p.id, p);
165
+ }
166
+ if (!byId.has('root'))
167
+ return null;
168
+ let moneyFormat;
169
+ try {
170
+ moneyFormat = new Intl.NumberFormat(locale, { style: 'currency', currency, maximumFractionDigits: 0 });
171
+ }
172
+ catch {
173
+ moneyFormat = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 });
174
+ }
175
+ const numberFormat = new Intl.NumberFormat(locale);
176
+ const ctx = {
177
+ byId,
178
+ seen: new Set(),
179
+ props,
180
+ money: (n) => moneyFormat.format(n),
181
+ number: (n) => numberFormat.format(n),
182
+ url: (v, use) => (typeof v === 'string' && httpsOnly(v) && (allowUrl ? allowUrl(v, use) : true) ? v : undefined),
183
+ };
184
+ return (_jsx(Boundary, { children: _jsx("div", { className: `an-w${props.className ? ` ${props.className}` : ''}`, "data-surface": widget.surfaceId, children: draw('root', ctx) }) }));
185
+ }
186
+ function Paragraphs({ text }) {
187
+ return (_jsx(_Fragment, { children: text
188
+ .trim()
189
+ .split(/\n{2,}/)
190
+ .map((p, i) => (_jsx("p", { className: "an-reply-text", children: p.split('\n').map((line, j) => (_jsxs(Fragment, { children: [j > 0 && _jsx("br", {}), line] }, j))) }, i))) }));
191
+ }
192
+ /** A whole reply: its words, with each widget drawn where it sits. */
193
+ export function ReplyView({ text, widgets, renderText, className, ...widgetProps }) {
194
+ return (_jsx("div", { className: `an-reply${className ? ` ${className}` : ''}`, children: placeWidgets(text, widgets ?? []).map((piece, i) => piece.kind === 'text' ? (_jsx(Fragment, { children: renderText ? renderText(piece.text) : _jsx(Paragraphs, { text: piece.text }) }, `t${i}`)) : (_jsx(WidgetView, { widget: piece.widget, ...widgetProps }, piece.widget.surfaceId))) }));
195
+ }
196
+ //# sourceMappingURL=react.js.map
package/react.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.js","sourceRoot":"","sources":["../src/react.tsx"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,EAAE;AACF,kEAAkE;AAClE,0DAA0D;AAC1D,EAAE;AACF,8DAA8D;AAC9D,EAAE;AACF,+EAA+E;AAC/E,+EAA+E;AAC/E,0EAA0E;AAC1E,0BAA0B;AAC1B,EAAE;AACF,4EAA4E;AAC5E,2EAA2E;AAC3E,0EAA0E;AAC1E,+EAA+E;AAC/E,iEAAiE;AAEjE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAkB,MAAM,OAAO,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,OAAO,EAAE,YAAY,EAAmB,MAAM,cAAc,CAAC;AAuD7D,MAAM,GAAG,GAAG,CAAC,CAAU,EAAU,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AACtG,MAAM,IAAI,GAAG,CAAe,CAAU,EAAO,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAE,CAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AACrF,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,QAAQ,EAAE,K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,YAAW,SAAS,EAAC,eAAe,YAClC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CAC/B,MAAC,QAAQ,eACP,CAAC,GAAG,CAAC,IAAI,cAAM,EACf,IAAI,KAFS,CAAC,CAGL,CACX,CAAC,IANK,CAAC,CAOL,CACJ,CAAC,GACD,CACH,CAAC;AACH,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,SAAS,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,GAAG,WAAW,EAAkB;IACjG,OAAO,CACN,cAAK,SAAS,EAAE,WAAW,SAAS,CAAC,CAAC,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,YAC3D,YAAY,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CACnD,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,CACvB,KAAC,QAAQ,cAAgB,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAC,UAAU,IAAC,IAAI,EAAE,KAAK,CAAC,IAAI,GAAI,IAAhF,IAAI,CAAC,EAAE,CAAqF,CAC3G,CAAC,CAAC,CAAC,CACH,KAAC,UAAU,IAA8B,MAAM,EAAE,KAAK,CAAC,MAAM,KAAM,WAAW,IAA7D,KAAK,CAAC,MAAM,CAAC,SAAS,CAA2C,CAClF,CACD,GACI,CACN,CAAC;AACH,CAAC","sourcesContent":["// Ready-made React views for the widgets an agent draws in its replies.\n//\n// import { ReplyView } from '@cerebro-labs/agentnava-sdk/react'\n// import '@cerebro-labs/agentnava-sdk/react/styles.css'\n//\n// <ReplyView text={reply} widgets={widgets} onAsk={send} />\n//\n// React is optional for the SDK: only this entry needs it, and the rest of the\n// package never imports it. Every kind of part has a default look (styles.css,\n// themed through CSS variables), and any kind can be swapped for your own\n// component with `parts`.\n//\n// A widget is written by the model, so it is drawn defensively: a kind this\n// does not know, or a part missing a field, is skipped; each part is drawn\n// once, even if two containers name it; links and pictures open only over\n// https:// (narrow it further with `allowUrl`); and a widget that throws while\n// drawing is left out rather than breaking the screen around it.\n\nimport { Component, Fragment, type ReactNode } from 'react';\nimport type { Widget, WidgetPart } from './types.ts';\nimport { placeWidgets } from './widgets.ts';\n\nexport { placeWidgets, type ReplyPiece } from './widgets.ts';\n\n/** Every kind of part an agent may draw. */\nexport type WidgetKind =\n\t| 'Column'\n\t| 'Row'\n\t| 'Card'\n\t| 'Text'\n\t| 'Stat'\n\t| 'KeyValue'\n\t| 'Table'\n\t| 'Chart'\n\t| 'Image'\n\t| 'List'\n\t| 'Note'\n\t| 'Badge'\n\t| 'Link'\n\t| 'Button'\n\t| 'Suggestions'\n\t| 'Divider';\n\n/** What a replacement for one kind of part receives. */\nexport interface PartProps {\n\tpart: WidgetPart;\n\t/** The part's children, already drawn (containers only). */\n\tchildren?: ReactNode;\n\t/** Send words as the reader's next message (Button, Suggestions). */\n\tonAsk?: ((text: string) => void) | undefined;\n}\n\nexport interface WidgetViewProps {\n\twidget: Widget;\n\t/** Called with a Button's label or a tapped suggestion: send it as the next message. */\n\tonAsk?: (text: string) => void;\n\t/** Your own component for any kind of part, in place of the default. */\n\tparts?: Partial<Record<WidgetKind, (props: PartProps) => ReactNode>>;\n\t/** ISO currency code for charts and numbers marked as money. Default \"USD\". */\n\tcurrency?: string;\n\t/** Locale for numbers. Default: the reader's. */\n\tlocale?: string;\n\t/** Whether a link or picture address may be opened. Default: https:// only. */\n\tallowUrl?: (url: string, use: 'link' | 'image') => boolean;\n\tclassName?: string;\n}\n\nexport interface ReplyViewProps extends Omit<WidgetViewProps, 'widget' | 'className'> {\n\t/** The reply's words, as `text` events or `done.reply` give them. */\n\ttext: string;\n\t/** The reply's widgets, as `widget` events or `done.widgets` give them. */\n\twidgets?: readonly Widget[] | undefined;\n\t/** How to draw the words. Default: paragraphs. Pass your markdown renderer here. */\n\trenderText?: (text: string) => ReactNode;\n\tclassName?: string;\n}\n\nconst str = (v: unknown): string => (typeof v === 'string' || typeof v === 'number' ? String(v) : '');\nconst list = <T = unknown,>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);\nconst TONES = new Set(['high', 'medium', 'low', 'good', 'info']);\nconst toneOf = (v: unknown): string => (typeof v === 'string' && TONES.has(v) ? v : 'info');\nconst httpsOnly = (url: string) => /^https:\\/\\//i.test(url);\n\n/** A widget that throws while drawing is left out, never a crash of the screen. */\nclass Boundary extends Component<{ children: ReactNode }, { failed: boolean }> {\n\toverride state = { failed: false };\n\tstatic getDerivedStateFromError() {\n\t\treturn { failed: true };\n\t}\n\toverride render() {\n\t\treturn this.state.failed ? null : this.props.children;\n\t}\n}\n\ninterface Ctx {\n\tbyId: Map<string, WidgetPart>;\n\tseen: Set<string>;\n\tprops: WidgetViewProps;\n\tmoney: (n: number) => string;\n\tnumber: (n: number) => string;\n\turl: (v: unknown, use: 'link' | 'image') => string | undefined;\n}\n\nfunction Chart({ part, ctx }: { part: WidgetPart; ctx: Ctx }) {\n\tconst series = list<{ name?: unknown; points?: unknown }>(part.series)\n\t\t.map((s) => ({\n\t\t\tname: str(s?.name),\n\t\t\tpoints: list<{ x?: unknown; y?: unknown }>(s?.points).filter((p) => typeof p?.y === 'number' && Number.isFinite(p.y)),\n\t\t}))\n\t\t.filter((s) => s.points.length > 0);\n\tif (series.length === 0) return null;\n\tconst xs = series[0]!.points.map((p) => str(p.x));\n\tconst ref = part.reference as { y?: unknown; label?: unknown } | undefined;\n\tconst refY = typeof ref?.y === 'number' && Number.isFinite(ref.y) ? ref.y : undefined;\n\tconst ys = [...series.flatMap((s) => s.points.map((p) => p.y as number)), ...(refY === undefined ? [] : [refY])];\n\tconst max = Math.max(...ys, 0) || 1;\n\tconst W = 320;\n\tconst H = 140;\n\tconst step = W / Math.max(xs.length, 1);\n\tconst fmt = (n: number) => (part.unit === 'currency' ? ctx.money(n) : part.unit === 'percent' ? `${ctx.number(n)}%` : ctx.number(n));\n\tconst yOf = (y: number) => H - (Math.max(y, 0) / max) * (H - 18);\n\tconst labelled = series.length === 1 && xs.length <= 6;\n\treturn (\n\t\t<figure className=\"an-w-chart\">\n\t\t\t{str(part.title) && <figcaption>{str(part.title)}</figcaption>}\n\t\t\t<svg viewBox={`0 0 ${W} ${H + 18}`} role=\"img\" aria-label={str(part.title) || 'Chart'}>\n\t\t\t\t{series.map((s, si) =>\n\t\t\t\t\tpart.type === 'bar' ? (\n\t\t\t\t\t\ts.points.map((p, i) => {\n\t\t\t\t\t\t\tconst bw = (step * 0.7) / series.length;\n\t\t\t\t\t\t\tconst x = i * step + step * 0.15 + si * bw;\n\t\t\t\t\t\t\tconst y = yOf(p.y as number);\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<g key={`${si}-${i}`}>\n\t\t\t\t\t\t\t\t\t<rect className={`an-w-s${si % 4}`} x={x} y={y} width={bw} height={H - y} rx={2}>\n\t\t\t\t\t\t\t\t\t\t<title>{`${str(p.x)}: ${fmt(p.y as number)}`}</title>\n\t\t\t\t\t\t\t\t\t</rect>\n\t\t\t\t\t\t\t\t\t{labelled && (\n\t\t\t\t\t\t\t\t\t\t<text x={x + bw / 2} y={y - 4} textAnchor=\"middle\">\n\t\t\t\t\t\t\t\t\t\t\t{fmt(p.y as number)}\n\t\t\t\t\t\t\t\t\t\t</text>\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t</g>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<g key={si}>\n\t\t\t\t\t\t\t<polyline\n\t\t\t\t\t\t\t\tclassName={`an-w-line an-w-s${si % 4}${part.type === 'area' ? ' is-area' : ''}`}\n\t\t\t\t\t\t\t\tpoints={s.points.map((p, i) => `${i * step + step / 2},${yOf(p.y as number)}`).join(' ')}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{s.points.map((p, i) => (\n\t\t\t\t\t\t\t\t<g key={i}>\n\t\t\t\t\t\t\t\t\t<circle className={`an-w-s${si % 4}`} cx={i * step + step / 2} cy={yOf(p.y as number)} r={3}>\n\t\t\t\t\t\t\t\t\t\t<title>{`${str(p.x)}: ${fmt(p.y as number)}`}</title>\n\t\t\t\t\t\t\t\t\t</circle>\n\t\t\t\t\t\t\t\t\t{labelled && (\n\t\t\t\t\t\t\t\t\t\t<text x={i * step + step / 2} y={yOf(p.y as number) - 7} textAnchor=\"middle\">\n\t\t\t\t\t\t\t\t\t\t\t{fmt(p.y as number)}\n\t\t\t\t\t\t\t\t\t\t</text>\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t</g>\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</g>\n\t\t\t\t\t),\n\t\t\t\t)}\n\t\t\t\t{refY !== undefined && (\n\t\t\t\t\t<g className=\"an-w-ref\">\n\t\t\t\t\t\t<line x1={0} x2={W} y1={yOf(refY)} y2={yOf(refY)} />\n\t\t\t\t\t\t{str(ref?.label) && (\n\t\t\t\t\t\t\t<text x={W} y={yOf(refY) - 4} textAnchor=\"end\">\n\t\t\t\t\t\t\t\t{str(ref?.label)}\n\t\t\t\t\t\t\t</text>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</g>\n\t\t\t\t)}\n\t\t\t\t{xs.map((x, i) => (\n\t\t\t\t\t<text key={i} x={i * step + step / 2} y={H + 14} textAnchor=\"middle\">\n\t\t\t\t\t\t{x}\n\t\t\t\t\t</text>\n\t\t\t\t))}\n\t\t\t</svg>\n\t\t\t{series.length > 1 && (\n\t\t\t\t<div className=\"an-w-legend\">\n\t\t\t\t\t{series.map((s, si) => (\n\t\t\t\t\t\t<span key={si}>\n\t\t\t\t\t\t\t<i className={`an-w-s${si % 4}`} />\n\t\t\t\t\t\t\t{s.name}\n\t\t\t\t\t\t</span>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t)}\n\t\t</figure>\n\t);\n}\n\n/** The default look of one part. `kids` is its children, already drawn. */\nfunction defaultPart(part: WidgetPart, kids: ReactNode, ctx: Ctx): ReactNode {\n\tconst onAsk = ctx.props.onAsk;\n\tswitch (part.component) {\n\t\tcase 'Column':\n\t\t\treturn <div className={`an-w-col an-w-gap-${['small', 'large'].includes(str(part.gap)) ? str(part.gap) : 'medium'}`}>{kids}</div>;\n\t\tcase 'Row':\n\t\t\treturn <div className={`an-w-row${part.scroll === true ? ' is-scroll' : ''}`}>{kids}</div>;\n\t\tcase 'Card': {\n\t\t\tconst image = ctx.url(part.image, 'image');\n\t\t\tconst href = ctx.url(part.href, 'link');\n\t\t\tconst body = (\n\t\t\t\t<div className=\"an-w-card\">\n\t\t\t\t\t{image && <img src={image} alt={str(part.imageAlt)} referrerPolicy=\"no-referrer\" loading=\"lazy\" />}\n\t\t\t\t\t<div className=\"an-w-card-body\">{kids}</div>\n\t\t\t\t</div>\n\t\t\t);\n\t\t\treturn href ? (\n\t\t\t\t<a className=\"an-w-card-link\" href={href} target=\"_blank\" rel=\"noreferrer noopener\">\n\t\t\t\t\t{body}\n\t\t\t\t</a>\n\t\t\t) : (\n\t\t\t\tbody\n\t\t\t);\n\t\t}\n\t\tcase 'Text': {\n\t\t\tif (!str(part.text)) return null;\n\t\t\tconst v = ['title', 'heading', 'caption'].includes(str(part.variant)) ? str(part.variant) : 'body';\n\t\t\treturn <p className={`an-w-text is-${v}`}>{str(part.text)}</p>;\n\t\t}\n\t\tcase 'Stat':\n\t\t\tif (!str(part.value)) return null;\n\t\t\treturn (\n\t\t\t\t<div className=\"an-w-stat\">\n\t\t\t\t\t<strong>{str(part.value)}</strong>\n\t\t\t\t\t{str(part.label) && <span>{str(part.label)}</span>}\n\t\t\t\t\t{str(part.caption) && <small>{str(part.caption)}</small>}\n\t\t\t\t</div>\n\t\t\t);\n\t\tcase 'KeyValue': {\n\t\t\tconst rows = list<{ label?: unknown; value?: unknown; emphasis?: unknown }>(part.rows).filter((r) => str(r?.label) || str(r?.value));\n\t\t\tif (rows.length === 0) return null;\n\t\t\treturn (\n\t\t\t\t<div className=\"an-w-kv\">\n\t\t\t\t\t{str(part.title) && <div className=\"an-w-title\">{str(part.title)}</div>}\n\t\t\t\t\t<dl>\n\t\t\t\t\t\t{rows.map((r, i) => (\n\t\t\t\t\t\t\t<div key={i} className={r?.emphasis ? 'is-total' : undefined}>\n\t\t\t\t\t\t\t\t<dt>{str(r?.label)}</dt>\n\t\t\t\t\t\t\t\t<dd>{str(r?.value)}</dd>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</dl>\n\t\t\t\t</div>\n\t\t\t);\n\t\t}\n\t\tcase 'Table': {\n\t\t\tconst cols = list(part.columns).map(str);\n\t\t\tconst rows = list(part.rows).filter(Array.isArray) as unknown[][];\n\t\t\tif (cols.length === 0 && rows.length === 0) return null;\n\t\t\treturn (\n\t\t\t\t<div className=\"an-w-table\">\n\t\t\t\t\t{str(part.title) && <div className=\"an-w-title\">{str(part.title)}</div>}\n\t\t\t\t\t<table>\n\t\t\t\t\t\t{cols.length > 0 && (\n\t\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{cols.map((c, j) => (\n\t\t\t\t\t\t\t\t\t\t<th key={j}>{c}</th>\n\t\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t<tbody>\n\t\t\t\t\t\t\t{rows.map((r, i) => (\n\t\t\t\t\t\t\t\t<tr key={i}>\n\t\t\t\t\t\t\t\t\t{r.map((c, j) => (\n\t\t\t\t\t\t\t\t\t\t<td key={j} className={typeof c === 'number' ? 'is-num' : undefined}>\n\t\t\t\t\t\t\t\t\t\t\t{typeof c === 'number' ? ctx.number(c) : str(c)}\n\t\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</tbody>\n\t\t\t\t\t</table>\n\t\t\t\t</div>\n\t\t\t);\n\t\t}\n\t\tcase 'Chart':\n\t\t\treturn <Chart part={part} ctx={ctx} />;\n\t\tcase 'Image': {\n\t\t\tconst url = ctx.url(part.url, 'image');\n\t\t\treturn url ? (\n\t\t\t\t<figure className=\"an-w-image\">\n\t\t\t\t\t<img src={url} alt={str(part.alt)} referrerPolicy=\"no-referrer\" loading=\"lazy\" />\n\t\t\t\t\t{str(part.caption) && <figcaption>{str(part.caption)}</figcaption>}\n\t\t\t\t</figure>\n\t\t\t) : null;\n\t\t}\n\t\tcase 'List': {\n\t\t\tconst items = list<{ title?: unknown; detail?: unknown; meta?: unknown; tone?: unknown }>(part.items).filter((it) => str(it?.title));\n\t\t\tif (items.length === 0) return null;\n\t\t\tconst Tag = part.ordered === true ? 'ol' : 'ul';\n\t\t\treturn (\n\t\t\t\t<div className=\"an-w-list\">\n\t\t\t\t\t{str(part.title) && <div className=\"an-w-title\">{str(part.title)}</div>}\n\t\t\t\t\t<Tag>\n\t\t\t\t\t\t{items.map((it, i) => (\n\t\t\t\t\t\t\t<li key={i}>\n\t\t\t\t\t\t\t\t<i className={`an-w-dot is-${toneOf(it?.tone)}`} aria-hidden=\"true\" />\n\t\t\t\t\t\t\t\t<div>\n\t\t\t\t\t\t\t\t\t<strong>{str(it?.title)}</strong>\n\t\t\t\t\t\t\t\t\t{str(it?.detail) && <span>{str(it?.detail)}</span>}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t{str(it?.meta) && <small>{str(it?.meta)}</small>}\n\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</Tag>\n\t\t\t\t</div>\n\t\t\t);\n\t\t}\n\t\tcase 'Note':\n\t\t\tif (!str(part.text)) return null;\n\t\t\treturn (\n\t\t\t\t<div className=\"an-w-note\">\n\t\t\t\t\t{str(part.title) && <strong>{str(part.title)}</strong>}\n\t\t\t\t\t<span>{str(part.text)}</span>\n\t\t\t\t</div>\n\t\t\t);\n\t\tcase 'Badge':\n\t\t\treturn str(part.text) ? <span className={`an-w-badge is-${toneOf(part.tone)}`}>{str(part.text)}</span> : null;\n\t\tcase 'Link': {\n\t\t\tconst url = ctx.url(part.url, 'link');\n\t\t\treturn url && str(part.label) ? (\n\t\t\t\t<a className=\"an-w-link\" href={url} target=\"_blank\" rel=\"noreferrer noopener\">\n\t\t\t\t\t{str(part.label)}\n\t\t\t\t</a>\n\t\t\t) : null;\n\t\t}\n\t\tcase 'Button':\n\t\t\tif (!str(part.label)) return null;\n\t\t\treturn (\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tclassName={`an-w-button is-${part.variant === 'secondary' ? 'secondary' : 'primary'}`}\n\t\t\t\t\tdisabled={!onAsk}\n\t\t\t\t\tonClick={() => onAsk?.(str(part.label))}\n\t\t\t\t>\n\t\t\t\t\t{str(part.label)}\n\t\t\t\t</button>\n\t\t\t);\n\t\tcase 'Suggestions': {\n\t\t\tconst options = list(part.options).map(str).filter(Boolean);\n\t\t\tif (options.length === 0) return null;\n\t\t\treturn (\n\t\t\t\t<div className=\"an-w-suggest\">\n\t\t\t\t\t{options.map((o, i) => (\n\t\t\t\t\t\t<button key={i} type=\"button\" disabled={!onAsk} onClick={() => onAsk?.(o)}>\n\t\t\t\t\t\t\t{o}\n\t\t\t\t\t\t</button>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t);\n\t\t}\n\t\tcase 'Divider':\n\t\t\treturn <hr className=\"an-w-divider\" />;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nconst CONTAINERS = new Set(['Column', 'Row', 'Card']);\n\n// A plain function, not a component: the set of parts already drawn lives for\n// one render of the widget. As a component, React's development mode would draw\n// each part twice and find every one \"already drawn\" on its second pass.\nfunction draw(id: string, ctx: Ctx): ReactNode {\n\tconst part = ctx.byId.get(id);\n\t// A part listed twice, or a loop of containers, is drawn once.\n\tif (!part || ctx.seen.has(id)) return null;\n\tctx.seen.add(id);\n\tconst kids = CONTAINERS.has(part.component)\n\t\t? list(part.children)\n\t\t\t\t.filter((k): k is string => typeof k === 'string')\n\t\t\t\t.map((k) => <Fragment key={k}>{draw(k, ctx)}</Fragment>)\n\t\t: undefined;\n\tconst own = ctx.props.parts?.[part.component as WidgetKind];\n\treturn own ? own({ part, children: kids, onAsk: ctx.props.onAsk }) : defaultPart(part, kids, ctx);\n}\n\n/** One widget, drawn from its root part. Draws nothing when there is no root yet. */\nexport function WidgetView(props: WidgetViewProps) {\n\tconst { widget, currency = 'USD', locale, allowUrl } = props;\n\tconst byId = new Map<string, WidgetPart>();\n\tfor (const p of Array.isArray(widget?.components) ? widget.components : []) {\n\t\tif (p && typeof p === 'object' && typeof p.id === 'string' && typeof p.component === 'string' && !byId.has(p.id)) byId.set(p.id, p);\n\t}\n\tif (!byId.has('root')) return null;\n\tlet moneyFormat: Intl.NumberFormat;\n\ttry {\n\t\tmoneyFormat = new Intl.NumberFormat(locale, { style: 'currency', currency, maximumFractionDigits: 0 });\n\t} catch {\n\t\tmoneyFormat = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 });\n\t}\n\tconst numberFormat = new Intl.NumberFormat(locale);\n\tconst ctx: Ctx = {\n\t\tbyId,\n\t\tseen: new Set(),\n\t\tprops,\n\t\tmoney: (n) => moneyFormat.format(n),\n\t\tnumber: (n) => numberFormat.format(n),\n\t\turl: (v, use) => (typeof v === 'string' && httpsOnly(v) && (allowUrl ? allowUrl(v, use) : true) ? v : undefined),\n\t};\n\treturn (\n\t\t<Boundary>\n\t\t\t<div className={`an-w${props.className ? ` ${props.className}` : ''}`} data-surface={widget.surfaceId}>\n\t\t\t\t{draw('root', ctx)}\n\t\t\t</div>\n\t\t</Boundary>\n\t);\n}\n\nfunction Paragraphs({ text }: { text: string }) {\n\treturn (\n\t\t<>\n\t\t\t{text\n\t\t\t\t.trim()\n\t\t\t\t.split(/\\n{2,}/)\n\t\t\t\t.map((p, i) => (\n\t\t\t\t\t<p key={i} className=\"an-reply-text\">\n\t\t\t\t\t\t{p.split('\\n').map((line, j) => (\n\t\t\t\t\t\t\t<Fragment key={j}>\n\t\t\t\t\t\t\t\t{j > 0 && <br />}\n\t\t\t\t\t\t\t\t{line}\n\t\t\t\t\t\t\t</Fragment>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</p>\n\t\t\t\t))}\n\t\t</>\n\t);\n}\n\n/** A whole reply: its words, with each widget drawn where it sits. */\nexport function ReplyView({ text, widgets, renderText, className, ...widgetProps }: ReplyViewProps) {\n\treturn (\n\t\t<div className={`an-reply${className ? ` ${className}` : ''}`}>\n\t\t\t{placeWidgets(text, widgets ?? []).map((piece, i) =>\n\t\t\t\tpiece.kind === 'text' ? (\n\t\t\t\t\t<Fragment key={`t${i}`}>{renderText ? renderText(piece.text) : <Paragraphs text={piece.text} />}</Fragment>\n\t\t\t\t) : (\n\t\t\t\t\t<WidgetView key={piece.widget.surfaceId} widget={piece.widget} {...widgetProps} />\n\t\t\t\t),\n\t\t\t)}\n\t\t</div>\n\t);\n}\n"]}
package/turn.d.ts CHANGED
@@ -6,6 +6,10 @@ export type Turn = Promise<string> & AsyncIterable<TurnEvent>;
6
6
  * Frames are `data: {json}` separated by blank lines. Anything else on the wire
7
7
  * (comments, retry directives, a stray blank) is ignored rather than treated as
8
8
  * an error: a proxy is allowed to insert keep-alive comments and a stream that
9
- * died because of one would be maddening to debug. */
10
- export declare function parseSSE(body: ReadableStream<Uint8Array>): AsyncGenerator<TurnEvent>;
9
+ * died because of one would be maddening to debug.
10
+ *
11
+ * `turnId` is the turn the API named in its X-Turn-ID header. It becomes the
12
+ * first event, `start`, yielded inside the same cleanup as the rest, so a caller
13
+ * who stops right there still releases the connection. */
14
+ export declare function parseSSE(body: ReadableStream<Uint8Array>, turnId?: string | null): AsyncGenerator<TurnEvent>;
11
15
  export declare function makeTurn(response: Promise<Response>, recoveryMessage?: string): Turn;
package/turn.js CHANGED
@@ -20,37 +20,50 @@ import { AgentNavaError } from "./errors.js";
20
20
  * Frames are `data: {json}` separated by blank lines. Anything else on the wire
21
21
  * (comments, retry directives, a stray blank) is ignored rather than treated as
22
22
  * an error: a proxy is allowed to insert keep-alive comments and a stream that
23
- * died because of one would be maddening to debug. */
24
- export async function* parseSSE(body) {
23
+ * died because of one would be maddening to debug.
24
+ *
25
+ * `turnId` is the turn the API named in its X-Turn-ID header. It becomes the
26
+ * first event, `start`, yielded inside the same cleanup as the rest, so a caller
27
+ * who stops right there still releases the connection. */
28
+ export async function* parseSSE(body, turnId) {
25
29
  const reader = body.getReader();
26
30
  const decoder = new TextDecoder();
27
31
  let buffer = '';
28
32
  let completed = false;
29
33
  let assembled = '';
30
34
  let finalReply;
35
+ let finalWidgets;
31
36
  let terminal = false;
32
- const eventForLine = (line) => {
37
+ const steps = new Map();
38
+ const eventsForLine = (line) => {
33
39
  const wire = parseLine(line);
34
40
  if (!wire)
35
- return undefined;
41
+ return [];
36
42
  // Text being final does not prove the turn completed. Persistence or the
37
43
  // observer can still fail before the runtime's terminal done marker.
38
44
  if (wire.type === 'message-end') {
39
45
  finalReply = typeof wire.final === 'string' ? wire.final : '';
40
- return undefined;
46
+ const widgets = Array.isArray(wire.widgets) ? wire.widgets.flatMap((w) => widgetOf(w) ?? []) : [];
47
+ finalWidgets = widgets.length > 0 ? widgets : undefined;
48
+ return [];
41
49
  }
42
50
  if (wire.type === 'done') {
43
51
  terminal = true;
44
- return { type: 'done', reply: finalReply ?? assembled };
52
+ return [{ type: 'done', reply: finalReply ?? assembled, ...(finalWidgets && { widgets: finalWidgets }) }];
45
53
  }
46
54
  const event = translate(wire);
47
- if (event?.type === 'text')
55
+ if (!event)
56
+ return [];
57
+ if (event.type === 'text')
48
58
  assembled += event.text;
49
- if (event?.type === 'error')
59
+ if (event.type === 'error')
50
60
  terminal = true;
51
- return event;
61
+ const progress = event.type === 'tool' ? trackStep(steps, wire) : undefined;
62
+ return progress ? [event, progress] : [event];
52
63
  };
53
64
  try {
65
+ if (turnId)
66
+ yield { type: 'start', turnId };
54
67
  while (true) {
55
68
  const { done, value } = await reader.read();
56
69
  if (done) {
@@ -64,8 +77,7 @@ export async function* parseSSE(body) {
64
77
  while (nl !== -1) {
65
78
  const line = buffer.slice(0, nl).replace(/\r$/, '');
66
79
  buffer = buffer.slice(nl + 1);
67
- const event = eventForLine(line);
68
- if (event)
80
+ for (const event of eventsForLine(line))
69
81
  yield event;
70
82
  if (terminal)
71
83
  return;
@@ -73,9 +85,8 @@ export async function* parseSSE(body) {
73
85
  }
74
86
  }
75
87
  // A final frame with no trailing newline still counts.
76
- const last = eventForLine(buffer.replace(/\r$/, ''));
77
- if (last)
78
- yield last;
88
+ for (const event of eventsForLine(buffer.replace(/\r$/, '')))
89
+ yield event;
79
90
  if (!terminal)
80
91
  yield { type: 'error', message: 'The response stream ended before the turn finished.', retryable: false };
81
92
  }
@@ -104,6 +115,50 @@ export async function* parseSSE(body) {
104
115
  }
105
116
  }
106
117
  }
118
+ /** A widget off the wire, or undefined for anything that is not one. */
119
+ function widgetOf(raw) {
120
+ const w = raw;
121
+ if (!w || typeof w.surfaceId !== 'string' || !Array.isArray(w.components))
122
+ return undefined;
123
+ return {
124
+ surfaceId: w.surfaceId,
125
+ at: typeof w.at === 'number' && w.at >= 0 ? w.at : 0,
126
+ components: w.components,
127
+ closed: w.closed !== false,
128
+ };
129
+ }
130
+ const STEP_KINDS = new Set(['read', 'write', 'edit', 'search', 'shell', 'web', 'data', 'task', 'plan', 'other']);
131
+ /**
132
+ * Update the turn's steps from one tool event, and return the whole list when
133
+ * it changed.
134
+ *
135
+ * The steps are the ones the portal's Working card shows: one per tool call a
136
+ * person should see, in the order they started, in the words the API put on
137
+ * the call. The API's labels come from the same mapping the portal uses
138
+ * (packages/backend-contract/src/tool-steps.ts), so a developer's own app and
139
+ * the portal list the same steps in the same words.
140
+ *
141
+ * Built from tool events on every runtime. The runtime's own `progress`
142
+ * snapshot, which only some runtimes send, is not used, so a turn never
143
+ * reports two different lists.
144
+ *
145
+ * An API from before labels sends none. A tool's identifier is not something
146
+ * to show a person, so such a turn has no steps rather than raw names.
147
+ */
148
+ function trackStep(steps, wire) {
149
+ if (wire.step === false || !wire.label || !wire.toolId)
150
+ return undefined;
151
+ const id = wire.toolId;
152
+ const known = steps.get(id);
153
+ if (wire.type === 'tool-start' && known)
154
+ return undefined;
155
+ // A kind this version does not know yet still gets a step, as 'other'.
156
+ const kind = STEP_KINDS.has(wire.kind) ? wire.kind : 'other';
157
+ const status = wire.type === 'tool-start' ? 'active' : wire.ok === false ? 'error' : 'done';
158
+ steps.set(id, known ? { ...known, status } : { id, label: wire.label, kind, status });
159
+ // Copies, so a caller who keeps one list and edits it cannot change the next.
160
+ return { type: 'progress', steps: [...steps.values()].map((step) => ({ ...step })) };
161
+ }
107
162
  /**
108
163
  * The API's event vocabulary, as the SDK's.
109
164
  *
@@ -119,6 +174,7 @@ export async function* parseSSE(body) {
119
174
  *
120
175
  * Returns undefined for a frame with nothing to report, including an event type
121
176
  * this version does not know. A new event must never break an old client.
177
+ * Steps (`progress`) are built beside this, from the tool events (trackStep).
122
178
  */
123
179
  function translate(wire) {
124
180
  switch (wire.type) {
@@ -128,14 +184,23 @@ function translate(wire) {
128
184
  ? { type: 'text', text: wire.delta }
129
185
  : undefined;
130
186
  case 'tool-start':
131
- return { type: 'tool', name: wire.name ?? 'tool', state: 'start' };
187
+ return { type: 'tool', name: wire.name ?? 'tool', state: 'start', ...(wire.label && { label: wire.label }) };
132
188
  case 'tool-end':
133
189
  return {
134
190
  type: 'tool',
135
191
  name: wire.name ?? 'tool',
136
192
  state: 'end',
193
+ ...(wire.label && { label: wire.label }),
137
194
  ...(wire.ok !== undefined && { ok: wire.ok }),
138
195
  };
196
+ case 'widget': {
197
+ const widget = widgetOf(wire.widget);
198
+ return widget ? { type: 'widget', widget } : undefined;
199
+ }
200
+ case 'file':
201
+ // A file the agent wrote in the conversation's drive. Its path is what
202
+ // conversation.readFile() takes.
203
+ return typeof wire.path === 'string' && wire.path ? { type: 'file', path: wire.path } : undefined;
139
204
  case 'error':
140
205
  return {
141
206
  type: 'error',
@@ -217,7 +282,7 @@ class TurnImpl {
217
282
  }
218
283
  this.consumed = how;
219
284
  }
220
- async body() {
285
+ async open() {
221
286
  const res = await this.response;
222
287
  if (!res.body) {
223
288
  throw new AgentNavaError({
@@ -226,13 +291,13 @@ class TurnImpl {
226
291
  status: res.status,
227
292
  });
228
293
  }
229
- return res.body;
294
+ return { body: res.body, turnId: res.headers.get('x-turn-id') };
230
295
  }
231
296
  /** Drain the stream and resolve to the final reply. */
232
297
  async settle() {
233
298
  // parseSSE withholds the final answer until wire done confirms completion.
234
299
  // EOF is an interruption even if some or all of the reply already arrived.
235
- for await (const event of parseSSE(await this.body())) {
300
+ for await (const event of parseSSE((await this.open()).body)) {
236
301
  if (event.type === 'done')
237
302
  return event.reply;
238
303
  if (event.type === 'error') {
@@ -279,7 +344,8 @@ class TurnImpl {
279
344
  }
280
345
  async *[Symbol.asyncIterator]() {
281
346
  this.claim('iterated');
282
- for await (const event of parseSSE(await this.body())) {
347
+ const { body, turnId } = await this.open();
348
+ for await (const event of parseSSE(body, turnId)) {
283
349
  yield event.type === 'error' && this.recoveryMessage
284
350
  ? { ...event, message: `${event.message} ${this.recoveryMessage}` }
285
351
  : event;
package/turn.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"turn.js","sourceRoot":"","sources":["../src/turn.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,EAAE;AACF,iFAAiF;AACjF,qEAAqE;AACrE,+EAA+E;AAC/E,+EAA+E;AAC/E,qBAAqB;AACrB,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,iFAAiF;AACjF,wDAAwD;AACxD,EAAE;AACF,gFAAgF;AAChF,iFA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AAI,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC;QAC5B,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACvB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YACvD,MAAM,KAAK,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,CAAC,eAAe;gBACnD,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,EAAE;gBACnE,CAAC,CAAC,KAAK,CAAC;QACV,CAAC;IACF,CAAC;CACD;AAED,MAAM,UAAU,QAAQ,CAAC,QAA2B,EAAE,eAAe,GAAG,EAAE;IACzE,OAAO,IAAI,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAoB,CAAC;AACnE,CAAC","sourcesContent":["// One turn: `Promise<string> & AsyncIterable<TurnEvent>`.\n//\n// A caller who wants the answer writes `await conversation.ask('...')`. A caller\n// who wants to render it as it arrives writes `for await (const e of\n// conversation.ask('...'))`. One method, two shapes, because making the caller\n// choose `ask` or `askStream` up front means changing the call site later just\n// to show a spinner.\n//\n// THE MESSAGE IS SENT WHEN ask() IS CALLED, not when the result is awaited or\n// iterated. A lazy promise would mean `const t = ask(...)` did nothing and\n// `await t` twice asked twice; sending eagerly makes `ask` the verb it reads as,\n// and calling it twice is then obviously two questions.\n//\n// Awaiting AND iterating the same turn throws rather than replaying. The events\n// are a live stream over a socket, not a stored list, so a second consumer would\n// silently receive nothing at all, which is far worse than an error.\n\nimport { AgentNavaError } from './errors.ts';\nimport type { TurnEvent } from './types.ts';\n\n/** What `conversation.ask()` returns. */\nexport type Turn = Promise<string> & AsyncIterable<TurnEvent>;\n\n/** Parse an SSE body into the events the API sends.\n *\n * Frames are `data: {json}` separated by blank lines. Anything else on the wire\n * (comments, retry directives, a stray blank) is ignored rather than treated as\n * an error: a proxy is allowed to insert keep-alive comments and a stream that\n * died because of one would be maddening to debug. */\nexport async function* parseSSE(body: ReadableStream<Uint8Array>): AsyncGenerator<TurnEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = '';\n\tlet completed = false;\n\tlet assembled = '';\n\tlet finalReply: string | undefined;\n\tlet terminal = false;\n\tconst eventForLine = (line: string): TurnEvent | undefined => {\n\t\tconst wire = parseLine(line);\n\t\tif (!wire) return undefined;\n\t\t// Text being final does not prove the turn completed. Persistence or the\n\t\t// observer can still fail before the runtime's terminal done marker.\n\t\tif (wire.type === 'message-end') {\n\t\t\tfinalReply = typeof wire.final === 'string' ? wire.final : '';\n\t\t\treturn undefined;\n\t\t}\n\t\tif (wire.type === 'done') {\n\t\t\tterminal = true;\n\t\t\treturn { type: 'done', reply: finalReply ?? assembled };\n\t\t}\n\t\tconst event = translate(wire);\n\t\tif (event?.type === 'text') assembled += event.text;\n\t\tif (event?.type === 'error') terminal = true;\n\t\treturn event;\n\t};\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tcompleted = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t// Split on newlines, keeping the last partial line in the buffer. A\n\t\t\t// frame can be split across two network reads at any byte.\n\t\t\tlet nl = buffer.indexOf('\\n');\n\t\t\twhile (nl !== -1) {\n\t\t\t\tconst line = buffer.slice(0, nl).replace(/\\r$/, '');\n\t\t\t\tbuffer = buffer.slice(nl + 1);\n\t\t\t\tconst event = eventForLine(line);\n\t\t\t\tif (event) yield event;\n\t\t\t\tif (terminal) return;\n\t\t\t\tnl = buffer.indexOf('\\n');\n\t\t\t}\n\t\t}\n\t\t// A final frame with no trailing newline still counts.\n\t\tconst last = eventForLine(buffer.replace(/\\r$/, ''));\n\t\tif (last) yield last;\n\t\tif (!terminal) yield { type: 'error', message: 'The response stream ended before the turn finished.', retryable: false };\n\t} catch (error) {\n\t\t// Explicit cancellation keeps its AbortError identity. A lost transport\n\t\t// is an interrupted observer, never evidence that asking again is safe.\n\t\tif (error instanceof Error && error.name === 'AbortError') throw error;\n\t\tyield { type: 'error', message: `The response stream was interrupted: ${error instanceof Error ? error.message : String(error)}`, retryable: false };\n\t} finally {\n\t\t// A final reply, a wire error, or a caller's early break can stop before\n\t\t// EOF. Releasing the lock alone leaves the HTTP body and abort listener\n\t\t// alive; cancel unread data before releasing ownership of the reader.\n\t\ttry {\n\t\t\t// Cleanup can be slow or never settle. Initiate it before releasing\n\t\t\t// ownership, but do not delay the reply/error or iterator return.\n\t\t\tif (!completed) void reader.cancel().catch(() => {});\n\t\t} catch {\n\t\t\t// Cleanup must not replace the reply or the original stream/wire error.\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t}\n}\n\n/** One frame as it arrives on the wire, before translation. */\ninterface WireEvent {\n\ttype: string;\n\tdelta?: string;\n\tfinal?: string;\n\tname?: string;\n\tok?: boolean;\n\tmessage?: string;\n\tretryable?: boolean;\n\tpath?: string;\n}\n\n/**\n * The API's event vocabulary, as the SDK's.\n *\n * The wire says `message-delta` / `message-end` / `tool-start` / `tool-end`, and\n * design/sdk-design.md says `text` / `done` / `tool`. Both are right for their\n * own audience: the wire shape is what apps/web's chat renders and has rendered\n * for a long time, and the SDK shape is what reads well at a call site\n * (`if (e.type === 'text')`).\n *\n * So this translates, which is the same job the SDK already does for drive\n * entries and connection rows. It is NOT a rename waiting to happen: changing\n * the wire would break a working chat UI to save a switch statement.\n *\n * Returns undefined for a frame with nothing to report, including an event type\n * this version does not know. A new event must never break an old client.\n */\nfunction translate(wire: WireEvent): TurnEvent | undefined {\n\tswitch (wire.type) {\n\t\tcase 'message-delta':\n\t\t\t// A FRAGMENT. Append, do not assemble.\n\t\t\treturn typeof wire.delta === 'string' && wire.delta.length > 0\n\t\t\t\t? { type: 'text', text: wire.delta }\n\t\t\t\t: undefined;\n\t\tcase 'tool-start':\n\t\t\treturn { type: 'tool', name: wire.name ?? 'tool', state: 'start' };\n\t\tcase 'tool-end':\n\t\t\treturn {\n\t\t\t\ttype: 'tool',\n\t\t\t\tname: wire.name ?? 'tool',\n\t\t\t\tstate: 'end',\n\t\t\t\t...(wire.ok !== undefined && { ok: wire.ok }),\n\t\t\t};\n\t\tcase 'error':\n\t\t\treturn {\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: wire.message ?? 'the turn failed',\n\t\t\t\tretryable: wire.retryable === true,\n\t\t\t};\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction parseLine(line: string): WireEvent | undefined {\n\tif (!line.startsWith('data:')) return undefined;\n\tconst payload = line.slice(5).trim();\n\tif (!payload || payload === '[DONE]') return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(payload) as WireEvent | null;\n\t\treturn parsed && typeof parsed.type === 'string' ? parsed : undefined;\n\t} catch {\n\t\t// A frame we cannot parse is dropped rather than thrown. A malformed frame\n\t\t// must not break a stream that is otherwise fine.\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Build the dual-shaped result.\n *\n * `response` is already in flight when this is called: the caller passes the\n * running request, so the turn is sent whether or not anyone ever consumes it.\n *\n * A THENABLE, not a Promise subclass, and that was measured rather than assumed.\n * A subclass whose base promise never settles deadlocks, because `await` can\n * settle against the base's own state instead of the overridden `then`. A\n * subclass whose base resolves immediately fixes the deadlock and passes\n * `instanceof Promise`, but then anything reading the promise's INTERNAL state\n * sees \"resolved\" for a turn whose `then` rejects, which is a lie that tooling\n * believes. A thenable is honest: `await`, `Promise.all` and `.then/.catch/\n * .finally` are all defined in terms of `then` and all work, and anything that\n * demands a real Promise says so out loud instead of reporting a wrong answer.\n */\nclass TurnImpl implements AsyncIterable<TurnEvent> {\n\tprivate consumed?: 'awaited' | 'iterated';\n\tprivate settled?: Promise<string>;\n\n\tconstructor(private readonly response: Promise<Response>, private readonly recoveryMessage = '') {\n\t\t// ask() starts eagerly, while consuming its thenable may happen later.\n\t\t// Observe early rejection now; keep the ORIGINAL promise so a later\n\t\t// await/iteration still receives that same error.\n\t\tvoid response.catch(() => {});\n\t}\n\n\t/**\n\t * Record how this turn is being consumed, and refuse a second, different way.\n\t *\n\t * AWAITING TWICE IS ALLOWED, deliberately. A promise handing the same value to\n\t * two awaits is exactly what a promise is, and `drain()` memoises so the second\n\t * await costs nothing. Refusing it would break `Promise.all([turn, turn])` and\n\t * every library that attaches a `.catch()` and then awaits the same value.\n\t *\n\t * ITERATING TWICE IS NOT, and neither is mixing the two. The events are a live\n\t * stream over a socket, not a stored list: a second iterator would receive\n\t * nothing at all and report an empty turn, which is worse than an error.\n\t */\n\tprivate claim(how: 'awaited' | 'iterated'): void {\n\t\tif (how === 'awaited' && this.consumed === 'awaited') return;\n\t\tif (this.consumed) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage:\n\t\t\t\t\tthis.consumed === how\n\t\t\t\t\t\t? `This turn was already ${how}. Call ask() again to ask again; a turn is a live stream, not a replayable list.`\n\t\t\t\t\t\t: `This turn was already ${this.consumed} and cannot also be ${how}. Pick one: await it for the reply, or iterate it for the events. Call ask() again to ask again.`,\n\t\t\t\tcode: 'turn_already_consumed',\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t}\n\t\tthis.consumed = how;\n\t}\n\n\tprivate async body(): Promise<ReadableStream<Uint8Array>> {\n\t\tconst res = await this.response;\n\t\tif (!res.body) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage: `The turn response had no body to stream. ${this.recoveryMessage}`.trim(),\n\t\t\t\tcode: 'bad_response',\n\t\t\t\tstatus: res.status,\n\t\t\t});\n\t\t}\n\t\treturn res.body;\n\t}\n\n\t/** Drain the stream and resolve to the final reply. */\n\tprivate async settle(): Promise<string> {\n\t\t// parseSSE withholds the final answer until wire done confirms completion.\n\t\t// EOF is an interruption even if some or all of the reply already arrived.\n\t\tfor await (const event of parseSSE(await this.body())) {\n\t\t\tif (event.type === 'done') return event.reply;\n\t\t\tif (event.type === 'error') {\n\t\t\t\t// Awaiting is the shape that throws. Iterating gets the error as an\n\t\t\t\t// event and the loop ends, because a for-await that throws mid-render\n\t\t\t\t// leaves the UI half-painted.\n\t\t\t\tthrow new AgentNavaError({\n\t\t\t\t\tmessage: `${event.message} ${this.recoveryMessage}`.trim(),\n\t\t\t\t\tcode: 'turn_failed',\n\t\t\t\t\tstatus: event.retryable ? 503 : 400,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthrow new AgentNavaError({ message: `The response stream ended before the turn finished. ${this.recoveryMessage}`.trim(), code: 'turn_failed', status: 400 });\n\t}\n\n\tprivate drain(): Promise<string> {\n\t\t// claim() runs HERE rather than inside settle(), because settle() runs only\n\t\t// once: a second await would skip the check entirely, and awaiting a turn\n\t\t// that was already iterated would quietly return an empty string instead of\n\t\t// saying what went wrong.\n\t\t//\n\t\t// REJECT, never throw. `then` must return a promise; a synchronous throw out\n\t\t// of it escapes the promise chain, so a caller writing\n\t\t// `turn.then(a, b).catch(c)` would get an exception past their own .catch.\n\t\ttry {\n\t\t\tthis.claim('awaited');\n\t\t} catch (err) {\n\t\t\treturn Promise.reject(err);\n\t\t}\n\t\t// Started once. `await` calls `then`, and so does Promise.all, and so does\n\t\t// anything that duck-types a thenable; all of them share one drain.\n\t\tthis.settled ??= this.settle();\n\t\treturn this.settled;\n\t}\n\n\tthen<A = string, B = never>(\n\t\tonOk?: ((value: string) => A | PromiseLike<A>) | null,\n\t\tonErr?: ((reason: unknown) => B | PromiseLike<B>) | null,\n\t): Promise<A | B> {\n\t\treturn this.drain().then(onOk, onErr);\n\t}\n\n\tcatch<B = never>(onErr?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<string | B> {\n\t\treturn this.drain().catch(onErr);\n\t}\n\n\tfinally(onDone?: (() => void) | null): Promise<string> {\n\t\treturn this.drain().finally(onDone);\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncGenerator<TurnEvent> {\n\t\tthis.claim('iterated');\n\t\tfor await (const event of parseSSE(await this.body())) {\n\t\t\tyield event.type === 'error' && this.recoveryMessage\n\t\t\t\t? { ...event, message: `${event.message} ${this.recoveryMessage}` }\n\t\t\t\t: event;\n\t\t}\n\t}\n}\n\nexport function makeTurn(response: Promise<Response>, recoveryMessage = ''): Turn {\n\treturn new TurnImpl(response, recoveryMessage) as unknown as Turn;\n}\n"]}
1
+ {"version":3,"file":"turn.js","sourceRoot":"","sources":["../src/turn.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,EAAE;AACF,iFAAiF;AACjF,qEAAqE;AACrE,+EAA+E;AAC/E,+EAA+E;AAC/E,qBAAqB;AACrB,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,iFAAiF;AACjF,wDAAwD;AACxD,EAAE;AACF,gFAAgF;AAChF,iFAAiF;AACjF,qEAAqE;AAErE,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAM7C;;;;;;;;;2DAS2D;AAC3D,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAgC,EAAE,MAAsB;IACvF,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;IAChC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,SAAS,GAAG,EAAE,CAAC;IACnB,IAAI,UAA8B,CAAC;IACnC,IAAI,YAAkC,CAAC;IACvC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,MAAM,KAAK,GAAG,IAAI,GAAG,EAAgB,CAAC;IACtC,MAAM,aAAa,GAAG,CAAC,IAAY,EAAe,EAAE;QACnD,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,IAAI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OAAO,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC,OAAO,CAAC;IACrB,CAAC;IAED,IAAI,CACH,IAAqD,EACrD,KAAwD;QAExD,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAY,KAAwD;QACxE,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAClC,CAAC;IAED,OAAO,CAAC,MAA4B;QACnC,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC;QAC5B,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACvB,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC;QAC3C,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC;YAClD,MAAM,KAAK,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,CAAC,eAAe;gBACnD,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,EAAE;gBACnE,CAAC,CAAC,KAAK,CAAC;QACV,CAAC;IACF,CAAC;CACD;AAED,MAAM,UAAU,QAAQ,CAAC,QAA2B,EAAE,eAAe,GAAG,EAAE;IACzE,OAAO,IAAI,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAoB,CAAC;AACnE,CAAC","sourcesContent":["// One turn: `Promise<string> & AsyncIterable<TurnEvent>`.\n//\n// A caller who wants the answer writes `await conversation.ask('...')`. A caller\n// who wants to render it as it arrives writes `for await (const e of\n// conversation.ask('...'))`. One method, two shapes, because making the caller\n// choose `ask` or `askStream` up front means changing the call site later just\n// to show a spinner.\n//\n// THE MESSAGE IS SENT WHEN ask() IS CALLED, not when the result is awaited or\n// iterated. A lazy promise would mean `const t = ask(...)` did nothing and\n// `await t` twice asked twice; sending eagerly makes `ask` the verb it reads as,\n// and calling it twice is then obviously two questions.\n//\n// Awaiting AND iterating the same turn throws rather than replaying. The events\n// are a live stream over a socket, not a stored list, so a second consumer would\n// silently receive nothing at all, which is far worse than an error.\n\nimport { AgentNavaError } from './errors.ts';\nimport type { Step, TurnEvent, Widget } from './types.ts';\n\n/** What `conversation.ask()` returns. */\nexport type Turn = Promise<string> & AsyncIterable<TurnEvent>;\n\n/** Parse an SSE body into the events the API sends.\n *\n * Frames are `data: {json}` separated by blank lines. Anything else on the wire\n * (comments, retry directives, a stray blank) is ignored rather than treated as\n * an error: a proxy is allowed to insert keep-alive comments and a stream that\n * died because of one would be maddening to debug.\n *\n * `turnId` is the turn the API named in its X-Turn-ID header. It becomes the\n * first event, `start`, yielded inside the same cleanup as the rest, so a caller\n * who stops right there still releases the connection. */\nexport async function* parseSSE(body: ReadableStream<Uint8Array>, turnId?: string | null): AsyncGenerator<TurnEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = '';\n\tlet completed = false;\n\tlet assembled = '';\n\tlet finalReply: string | undefined;\n\tlet finalWidgets: Widget[] | undefined;\n\tlet terminal = false;\n\tconst steps = new Map<string, Step>();\n\tconst eventsForLine = (line: string): TurnEvent[] => {\n\t\tconst wire = parseLine(line);\n\t\tif (!wire) return [];\n\t\t// Text being final does not prove the turn completed. Persistence or the\n\t\t// observer can still fail before the runtime's terminal done marker.\n\t\tif (wire.type === 'message-end') {\n\t\t\tfinalReply = typeof wire.final === 'string' ? wire.final : '';\n\t\t\tconst widgets = Array.isArray(wire.widgets) ? wire.widgets.flatMap((w) => widgetOf(w) ?? []) : [];\n\t\t\tfinalWidgets = widgets.length > 0 ? widgets : undefined;\n\t\t\treturn [];\n\t\t}\n\t\tif (wire.type === 'done') {\n\t\t\tterminal = true;\n\t\t\treturn [{ type: 'done', reply: finalReply ?? assembled, ...(finalWidgets && { widgets: finalWidgets }) }];\n\t\t}\n\t\tconst event = translate(wire);\n\t\tif (!event) return [];\n\t\tif (event.type === 'text') assembled += event.text;\n\t\tif (event.type === 'error') terminal = true;\n\t\tconst progress = event.type === 'tool' ? trackStep(steps, wire) : undefined;\n\t\treturn progress ? [event, progress] : [event];\n\t};\n\ttry {\n\t\tif (turnId) yield { type: 'start', turnId };\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tcompleted = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t// Split on newlines, keeping the last partial line in the buffer. A\n\t\t\t// frame can be split across two network reads at any byte.\n\t\t\tlet nl = buffer.indexOf('\\n');\n\t\t\twhile (nl !== -1) {\n\t\t\t\tconst line = buffer.slice(0, nl).replace(/\\r$/, '');\n\t\t\t\tbuffer = buffer.slice(nl + 1);\n\t\t\t\tfor (const event of eventsForLine(line)) yield event;\n\t\t\t\tif (terminal) return;\n\t\t\t\tnl = buffer.indexOf('\\n');\n\t\t\t}\n\t\t}\n\t\t// A final frame with no trailing newline still counts.\n\t\tfor (const event of eventsForLine(buffer.replace(/\\r$/, ''))) yield event;\n\t\tif (!terminal) yield { type: 'error', message: 'The response stream ended before the turn finished.', retryable: false };\n\t} catch (error) {\n\t\t// Explicit cancellation keeps its AbortError identity. A lost transport\n\t\t// is an interrupted observer, never evidence that asking again is safe.\n\t\tif (error instanceof Error && error.name === 'AbortError') throw error;\n\t\tyield { type: 'error', message: `The response stream was interrupted: ${error instanceof Error ? error.message : String(error)}`, retryable: false };\n\t} finally {\n\t\t// A final reply, a wire error, or a caller's early break can stop before\n\t\t// EOF. Releasing the lock alone leaves the HTTP body and abort listener\n\t\t// alive; cancel unread data before releasing ownership of the reader.\n\t\ttry {\n\t\t\t// Cleanup can be slow or never settle. Initiate it before releasing\n\t\t\t// ownership, but do not delay the reply/error or iterator return.\n\t\t\tif (!completed) void reader.cancel().catch(() => {});\n\t\t} catch {\n\t\t\t// Cleanup must not replace the reply or the original stream/wire error.\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t}\n}\n\n/** One frame as it arrives on the wire, before translation. */\ninterface WireEvent {\n\ttype: string;\n\tdelta?: string;\n\tfinal?: string;\n\ttoolId?: string;\n\tname?: string;\n\t/** What a person sees for the tool call (\"Searching the web: <query>\"). */\n\tlabel?: string;\n\tkind?: string;\n\t/** False for a call that is not a step a person should see. */\n\tstep?: boolean;\n\tok?: boolean;\n\tmessage?: string;\n\tretryable?: boolean;\n\tpath?: string;\n\t/** A widget drawn inside the reply (`widget`), or the final list (`message-end`). */\n\twidget?: unknown;\n\twidgets?: unknown[];\n}\n\n/** A widget off the wire, or undefined for anything that is not one. */\nfunction widgetOf(raw: unknown): Widget | undefined {\n\tconst w = raw as Partial<Widget> | null;\n\tif (!w || typeof w.surfaceId !== 'string' || !Array.isArray(w.components)) return undefined;\n\treturn {\n\t\tsurfaceId: w.surfaceId,\n\t\tat: typeof w.at === 'number' && w.at >= 0 ? w.at : 0,\n\t\tcomponents: w.components,\n\t\tclosed: w.closed !== false,\n\t};\n}\n\nconst STEP_KINDS = new Set<Step['kind']>(['read', 'write', 'edit', 'search', 'shell', 'web', 'data', 'task', 'plan', 'other']);\n\n/**\n * Update the turn's steps from one tool event, and return the whole list when\n * it changed.\n *\n * The steps are the ones the portal's Working card shows: one per tool call a\n * person should see, in the order they started, in the words the API put on\n * the call. The API's labels come from the same mapping the portal uses\n * (packages/backend-contract/src/tool-steps.ts), so a developer's own app and\n * the portal list the same steps in the same words.\n *\n * Built from tool events on every runtime. The runtime's own `progress`\n * snapshot, which only some runtimes send, is not used, so a turn never\n * reports two different lists.\n *\n * An API from before labels sends none. A tool's identifier is not something\n * to show a person, so such a turn has no steps rather than raw names.\n */\nfunction trackStep(steps: Map<string, Step>, wire: WireEvent): TurnEvent | undefined {\n\tif (wire.step === false || !wire.label || !wire.toolId) return undefined;\n\tconst id = wire.toolId;\n\tconst known = steps.get(id);\n\tif (wire.type === 'tool-start' && known) return undefined;\n\t// A kind this version does not know yet still gets a step, as 'other'.\n\tconst kind = STEP_KINDS.has(wire.kind as Step['kind']) ? (wire.kind as Step['kind']) : 'other';\n\tconst status: Step['status'] = wire.type === 'tool-start' ? 'active' : wire.ok === false ? 'error' : 'done';\n\tsteps.set(id, known ? { ...known, status } : { id, label: wire.label, kind, status });\n\t// Copies, so a caller who keeps one list and edits it cannot change the next.\n\treturn { type: 'progress', steps: [...steps.values()].map((step) => ({ ...step })) };\n}\n\n/**\n * The API's event vocabulary, as the SDK's.\n *\n * The wire says `message-delta` / `message-end` / `tool-start` / `tool-end`, and\n * design/sdk-design.md says `text` / `done` / `tool`. Both are right for their\n * own audience: the wire shape is what apps/web's chat renders and has rendered\n * for a long time, and the SDK shape is what reads well at a call site\n * (`if (e.type === 'text')`).\n *\n * So this translates, which is the same job the SDK already does for drive\n * entries and connection rows. It is NOT a rename waiting to happen: changing\n * the wire would break a working chat UI to save a switch statement.\n *\n * Returns undefined for a frame with nothing to report, including an event type\n * this version does not know. A new event must never break an old client.\n * Steps (`progress`) are built beside this, from the tool events (trackStep).\n */\nfunction translate(wire: WireEvent): TurnEvent | undefined {\n\tswitch (wire.type) {\n\t\tcase 'message-delta':\n\t\t\t// A FRAGMENT. Append, do not assemble.\n\t\t\treturn typeof wire.delta === 'string' && wire.delta.length > 0\n\t\t\t\t? { type: 'text', text: wire.delta }\n\t\t\t\t: undefined;\n\t\tcase 'tool-start':\n\t\t\treturn { type: 'tool', name: wire.name ?? 'tool', state: 'start', ...(wire.label && { label: wire.label }) };\n\t\tcase 'tool-end':\n\t\t\treturn {\n\t\t\t\ttype: 'tool',\n\t\t\t\tname: wire.name ?? 'tool',\n\t\t\t\tstate: 'end',\n\t\t\t\t...(wire.label && { label: wire.label }),\n\t\t\t\t...(wire.ok !== undefined && { ok: wire.ok }),\n\t\t\t};\n\t\tcase 'widget': {\n\t\t\tconst widget = widgetOf(wire.widget);\n\t\t\treturn widget ? { type: 'widget', widget } : undefined;\n\t\t}\n\t\tcase 'file':\n\t\t\t// A file the agent wrote in the conversation's drive. Its path is what\n\t\t\t// conversation.readFile() takes.\n\t\t\treturn typeof wire.path === 'string' && wire.path ? { type: 'file', path: wire.path } : undefined;\n\t\tcase 'error':\n\t\t\treturn {\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: wire.message ?? 'the turn failed',\n\t\t\t\tretryable: wire.retryable === true,\n\t\t\t};\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction parseLine(line: string): WireEvent | undefined {\n\tif (!line.startsWith('data:')) return undefined;\n\tconst payload = line.slice(5).trim();\n\tif (!payload || payload === '[DONE]') return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(payload) as WireEvent | null;\n\t\treturn parsed && typeof parsed.type === 'string' ? parsed : undefined;\n\t} catch {\n\t\t// A frame we cannot parse is dropped rather than thrown. A malformed frame\n\t\t// must not break a stream that is otherwise fine.\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Build the dual-shaped result.\n *\n * `response` is already in flight when this is called: the caller passes the\n * running request, so the turn is sent whether or not anyone ever consumes it.\n *\n * A THENABLE, not a Promise subclass, and that was measured rather than assumed.\n * A subclass whose base promise never settles deadlocks, because `await` can\n * settle against the base's own state instead of the overridden `then`. A\n * subclass whose base resolves immediately fixes the deadlock and passes\n * `instanceof Promise`, but then anything reading the promise's INTERNAL state\n * sees \"resolved\" for a turn whose `then` rejects, which is a lie that tooling\n * believes. A thenable is honest: `await`, `Promise.all` and `.then/.catch/\n * .finally` are all defined in terms of `then` and all work, and anything that\n * demands a real Promise says so out loud instead of reporting a wrong answer.\n */\nclass TurnImpl implements AsyncIterable<TurnEvent> {\n\tprivate consumed?: 'awaited' | 'iterated';\n\tprivate settled?: Promise<string>;\n\n\tconstructor(private readonly response: Promise<Response>, private readonly recoveryMessage = '') {\n\t\t// ask() starts eagerly, while consuming its thenable may happen later.\n\t\t// Observe early rejection now; keep the ORIGINAL promise so a later\n\t\t// await/iteration still receives that same error.\n\t\tvoid response.catch(() => {});\n\t}\n\n\t/**\n\t * Record how this turn is being consumed, and refuse a second, different way.\n\t *\n\t * AWAITING TWICE IS ALLOWED, deliberately. A promise handing the same value to\n\t * two awaits is exactly what a promise is, and `drain()` memoises so the second\n\t * await costs nothing. Refusing it would break `Promise.all([turn, turn])` and\n\t * every library that attaches a `.catch()` and then awaits the same value.\n\t *\n\t * ITERATING TWICE IS NOT, and neither is mixing the two. The events are a live\n\t * stream over a socket, not a stored list: a second iterator would receive\n\t * nothing at all and report an empty turn, which is worse than an error.\n\t */\n\tprivate claim(how: 'awaited' | 'iterated'): void {\n\t\tif (how === 'awaited' && this.consumed === 'awaited') return;\n\t\tif (this.consumed) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage:\n\t\t\t\t\tthis.consumed === how\n\t\t\t\t\t\t? `This turn was already ${how}. Call ask() again to ask again; a turn is a live stream, not a replayable list.`\n\t\t\t\t\t\t: `This turn was already ${this.consumed} and cannot also be ${how}. Pick one: await it for the reply, or iterate it for the events. Call ask() again to ask again.`,\n\t\t\t\tcode: 'turn_already_consumed',\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t}\n\t\tthis.consumed = how;\n\t}\n\n\tprivate async open(): Promise<{ body: ReadableStream<Uint8Array>; turnId: string | null }> {\n\t\tconst res = await this.response;\n\t\tif (!res.body) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage: `The turn response had no body to stream. ${this.recoveryMessage}`.trim(),\n\t\t\t\tcode: 'bad_response',\n\t\t\t\tstatus: res.status,\n\t\t\t});\n\t\t}\n\t\treturn { body: res.body, turnId: res.headers.get('x-turn-id') };\n\t}\n\n\t/** Drain the stream and resolve to the final reply. */\n\tprivate async settle(): Promise<string> {\n\t\t// parseSSE withholds the final answer until wire done confirms completion.\n\t\t// EOF is an interruption even if some or all of the reply already arrived.\n\t\tfor await (const event of parseSSE((await this.open()).body)) {\n\t\t\tif (event.type === 'done') return event.reply;\n\t\t\tif (event.type === 'error') {\n\t\t\t\t// Awaiting is the shape that throws. Iterating gets the error as an\n\t\t\t\t// event and the loop ends, because a for-await that throws mid-render\n\t\t\t\t// leaves the UI half-painted.\n\t\t\t\tthrow new AgentNavaError({\n\t\t\t\t\tmessage: `${event.message} ${this.recoveryMessage}`.trim(),\n\t\t\t\t\tcode: 'turn_failed',\n\t\t\t\t\tstatus: event.retryable ? 503 : 400,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthrow new AgentNavaError({ message: `The response stream ended before the turn finished. ${this.recoveryMessage}`.trim(), code: 'turn_failed', status: 400 });\n\t}\n\n\tprivate drain(): Promise<string> {\n\t\t// claim() runs HERE rather than inside settle(), because settle() runs only\n\t\t// once: a second await would skip the check entirely, and awaiting a turn\n\t\t// that was already iterated would quietly return an empty string instead of\n\t\t// saying what went wrong.\n\t\t//\n\t\t// REJECT, never throw. `then` must return a promise; a synchronous throw out\n\t\t// of it escapes the promise chain, so a caller writing\n\t\t// `turn.then(a, b).catch(c)` would get an exception past their own .catch.\n\t\ttry {\n\t\t\tthis.claim('awaited');\n\t\t} catch (err) {\n\t\t\treturn Promise.reject(err);\n\t\t}\n\t\t// Started once. `await` calls `then`, and so does Promise.all, and so does\n\t\t// anything that duck-types a thenable; all of them share one drain.\n\t\tthis.settled ??= this.settle();\n\t\treturn this.settled;\n\t}\n\n\tthen<A = string, B = never>(\n\t\tonOk?: ((value: string) => A | PromiseLike<A>) | null,\n\t\tonErr?: ((reason: unknown) => B | PromiseLike<B>) | null,\n\t): Promise<A | B> {\n\t\treturn this.drain().then(onOk, onErr);\n\t}\n\n\tcatch<B = never>(onErr?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<string | B> {\n\t\treturn this.drain().catch(onErr);\n\t}\n\n\tfinally(onDone?: (() => void) | null): Promise<string> {\n\t\treturn this.drain().finally(onDone);\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncGenerator<TurnEvent> {\n\t\tthis.claim('iterated');\n\t\tconst { body, turnId } = await this.open();\n\t\tfor await (const event of parseSSE(body, turnId)) {\n\t\t\tyield event.type === 'error' && this.recoveryMessage\n\t\t\t\t? { ...event, message: `${event.message} ${this.recoveryMessage}` }\n\t\t\t\t: event;\n\t\t}\n\t}\n}\n\nexport function makeTurn(response: Promise<Response>, recoveryMessage = ''): Turn {\n\treturn new TurnImpl(response, recoveryMessage) as unknown as Turn;\n}\n"]}