@ateam-ai-mobile/core 0.1.35 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ateam-ai-mobile/core",
3
- "version": "0.1.35",
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",
@@ -32,12 +32,20 @@ export const DETAILS_BLOCK_CLOSE = '\uE103';
32
32
  export const DIAGRAM_BLOCK_OPEN = '\uE104';
33
33
  export const DIAGRAM_BLOCK_CLOSE = '\uE105';
34
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
+
35
43
  /**
36
- * A block's own text can hold one of the six sentinels (a glyph from an icon font, a paste). One inside a text would cut the
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
37
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
38
- * the text of a block. A table, a folded block and a diagram carry their payload percent-encoded, which cannot hold one.
46
+ * the text of a block. A table, a folded block and a visual carry their payload percent-encoded, which cannot hold one.
39
47
  */
40
- const SENTINEL_CHARS = /[\uE100-\uE105]/g;
48
+ const SENTINEL_CHARS = /[\uE100-\uE10B]/g;
41
49
  const clean = (text: string): string => text.replace(SENTINEL_CHARS, '');
42
50
 
43
51
  /** A block of a conversation turn, as /api/conversation serves it. */
@@ -69,9 +77,23 @@ function renderTableShape(content: any): string | null {
69
77
  export const DIAGRAM_STATUSES = ['ok', 'bad', 'warn', 'info'] as const;
70
78
  export type DiagramStatus = (typeof DIAGRAM_STATUSES)[number];
71
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
+
72
94
  export interface DiagramView {
73
95
  title: string;
74
- steps: Array<{ title: string; text: string; status: DiagramStatus | ''; badges: Array<{ text: string; status: DiagramStatus | '' }> }>;
96
+ steps: DiagramStep[];
75
97
  }
76
98
 
77
99
  const str = (v: any): string => (typeof v === 'string' ? v : typeof v === 'number' || typeof v === 'boolean' ? String(v) : '');
@@ -79,36 +101,221 @@ const statusOf = (v: any): DiagramStatus | '' => ((DIAGRAM_STATUSES as readonly
79
101
 
80
102
  /**
81
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
82
- * clean (`diagramOf`); this is the phone's own net, so a field of the wrong type can never reach a native <Text>.
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).
83
106
  */
84
107
  export function diagramView(content: any): DiagramView | null {
85
108
  if (!content || typeof content !== 'object' || !Array.isArray(content.steps)) return null;
86
- const steps: DiagramView['steps'] = [];
87
- for (const s of content.steps) {
88
- if (!s || typeof s !== 'object') continue;
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;
89
115
  const title = str(s.title);
90
116
  const text = str(s.text);
91
- if (!title && !text) continue;
92
- const badges: DiagramView['steps'][number]['badges'] = [];
117
+ if (!title && !text) return;
118
+ const badges: DiagramStep['badges'] = [];
93
119
  for (const b of Array.isArray(s.badges) ? s.badges : []) {
94
120
  const bt = str(b && typeof b === 'object' ? b.text : b);
95
121
  if (bt) badges.push({ text: bt, status: statusOf(b && b.status) });
96
122
  }
97
- steps.push({ title: title || text, text: title ? text : '', status: statusOf(s.status), badges });
98
- }
99
- return steps.length < 2 ? null : { title: str(content.title), steps };
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
+ });
100
168
  }
101
169
 
102
- /** A diagram as readable text, the same numbered list Core gives other channels (backend `diagramToText`). */
170
+ /** A diagram as readable text, the same list Core gives other channels (backend `diagramToText`). */
103
171
  export function diagramAsText(d: DiagramView): string {
104
172
  const lines = d.title ? [d.title] : [];
105
173
  d.steps.forEach((s, i) => {
106
174
  const badges = s.badges.length ? ` [${s.badges.map(b => b.text).join(', ')}]` : '';
107
- lines.push(`${i + 1}. ${s.title}${s.text ? ` — ${s.text}` : ''}${badges}`);
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)' : ''}`);
108
232
  });
109
233
  return lines.join('\n');
110
234
  }
111
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
+
112
319
  /** A markdown fence around `code`, long enough that a run of backticks inside the code cannot close it early. */
