@opengeni/react-native 6.39.1-canary.45627434309001 → 6.40.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/react-native",
3
- "version": "6.39.1-canary.45627434309001",
3
+ "version": "6.40.0",
4
4
  "description": "React Native and Expo kit for Opengeni agents: the native session timeline, composer adapters, voice dictation, and realtime voice calls (CallKit) on the same SDK controllers as the web.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -76,9 +76,9 @@
76
76
  "prepublishOnly": "bash ../../scripts/prepublish-guard"
77
77
  },
78
78
  "dependencies": {
79
- "@opengeni/contracts": "6.39.1-canary.45627434309001",
80
- "@opengeni/react": "6.39.1-canary.45627434309001",
81
- "@opengeni/sdk": "6.39.1-canary.45627434309001",
79
+ "@opengeni/contracts": "6.40.0",
80
+ "@opengeni/react": "6.40.0",
81
+ "@opengeni/sdk": "6.40.0",
82
82
  "thinking-orbs": "^0.3.1"
83
83
  },
84
84
  "peerDependencies": {
@@ -109,6 +109,5 @@
109
109
  "react-native-webview": {
110
110
  "optional": true
111
111
  }
112
- },
113
- "gitHead": "8a8579aabc65881774d197b51997e7eda7011c76"
112
+ }
114
113
  }
@@ -1,19 +1,344 @@
1
- import { prepareMathMarkdown } from "@opengeni/react/markdown-math";
1
+ import {
2
+ displayMathRanges,
3
+ prepareMathMarkdown,
4
+ type PreparedMathMarkdown,
5
+ } from "@opengeni/react/markdown-math";
2
6
 
3
- // About 1,300 words: ordinary replies keep formatting; long reports/logs must
4
- // not make synchronous Markdown, math or preview parsing grow without bound.
5
- export const MAX_MARKDOWN_LENGTH = 8_192;
7
+ /*
8
+ * Bounds for drawing assistant Markdown in the native timeline.
9
+ *
10
+ * One Markdown parse never sees more than MAX_MARKDOWN_CHUNK_LENGTH UTF-16 code units
11
+ * (about 1,300 words, after math normalization). A longer message is cut into chunks
12
+ * where markdown-it's own block parser starts a top-level block (display math counted
13
+ * as one block, as the math parser draws it), and each chunk is prepared and parsed on
14
+ * its own: every chunk parses to the blocks a single parse would give, the inline work grows linearly with the message, and
15
+ * crafted input can never cost more than one bounded parse per chunk. The block pass over
16
+ * the whole message is linear; while a message streams, only its last blocks are
17
+ * block-parsed again, and chunks whose text did not change are not prepared or parsed.
18
+ *
19
+ * In a long message, a top-level code fence too long to share a chunk is its own unit,
20
+ * drawn directly (code block, interactive preview or interactive answer) without
21
+ * Markdown, so an `opengeni-html` visual of any length still renders. Smaller fences
22
+ * stay in their chunk and render through Markdown's fence rule, which draws them the
23
+ * same way.
24
+ *
25
+ * A long message is mounted a bounded slice at a time (mountedSegmentCount), one slice
26
+ * per frame, so no frame parses or mounts more than about one chunk of Markdown (the
27
+ * linear block pass aside). A code
28
+ * block longer than one chunk is shown as plain-text pages; a large preview loads in its
29
+ * own web view.
30
+ *
31
+ * A message longer than MAX_MARKDOWN_LENGTH, and a single text block longer than one
32
+ * chunk (one giant paragraph), are shown as selectable plain-text pages instead.
33
+ */
6
34
 
