@jsb188/ai-chat 0.0.0-stage → 1.1.12

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.
Files changed (51) hide show
  1. package/README.md +109 -2
  2. package/VERIFICATION.md +118 -0
  3. package/benchmarks/browser.mjs +204 -0
  4. package/benchmarks/streaming.mjs +89 -0
  5. package/package.json +36 -5
  6. package/src/main.ts +5 -0
  7. package/src/modules/AIChatContent.tsx +84 -0
  8. package/src/modules/AgentNoteActionsMenu.tsx +121 -0
  9. package/src/modules/AgentNoteBootstrapProgress.tsx +41 -0
  10. package/src/modules/AgentNoteItem.helpers.ts +115 -0
  11. package/src/modules/AgentNoteItem.tsx +232 -0
  12. package/src/modules/AgentNotes.constants.ts +10 -0
  13. package/src/modules/AgentNotes.helpers.ts +274 -0
  14. package/src/modules/AgentNotes.hooks.ts +449 -0
  15. package/src/modules/AgentNotes.tsx +74 -0
  16. package/src/modules/AgentNotes.types.ts +50 -0
  17. package/src/modules/AgentNotesCollection.hooks.ts +69 -0
  18. package/src/modules/AgentNotesSection.tsx +145 -0
  19. package/src/parser.ts +4 -0
  20. package/src/types/content.ts +103 -0
  21. package/src/ui/AIChatUI.css +557 -0
  22. package/src/ui/AIChatUI.tsx +816 -0
  23. package/src/ui/AgentNotesUI.tsx +375 -0
  24. package/src/ui/AgentNotesUI.types.ts +19 -0
  25. package/src/ui/ChatBlocks.tsx +92 -0
  26. package/src/ui/ChatCodeBlock.tsx +16 -0
  27. package/src/ui/ChatInline.helpers.ts +20 -0
  28. package/src/ui/ChatInline.tsx +89 -0
  29. package/src/ui/ChatTable.helpers.ts +37 -0
  30. package/src/ui/ChatTable.tsx +126 -0
  31. package/src/utils/contentIdentity.ts +108 -0
  32. package/src/utils/parseBlocks.helpers.ts +50 -0
  33. package/src/utils/parseBlocks.ts +266 -0
  34. package/src/utils/parseContent.helpers.ts +102 -0
  35. package/src/utils/parseContent.ts +33 -0
  36. package/src/utils/parseContentIncrementally.ts +46 -0
  37. package/src/utils/parseCsv.ts +99 -0
  38. package/src/utils/parseInline.helpers.ts +48 -0
  39. package/src/utils/parseInline.ts +396 -0
  40. package/src/utils/parseTable.ts +202 -0
  41. package/tests/AgentNotes.test.tsx +1672 -0
  42. package/tests/fixtures/content.ts +13 -0
  43. package/tests/parseContent.test.ts +227 -0
  44. package/tests/parseCsv.test.ts +82 -0
  45. package/tests/parseInline.test.ts +222 -0
  46. package/tests/renderContent.ssr.test.tsx +19 -0
  47. package/tests/renderContent.test.tsx +282 -0
  48. package/tests/streaming.test.ts +51 -0
  49. package/tests/streamingEquivalence.test.ts +265 -0
  50. package/tsconfig.json +16 -0
  51. package/vitest.config.ts +18 -0
