@ateam-ai-mobile/core 0.1.33 → 0.1.37
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/dist/index.d.mts +202 -20
- package/dist/index.d.ts +202 -20
- package/dist/index.js +343 -46
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +315 -45
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/chat/blockText.ts +459 -0
- package/src/chat/store.ts +1 -70
- package/src/index.ts +42 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ateam-ai-mobile/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.37",
|
|
4
4
|
"description": "Headless ADAS SDK core — auth bridge, API client, chat/job streaming, MCP calls, theme tokens. No UI, no Expo dependencies.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the phone's chat bubble is handed for a reply: the blocks of a conversation turn as ONE flat string, and that string
|
|
3
|
+
* split back into what the bubble draws. Pure and import-free, so a test runs it in node (it used to sit in store.ts).
|
|
4
|
+
*
|
|
5
|
+
* Nothing a reply holds is dropped. This file used to throw away every json and code block that sat beside a text block (a copy of
|
|
6
|
+
* the web chat's March rule), so a script, a command or a diagram under the answer never reached the person. Which raw data is
|
|
7
|
+
* shown CLOSED is Core's call, made once, at read (backend utils/blockDisplay.js marks it `meta.display: "folded"`); this file only
|
|
8
|
+
* carries that mark to the bubble: a marked block's text is wrapped in the DETAILS sentinels, and the bubble draws that segment as
|
|
9
|
+
* a closed "Details" row. It never decides what folds.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Sentinel delimiters used to embed structured table data inside a flat message string. UI layers split on these and render the
|
|
14
|
+
* contents with a native table component instead of markdown tables, which look terrible on narrow phone screens.
|
|
15
|
+
*
|
|
16
|
+
* Unicode Private Use Area chars so they never collide with anything the model could legitimately emit.
|
|
17
|
+
*/
|
|
18
|
+
export const TABLE_BLOCK_OPEN = '\uE100';
|
|
19
|
+
export const TABLE_BLOCK_CLOSE = '\uE101';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The same, for a block Core marked folded: its text (already rendered to markdown) travels between these, percent-encoded so it
|
|
23
|
+
* can never hold a newline or a sentinel, and the bubble draws it closed under "Details".
|
|
24
|
+
*/
|
|
25
|
+
export const DETAILS_BLOCK_OPEN = '\uE102';
|
|
26
|
+
export const DETAILS_BLOCK_CLOSE = '\uE103';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The same, for a `diagram` block: a straight list of numbered steps with arrows and a colour per status word. Its payload is the
|
|
30
|
+
* clean `DiagramView` (below) as percent-encoded JSON, and the bubble draws it with a native component.
|
|
31
|
+
*/
|
|
32
|
+
export const DIAGRAM_BLOCK_OPEN = '\uE104';
|
|
33
|
+
export const DIAGRAM_BLOCK_CLOSE = '\uE105';
|
|
34
|
+
|
|
35
|
+
/** The same for the other visual kinds (the registry `VISUALS` below says which is which): chart, comparison, timeline. */
|
|
36
|
+
export const CHART_BLOCK_OPEN = '\uE106';
|
|
37
|
+
export const CHART_BLOCK_CLOSE = '\uE107';
|
|
38
|
+
export const COMPARISON_BLOCK_OPEN = '\uE108';
|
|
39
|
+
export const COMPARISON_BLOCK_CLOSE = '\uE109';
|
|
40
|
+
export const TIMELINE_BLOCK_OPEN = '\uE10A';
|
|
41
|
+
export const TIMELINE_BLOCK_CLOSE = '\uE10B';
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* A block's own text can hold one of the twelve sentinels (a glyph from an icon font, a paste). One inside a text would cut the
|
|
45
|
+
* message in the wrong place (a stray DETAILS mark would swallow the words before it into a closed row), so they are taken out of
|
|
46
|
+
* the text of a block. A table, a folded block and a visual carry their payload percent-encoded, which cannot hold one.
|
|
47
|
+
*/
|
|
48
|
+
const SENTINEL_CHARS = /[\uE100-\uE10B]/g;
|
|
49
|
+
const clean = (text: string): string => text.replace(SENTINEL_CHARS, '');
|
|
50
|
+
|
|
51
|
+
/** A block of a conversation turn, as /api/conversation serves it. */
|
|
52
|
+
export interface ConversationBlock {
|
|
53
|
+
kind: string;
|
|
54
|
+
content?: any;
|
|
55
|
+
language?: string;
|
|
56
|
+
meta?: { display?: string };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Render a `{ columns: [...], rows: [...] }` payload as a sentinel-wrapped JSON marker. Returns null if the shape doesn't match.
|
|
61
|
+
*/
|
|
62
|
+
function renderTableShape(content: any): string | null {
|
|
63
|
+
if (!content || typeof content !== 'object') return null;
|
|
64
|
+
const cols = Array.isArray(content.columns) ? content.columns : null;
|
|
65
|
+
const rows = Array.isArray(content.rows) ? content.rows : null;
|
|
66
|
+
if (!cols || !rows) return null;
|
|
67
|
+
// encodeURIComponent so the JSON can never contain newlines or sentinel chars.
|
|
68
|
+
const payload = encodeURIComponent(JSON.stringify({ columns: cols, rows }));
|
|
69
|
+
return `${TABLE_BLOCK_OPEN}${payload}${TABLE_BLOCK_CLOSE}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The status words a diagram step or badge may carry; none is neutral. The same four as Core's `DIAGRAM_STATUSES` (backend
|
|
74
|
+
* utils/blockShape.js) and the web's (apps/frontend chat/blocks/diagramView.js): a test on each side holds the list. Colours are
|
|
75
|
+
* this app's own; Core never sends one.
|
|
76
|
+
*/
|
|
77
|
+
export const DIAGRAM_STATUSES = ['ok', 'bad', 'warn', 'info'] as const;
|
|
78
|
+
export type DiagramStatus = (typeof DIAGRAM_STATUSES)[number];
|
|
79
|
+
|
|
80
|
+
export interface DiagramStep {
|
|
81
|
+
title: string;
|
|
82
|
+
text: string;
|
|
83
|
+
status: DiagramStatus | '';
|
|
84
|
+
badges: Array<{ text: string; status: DiagramStatus | '' }>;
|
|
85
|
+
/** A decision (a gate): drawn as a dashed card with a diamond number. */
|
|
86
|
+
decision: boolean;
|
|
87
|
+
/**
|
|
88
|
+
* The ways out of this step, `to` a 1-based step number. null = the natural arrow to the following step (a straight list is all
|
|
89
|
+
* null). [] = an end. Core settles them (backend `diagramOf`); this is the phone's net.
|
|
90
|
+
*/
|
|
91
|
+
next: Array<{ to: number; label: string }> | null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface DiagramView {
|
|
95
|
+
title: string;
|
|
96
|
+
steps: DiagramStep[];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const str = (v: any): string => (typeof v === 'string' ? v : typeof v === 'number' || typeof v === 'boolean' ? String(v) : '');
|
|
100
|
+
const statusOf = (v: any): DiagramStatus | '' => ((DIAGRAM_STATUSES as readonly string[]).includes(v) ? v : '');
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The diagram a block holds, ready to draw, every field text; null when there is nothing to draw (fewer than 2 steps). Core sends it
|
|
104
|
+
* clean (`diagramOf`); this is the phone's own net, so a field of the wrong type can never reach a native <Text>, and a way out that
|
|
105
|
+
* points at a step that is not there is dropped (the numbers follow the steps that remain).
|
|
106
|
+
*/
|
|
107
|
+
export function diagramView(content: any): DiagramView | null {
|
|
108
|
+
if (!content || typeof content !== 'object' || !Array.isArray(content.steps)) return null;
|
|
109
|
+
const steps: DiagramStep[] = [];
|
|
110
|
+
const kept: number[] = []; // original 1-based number -> new number (0 = dropped)
|
|
111
|
+
const rawNext: any[] = [];
|
|
112
|
+
content.steps.forEach((s: any, i: number) => {
|
|
113
|
+
kept[i + 1] = 0;
|
|
114
|
+
if (!s || typeof s !== 'object') return;
|
|
115
|
+
const title = str(s.title);
|
|
116
|
+
const text = str(s.text);
|
|
117
|
+
if (!title && !text) return;
|
|
118
|
+
const badges: DiagramStep['badges'] = [];
|
|
119
|
+
for (const b of Array.isArray(s.badges) ? s.badges : []) {
|
|
120
|
+
const bt = str(b && typeof b === 'object' ? b.text : b);
|
|
121
|
+
if (bt) badges.push({ text: bt, status: statusOf(b && b.status) });
|
|
122
|
+
}
|
|
123
|
+
steps.push({ title: title || text, text: title ? text : '', status: statusOf(s.status), badges, decision: s.kind === 'decision' || s.decision === true, next: null });
|
|
124
|
+
rawNext.push(Array.isArray(s.next) ? s.next : null);
|
|
125
|
+
kept[i + 1] = steps.length;
|
|
126
|
+
});
|
|
127
|
+
if (steps.length < 2) return null;
|
|
128
|
+
steps.forEach((st, i) => {
|
|
129
|
+
const raw = rawNext[i];
|
|
130
|
+
if (!raw) return;
|
|
131
|
+
const out: Array<{ to: number; label: string }> = [];
|
|
132
|
+
for (const e of raw) {
|
|
133
|
+
const to = e && typeof e === 'object' && Number.isInteger(e.to) ? kept[e.to] || 0 : 0;
|
|
134
|
+
if (!to || to === i + 1 || out.some(x => x.to === to) || out.length >= 3) continue;
|
|
135
|
+
out.push({ to, label: str(e.label).slice(0, 40) });
|
|
136
|
+
}
|
|
137
|
+
st.next = out;
|
|
138
|
+
});
|
|
139
|
+
return { title: str(content.title), steps };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Where each arrow of a step is drawn: the arrow down to the next step, the jumps ahead, the loops back. */
|
|
143
|
+
export interface DiagramFlow {
|
|
144
|
+
/** The arrow to the following step, with its label ('' = none); null = no arrow (this step does not flow into the next). */
|
|
145
|
+
arrow: { label: string } | null;
|
|
146
|
+
/** Ways out that skip ahead: drawn as a "Go to step N" pill under the step. */
|
|
147
|
+
jumps: Array<{ to: number; label: string }>;
|
|
148
|
+
/** Ways out that go back to an earlier step: drawn as a loop in the margin. */
|
|
149
|
+
loops: Array<{ to: number; label: string }>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The ONE layout rule for the phone and the web: natural arrow, forward jumps, back loops. */
|
|
153
|
+
export function diagramFlow(view: DiagramView): DiagramFlow[] {
|
|
154
|
+
const last = view.steps.length - 1;
|
|
155
|
+
return view.steps.map((st, i) => {
|
|
156
|
+
const flow: DiagramFlow = { arrow: null, jumps: [], loops: [] };
|
|
157
|
+
if (!st.next) {
|
|
158
|
+
if (i < last) flow.arrow = { label: '' };
|
|
159
|
+
return flow;
|
|
160
|
+
}
|
|
161
|
+
for (const e of st.next) {
|
|
162
|
+
if (e.to === i + 2) flow.arrow = { label: e.label };
|
|
163
|
+
else if (e.to > i + 2) flow.jumps.push(e);
|
|
164
|
+
else flow.loops.push(e);
|
|
165
|
+
}
|
|
166
|
+
return flow;
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A diagram as readable text, the same list Core gives other channels (backend `diagramToText`). */
|
|
171
|
+
export function diagramAsText(d: DiagramView): string {
|
|
172
|
+
const lines = d.title ? [d.title] : [];
|
|
173
|
+
d.steps.forEach((s, i) => {
|
|
174
|
+
const badges = s.badges.length ? ` [${s.badges.map(b => b.text).join(', ')}]` : '';
|
|
175
|
+
lines.push(`${i + 1}. ${s.title}${s.decision ? ' (decision)' : ''}${s.text ? ` — ${s.text}` : ''}${badges}`);
|
|
176
|
+
if (s.next) lines.push(s.next.length ? ` ${s.next.map(e => `${e.label ? `${e.label} ` : ''}→ ${e.to}`).join('; ')}` : ' (end)');
|
|
177
|
+
});
|
|
178
|
+
return lines.join('\n');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
// ---- chart, comparison, timeline: the phone's nets. Core sends each clean (backend utils/visuals/*.js, the one definition); these
|
|
183
|
+
// are the phone's own net, so a field of the wrong type can never reach a native <Text>. The same rules as the web's (apps/frontend
|
|
184
|
+
// chat/blocks/visualViews.js); each text form equals Core's, a test on each side holds them.
|
|
185
|
+
|
|
186
|
+
const num = (v: any): number | null => (typeof v === 'number' && Number.isFinite(v) && Math.abs(v) <= 1e15 ? v : null); // the same cap as Core: a span between two values can never overflow
|
|
187
|
+
const list = (v: any): any[] => (Array.isArray(v) ? v : []);
|
|
188
|
+
const obj = (v: any): any => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
|
|
189
|
+
/** How a number is written on a chart and in its text form: at most 2 decimals (0.1 + 0.2 is 0.3), the same as Core's text form. */
|
|
190
|
+
export const numText = (n: number): string => String(Math.round(n * 100) / 100);
|
|
191
|
+
|
|
192
|
+
export interface ChartSeries { name: string; values: number[] }
|
|
193
|
+
export interface ChartView {
|
|
194
|
+
title: string;
|
|
195
|
+
type: 'bar' | 'line';
|
|
196
|
+
labels: string[];
|
|
197
|
+
series: ChartSeries[];
|
|
198
|
+
unit: string;
|
|
199
|
+
/** One of the labels, or ''. */
|
|
200
|
+
highlight: string;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** The chart a block holds, ready to draw; null when there is nothing to draw (fewer than 2 points, or no readable series). */
|
|
204
|
+
export function chartView(content: any): ChartView | null {
|
|
205
|
+
const c = obj(content);
|
|
206
|
+
const labels = list(c.labels).map(str);
|
|
207
|
+
if (labels.length < 2) return null;
|
|
208
|
+
const series: ChartSeries[] = [];
|
|
209
|
+
for (const s of list(c.series)) {
|
|
210
|
+
const values = list(obj(s).values).slice(0, labels.length).map(num);
|
|
211
|
+
if (values.length === labels.length && values.every(v => v !== null)) series.push({ name: str(obj(s).name), values: values as number[] });
|
|
212
|
+
}
|
|
213
|
+
if (!series.length) return null;
|
|
214
|
+
const highlight = str(c.highlight);
|
|
215
|
+
return { title: str(c.title), type: c.type === 'line' ? 'line' : 'bar', labels, series, unit: str(c.unit), highlight: labels.includes(highlight) ? highlight : '' };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Where values sit between the baseline and the top: always spans zero, so a bar grows from a zero line; a flat chart still has a span. */
|
|
219
|
+
export function chartScale(view: ChartView): { lo: number; hi: number } {
|
|
220
|
+
const all = view.series.flatMap(s => s.values);
|
|
221
|
+
const lo = Math.min(0, ...all);
|
|
222
|
+
const hi = Math.max(0, ...all);
|
|
223
|
+
return { lo, hi: hi === lo ? lo + 1 : hi };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function chartAsText(view: ChartView): string {
|
|
227
|
+
const u = view.unit ? ` ${view.unit}` : '';
|
|
228
|
+
const lines = view.title ? [view.title] : [];
|
|
229
|
+
view.labels.forEach((l, i) => {
|
|
230
|
+
const cells = view.series.map(s => `${s.name ? `${s.name} ` : ''}${numText(s.values[i])}${u}`);
|
|
231
|
+
lines.push(`${l}: ${cells.join(', ')}${view.highlight === l ? ' (highlighted)' : ''}`);
|
|
232
|
+
});
|
|
233
|
+
return lines.join('\n');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export interface ComparisonRow { text: string; ok: boolean | null }
|
|
237
|
+
export interface ComparisonOption { name: string; price: string; badge: string; best: boolean; rows: ComparisonRow[] }
|
|
238
|
+
export interface ComparisonView { title: string; options: ComparisonOption[] }
|
|
239
|
+
|
|
240
|
+
/** The comparison a block holds (2 or 3 options, at most one best); null when there is nothing to draw. */
|
|
241
|
+
export function comparisonView(content: any): ComparisonView | null {
|
|
242
|
+
const c = obj(content);
|
|
243
|
+
const options: ComparisonOption[] = [];
|
|
244
|
+
for (const o of list(c.options)) {
|
|
245
|
+
const ob = obj(o);
|
|
246
|
+
const name = str(ob.name);
|
|
247
|
+
if (!name) continue;
|
|
248
|
+
const rows = list(ob.rows)
|
|
249
|
+
.map((r): ComparisonRow => ({ text: str(obj(r).text), ok: typeof obj(r).ok === 'boolean' ? obj(r).ok : null }))
|
|
250
|
+
.filter(r => r.text);
|
|
251
|
+
options.push({ name, price: str(ob.price), badge: str(ob.badge), best: ob.best === true, rows });
|
|
252
|
+
}
|
|
253
|
+
if (options.length < 2) return null;
|
|
254
|
+
const first = options.findIndex(o => o.best);
|
|
255
|
+
options.forEach((o, i) => { if (i !== first) o.best = false; });
|
|
256
|
+
return { title: str(c.title), options: options.slice(0, 3) };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function comparisonAsText(view: ComparisonView): string {
|
|
260
|
+
const lines = view.title ? [view.title] : [];
|
|
261
|
+
for (const o of view.options) {
|
|
262
|
+
lines.push(`${o.name}${o.price ? ` (${o.price})` : ''}${o.badge ? ` [${o.badge}]` : ''}${o.best ? ' (best)' : ''}`);
|
|
263
|
+
for (const r of o.rows) lines.push(` ${r.ok === true ? '+' : r.ok === false ? '-' : '·'} ${r.text}`);
|
|
264
|
+
}
|
|
265
|
+
return lines.join('\n');
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export interface TimelineEvent { time: string; text: string }
|
|
269
|
+
export interface TimelineDay { title: string; events: TimelineEvent[] }
|
|
270
|
+
export interface TimelineView { title: string; subtitle: string; days: TimelineDay[] }
|
|
271
|
+
|
|
272
|
+
/** The timeline a block holds; null when there is nothing to draw (fewer than 2 events in all). */
|
|
273
|
+
export function timelineView(content: any): TimelineView | null {
|
|
274
|
+
const c = obj(content);
|
|
275
|
+
const days = list(c.days)
|
|
276
|
+
.map((d): TimelineDay => ({
|
|
277
|
+
title: str(obj(d).title),
|
|
278
|
+
events: list(obj(d).events).map((e): TimelineEvent => ({ time: str(obj(e).time), text: str(obj(e).text) })).filter(e => e.text),
|
|
279
|
+
}))
|
|
280
|
+
.filter(d => d.title || d.events.length);
|
|
281
|
+
if (days.reduce((n, d) => n + d.events.length, 0) < 2) return null;
|
|
282
|
+
return { title: str(c.title), subtitle: str(c.subtitle), days };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function timelineAsText(view: TimelineView): string {
|
|
286
|
+
const lines: string[] = [];
|
|
287
|
+
if (view.title) lines.push(view.title);
|
|
288
|
+
if (view.subtitle) lines.push(view.subtitle);
|
|
289
|
+
for (const d of view.days) {
|
|
290
|
+
if (d.title) lines.push(d.title);
|
|
291
|
+
for (const e of d.events) lines.push(` ${e.time ? `${e.time} ` : ''}${e.text}`);
|
|
292
|
+
}
|
|
293
|
+
return lines.join('\n');
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The visual block kinds the phone draws, each between its own pair of sentinels. Same four as Core's `VISUALS` (backend utils/blockShape.js). */
|
|
297
|
+
export type VisualKind = 'diagram' | 'chart' | 'comparison' | 'timeline';
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* THE REGISTRY of visual kinds on the phone: for each, its sentinels, the net that reads the content into a clean view (null when
|
|
301
|
+
* there is nothing to draw), and the view's text form (what copy and a screen reader are given). A new kind is one more entry here,
|
|
302
|
+
* one component in the UI package (`VISUAL_BLOCKS`), and one in Core; nothing else names a visual.
|
|
303
|
+
*/
|
|
304
|
+
export const VISUALS: Record<VisualKind, { open: string; close: string; view: (content: any) => any | null; asText: (view: any) => string }> = {
|
|
305
|
+
diagram: { open: DIAGRAM_BLOCK_OPEN, close: DIAGRAM_BLOCK_CLOSE, view: diagramView, asText: diagramAsText },
|
|
306
|
+
chart: { open: CHART_BLOCK_OPEN, close: CHART_BLOCK_CLOSE, view: chartView, asText: chartAsText },
|
|
307
|
+
comparison: { open: COMPARISON_BLOCK_OPEN, close: COMPARISON_BLOCK_CLOSE, view: comparisonView, asText: comparisonAsText },
|
|
308
|
+
timeline: { open: TIMELINE_BLOCK_OPEN, close: TIMELINE_BLOCK_CLOSE, view: timelineView, asText: timelineAsText },
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
/** Whether a block kind is a visual the phone knows. */
|
|
312
|
+
export const isVisualKind = (kind: any): kind is VisualKind => typeof kind === 'string' && Object.prototype.hasOwnProperty.call(VISUALS, kind);
|
|
313
|
+
|
|
314
|
+
/** The clean view inside a visual segment's payload (still percent-encoded, as `splitBlockSegments` gives it), or null when it cannot be read. */
|
|
315
|
+
export function visualViewOf(kind: VisualKind, payload: string): any | null {
|
|
316
|
+
try { return VISUALS[kind].view(JSON.parse(decodeURIComponent(payload))); } catch { return null; }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** A markdown fence around `code`, long enough that a run of backticks inside the code cannot close it early. */
|
|
320
|
+
function fence(code: string, language: string): string {
|
|
321
|
+
const longest = (code.match(/`+/g) || []).reduce((n, run) => Math.max(n, run.length), 0);
|
|
322
|
+
const ticks = '`'.repeat(Math.max(3, longest + 1));
|
|
323
|
+
return `${ticks}${language}\n${code}\n${ticks}`;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** The text of one block, before any "folded" wrapping. Empty when the block holds nothing to draw. */
|
|
327
|
+
function blockText(b: ConversationBlock): string {
|
|
328
|
+
if (b.kind === 'text' || b.kind === 'markdown' || b.kind === 'description') {
|
|
329
|
+
return typeof b.content === 'string' ? clean(b.content) : '';
|
|
330
|
+
}
|
|
331
|
+
if (b.kind === 'code') {
|
|
332
|
+
// Core sends { kind: 'code', content: { content: '...', language: '...' } }; a flat string with a `language` also reads.
|
|
333
|
+
const nested = b.content && typeof b.content === 'object';
|
|
334
|
+
const code = nested ? b.content.content : b.content;
|
|
335
|
+
if (typeof code !== 'string' || !code.trim()) return '';
|
|
336
|
+
const lang = clean(String((nested ? b.content.language : b.language) || '').trim());
|
|
337
|
+
return fence(clean(code), lang && lang.toLowerCase() !== 'auto' ? lang : '');
|
|
338
|
+
}
|
|
339
|
+
if (b.kind === 'table' && b.content && typeof b.content === 'object') {
|
|
340
|
+
const md = renderTableShape(b.content);
|
|
341
|
+
if (md) return md;
|
|
342
|
+
// Fall through to generic JSON rendering if shape is unexpected.
|
|
343
|
+
}
|
|
344
|
+
if (isVisualKind(b.kind)) {
|
|
345
|
+
const v = VISUALS[b.kind];
|
|
346
|
+
const view = v.view(b.content);
|
|
347
|
+
if (view) return `${v.open}${encodeURIComponent(JSON.stringify(view))}${v.close}`;
|
|
348
|
+
// Not a visual the phone can draw: fall through to the generic text below, never a lost block.
|
|
349
|
+
}
|
|
350
|
+
if (b.kind === 'json') {
|
|
351
|
+
// Polisher sometimes wraps tables as kind:'json' when the content has columns/rows — render those as table blocks too.
|
|
352
|
+
const md = renderTableShape(b.content);
|
|
353
|
+
if (md) return md;
|
|
354
|
+
const pretty = JSON.stringify(b.content, null, 2); // undefined when there is nothing to write
|
|
355
|
+
return typeof pretty === 'string' ? fence(clean(pretty), 'json') : '';
|
|
356
|
+
}
|
|
357
|
+
if (b.kind === 'html') {
|
|
358
|
+
return typeof b.content === 'string' ? clean(b.content) : '';
|
|
359
|
+
}
|
|
360
|
+
if (typeof b.content === 'string') return clean(b.content);
|
|
361
|
+
return b.content === undefined ? '' : clean(JSON.stringify(b.content) ?? '');
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Extract display text from a conversation turn's blocks. Handles multiple block kinds (text, code, json, markdown, table, html).
|
|
366
|
+
* Every block that holds something is in the result, in order; a block Core marked `meta.display: "folded"` is wrapped in the
|
|
367
|
+
* DETAILS sentinels so the bubble draws it closed.
|
|
368
|
+
*/
|
|
369
|
+
export function blocksToText(blocks?: ConversationBlock[]): string {
|
|
370
|
+
if (!blocks || blocks.length === 0) return '';
|
|
371
|
+
return blocks.map(b => {
|
|
372
|
+
if (!b || typeof b !== 'object') return '';
|
|
373
|
+
const text = blockText(b);
|
|
374
|
+
if (!text) return '';
|
|
375
|
+
// A table or a visual is drawn as itself whatever the mark says (Core never marks one; either inside a closed row would show as characters).
|
|
376
|
+
if (text.startsWith(TABLE_BLOCK_OPEN) || Object.values(VISUALS).some(v => text.startsWith(v.open))) return text;
|
|
377
|
+
return b.meta?.display === 'folded'
|
|
378
|
+
? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text)}${DETAILS_BLOCK_CLOSE}`
|
|
379
|
+
: text;
|
|
380
|
+
}).filter(Boolean).join('\n\n');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** One piece of a flat message string, as the bubble draws it: markdown, a table payload, a visual payload, or a closed "Details" payload. */
|
|
384
|
+
export interface BlockSegment {
|
|
385
|
+
kind: 'md' | 'table' | 'details' | VisualKind;
|
|
386
|
+
/** md: the markdown. table / details / a visual: the still percent-encoded payload between the sentinels. */
|
|
387
|
+
content: string;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const PAIRS: Array<{ kind: BlockSegment['kind']; open: string; close: string }> = [
|
|
391
|
+
{ kind: 'table', open: TABLE_BLOCK_OPEN, close: TABLE_BLOCK_CLOSE },
|
|
392
|
+
{ kind: 'details', open: DETAILS_BLOCK_OPEN, close: DETAILS_BLOCK_CLOSE },
|
|
393
|
+
...(Object.keys(VISUALS) as VisualKind[]).map(kind => ({ kind, open: VISUALS[kind].open, close: VISUALS[kind].close })),
|
|
394
|
+
];
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Split a flat message string on the table, details and visual sentinels, in order. A string with none is one markdown segment. An
|
|
398
|
+
* unterminated marker is kept as markdown from the marker on, so nothing is lost.
|
|
399
|
+
*/
|
|
400
|
+
export function splitBlockSegments(content: string): BlockSegment[] {
|
|
401
|
+
const segments: BlockSegment[] = [];
|
|
402
|
+
if (!content) return segments;
|
|
403
|
+
let cursor = 0;
|
|
404
|
+
while (cursor < content.length) {
|
|
405
|
+
let found: { index: number; pair: (typeof PAIRS)[number] } | null = null;
|
|
406
|
+
for (const pair of PAIRS) {
|
|
407
|
+
const index = content.indexOf(pair.open, cursor);
|
|
408
|
+
if (index !== -1 && (!found || index < found.index)) found = { index, pair };
|
|
409
|
+
}
|
|
410
|
+
if (!found) {
|
|
411
|
+
segments.push({ kind: 'md', content: content.slice(cursor) });
|
|
412
|
+
break;
|
|
413
|
+
}
|
|
414
|
+
if (found.index > cursor) {
|
|
415
|
+
segments.push({ kind: 'md', content: content.slice(cursor, found.index) });
|
|
416
|
+
}
|
|
417
|
+
const close = content.indexOf(found.pair.close, found.index + found.pair.open.length);
|
|
418
|
+
if (close === -1) {
|
|
419
|
+
// Unterminated marker — keep the rest as markdown so we don't lose data.
|
|
420
|
+
segments.push({ kind: 'md', content: content.slice(found.index) });
|
|
421
|
+
break;
|
|
422
|
+
}
|
|
423
|
+
segments.push({ kind: found.pair.kind, content: content.slice(found.index + found.pair.open.length, close) });
|
|
424
|
+
cursor = close + found.pair.close.length;
|
|
425
|
+
}
|
|
426
|
+
return segments;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** A table payload as readable text: its columns, then one line per row, cells separated by " | ". */
|
|
430
|
+
function tableAsText(payload: string): string {
|
|
431
|
+
try {
|
|
432
|
+
const data = JSON.parse(decodeURIComponent(payload));
|
|
433
|
+
const cols: any[] = Array.isArray(data?.columns) ? data.columns : [];
|
|
434
|
+
const rows: any[] = Array.isArray(data?.rows) ? data.rows : [];
|
|
435
|
+
const cell = (v: any) => (v == null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v));
|
|
436
|
+
const line = (cells: any) => (Array.isArray(cells) ? cells : [cells]).map(cell).join(' | ');
|
|
437
|
+
return [line(cols), ...rows.map(line)].join('\n');
|
|
438
|
+
} catch {
|
|
439
|
+
return '';
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* The flat content of a message as the person would read it: a table is its columns and rows as lines, and a "Details" payload is
|
|
445
|
+
* its text. What long-press copy and a screen reader are given; the raw string holds percent-encoded payloads between private-use
|
|
446
|
+
* characters, which nobody should hear or paste.
|
|
447
|
+
*/
|
|
448
|
+
export function plainTextOf(content: string): string {
|
|
449
|
+
if (!content) return '';
|
|
450
|
+
return splitBlockSegments(content).map(seg => {
|
|
451
|
+
if (seg.kind === 'md') return seg.content;
|
|
452
|
+
if (seg.kind === 'table') return tableAsText(seg.content);
|
|
453
|
+
if (isVisualKind(seg.kind)) {
|
|
454
|
+
const view = visualViewOf(seg.kind, seg.content);
|
|
455
|
+
return view ? VISUALS[seg.kind].asText(view) : '';
|
|
456
|
+
}
|
|
457
|
+
try { return decodeURIComponent(seg.content); } catch { return seg.content; }
|
|
458
|
+
}).join('');
|
|
459
|
+
}
|
package/src/chat/store.ts
CHANGED
|
@@ -17,6 +17,7 @@ import { pluginCommandEmitter } from '../utils/emitter';
|
|
|
17
17
|
import { focusPlugin } from '../utils/hostIntents';
|
|
18
18
|
import type { OutgoingAttachment } from '../storage/types';
|
|
19
19
|
import { prepareAttachments } from './attachments';
|
|
20
|
+
import { blocksToText } from './blockText';
|
|
20
21
|
import type { Message, MessageAttachment, JobProgress, UIAction } from './types';
|
|
21
22
|
|
|
22
23
|
// ---------------------------------------------------------------------------
|
|
@@ -152,76 +153,6 @@ function isTerminalSnapshot(snap: any): boolean {
|
|
|
152
153
|
return snap?.done === true || isTerminalStatus(snap?.status);
|
|
153
154
|
}
|
|
154
155
|
|
|
155
|
-
/**
|
|
156
|
-
* Sentinel delimiters used to embed structured table data inside a flat
|
|
157
|
-
* message string. UI layers split on these and render the contents with a
|
|
158
|
-
* native table component instead of markdown tables — markdown tables look
|
|
159
|
-
* terrible on narrow phone screens.
|
|
160
|
-
*
|
|
161
|
-
* Unicode Private Use Area chars (U+E100/U+E101) so they never collide with
|
|
162
|
-
* anything the model could legitimately emit.
|
|
163
|
-
*/
|
|
164
|
-
export const TABLE_BLOCK_OPEN = '\uE100';
|
|
165
|
-
export const TABLE_BLOCK_CLOSE = '\uE101';
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* Render a `{ columns: [...], rows: [...] }` payload as a sentinel-wrapped
|
|
169
|
-
* JSON marker. Returns null if the shape doesn't match.
|
|
170
|
-
*/
|
|
171
|
-
function renderTableShape(content: any): string | null {
|
|
172
|
-
if (!content || typeof content !== 'object') return null;
|
|
173
|
-
const cols = Array.isArray(content.columns) ? content.columns : null;
|
|
174
|
-
const rows = Array.isArray(content.rows) ? content.rows : null;
|
|
175
|
-
if (!cols || !rows) return null;
|
|
176
|
-
// encodeURIComponent so the JSON can never contain newlines or sentinel chars.
|
|
177
|
-
const payload = encodeURIComponent(JSON.stringify({ columns: cols, rows }));
|
|
178
|
-
return `${TABLE_BLOCK_OPEN}${payload}${TABLE_BLOCK_CLOSE}`;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
/**
|
|
182
|
-
* Extract display text from a conversation turn's assistant blocks.
|
|
183
|
-
* Handles multiple block kinds (text, code, json, markdown, table, html).
|
|
184
|
-
*/
|
|
185
|
-
export function blocksToText(blocks?: Array<{ kind: string; content: any }>): string {
|
|
186
|
-
if (!blocks || blocks.length === 0) return '';
|
|
187
|
-
// Mirror the web renderer: when a human-readable text/markdown block exists in
|
|
188
|
-
// the same turn, drop internal-state json/code blocks (planning state,
|
|
189
|
-
// askUser payloads) — otherwise they render as a raw ```json blob AFTER the
|
|
190
|
-
// real answer. Standalone json/code (no text block, e.g. a table-only turn)
|
|
191
|
-
// still renders as before.
|
|
192
|
-
const hasTextBlock = blocks.some(
|
|
193
|
-
b => b.kind === 'text' || b.kind === 'markdown' || b.kind === 'description',
|
|
194
|
-
);
|
|
195
|
-
return blocks.map(b => {
|
|
196
|
-
if ((b.kind === 'json' || b.kind === 'code') && hasTextBlock) return '';
|
|
197
|
-
if (b.kind === 'text' || b.kind === 'markdown' || b.kind === 'description') {
|
|
198
|
-
return typeof b.content === 'string' ? b.content : '';
|
|
199
|
-
}
|
|
200
|
-
if (b.kind === 'code') {
|
|
201
|
-
const code = typeof b.content === 'object' ? b.content.content : b.content;
|
|
202
|
-
return `\`\`\`\n${code}\n\`\`\``;
|
|
203
|
-
}
|
|
204
|
-
if (b.kind === 'table' && b.content && typeof b.content === 'object') {
|
|
205
|
-
const md = renderTableShape(b.content);
|
|
206
|
-
if (md) return md;
|
|
207
|
-
// Fall through to generic JSON rendering if shape is unexpected.
|
|
208
|
-
}
|
|
209
|
-
if (b.kind === 'json') {
|
|
210
|
-
// Skip pendingQuestion state objects — internal sys.askUser data
|
|
211
|
-
if (b.content && typeof b.content === 'object' && 'pendingQuestion' in b.content) return '';
|
|
212
|
-
// Polisher sometimes wraps tables as kind:'json' when the content has
|
|
213
|
-
// columns/rows — render those as table blocks too.
|
|
214
|
-
const md = renderTableShape(b.content);
|
|
215
|
-
if (md) return md;
|
|
216
|
-
return '```json\n' + JSON.stringify(b.content, null, 2) + '\n```';
|
|
217
|
-
}
|
|
218
|
-
if (b.kind === 'html') {
|
|
219
|
-
return typeof b.content === 'string' ? b.content : '';
|
|
220
|
-
}
|
|
221
|
-
return typeof b.content === 'string' ? b.content : JSON.stringify(b.content);
|
|
222
|
-
}).filter(Boolean).join('\n\n');
|
|
223
|
-
}
|
|
224
|
-
|
|
225
156
|
/** Extract image/file attachments from conversation blocks */
|
|
226
157
|
function blocksToAttachments(blocks?: Array<{ kind: string; hash?: string; url?: string; mimeType?: string; name?: string }>): MessageAttachment[] | undefined {
|
|
227
158
|
if (!blocks || blocks.length === 0) return undefined;
|
package/src/index.ts
CHANGED
|
@@ -146,10 +146,51 @@ export {
|
|
|
146
146
|
setClientDeclarationProvider,
|
|
147
147
|
useChatStore,
|
|
148
148
|
closeChatStream,
|
|
149
|
+
} from './chat/store';
|
|
150
|
+
export {
|
|
149
151
|
blocksToText,
|
|
152
|
+
splitBlockSegments,
|
|
153
|
+
plainTextOf,
|
|
150
154
|
TABLE_BLOCK_OPEN,
|
|
151
155
|
TABLE_BLOCK_CLOSE,
|
|
152
|
-
|
|
156
|
+
DETAILS_BLOCK_OPEN,
|
|
157
|
+
DETAILS_BLOCK_CLOSE,
|
|
158
|
+
DIAGRAM_BLOCK_OPEN,
|
|
159
|
+
DIAGRAM_BLOCK_CLOSE,
|
|
160
|
+
DIAGRAM_STATUSES,
|
|
161
|
+
diagramView,
|
|
162
|
+
diagramAsText,
|
|
163
|
+
diagramFlow,
|
|
164
|
+
chartView,
|
|
165
|
+
chartScale,
|
|
166
|
+
chartAsText,
|
|
167
|
+
numText,
|
|
168
|
+
comparisonView,
|
|
169
|
+
comparisonAsText,
|
|
170
|
+
timelineView,
|
|
171
|
+
timelineAsText,
|
|
172
|
+
VISUALS,
|
|
173
|
+
isVisualKind,
|
|
174
|
+
visualViewOf,
|
|
175
|
+
CHART_BLOCK_OPEN,
|
|
176
|
+
CHART_BLOCK_CLOSE,
|
|
177
|
+
COMPARISON_BLOCK_OPEN,
|
|
178
|
+
COMPARISON_BLOCK_CLOSE,
|
|
179
|
+
TIMELINE_BLOCK_OPEN,
|
|
180
|
+
TIMELINE_BLOCK_CLOSE,
|
|
181
|
+
} from './chat/blockText';
|
|
182
|
+
export type { ConversationBlock, BlockSegment, DiagramView, DiagramStep, DiagramFlow, DiagramStatus, VisualKind } from './chat/blockText';
|
|
183
|
+
|
|
184
|
+
export type {
|
|
185
|
+
ChartView,
|
|
186
|
+
ChartSeries,
|
|
187
|
+
ComparisonView,
|
|
188
|
+
ComparisonOption,
|
|
189
|
+
ComparisonRow,
|
|
190
|
+
TimelineView,
|
|
191
|
+
TimelineDay,
|
|
192
|
+
TimelineEvent,
|
|
193
|
+
} from './chat/blockText';
|
|
153
194
|
export type {
|
|
154
195
|
Message,
|
|
155
196
|
MessageAttachment,
|