113
320
  function fence(code: string, language: string): string {
114
321
  const longest = (code.match(/`+/g) || []).reduce((n, run) => Math.max(n, run.length), 0);
@@ -134,10 +341,11 @@ function blockText(b: ConversationBlock): string {
134
341
  if (md) return md;
135
342
  // Fall through to generic JSON rendering if shape is unexpected.
136
343
  }
137
- if (b.kind === 'diagram') {
138
- const view = diagramView(b.content);
139
- if (view) return `${DIAGRAM_BLOCK_OPEN}${encodeURIComponent(JSON.stringify(view))}${DIAGRAM_BLOCK_CLOSE}`;
140
- // Not a diagram the phone can draw: fall through to the generic text below, never a lost block.
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.
141
349
  }
142
350
  if (b.kind === 'json') {
143
351
  // Polisher sometimes wraps tables as kind:'json' when the content has columns/rows — render those as table blocks too.
@@ -164,29 +372,29 @@ export function blocksToText(blocks?: ConversationBlock[]): string {
164
372
  if (!b || typeof b !== 'object') return '';
165
373
  const text = blockText(b);
166
374
  if (!text) return '';
167
- // A table or a diagram is drawn as itself whatever the mark says (Core never marks one; either inside a closed row would show as characters).
168
- if (text.startsWith(TABLE_BLOCK_OPEN) || text.startsWith(DIAGRAM_BLOCK_OPEN)) return text;
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;
169
377
  return b.meta?.display === 'folded'
170
378
  ? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text)}${DETAILS_BLOCK_CLOSE}`
171
379
  : text;
172
380
  }).filter(Boolean).join('\n\n');
173
381
  }
174
382
 
175
- /** One piece of a flat message string, as the bubble draws it: markdown, a table payload, a diagram payload, or a closed "Details" payload. */
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. */
176
384
  export interface BlockSegment {
177
- kind: 'md' | 'table' | 'details' | 'diagram';
178
- /** md: the markdown. table / details / diagram: the still percent-encoded payload between the sentinels. */
385
+ kind: 'md' | 'table' | 'details' | VisualKind;
386
+ /** md: the markdown. table / details / a visual: the still percent-encoded payload between the sentinels. */
179
387
  content: string;
180
388
  }
181
389
 
182
- const PAIRS: Array<{ kind: 'table' | 'details' | 'diagram'; open: string; close: string }> = [
390
+ const PAIRS: Array<{ kind: BlockSegment['kind']; open: string; close: string }> = [
183
391
  { kind: 'table', open: TABLE_BLOCK_OPEN, close: TABLE_BLOCK_CLOSE },
184
392
  { kind: 'details', open: DETAILS_BLOCK_OPEN, close: DETAILS_BLOCK_CLOSE },
185
- { kind: 'diagram', open: DIAGRAM_BLOCK_OPEN, close: DIAGRAM_BLOCK_CLOSE },
393
+ ...(Object.keys(VISUALS) as VisualKind[]).map(kind => ({ kind, open: VISUALS[kind].open, close: VISUALS[kind].close })),
186
394
  ];
187
395
 
188
396
  /**
189
- * Split a flat message string on the table, details and diagram sentinels, in order. A string with none is one markdown segment. An
397
+ * Split a flat message string on the table, details and visual sentinels, in order. A string with none is one markdown segment. An
190
398
  * unterminated marker is kept as markdown from the marker on, so nothing is lost.
191
399
  */
192
400
  export function splitBlockSegments(content: string): BlockSegment[] {
@@ -242,11 +450,9 @@ export function plainTextOf(content: string): string {
242
450
  return splitBlockSegments(content).map(seg => {
243
451
  if (seg.kind === 'md') return seg.content;
244
452
  if (seg.kind === 'table') return tableAsText(seg.content);
245
- if (seg.kind === 'diagram') {
246
- try {
247
- const view = diagramView(JSON.parse(decodeURIComponent(seg.content)));
248
- return view ? diagramAsText(view) : '';
249
- } catch { return ''; }
453
+ if (isVisualKind(seg.kind)) {
454
+ const view = visualViewOf(seg.kind, seg.content);
455
+ return view ? VISUALS[seg.kind].asText(view) : '';
250
456
  }
251
457
  try { return decodeURIComponent(seg.content); } catch { return seg.content; }
252
458
  }).join('');
package/src/index.ts CHANGED
@@ -160,8 +160,37 @@ export {
160
160
  DIAGRAM_STATUSES,
161
161
  diagramView,
162
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,
163
193
  } from './chat/blockText';
164
- export type { ConversationBlock, BlockSegment, DiagramView, DiagramStatus } from './chat/blockText';
165
194
  export type {
166
195
  Message,
167
196
  MessageAttachment,