@@ -0,0 +1,126 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { cn } from '@jsb188/app/utils/string.ts';
3
+ import { HorizontalScrollIndicators } from '@jsb188/react-web/modules/Scroll';
4
+ import { TableList } from '@jsb188/react-web/ui/TableListUI';
5
+ import { memo, useMemo, type ComponentProps, type RefObject } from 'react';
6
+ import type { TableBlock, TableCell, TableRow } from '../types/content.ts';
7
+ import { ChatInline } from './ChatInline.tsx';
8
+ import { downloadChatTableCsv } from './ChatTable.helpers.ts';
9
+
10
+ export interface ChatTableContentProps {
11
+ block: TableBlock;
12
+ className?: string;
13
+ scrollIndicatorOffset?: number;
14
+ }
15
+
16
+ /*
17
+ * Preserve empty and multiline CSV strings as literal React text; only Markdown cells contain inline nodes.
18
+ */
19
+ const ChatTableCell = memo((p: { cell: TableCell }) => {
20
+ return (
21
+ <span
22
+ className='ofw w_f pre_wrap'
23
+ style={{ display: 'block' }}
24
+ >
25
+ {p.cell.kind === 'literal' ? p.cell.value : <ChatInline nodes={p.cell.children} />}
26
+ </span>
27
+ );
28
+ });
29
+
30
+ /*
31
+ * Adapt chat tables to the shared static table UI with consistent columns and complete accessible roles.
32
+ */
33
+ export const ChatTable = memo(
34
+ (
35
+ p: ChatTableContentProps & {
36
+ scrollRef: RefObject<HTMLDivElement | null> | null;
37
+ overflowing: boolean;
38
+ scrollLabel: string;
39
+ },
40
+ ) => {
41
+ const { block, scrollRef, overflowing, scrollLabel } = p;
42
+ const columnWidth = block.headers.length <= 2 ? 240 : block.headers.length <= 4 ? 190 : 160;
43
+ const gridLayoutStyle = `repeat(${block.headers.length}, minmax(${columnWidth}px, 1fr))`;
44
+ const rowCache = useMemo(() => new WeakMap<TableRow, ComponentProps<typeof TableList>['rows'][number]>(), [block.alignments]);
45
+ const headers = useMemo(
46
+ () =>
47
+ block.headers.map((cell, index) => ({
48
+ headerContent: <ChatTableCell cell={cell} />,
49
+ className: 'ft_semibold min_w_0 lh_4',
50
+ style: {
51
+ minHeight: 0,
52
+ alignItems: 'flex-start',
53
+ textAlign: block.alignments[index] || 'left',
54
+ },
55
+ })),
56
+ [block.headers, block.alignments],
57
+ );
58
+ const rows = useMemo(
59
+ () =>
60
+ block.rows.map((row) => {
61
+ const cached = rowCache.get(row);
62
+ if (cached) return cached;
63
+ const presentation = {
64
+ key: row.start,
65
+ removeBorderLine: false,
66
+ columns: row.cells.map((cell, index) => ({
67
+ children: <ChatTableCell cell={cell} />,
68
+ className: 'py_8 min_w_0 lh_4',
69
+ style: { alignItems: 'flex-start', textAlign: block.alignments[index] || 'left' },
70
+ })),
71
+ };
72
+ rowCache.set(row, presentation);
73
+ return presentation;
74
+ }),
75
+ [block.rows, block.alignments, rowCache],
76
+ );
77
+ return (
78
+ <>
79
+ <div className='my_sm min_w_0'>
80
+ <div className='h_right mb_2'>
81
+ <button
82
+ type='button'
83
+ className='ft_xxxs cl_lt link'
84
+ onClick={() => downloadChatTableCsv(block)}
85
+ >
86
+ {i18n.t('c.download_csv')}
87
+ </button>
88
+ </div>
89
+ <div className='chat_table rel min_w_0'>
90
+ <div
91
+ ref={scrollRef}
92
+ className={cn('min_w_0 w_f max_w_f', p.className ?? 'bd_1 bd_lt r_xs')}
93
+ style={{ overflowX: 'auto', overscrollBehaviorX: 'contain' }}
94
+ {...(overflowing ? { role: 'region', tabIndex: 0, 'aria-label': scrollLabel } : {})}
95
+ >
96
+ {/* biome-ignore lint/a11y/useSemanticElements: TableList uses div grid rows; ARIA table semantics preserve its existing layout. */}
97
+ <div
98
+ role='table'
99
+ className='w_f'
100
+ style={{ minWidth: 'min-content' }}
101
+ >
102
+ <TableList
103
+ semantic
104
+ gridLayoutStyle={gridLayoutStyle}
105
+ headers={headers}
106
+ rows={rows}
107
+ />
108
+ </div>
109
+ </div>
110
+ {overflowing && scrollRef && (
111
+ <HorizontalScrollIndicators
112
+ scrollRef={scrollRef}
113
+ offset={p.scrollIndicatorOffset}
114
+ />
115
+ )}
116
+ </div>
117
+ </div>
118
+ {block.provisionalTail && (
119
+ <p className='ofw pre_wrap'>
120
+ <span>{block.provisionalTail.source}</span>
121
+ </p>
122
+ )}
123
+ </>
124
+ );
125
+ },
126
+ );
@@ -0,0 +1,108 @@
1
+ import type { ContentBlock, ContentDocument, SourceRange, TableBlock, TableCell } from '../types/content.ts';
2
+ import { getContentParseLimits, sameParserLimits } from './parseContent.helpers.ts';
3
+
4
+ /*
5
+ * Compare a table range without allocating whole-document cache keys or depending on newly parsed node objects.
6
+ */
7
+ function sameTableRange(previous: SourceRange, next: SourceRange, previousBlock: TableBlock, nextBlock: TableBlock) {
8
+ return (
9
+ previous.start === next.start &&
10
+ previous.end === next.end &&
11
+ previousBlock.source.slice(previous.start - previousBlock.start, previous.end - previousBlock.start) ===
12
+ nextBlock.source.slice(next.start - nextBlock.start, next.end - nextBlock.start)
13
+ );
14
+ }
15
+
16
+ /*
17
+ * Preserve unchanged cell objects and arrays when only later table source has changed.
18
+ */
19
+ function reconcileCells(previous: TableCell[], next: TableCell[], previousBlock: TableBlock, nextBlock: TableBlock) {
20
+ const cells = next.map((cell, index) => {
21
+ const oldCell = previous[index];
22
+ return oldCell?.kind === cell.kind && sameTableRange(oldCell, cell, previousBlock, nextBlock) ? oldCell : cell;
23
+ });
24
+ return previous.length === cells.length && cells.every((cell, index) => cell === previous[index]) ? previous : cells;
25
+ }
26
+
27
+ /*
28
+ * Reuse committed table rows, headers, and alignment so appending source only renders newly completed rows.
29
+ */
30
+ function reconcileTable(previous: TableBlock, next: TableBlock): TableBlock {
31
+ if (previous.origin !== next.origin) return next;
32
+ const previousRows = new Map(previous.rows.map((row) => [row.start, row]));
33
+ const rows = next.rows.map((row) => {
34
+ const oldRow = previousRows.get(row.start);
35
+ if (!oldRow) return row;
36
+ if (sameTableRange(oldRow, row, previous, next)) return oldRow;
37
+ return { ...row, cells: reconcileCells(oldRow.cells, row.cells, previous, next) };
38
+ });
39
+ return {
40
+ ...next,
41
+ headers: reconcileCells(previous.headers, next.headers, previous, next),
42
+ rows: previous.rows.length === rows.length && rows.every((row, index) => row === previous.rows[index]) ? previous.rows : rows,
43
+ alignments:
44
+ previous.alignments.length === next.alignments.length &&
45
+ next.alignments.every((value, index) => value === previous.alignments[index])
46
+ ? previous.alignments
47
+ : next.alignments,
48
+ };
49
+ }
50
+
51
+ /*
52
+ * Keep block identity tied to source position and structure rather than accumulated message text.
53
+ */
54
+ export function getContentBlockKey(block: ContentBlock) {
55
+ return `${block.kind}:${block.start}`;
56
+ }
57
+
58
+ /*
59
+ * Index nested blocks so completed list content can also survive append-only updates.
60
+ */
61
+ function indexContentBlocks(blocks: ContentBlock[], index: Map<string, ContentBlock>) {
62
+ for (const block of blocks) {
63
+ index.set(getContentBlockKey(block), block);
64
+ if (block.kind === 'list') {
65
+ for (const item of block.items) {
66
+ indexContentBlocks(item.blocks, index);
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ /*
73
+ * Reuse identical parsed blocks, checking EOF-sensitive structure when the message status changes.
74
+ */
75
+ function reconcileBlocks(blocks: ContentBlock[], index: Map<string, ContentBlock>, statusChanged: boolean): ContentBlock[] {
76
+ return blocks.map((block) => {
77
+ const previous = index.get(getContentBlockKey(block));
78
+ if (
79
+ previous &&
80
+ previous.end === block.end &&
81
+ previous.source === block.source &&
82
+ previous.complete === block.complete &&
83
+ previous.fallbackReason === block.fallbackReason &&
84
+ (!statusChanged || JSON.stringify(previous) === JSON.stringify(block))
85
+ ) {
86
+ return previous;
87
+ }
88
+ if (block.kind === 'table' && previous?.kind === 'table') {
89
+ return reconcileTable(previous, block);
90
+ }
91
+ if (block.kind === 'list') {
92
+ return { ...block, items: block.items.map((item) => ({ ...item, blocks: reconcileBlocks(item.blocks, index, statusChanged) })) };
93
+ }
94
+ return block;
95
+ });
96
+ }
97
+
98
+ /*
99
+ * Reconcile only against the document held by this renderer instance; never cache conversation text globally.
100
+ */
101
+ export function reconcileContentDocument(previous: ContentDocument | null, next: ContentDocument): ContentDocument {
102
+ if (!previous || !sameParserLimits(getContentParseLimits(previous), getContentParseLimits(next))) {
103
+ return next;
104
+ }
105
+ const index = new Map<string, ContentBlock>();
106
+ indexContentBlocks(previous.blocks, index);
107
+ return { ...next, blocks: reconcileBlocks(next.blocks, index, previous.status !== next.status) };
108
+ }
@@ -0,0 +1,50 @@
1
+ import { DEFAULT_PARSER_LIMITS, type ParserLimits } from '../types/content.ts';
2
+
3
+ export interface SourceLine {
4
+ start: number;
5
+ contentEnd: number;
6
+ end: number;
7
+ text: string;
8
+ }
9
+
10
+ /*
11
+ * Scan physical lines without changing JavaScript offsets or original line endings.
12
+ */
13
+ export function scanLines(source: string, offset = 0): SourceLine[] {
14
+ const lines: SourceLine[] = [];
15
+ let start = offset;
16
+ for (let index = offset; index < source.length; index++) {
17
+ if (source[index] !== '\r' && source[index] !== '\n') continue;
18
+ const contentEnd = index;
19
+ if (source[index] === '\r' && source[index + 1] === '\n') index++;
20
+ lines.push({ start, contentEnd, end: index + 1, text: source.slice(start, contentEnd) });
21
+ start = index + 1;
22
+ }
23
+ if (start < source.length) lines.push({ start, contentEnd: source.length, end: source.length, text: source.slice(start) });
24
+ return lines;
25
+ }
26
+
27
+ /*
28
+ * Resolve finite nonnegative resource budgets while retaining omitted defaults.
29
+ */
30
+ export function resolveLimits(limits: Partial<ParserLimits> = {}): ParserLimits {
31
+ const resolved = { ...DEFAULT_PARSER_LIMITS };
32
+ for (const key of Object.keys(resolved) as (keyof ParserLimits)[]) {
33
+ const value = limits[key];
34
+ if (value !== undefined && Number.isFinite(value)) resolved[key] = Math.max(0, Math.floor(value));
35
+ }
36
+ return resolved;
37
+ }
38
+
39
+ /*
40
+ * Count indentation columns, with tabs advancing to four-column stops.
41
+ */
42
+ export function indentation(text: string): { columns: number; length: number } {
43
+ let columns = 0;
44
+ let length = 0;
45
+ while (text[length] === ' ' || text[length] === '\t') {
46
+ columns += text[length] === '\t' ? 4 - (columns % 4) : 1;
47
+ length++;
48
+ }
49
+ return { columns, length };
50
+ }
@@ -0,0 +1,266 @@
1
+ import type {
2
+ ChatContentStatus,
3
+ CodeBlock,
4
+ ContentBlock,
5
+ ContentDiagnostic,
6
+ ContentDocument,
7
+ HeadingBlock,
8
+ ListBlock,
9
+ ParserLimits,
10
+ } from '../types/content.ts';
11
+ import { indentation, resolveLimits, scanLines, type SourceLine } from './parseBlocks.helpers.ts';
12
+ import { parseCsv } from './parseCsv.ts';
13
+ import { parseInline } from './parseInline.ts';
14
+ import { markdownTableCandidate, parseMarkdownTable } from './parseTable.ts';
15
+
16
+ export interface BlocksParseResult {
17
+ blocks: ContentBlock[];
18
+ diagnostics: ContentDiagnostic[];
19
+ }
20
+
21
+ /*
22
+ * Identify a list marker and the exact source offset where its item content begins.
23
+ */
24
+ function listMarker(line: SourceLine) {
25
+ const match = /^([ \t]*)([-+*•]|\d{1,9}[.)])(?:([ \t]+)|$)/.exec(line.text);
26
+ if (!match) return null;
27
+ let contentIndent = indentation(match[1]).columns + match[2].length;
28
+ for (const character of match[3] || ' ') contentIndent += character === '\t' ? 4 - (contentIndent % 4) : 1;
29
+ return {
30
+ indent: indentation(match[1]).columns,
31
+ ordered: /^\d/.test(match[2]),
32
+ startNumber: /^\d/.test(match[2]) ? Number.parseInt(match[2], 10) : undefined,
33
+ contentOffset: match[0].length,
34
+ contentIndent,
35
+ };
36
+ }
37
+
38
+ /*
39
+ * Recognize a fence only within the supported three-space block indentation.
40
+ */
41
+ function openingFence(line: SourceLine) {
42
+ const match = /^ {0,3}(`{3,}|~{3,})([^\r\n]*)$/.exec(line.text);
43
+ if (!match || (match[1][0] === '`' && match[2].includes('`'))) return null;
44
+ return {
45
+ character: match[1][0] as '`' | '~',
46
+ length: match[1].length,
47
+ language: match[2]
48
+ .trim()
49
+ .split(/[ \t]+/, 1)[0]
50
+ .toLowerCase(),
51
+ };
52
+ }
53
+
54
+ /*
55
+ * Test for a same-character closing fence at least as long as its opener.
56
+ */
57
+ function closesFence(line: SourceLine, fence: { character: '`' | '~'; length: number }) {
58
+ const match = /^ {0,3}(`+|~+)[ \t]*$/.exec(line.text);
59
+ return !!match && match[1][0] === fence.character && match[1].length >= fence.length;
60
+ }
61
+
62
+ /*
63
+ * Identify supported block boundaries without treating indented examples as top-level syntax.
64
+ */
65
+ function structuralBoundary(line: SourceLine) {
66
+ return (
67
+ !!openingFence(line) || /^ {0,3}#{1,6}(?:[ \t]+|$)/.test(line.text) || (indentation(line.text).columns <= 3 && !!listMarker(line))
68
+ );
69
+ }
70
+
71
+ /*
72
+ * Keep fence and container boundaries outside tables while allowing heading-like cell text.
73
+ */
74
+ function tableBoundary(line: SourceLine) {
75
+ return !!openingFence(line) || /^ {0,3}>/.test(line.text) || (indentation(line.text).columns <= 3 && !!listMarker(line));
76
+ }
77
+
78
+ /*
79
+ * Remove a known container indentation while retaining original source coordinates.
80
+ */
81
+ function stripIndent(line: SourceLine, columns: number): SourceLine {
82
+ let removed = 0;
83
+ let length = 0;
84
+ while (removed < columns && (line.text[length] === ' ' || line.text[length] === '\t')) {
85
+ removed += line.text[length] === '\t' ? 4 - (removed % 4) : 1;
86
+ length++;
87
+ }
88
+ return { ...line, start: line.start + length, text: line.text.slice(length) };
89
+ }
90
+
91
+ /*
92
+ * Parse a source-preserving block subset with explicitly bounded list containers.
93
+ */
94
+ export function parseBlocks(
95
+ source: string,
96
+ status: ChatContentStatus = 'complete',
97
+ limits?: Partial<ParserLimits>,
98
+ options: { start?: number; previous?: ContentDocument } = {},
99
+ ): BlocksParseResult {
100
+ const budget = resolveLimits(limits);
101
+ const diagnostics: ContentDiagnostic[] = [];
102
+ const previousTables = new Map(
103
+ options.previous?.blocks.filter((block) => block.kind === 'table').map((block) => [block.start, block]),
104
+ );
105
+
106
+ /*
107
+ * Parse a physical or list-relative line sequence without enabling nested tables.
108
+ */
109
+ function sequence(lines: SourceLine[], depth: number): ContentBlock[] {
110
+ const blocks: ContentBlock[] = [];
111
+ let index = 0;
112
+ while (index < lines.length) {
113
+ const line = lines[index];
114
+ if (!line.text.trim()) {
115
+ index++;
116
+ continue;
117
+ }
118
+ const fence = openingFence(line);
119
+ if (fence) {
120
+ let nextLine = index + 1;
121
+ while (nextLine < lines.length && !closesFence(lines[nextLine], fence)) nextLine++;
122
+ const closed = nextLine < lines.length;
123
+ const bodyRange = { start: line.end, end: closed ? lines[nextLine].start : lines[lines.length - 1].end };
124
+ const end = closed ? lines[nextLine++].end : bodyRange.end;
125
+ const code: CodeBlock = {
126
+ kind: 'code',
127
+ start: line.start,
128
+ end,
129
+ source: source.slice(line.start, end),
130
+ complete: closed,
131
+ language: fence.language,
132
+ body: source.slice(bodyRange.start, bodyRange.end),
133
+ bodyRange,
134
+ fence: { character: fence.character, length: fence.length, closed },
135
+ };
136
+ if (!closed) diagnostics.push({ code: 'incomplete', reason: 'Unclosed code fence.', start: line.start, end });
137
+ if (depth === 0 && fence.language === 'csv' && (closed || status === 'complete')) {
138
+ const csv = parseCsv(code.body, bodyRange.start, budget);
139
+ if (csv.valid) {
140
+ blocks.push({
141
+ kind: 'table',
142
+ origin: 'csv',
143
+ csvSource: code.body,
144
+ start: code.start,
145
+ end,
146
+ source: code.source,
147
+ complete: closed || status === 'complete',
148
+ headers: csv.rows[0].cells,
149
+ rows: csv.rows.slice(1),
150
+ alignments: csv.rows[0].cells.map(() => null),
151
+ });
152
+ } else {
153
+ code.fallbackReason = csv.diagnostics[0].reason;
154
+ diagnostics.push(...csv.diagnostics);
155
+ blocks.push(code);
156
+ }
157
+ } else blocks.push(code);
158
+ index = nextLine;
159
+ continue;
160
+ }
161
+ if (depth === 0) {
162
+ const table = parseMarkdownTable(source, lines, index, status, budget, tableBoundary, previousTables.get(line.start));
163
+ if (table) {
164
+ blocks.push(table.block);
165
+ diagnostics.push(...table.diagnostics);
166
+ index = table.nextLine;
167
+ continue;
168
+ }
169
+ }
170
+ const heading = /^ {0,3}(#{1,6})(?:[ \t]+|$)/.exec(line.text);
171
+ if (heading) {
172
+ const contentStart = line.start + heading[0].length;
173
+ blocks.push({
174
+ kind: 'heading',
175
+ level: heading[1].length as HeadingBlock['level'],
176
+ start: line.start,
177
+ end: line.end,
178
+ source: source.slice(line.start, line.end),
179
+ complete: line.end > line.contentEnd || status === 'complete',
180
+ children: parseInline(source.slice(contentStart, line.contentEnd), contentStart, budget, diagnostics),
181
+ });
182
+ index++;
183
+ continue;
184
+ }
185
+ const marker = listMarker(line);
186
+ if (marker && marker.indent <= 3) {
187
+ const list: ListBlock = {
188
+ kind: 'list',
189
+ start: line.start,
190
+ end: line.end,
191
+ source: '',
192
+ complete: true,
193
+ ordered: marker.ordered,
194
+ ...(marker.ordered ? { startNumber: marker.startNumber } : {}),
195
+ indent: marker.indent,
196
+ items: [],
197
+ };
198
+ while (index < lines.length) {
199
+ const itemStart = lines[index];
200
+ const itemMarker = listMarker(itemStart);
201
+ if (!itemMarker || itemMarker.indent !== marker.indent || itemMarker.ordered !== marker.ordered) break;
202
+ const itemLines = [
203
+ { ...itemStart, start: itemStart.start + itemMarker.contentOffset, text: itemStart.text.slice(itemMarker.contentOffset) },
204
+ ];
205
+ index++;
206
+ while (index < lines.length) {
207
+ const continuation = lines[index];
208
+ if (continuation.text.trim() && indentation(continuation.text).columns < itemMarker.contentIndent) break;
209
+ itemLines.push(stripIndent(continuation, itemMarker.contentIndent));
210
+ index++;
211
+ }
212
+ const end = itemLines[itemLines.length - 1].end;
213
+ let itemBlocks: ContentBlock[];
214
+ if (depth >= Math.min(budget.nestingDepth, 64)) {
215
+ const reason = 'List nesting depth limit exceeded.';
216
+ itemBlocks = [
217
+ {
218
+ kind: 'literal',
219
+ start: itemStart.start,
220
+ end,
221
+ source: source.slice(itemStart.start, end),
222
+ complete: true,
223
+ fallbackReason: reason,
224
+ },
225
+ ];
226
+ diagnostics.push({ code: 'limit-exceeded', reason, start: itemStart.start, end });
227
+ } else itemBlocks = sequence(itemLines, depth + 1);
228
+ list.items.push({ start: itemStart.start, end, blocks: itemBlocks });
229
+ list.end = end;
230
+ }
231
+ list.source = source.slice(list.start, list.end);
232
+ list.complete = list.end < source.length || status === 'complete' || source.endsWith('\n') || source.endsWith('\r');
233
+ blocks.push(list);
234
+ continue;
235
+ }
236
+ const firstLine = index;
237
+ index++;
238
+ while (
239
+ index < lines.length &&
240
+ lines[index].text.trim() &&
241
+ !structuralBoundary(lines[index]) &&
242
+ !(depth === 0 && markdownTableCandidate(source, lines, index, status))
243
+ )
244
+ index++;
245
+ const paragraphLines = lines.slice(firstLine, index);
246
+ const children = parseInline(
247
+ source.slice(line.start, paragraphLines[paragraphLines.length - 1].contentEnd),
248
+ line.start,
249
+ budget,
250
+ diagnostics,
251
+ );
252
+ const end = paragraphLines[paragraphLines.length - 1].end;
253
+ blocks.push({
254
+ kind: 'paragraph',
255
+ start: line.start,
256
+ end,
257
+ source: source.slice(line.start, end),
258
+ complete: end < source.length || status === 'complete' || end > paragraphLines[paragraphLines.length - 1].contentEnd,
259
+ children,
260
+ });
261
+ }
262
+ return blocks;
263
+ }
264
+
265
+ return { blocks: sequence(scanLines(source, options.start), 0), diagnostics };
266
+ }
@@ -0,0 +1,102 @@
1
+ import type {
2
+ ContentBlock,
3
+ ContentDiagnostic,
4
+ ContentDocument,
5
+ InlineNode,
6
+ ParserLimits,
7
+ TableCell,
8
+ TableRow,
9
+ } from '../types/content.ts';
10
+
11
+ const nodeCounts = new WeakMap<object, number>();
12
+ const parsedLimits = new WeakMap<ContentDiagnostic[], ParserLimits>();
13
+
14
+ /*
15
+ * Keep budgets attached to the parse's diagnostics array, which reconciliation preserves while replacing document and block objects.
16
+ */
17
+ export function withContentParseLimits(document: ContentDocument, limits: ParserLimits): ContentDocument {
18
+ parsedLimits.set(document.diagnostics, limits);
19
+ return document;
20
+ }
21
+
22
+ /*
23
+ * Read the exact budget used for a document without exposing metadata in its source-preserving AST.
24
+ */
25
+ export function getContentParseLimits(document: ContentDocument): ParserLimits | undefined {
26
+ return parsedLimits.get(document.diagnostics);
27
+ }
28
+
29
+ /*
30
+ * Compare normalized budgets before reusing any previously validated source structure.
31
+ */
32
+ export function sameParserLimits(previous: ParserLimits | undefined, next: ParserLimits | undefined): boolean {
33
+ return (
34
+ previous === next ||
35
+ (!!previous && !!next && (Object.keys(next) as (keyof ParserLimits)[]).every((key) => previous[key] === next[key]))
36
+ );
37
+ }
38
+
39
+ /*
40
+ * Count immutable inline subtrees once, including their container nodes.
41
+ */
42
+ function inlineNodeCount(nodes: InlineNode[]): number {
43
+ const retained = nodeCounts.get(nodes);
44
+ if (retained !== undefined) return retained;
45
+ let count = nodes.length;
46
+ for (const node of nodes) if ('children' in node) count += inlineNodeCount(node.children);
47
+ nodeCounts.set(nodes, count);
48
+ return count;
49
+ }
50
+
51
+ /*
52
+ * Reuse counts for table cells whose inline trees survived an accumulated update.
53
+ */
54
+ function cellNodeCount(cells: TableCell[]): number {
55
+ const retained = nodeCounts.get(cells);
56
+ if (retained !== undefined) return retained;
57
+ let count = cells.length;
58
+ for (const cell of cells) if (cell.kind === 'inline') count += inlineNodeCount(cell.children);
59
+ nodeCounts.set(cells, count);
60
+ return count;
61
+ }
62
+
63
+ /*
64
+ * Retain a row's total so growing tables do not repeatedly walk completed cells.
65
+ */
66
+ function rowNodeCount(row: TableRow): number {
67
+ const retained = nodeCounts.get(row);
68
+ if (retained !== undefined) return retained;
69
+ const count = 1 + cellNodeCount(row.cells);
70
+ nodeCounts.set(row, count);
71
+ return count;
72
+ }
73
+
74
+ /*
75
+ * Count source-preserving blocks and bounded nested containers without revisiting unchanged trees.
76
+ */
77
+ function blockNodeCount(block: ContentBlock): number {
78
+ const retained = nodeCounts.get(block);
79
+ if (retained !== undefined) return retained;
80
+ let count = 1;
81
+ if (block.kind === 'table') {
82
+ count += cellNodeCount(block.headers);
83
+ for (const row of block.rows) count += rowNodeCount(row);
84
+ } else if (block.kind === 'list') {
85
+ count += block.items.length;
86
+ for (const item of block.items) for (const child of item.blocks) count += blockNodeCount(child);
87
+ } else if ('children' in block) count += inlineNodeCount(block.children);
88
+ nodeCounts.set(block, count);
89
+ return count;
90
+ }
91
+
92
+ /*
93
+ * Enforce the whole-document node budget while sharing counts for retained immutable blocks.
94
+ */
95
+ export function exceedsNodeBudget(blocks: ContentBlock[], limit: number): boolean {
96
+ let count = 0;
97
+ for (const block of blocks) {
98
+ count += blockNodeCount(block);
99
+ if (count > limit) return true;
100
+ }
101
+ return false;
102
+ }
@@ -0,0 +1,33 @@
1
+ import type { ChatContentStatus, ContentDocument, ParserLimits } from '../types/content.ts';
2
+ import { parseBlocks } from './parseBlocks.ts';
3
+ import { resolveLimits } from './parseBlocks.helpers.ts';
4
+ import { exceedsNodeBudget, withContentParseLimits } from './parseContent.helpers.ts';
5
+
6
+ /*
7
+ * Parse the full accumulated message and preserve whole-source fallback on global limits.
8
+ */
9
+ export function parseContent(source: string, status: ChatContentStatus = 'complete', limits?: Partial<ParserLimits>): ContentDocument {
10
+ const budget = resolveLimits(limits);
11
+
12
+ /*
13
+ * Retain every source character when the document cannot safely fit its rendering budget.
14
+ */
15
+ function fallback(reason: string): ContentDocument {
16
+ return withContentParseLimits(
17
+ {
18
+ source,
19
+ status,
20
+ blocks: source
21
+ ? [{ kind: 'literal', start: 0, end: source.length, source, complete: status === 'complete', fallbackReason: reason }]
22
+ : [],
23
+ diagnostics: [{ code: 'limit-exceeded', reason, start: 0, end: source.length }],
24
+ },
25
+ budget,
26
+ );
27
+ }
28
+
29
+ if (source.length > budget.inputLength) return fallback('Input length limit exceeded.');
30
+ const parsed = parseBlocks(source, status, budget);
31
+ if (exceedsNodeBudget(parsed.blocks, budget.nodes)) return fallback('Document node limit exceeded.');
32
+ return withContentParseLimits({ source, status, ...parsed }, budget);
33
+ }