7
- export function prepareBoundedMarkdown(text: string) {
8
- if (text.length > MAX_MARKDOWN_LENGTH) return null;
35
+ /** The most text one Markdown parse sees. */
36
+ export const MAX_MARKDOWN_CHUNK_LENGTH = 8_192;
37
+ /** The longest message drawn with formatting (about 10,000 words). */
38
+ export const MAX_MARKDOWN_LENGTH = 65_536;
39
+ /** Chunks are packed up to this size, leaving room for math normalization to expand. */
40
+ const CHUNK_TARGET_LENGTH = MAX_MARKDOWN_CHUNK_LENGTH / 2;
41
+
42
+ /** Math-normalized Markdown that fits one bounded parse, or null. */
43
+ export function prepareBoundedMarkdown(text: string): PreparedMathMarkdown | null {
44
+ if (text.length > MAX_MARKDOWN_CHUNK_LENGTH) return null;
9
45
  const prepared = prepareMathMarkdown(text);
10
46
  // Math delimiter normalization can expand otherwise in-budget input.
11
- return prepared.text.length <= MAX_MARKDOWN_LENGTH ? prepared : null;
47
+ return prepared.text.length <= MAX_MARKDOWN_CHUNK_LENGTH ? prepared : null;
48
+ }
49
+
50
+ export type MarkdownSegment =
51
+ /** At most one chunk of Markdown (a parse after math normalization, or plain pages). */
52
+ | { kind: "markdown"; source: string }
53
+ /** A top-level code fence, drawn without Markdown. `closed` is false while it streams. */
54
+ | { kind: "fence"; source: string; language: string; content: string; closed: boolean }
55
+ /** A block too long for one parse, shown as plain-text pages. */
56
+ | { kind: "plain"; source: string };
57
+
58
+ /** A source line without its ending. Lines end as markdown-it reads them: LF, CRLF or CR. */
59
+ type Line = { start: number; end: number; text: string };
60
+
61
+ function linesOf(text: string): Line[] {
62
+ const lines: Line[] = [];
63
+ const ending = /\r\n?|\n/g;
64
+ let start = 0;
65
+ while (start < text.length) {
66
+ ending.lastIndex = start;
67
+ const match = ending.exec(text);
68
+ const stop = match ? match.index : text.length;
69
+ const end = match ? stop + match[0].length : text.length;
70
+ lines.push({ start, end, text: text.slice(start, stop) });
71
+ start = end;
72
+ }
73
+ return lines;
74
+ }
75
+
76
+ /** The fields of a markdown-it block token the segmenter reads. */
77
+ type BlockToken = {
78
+ type: string;
79
+ level: number;
80
+ nesting: number;
81
+ map: [number, number] | null;
82
+ info: string;
83
+ content: string;
84
+ markup: string;
85
+ };
86
+
87
+ const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
88
+
89
+ /** A markdown-it instance: the parser whose block structure the cuts follow. */
90
+ export type MarkdownBlockParser = {
91
+ block: { parse(src: string, md: never, env: object, tokens: BlockToken[]): void };
92
+ };
93
+
94
+ /** A top-level block as markdown-it parsed it, by line. */
95
+ type Unit = {
96
+ line: number;
97
+ fence: { language: string; content: string; closed: boolean } | null;
98
+ /** The lines where the items of a top-level list start. */
99
+ items: number[] | null;
100
+ };
101
+
102
+ /** Top-level blocks of `lines[from…]`, by markdown-it's own block parser. */
103
+ function unitsOf(
104
+ parser: MarkdownBlockParser,
105
+ lines: Line[],
106
+ mathEnds: Int32Array,
107
+ from: number,
108
+ ): Unit[] {
109
+ const tokens: BlockToken[] = [];
110
+ // As markdown-it's normalization reads it (line endings are already split).
111
+ const src = lines
112
+ .slice(from)
113
+ .map((line) => line.text)
114
+ .join("\n")
115
+ .replaceAll("\0", "\uFFFD");
116
+ const env: MathRangeEnv = { mathRangeEnds: mathEnds, mathRangeOffset: from };
117
+ parser.block.parse(src, parser as never, env, tokens);
118
+ const units: Unit[] = [];
119
+ let list: Unit | null = null;
120
+ for (const token of tokens) {
121
+ if (!token.map) continue;
122
+ const line = from + token.map[0];
123
+ if (token.level === 0 && token.nesting !== -1) {
124
+ const isList = token.type === "bullet_list_open" || token.type === "ordered_list_open";
125
+ const unit: Unit = { line, fence: null, items: isList ? [] : null };
126
+ if (token.type === "fence") {
127
+ // At the top level, a last line that can close the fence did close it.
128
+ const last = token.map[1] - token.map[0] >= 2 ? lines[from + token.map[1] - 1] : null;
129
+ const closer = last ? FENCE_CLOSE.exec(last.text)?.[1] : undefined;
130
+ unit.fence = {
131
+ language: token.info.trim().split(/\s+/)[0] ?? "",
132
+ content: token.content.endsWith("\n") ? token.content.slice(0, -1) : token.content,
133
+ closed: !!closer && closer[0] === token.markup[0] && closer.length >= token.markup.length,
134
+ };
135
+ }
136
+ units.push(unit);
137
+ list = isList ? unit : null;
138
+ } else if (list && token.level === 1 && token.type === "list_item_open") {
139
+ list.items!.push(line);
140
+ }
141
+ }
142
+ return units;
143
+ }
144
+
145
+ type Piece = { start: number; end: number; fence: Unit["fence"] };
146
+
147
+ type MathRangeEnv = { mathRangeEnds: Int32Array; mathRangeOffset: number };
148
+ type MathRangeState = {
149
+ src: string;
150
+ env: Partial<MathRangeEnv>;
151
+ bMarks: number[];
152
+ eMarks: number[];
153
+ tShift: number[];
154
+ line: number;
155
+ push: (type: string, tag: string, nesting: number) => { map: [number, number] | null };
156
+ };
157
+ type RulableParser = {
158
+ block: {
159
+ ruler: {
160
+ before: (name: string, rule: string, fn: never, options: { alt: string[] }) => void;
161
+ };
162
+ };
163
+ };
164
+
165
+ /**
166
+ * The segmenting parser's view of display math. A chunk with math is drawn from its
167
+ * math-normalized text, where each display block (the math pass's `displayMathRanges`)
168
+ * is a `$$` block that interrupts paragraphs and ends lazy lines (`markdownItMath`). This
169
+ * rule makes the same lines one block in the original text, so the cuts follow the block
170
+ * structure the renderer sees. Without `env.mathRangeEnds` it never matches.
171
+ */
172
+ export function markdownItMathRanges(md: RulableParser): void {
173
+ const rule = (state: MathRangeState, startLine: number, endLine: number, silent: boolean) => {
174
+ // The ends are by line of the whole message; this parse starts at line `offset`.
175
+ const offset = state.env.mathRangeOffset ?? 0;
176
+ const end = (state.env.mathRangeEnds?.[startLine + offset] ?? -1) - offset;
177
+ // Like `markdownItMath`, the block must close inside its container.
178
+ if (end < startLine || end >= endLine) return false;
179
+ const first = state.src
180
+ .slice(state.bMarks[startLine]! + state.tShift[startLine]!, state.eMarks[startLine]!)
181
+ .trim();
182
+ if (!first.startsWith("$$") && !first.startsWith("\\[")) return false;
183
+ if (silent) return true;
184
+ state.push("math_range", "math", 0).map = [startLine, end + 1];
185
+ state.line = end + 1;
186
+ return true;
187
+ };
188
+ md.block.ruler.before("fence", "math_range", rule as never, {
189
+ alt: ["paragraph", "reference", "blockquote", "list"],
190
+ });
191
+ }
192
+
193
+ /**
194
+ * How to draw a message: one Markdown segment when it fits one parse, bounded segments
195
+ * when it is long, or null when it is too long to format at all (plain-text pages).
196
+ *
197
+ * Cuts follow markdown-it's own block structure: a long message is cut only where one of
198
+ * its top-level blocks starts (or, inside a list longer than one chunk, where one of its
199
+ * items starts), so every chunk parses to the same blocks a single parse would give, and
200
+ * a fence is a fence exactly when a single parse says so. Display math blocks, as the
201
+ * math pass finds them, are never cut. Linear in the message length.
202
+ *
203
+ * The segmenter keeps the block structure of the last message it saw: when the new text
204
+ * extends it (streaming), only the blocks from the end of the stable part are parsed again.
205
+ */
206
+ export function createMarkdownSegmenter(parser: MarkdownBlockParser) {
207
+ let cached: { text: string; lineCount: number; units: Unit[] } | null = null;
208
+ return (text: string): MarkdownSegment[] | null => {
209
+ if (text.length > MAX_MARKDOWN_LENGTH) return null;
210
+ if (text.length <= MAX_MARKDOWN_CHUNK_LENGTH) return [{ kind: "markdown", source: text }];
211
+ const lines = linesOf(text);
212
+ const ranges = displayMathRanges(lines.map((line) => line.text));
213
+ // For each line, the last line of the display math block it starts, or -1.
214
+ const mathEnds = new Int32Array(lines.length).fill(-1);
215
+ const inMath = new Uint8Array(lines.length);
216
+ for (const { start, end } of ranges) {
217
+ mathEnds[start] = end;
218
+ inMath.fill(1, start + 1, end + 1);
219
+ }
220
+ // Reuse the blocks before a restart line B when text was only appended: markdown-it
221
+ // decides where a block ends from the lines up to the next block's first two lines,
222
+ // and no lookahead (a paragraph, a setext underline, a reference definition's title)
223
+ // runs across a blank line. So a top-level block start B with a blank line before it,
224
+ // B and B + 1 whole lines of the old text, and B outside display math (which may close
225
+ // later) starts afresh with the same blocks before it.
226
+ let keep = -1;
227
+ if (cached && text.startsWith(cached.text)) {
228
+ const last = cached.lineCount - 1;
229
+ for (let index = cached.units.length - 1; index > 0; index--) {
230
+ const line = cached.units[index]!.line;
231
+ if (line + 2 <= last && lines[line - 1]!.text.trim() === "" && !inMath[line]) {
232
+ keep = index;
233
+ break;
234
+ }
235
+ }
236
+ }
237
+ const units =
238
+ cached && keep > 0
239
+ ? [
240
+ ...cached.units.slice(0, keep),
241
+ ...unitsOf(parser, lines, mathEnds, cached.units[keep]!.line),
242
+ ]
243
+ : unitsOf(parser, lines, mathEnds, 0);
244
+ cached = { text, lineCount: lines.length, units };
245
+ return segmentsOf(text, lines, units, inMath);
246
+ };
247
+ }
248
+
249
+ /** `createMarkdownSegmenter` for a single message. */
250
+ export function markdownSegments(
251
+ text: string,
252
+ parser: MarkdownBlockParser,
253
+ ): MarkdownSegment[] | null {
254
+ return createMarkdownSegmenter(parser)(text);
255
+ }
256
+
257
+ function segmentsOf(
258
+ text: string,
259
+ lines: Line[],
260
+ units: Unit[],
261
+ /** Lines inside a display math block: no cut before them. */
262
+ inMath: Uint8Array,
263
+ ): MarkdownSegment[] {
264
+ const offset = (line: number) => (line < lines.length ? lines[line]!.start : text.length);
265
+ const pieces: Piece[] = [];
266
+ const add = (start: number, end: number, fence: Unit["fence"]) => {
267
+ const previous = pieces[pieces.length - 1];
268
+ if (previous && inMath[start]) {
269
+ previous.end = end;
270
+ previous.fence = null;
271
+ } else {
272
+ pieces.push({ start, end, fence });
273
+ }
274
+ };
275
+ units.forEach((unit, index) => {
276
+ const start = index === 0 ? 0 : unit.line;
277
+ const end = units[index + 1]?.line ?? lines.length;
278
+ if (!unit.items || offset(end) - offset(start) <= CHUNK_TARGET_LENGTH) {
279
+ add(start, end, unit.fence);
280
+ return;
281
+ }
282
+ // A list longer than one chunk may be cut between its items.
283
+ const starts = [start, ...unit.items.filter((line) => line > start)];
284
+ starts.forEach((item, at) => add(item, starts[at + 1] ?? end, null));
285
+ });
286
+ if (pieces.length === 0) pieces.push({ start: 0, end: lines.length, fence: null });
287
+
288
+ const segments: MarkdownSegment[] = [];
289
+ let chunk: { start: number; end: number } | null = null;
290
+ const flush = () => {
291
+ if (chunk) {
292
+ const source = text.slice(chunk.start, chunk.end);
293
+ segments.push({
294
+ kind: source.length <= MAX_MARKDOWN_CHUNK_LENGTH ? "markdown" : "plain",
295
+ source,
296
+ });
297
+ }
298
+ chunk = null;
299
+ };
300
+ for (const piece of pieces) {
301
+ const start = offset(piece.start);
302
+ const end = offset(piece.end);
303
+ if (piece.fence && end - start > CHUNK_TARGET_LENGTH) {
304
+ flush();
305
+ segments.push({ kind: "fence", source: text.slice(start, end), ...piece.fence });
306
+ } else if (chunk && end - chunk.start <= CHUNK_TARGET_LENGTH) {
307
+ chunk.end = end;
308
+ } else {
309
+ flush();
310
+ chunk = { start, end };
311
+ }
312
+ }
313
+ flush();
314
+ return segments;
315
+ }
316
+
317
+ /** Segments mounted per frame: about one chunk of text, and a few at most. */
318
+ const MOUNT_LENGTH_PER_FRAME = CHUNK_TARGET_LENGTH;
319
+ const MOUNT_SEGMENTS_PER_FRAME = 8;
320
+
321
+ /**
322
+ * How many leading segments to have mounted after one more frame, starting from
323
+ * `mounted`: at least one more, then more while they fit one frame's budget. The first
324
+ * frame takes up to one full chunk, the bound a single message had before chunking.
325
+ */
326
+ export function mountedSegmentCount(segments: readonly MarkdownSegment[], mounted: number) {
327
+ if (mounted >= segments.length) return segments.length;
328
+ const budget = mounted === 0 ? MAX_MARKDOWN_CHUNK_LENGTH : MOUNT_LENGTH_PER_FRAME;
329
+ let next = mounted;
330
+ let length = 0;
331
+ while (next < segments.length && next - mounted < MOUNT_SEGMENTS_PER_FRAME) {
332
+ length += segments[next]!.source.length;
333
+ if (next > mounted && length > budget) break;
334
+ next++;
335
+ }
336
+ return next;
12
337
  }
13
338
 
14
339
  // Leave one code unit of headroom to keep surrogate pairs together without
15
340
  // scanning/splitting the entire message or exceeding the per-page bound.
16
- const PAGE_LENGTH = MAX_MARKDOWN_LENGTH - 1;
341
+ const PAGE_LENGTH = MAX_MARKDOWN_CHUNK_LENGTH - 1;
17
342
 
18
343
  export function plainTextPage(text: string, requestedPage: number) {
19
344
  const count = Math.max(1, Math.ceil(text.length / PAGE_LENGTH));