@convai/web-sdk 2.1.0-beta.3 → 2.2.0-beta.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.
@@ -23,6 +23,8 @@ export { fetchCharacterInfo, readCharacterInfo, DEFAULT_CHARACTER_INFO_URL, FALL
23
23
  export type { CharacterInfo, FetchCharacterInfoOptions } from './characterInfo.js';
24
24
  export { parseInlineMarkdown, mediaKindForUrl, isSafeHref, compactUrl } from '../utils/inlineMarkdown.js';
25
25
  export type { InlineNode, MediaKind } from '../utils/inlineMarkdown.js';
26
+ export { parseMarkdownBlocks, parseMarkdownInline } from '../utils/markdownBlocks.js';
27
+ export type { MarkdownBlock, MarkdownInline } from '../utils/markdownBlocks.js';
26
28
  export { linkKindForUrl, describeUrl, fileNameOf, documentBadge, contactLabel, hoverTitle, isMixedContent, } from '../utils/linkPresentation.js';
27
29
  export type { LinkKind } from '../utils/linkPresentation.js';
28
30
  export { resolveLinkPreviewCached, isCardWorthy, LINK_PREVIEW_TIMEOUT_MS, safeHttpUrl, siteNameFor, faviconFor, resetLinkPreviewCache, } from '../utils/linkPreview.js';
@@ -34,6 +34,7 @@ export { fetchCharacterInfo, readCharacterInfo, DEFAULT_CHARACTER_INFO_URL, FALL
34
34
  // `isSafeHref` becomes a link, so a renderer built on these nodes cannot emit
35
35
  // a javascript: href however the server framed it.
36
36
  export { parseInlineMarkdown, mediaKindForUrl, isSafeHref, compactUrl } from '../utils/inlineMarkdown.js';
37
+ export { parseMarkdownBlocks, parseMarkdownInline } from '../utils/markdownBlocks.js';
37
38
  // Pure functions for labelling a link: URL in, string out. Public so a UI
38
39
  // rendering links — the bundled widgets, @convai/web-widget, or your own —
39
40
  // derives the same file name, badge, contact label and hover text. The
@@ -436,6 +436,23 @@ export interface VisionInputConfig {
436
436
  maxResolution?: number | null;
437
437
  replacePreviousVisionContext?: boolean;
438
438
  }
439
+ /** Source labels Core keys `vision_buffer.sources` by. */
440
+ export type VisionBufferSourceLabel = "webcam" | "screen" | "canvas" | "custom";
441
+ /**
442
+ * One source's entry in `vision_buffer.sources`. Core sends every field for
443
+ * each source it knows, including one that has stopped.
444
+ */
445
+ export interface VisionBufferSourceStatus {
446
+ /** `"frames_available"`, `"buffer_empty"` or `"no_active_video"`. */
447
+ status: string;
448
+ /** False once the source stopped or muted. */
449
+ source_active: boolean;
450
+ retained_frames: number;
451
+ first_frame_pts: number | null;
452
+ last_frame_pts: number | null;
453
+ last_frame_age_ms: number | null;
454
+ frames_admitted: number;
455
+ }
439
456
  export interface VisionBufferStatus {
440
457
  enabled?: boolean;
441
458
  /** Buffer state as Core reports it, e.g. `"vision_not_enabled"`. */
@@ -462,6 +479,17 @@ export interface VisionBufferStatus {
462
479
  vision_source_participant?: string | null;
463
480
  attached_frame_pts?: number[];
464
481
  };
482
+ /**
483
+ * `true` when Core keeps one buffer per video source for this session.
484
+ * Absent on a Core without multi-source vision, or with it off; the fields
485
+ * above then describe the single buffer.
486
+ */
487
+ multi_source?: boolean;
488
+ /**
489
+ * Per-source buffer state, keyed by source label. Sent only with
490
+ * `multi_source: true`; the fields above are then computed over all sources.
491
+ */
492
+ sources?: Partial<Record<VisionBufferSourceLabel, VisionBufferSourceStatus>>;
465
493
  }
466
494
  export interface VisionStatusOptions {
467
495
  updateId?: string;
@@ -482,6 +510,26 @@ export interface UpdateSceneMetadataOptions {
482
510
  respondMode?: RespondMode;
483
511
  }
484
512
  export type VisionSourceKind = "webcam" | "canvas" | "screen" | "custom" | "camera" | "screen_share" | "unknown";
513
+ /**
514
+ * What `videoControls` does when a second vision source starts.
515
+ *
516
+ * - `"single"` (default): the new source replaces the one that is live.
517
+ * - `"multi"`: sources with different labels (webcam, screen, canvas, custom)
518
+ * stay live together, once the server has reported multi-source vision for
519
+ * the session. Until then, and on a server without it, it behaves as
520
+ * `"single"`.
521
+ */
522
+ export type VisionSourceMode = "single" | "multi";
523
+ /**
524
+ * Where multi-source vision stands for the current session.
525
+ *
526
+ * - `"off"`: not requested (`visionSourceMode` is `"single"`), or not connected.
527
+ * - `"pending"`: requested; the server has not answered yet.
528
+ * - `"active"`: the server reported `vision_buffer.multi_source: true`.
529
+ * Sources with different labels stay live together.
530
+ * - `"unsupported"`: requested, but this session keeps one source at a time.
531
+ */
532
+ export type VisionMultiSourceState = "off" | "pending" | "active" | "unsupported";
485
533
  export interface VisionSourceState {
486
534
  active: boolean;
487
535
  source: VisionSourceKind | null;
@@ -785,6 +833,20 @@ export interface ConvaiConfig {
785
833
  * visual perception.
786
834
  */
787
835
  visionPromptMode?: "auto" | "disabled";
836
+ /**
837
+ * Whether several vision sources may be live at once. Default `"single"`:
838
+ * starting a source through `videoControls` replaces the one that is live.
839
+ *
840
+ * With `"multi"`, a webcam, a screen, a canvas and a custom source can be
841
+ * live together, each on its own track. It takes effect only on the
842
+ * `livekit` transport, in a single-character session, after the server has
843
+ * reported `vision_buffer.multi_source: true`: a server without multi-source
844
+ * vision keeps one buffer for all of a participant's tracks and would label
845
+ * every frame as the same source. Until the server answers, and whenever it
846
+ * does not support it, this behaves as `"single"`. Read the outcome from
847
+ * `videoControls.multiSourceVision`.
848
+ */
849
+ visionSourceMode?: VisionSourceMode;
788
850
  /** Connect-time respond-mode defaults by modality. */
789
851
  respondModes?: RespondModesConfig;
790
852
  /** Descriptive objects visible in the scene at connection time. */
@@ -1016,6 +1078,34 @@ export interface ConvaiConfig {
1016
1078
  * ```
1017
1079
  */
1018
1080
  preserveLinksInOutput?: boolean;
1081
+ /**
1082
+ * Keep Markdown in the character's text for this session (bold, lists,
1083
+ * tables, fenced code, quotes) and ask the model to use it.
1084
+ *
1085
+ * Leave it unset to let the character decide: a character with "Format
1086
+ * replies with Markdown" on already sends Markdown. Set `false` from a UI
1087
+ * that cannot render Markdown to opt out for an enabled character; set
1088
+ * `true` to turn it on for one session.
1089
+ *
1090
+ * The server does not sanitise Markdown or HTML in model text: render it
1091
+ * without raw HTML and check every link and image target with `isSafeHref`.
1092
+ * `parseMarkdownBlocks` turns a message into safe block and inline nodes.
1093
+ * Voice output is unaffected: the server strips formatting before speech and
1094
+ * skips code, JSON, YAML and tables.
1095
+ *
1096
+ * Sent as `preserve_markdown_in_output` on `/connect` and on SSE interaction
1097
+ * requests; omitted when undefined.
1098
+ *
1099
+ * @example
1100
+ * ```typescript
1101
+ * const client = new ConvaiClient({
1102
+ * apiKey: 'your-api-key',
1103
+ * characterId: 'your-character-id',
1104
+ * preserveMarkdownInOutput: true,
1105
+ * });
1106
+ * ```
1107
+ */
1108
+ preserveMarkdownInOutput?: boolean;
1019
1109
  /**
1020
1110
  * Log decoded RTVI data messages to the browser console (default: true).
1021
1111
  * Set to false to silence incoming and outgoing RTVI message logs.
@@ -1624,6 +1714,10 @@ export interface VideoStateChange {
1624
1714
  isVideoEnabled?: boolean;
1625
1715
  /** True while the camera is published but hidden (a soft mute). */
1626
1716
  isVideoHidden?: boolean;
1717
+ /** Every live vision source published through `videoControls`, oldest first. */
1718
+ visionSources?: VisionSourceHandle[];
1719
+ /** Where multi-source vision stands for this session. */
1720
+ multiSourceVision?: VisionMultiSourceState;
1627
1721
  }
1628
1722
  /** Payload of `screenShareControls.on('screenShareStateChange')`. Partial, like {@link AudioStateChange}. */
1629
1723
  export interface ScreenShareStateChange {
@@ -1670,9 +1764,20 @@ export interface AudioControls {
1670
1764
  export interface VideoControls {
1671
1765
  isVideoEnabled: boolean;
1672
1766
  isVideoHidden: boolean;
1767
+ /** The live vision source that started last, or `null`. */
1673
1768
  activeVisionSource: VisionSourceHandle | null;
1674
1769
  hasActiveVisionSource: boolean;
1675
1770
  visionSourceState: VisionSourceState;
1771
+ /**
1772
+ * Every live vision source published through `videoControls`, oldest first.
1773
+ * At most one unless `multiSourceVision` is `"active"`.
1774
+ */
1775
+ visionSources: VisionSourceHandle[];
1776
+ /**
1777
+ * Where multi-source vision stands for this session. Sources stay live
1778
+ * together only while this is `"active"`; see `visionSourceMode`.
1779
+ */
1780
+ multiSourceVision: VisionMultiSourceState;
1676
1781
  enableVideo: () => Promise<void>;
1677
1782
  disableVideo: () => Promise<void>;
1678
1783
  hideVideo: () => Promise<void>;
@@ -1,3 +1,27 @@
1
- import type { VisionSourceKind } from "./types.js";
1
+ import type { VisionBufferSourceLabel, VisionSourceKind } from "./types.js";
2
2
  export declare function isWebcamVisionSource(source?: VisionSourceKind | null): boolean;
3
3
  export declare function shouldKeepExistingVisionSource(currentSource: VisionSourceKind, nextSource: VisionSourceKind, hasReplacementTrack: boolean): boolean;
4
+ /**
5
+ * The label Core files a source under: one buffer, and one entry in
6
+ * `vision_buffer.sources`, per label. Two sources with the same label are the
7
+ * same source to Core.
8
+ */
9
+ export declare function visionSourceLabel(source: VisionSourceKind): VisionBufferSourceLabel;
10
+ /**
11
+ * The label Core gives a published LiveKit video track. Mirrors
12
+ * `_normalize_video_source_hint` in core-service `transport/services/livekit.py`:
13
+ * the track name is searched first, in this order, then the LiveKit source
14
+ * decides, and a track that says neither is a webcam.
15
+ *
16
+ * @param liveKitSource `Track.Source` value: `"camera"`, `"screen_share"`, `"unknown"`.
17
+ */
18
+ export declare function coreVisionSourceLabel(publicationName: string | undefined, liveKitSource: string): VisionBufferSourceLabel;
19
+ /**
20
+ * The name a vision track is published under: the caller's name, prefixed with
21
+ * the source when the name does not already say it.
22
+ *
23
+ * With `guaranteeLabel`, a name Core would file under another label (a custom
24
+ * source named "pov-feed" reads as a canvas) is replaced by the bare label, so
25
+ * two sources that must stay apart cannot land in one buffer.
26
+ */
27
+ export declare function visionPublicationName(source: VisionSourceKind, sourceName: string, liveKitSource: string, guaranteeLabel: boolean): string;
@@ -6,3 +6,58 @@ export function shouldKeepExistingVisionSource(currentSource, nextSource, hasRep
6
6
  isWebcamVisionSource(currentSource) &&
7
7
  isWebcamVisionSource(nextSource));
8
8
  }
9
+ /**
10
+ * The label Core files a source under: one buffer, and one entry in
11
+ * `vision_buffer.sources`, per label. Two sources with the same label are the
12
+ * same source to Core.
13
+ */
14
+ export function visionSourceLabel(source) {
15
+ if (source === "webcam" || source === "camera")
16
+ return "webcam";
17
+ if (source === "canvas")
18
+ return "canvas";
19
+ if (source === "screen" || source === "screen_share")
20
+ return "screen";
21
+ return "custom";
22
+ }
23
+ /**
24
+ * The label Core gives a published LiveKit video track. Mirrors
25
+ * `_normalize_video_source_hint` in core-service `transport/services/livekit.py`:
26
+ * the track name is searched first, in this order, then the LiveKit source
27
+ * decides, and a track that says neither is a webcam.
28
+ *
29
+ * @param liveKitSource `Track.Source` value: `"camera"`, `"screen_share"`, `"unknown"`.
30
+ */
31
+ export function coreVisionSourceLabel(publicationName, liveKitSource) {
32
+ const name = (publicationName ?? "").trim().toLowerCase();
33
+ if (name) {
34
+ if (name.includes("canvas") || name.includes("pov"))
35
+ return "canvas";
36
+ if (name.includes("screen"))
37
+ return "screen";
38
+ if (name.includes("webcam") || name.includes("camera"))
39
+ return "webcam";
40
+ if (name.includes("custom"))
41
+ return "custom";
42
+ }
43
+ if (liveKitSource === "screen_share")
44
+ return "screen";
45
+ return "webcam";
46
+ }
47
+ /**
48
+ * The name a vision track is published under: the caller's name, prefixed with
49
+ * the source when the name does not already say it.
50
+ *
51
+ * With `guaranteeLabel`, a name Core would file under another label (a custom
52
+ * source named "pov-feed" reads as a canvas) is replaced by the bare label, so
53
+ * two sources that must stay apart cannot land in one buffer.
54
+ */
55
+ export function visionPublicationName(source, sourceName, liveKitSource, guaranteeLabel) {
56
+ const name = sourceName.toLowerCase().includes(source.toLowerCase())
57
+ ? sourceName
58
+ : `${source}:${sourceName}`;
59
+ if (!guaranteeLabel)
60
+ return name;
61
+ const label = visionSourceLabel(source);
62
+ return coreVisionSourceLabel(name, liveKitSource) === label ? name : label;
63
+ }
@@ -1,6 +1,8 @@
1
1
  export { useConvaiClient } from './hooks/useConvaiClient.js';
2
2
  export { parseInlineMarkdown, mediaKindForUrl, isSafeHref, compactUrl } from '../utils/inlineMarkdown.js';
3
3
  export type { InlineNode, MediaKind } from '../utils/inlineMarkdown.js';
4
+ export { parseMarkdownBlocks, parseMarkdownInline } from '../utils/markdownBlocks.js';
5
+ export type { MarkdownBlock, MarkdownInline } from '../utils/markdownBlocks.js';
4
6
  export { linkKindForUrl, describeUrl } from '../utils/linkPresentation.js';
5
7
  export type { LinkKind } from '../utils/linkPresentation.js';
6
8
  export { resolveLinkPreviewCached, isCardWorthy, LINK_PREVIEW_TIMEOUT_MS } from '../utils/linkPreview.js';
@@ -4,6 +4,7 @@ export { useConvaiClient } from './hooks/useConvaiClient.js';
4
4
  // AudioRenderer and AudioContext are in @convai/web-widget/react.
5
5
  // The bubble tokenizer, for building a renderer from scratch.
6
6
  export { parseInlineMarkdown, mediaKindForUrl, isSafeHref, compactUrl } from '../utils/inlineMarkdown.js';
7
+ export { parseMarkdownBlocks, parseMarkdownInline } from '../utils/markdownBlocks.js';
7
8
  export { linkKindForUrl, describeUrl } from '../utils/linkPresentation.js';
8
9
  export { resolveLinkPreviewCached, isCardWorthy, LINK_PREVIEW_TIMEOUT_MS } from '../utils/linkPreview.js';
9
10
  // Additional hooks (for advanced usage)
@@ -96,7 +96,10 @@ const TOKEN = new RegExp([
96
96
  // The target allows one level of balanced parens, so `javascript:alert(1)`
97
97
  // and `…/a_(b).pdf` are consumed whole. Without it the inner `)` ended the
98
98
  // match and the outer one was left stranded in the text.
99
- `(!?)\\[([^\\]]*)\\]\\(\\s*((?:[^\\s()]|\\([^()]*\\))+)(?:\\s+"[^"]*")?\\s*\\)`,
99
+ // The label excludes `[` as well as `]` so a run of `[` costs one step each
100
+ // instead of a scan to the end of the line from every one (quadratic on
101
+ // "[[[[…", security review CORE-2299). Nested-bracket labels stay text.
102
+ `(!?)\\[([^\\[\\]]*)\\]\\(\\s*((?:[^\\s()]|\\([^()]*\\))+)(?:\\s+"[^"]*")?\\s*\\)`,
100
103
  `<((?:${schemeAlt}):[^\\s<>]+)>`,
101
104
  `(?<!\\]\\()((?:${networkAlt}):\\/\\/[^\\s<>"'\`]+|(?:mailto|tel|sms):[^\\s<>"'\`]+)`,
102
105
  `(\\*\\*|__)(.*?)\\6`,
@@ -109,24 +112,32 @@ const TRAILING_PUNCTUATION = ".,;:!?'\"";
109
112
  * unbalanced `)` belongs to the surrounding parenthetical.
110
113
  */
111
114
  function splitTrailingPunctuation(raw) {
112
- let url = raw;
113
- while (url.length > 0) {
114
- const last = url[url.length - 1];
115
+ // Count the parens once and move an end index, so a URL followed by a long
116
+ // run of `)` or punctuation is trimmed in one pass (it was re-counted and
117
+ // re-sliced per character: quadratic, security review CORE-2299).
118
+ let opens = 0;
119
+ let closes = 0;
120
+ for (const char of raw) {
121
+ if (char === "(")
122
+ opens++;
123
+ else if (char === ")")
124
+ closes++;
125
+ }
126
+ let end = raw.length;
127
+ while (end > 0) {
128
+ const last = raw[end - 1];
115
129
  if (TRAILING_PUNCTUATION.includes(last)) {
116
- url = url.slice(0, -1);
130
+ end--;
117
131
  continue;
118
132
  }
119
- if (last === ")") {
120
- const opens = (url.match(/\(/g) ?? []).length;
121
- const closes = (url.match(/\)/g) ?? []).length;
122
- if (closes > opens) {
123
- url = url.slice(0, -1);
124
- continue;
125
- }
133
+ if (last === ")" && closes > opens) {
134
+ closes--;
135
+ end--;
136
+ continue;
126
137
  }
127
138
  break;
128
139
  }
129
- return [url, raw.slice(url.length)];
140
+ return [raw.slice(0, end), raw.slice(end)];
130
141
  }
131
142
  export function parseInlineMarkdown(line) {
132
143
  const nodes = [];
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Block-level Markdown for a character message (CORE-2008).
3
+ *
4
+ * A character with Markdown output on (`preserveMarkdownInOutput`, or the
5
+ * character's "Format replies with Markdown" setting) sends headings, lists,
6
+ * tables, fenced code, quotes and rules. This turns one whole message into
7
+ * nodes a renderer maps onto DOM or JSX.
8
+ *
9
+ * Safety: model text is untrusted and the server does not sanitise it. No node
10
+ * here carries raw HTML: `<tags>` stay literal text. Every link and image goes
11
+ * through `parseInlineMarkdown`, so targets outside its scheme allowlist come
12
+ * back as `blocked` nodes. A renderer must build elements and set text, never
13
+ * inject HTML, and must not put `href` on a `blocked` node.
14
+ *
15
+ * Streaming: call it again on the accumulated text. An unclosed fence renders
16
+ * as code so far; a table line without its delimiter row stays text until the
17
+ * delimiter arrives.
18
+ *
19
+ * Cost: one pass over the lines; backtick runs are indexed once per line and a
20
+ * code span closes at most `MAX_CODE_SPAN` characters ahead. Linear on
21
+ * adversarial input (bracket and backtick runs included) - see the tests.
22
+ */
23
+ import { type InlineNode } from "./inlineMarkdown.js";
24
+ /** An inline node from `parseInlineMarkdown`, or an inline code span. */
25
+ export type MarkdownInline = InlineNode | {
26
+ kind: "code";
27
+ text: string;
28
+ };
29
+ export type MarkdownBlock = {
30
+ kind: "heading";
31
+ level: number;
32
+ content: MarkdownInline[];
33
+ } | {
34
+ kind: "paragraph";
35
+ lines: MarkdownInline[][];
36
+ } | {
37
+ kind: "list";
38
+ ordered: boolean;
39
+ start: number;
40
+ items: MarkdownInline[][];
41
+ } | {
42
+ kind: "code";
43
+ language: string;
44
+ text: string;
45
+ } | {
46
+ kind: "quote";
47
+ lines: MarkdownInline[][];
48
+ } | {
49
+ kind: "table";
50
+ header: MarkdownInline[][];
51
+ rows: MarkdownInline[][][];
52
+ } | {
53
+ kind: "rule";
54
+ };
55
+ /** Parse one line: inline code spans first, the rest through parseInlineMarkdown. */
56
+ export declare function parseMarkdownInline(line: string): MarkdownInline[];
57
+ export declare function parseMarkdownBlocks(text: string): MarkdownBlock[];
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Block-level Markdown for a character message (CORE-2008).
3
+ *
4
+ * A character with Markdown output on (`preserveMarkdownInOutput`, or the
5
+ * character's "Format replies with Markdown" setting) sends headings, lists,
6
+ * tables, fenced code, quotes and rules. This turns one whole message into
7
+ * nodes a renderer maps onto DOM or JSX.
8
+ *
9
+ * Safety: model text is untrusted and the server does not sanitise it. No node
10
+ * here carries raw HTML: `<tags>` stay literal text. Every link and image goes
11
+ * through `parseInlineMarkdown`, so targets outside its scheme allowlist come
12
+ * back as `blocked` nodes. A renderer must build elements and set text, never
13
+ * inject HTML, and must not put `href` on a `blocked` node.
14
+ *
15
+ * Streaming: call it again on the accumulated text. An unclosed fence renders
16
+ * as code so far; a table line without its delimiter row stays text until the
17
+ * delimiter arrives.
18
+ *
19
+ * Cost: one pass over the lines; backtick runs are indexed once per line and a
20
+ * code span closes at most `MAX_CODE_SPAN` characters ahead. Linear on
21
+ * adversarial input (bracket and backtick runs included) - see the tests.
22
+ */
23
+ import { parseInlineMarkdown } from "./inlineMarkdown.js";
24
+ const MAX_CODE_SPAN = 2000;
25
+ const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})(.*)$/;
26
+ const HEADING = /^ {0,3}(#{1,6})(?:[ \t]+|$)/;
27
+ const RULE = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
28
+ const BULLET = /^[ \t]*([-*+])[ \t]+/;
29
+ const ORDERED = /^[ \t]*(\d{1,9})[.)][ \t]+/;
30
+ const QUOTE = /^ {0,3}>[ \t]?/;
31
+ function isBlank(line) {
32
+ return line.trim() === "";
33
+ }
34
+ function headingText(line, prefixLength) {
35
+ let text = line.slice(prefixLength).trimEnd();
36
+ let end = text.length;
37
+ while (end > 0 && text[end - 1] === "#")
38
+ end--;
39
+ if (end < text.length && (end === 0 || text[end - 1] === " " || text[end - 1] === "\t")) {
40
+ text = text.slice(0, end);
41
+ }
42
+ return text.trimEnd();
43
+ }
44
+ function splitCells(line) {
45
+ let body = line.trim();
46
+ if (body.startsWith("|"))
47
+ body = body.slice(1);
48
+ if (body.endsWith("|"))
49
+ body = body.slice(0, -1);
50
+ return body.split("|").map((cell) => cell.trim());
51
+ }
52
+ function isDelimiterRow(line) {
53
+ if (!line.includes("-"))
54
+ return false;
55
+ const cells = splitCells(line);
56
+ if (cells.length === 0)
57
+ return false;
58
+ return cells.every((cell) => {
59
+ let i = 0;
60
+ let j = cell.length;
61
+ if (cell[i] === ":")
62
+ i++;
63
+ if (j > i && cell[j - 1] === ":")
64
+ j--;
65
+ if (j <= i)
66
+ return false;
67
+ for (let k = i; k < j; k++)
68
+ if (cell[k] !== "-")
69
+ return false;
70
+ return true;
71
+ });
72
+ }
73
+ function isTableRow(line) {
74
+ return line.includes("|") && !isBlank(line);
75
+ }
76
+ /** Start positions of every backtick run in `line`, grouped by run length. */
77
+ function backtickRuns(line) {
78
+ const runs = new Map();
79
+ let i = 0;
80
+ while (i < line.length) {
81
+ if (line[i] !== "`") {
82
+ i++;
83
+ continue;
84
+ }
85
+ const start = i;
86
+ while (i < line.length && line[i] === "`")
87
+ i++;
88
+ const length = i - start;
89
+ const starts = runs.get(length);
90
+ if (starts)
91
+ starts.push(start);
92
+ else
93
+ runs.set(length, [start]);
94
+ }
95
+ return runs;
96
+ }
97
+ /** First entry of a sorted array greater than `after`, or -1. */
98
+ function nextAfter(sorted, after) {
99
+ let lo = 0;
100
+ let hi = sorted.length;
101
+ while (lo < hi) {
102
+ const mid = (lo + hi) >> 1;
103
+ if (sorted[mid] <= after)
104
+ lo = mid + 1;
105
+ else
106
+ hi = mid;
107
+ }
108
+ return lo < sorted.length ? sorted[lo] : -1;
109
+ }
110
+ /** Parse one line: inline code spans first, the rest through parseInlineMarkdown. */
111
+ export function parseMarkdownInline(line) {
112
+ const out = [];
113
+ const pushRest = (text) => {
114
+ if (!text)
115
+ return;
116
+ for (const node of parseInlineMarkdown(text)) {
117
+ const last = out[out.length - 1];
118
+ if (node.kind === "text" && last?.kind === "text")
119
+ last.text += node.text;
120
+ else
121
+ out.push(node);
122
+ }
123
+ };
124
+ // Every backtick run is found once and a closer is looked up by run length
125
+ // (binary search), so a line of many unmatched runs stays linear.
126
+ const runs = line.includes("`") ? backtickRuns(line) : null;
127
+ let textStart = 0;
128
+ let i = 0;
129
+ while (runs && i < line.length) {
130
+ if (line[i] !== "`") {
131
+ i++;
132
+ continue;
133
+ }
134
+ let runEnd = i;
135
+ while (runEnd < line.length && line[runEnd] === "`")
136
+ runEnd++;
137
+ const length = runEnd - i;
138
+ const close = nextAfter(runs.get(length) ?? [], i);
139
+ if (close === -1 || close - runEnd > MAX_CODE_SPAN) {
140
+ i = runEnd;
141
+ continue;
142
+ }
143
+ pushRest(line.slice(textStart, i));
144
+ let code = line.slice(runEnd, close);
145
+ if (code.length > 1 && code.startsWith(" ") && code.endsWith(" ") && code.trim()) {
146
+ code = code.slice(1, -1);
147
+ }
148
+ out.push({ kind: "code", text: code });
149
+ i = close + length;
150
+ textStart = i;
151
+ }
152
+ pushRest(line.slice(textStart));
153
+ return out;
154
+ }
155
+ export function parseMarkdownBlocks(text) {
156
+ const lines = text.replace(/\r\n?/g, "\n").split("\n");
157
+ const blocks = [];
158
+ let i = 0;
159
+ while (i < lines.length) {
160
+ const line = lines[i];
161
+ if (isBlank(line)) {
162
+ i++;
163
+ continue;
164
+ }
165
+ const fence = FENCE_OPEN.exec(line);
166
+ if (fence && !(fence[1][0] === "`" && fence[2].includes("`"))) {
167
+ const marker = fence[1];
168
+ const language = fence[2].trim().split(/[ \t]/)[0] ?? "";
169
+ const body = [];
170
+ i++;
171
+ while (i < lines.length) {
172
+ const candidate = lines[i].trim();
173
+ let run = 0;
174
+ while (run < candidate.length && candidate[run] === marker[0])
175
+ run++;
176
+ if (run >= marker.length && run === candidate.length && lines[i].search(/\S/) <= 3)
177
+ break;
178
+ body.push(lines[i]);
179
+ i++;
180
+ }
181
+ i++; // the closing fence, or past the end when it has not arrived yet
182
+ blocks.push({ kind: "code", language, text: body.join("\n") });
183
+ continue;
184
+ }
185
+ const heading = HEADING.exec(line);
186
+ if (heading) {
187
+ blocks.push({
188
+ kind: "heading",
189
+ level: heading[1].length,
190
+ content: parseMarkdownInline(headingText(line, heading[0].length)),
191
+ });
192
+ i++;
193
+ continue;
194
+ }
195
+ if (RULE.test(line)) {
196
+ blocks.push({ kind: "rule" });
197
+ i++;
198
+ continue;
199
+ }
200
+ if (isTableRow(line) && i + 1 < lines.length && isDelimiterRow(lines[i + 1])) {
201
+ const header = splitCells(line).map(parseMarkdownInline);
202
+ const rows = [];
203
+ i += 2;
204
+ while (i < lines.length && isTableRow(lines[i])) {
205
+ rows.push(splitCells(lines[i]).map(parseMarkdownInline));
206
+ i++;
207
+ }
208
+ blocks.push({ kind: "table", header, rows });
209
+ continue;
210
+ }
211
+ if (QUOTE.test(line)) {
212
+ const quoteLines = [];
213
+ while (i < lines.length && QUOTE.test(lines[i])) {
214
+ quoteLines.push(parseMarkdownInline(lines[i].replace(QUOTE, "")));
215
+ i++;
216
+ }
217
+ blocks.push({ kind: "quote", lines: quoteLines });
218
+ continue;
219
+ }
220
+ const ordered = ORDERED.exec(line);
221
+ const bullet = ordered ? null : BULLET.exec(line);
222
+ if (ordered || bullet) {
223
+ const isOrdered = Boolean(ordered);
224
+ const items = [];
225
+ const start = ordered ? Number(ordered[1]) : 1;
226
+ while (i < lines.length) {
227
+ const item = isOrdered ? ORDERED.exec(lines[i]) : BULLET.exec(lines[i]);
228
+ if (!item)
229
+ break;
230
+ items.push(parseMarkdownInline(lines[i].slice(item[0].length)));
231
+ i++;
232
+ }
233
+ blocks.push({ kind: "list", ordered: isOrdered, start, items });
234
+ continue;
235
+ }
236
+ const paragraph = [];
237
+ while (i < lines.length && !isBlank(lines[i])) {
238
+ const next = lines[i];
239
+ if (paragraph.length > 0 &&
240
+ (FENCE_OPEN.test(next) ||
241
+ HEADING.test(next) ||
242
+ QUOTE.test(next) ||
243
+ ORDERED.test(next) ||
244
+ BULLET.test(next) ||
245
+ (isTableRow(next) && i + 1 < lines.length && isDelimiterRow(lines[i + 1])))) {
246
+ break;
247
+ }
248
+ paragraph.push(parseMarkdownInline(next));
249
+ i++;
250
+ }
251
+ blocks.push({ kind: "paragraph", lines: paragraph });
252
+ }
253
+ return blocks;
254
+ }
@@ -25,6 +25,8 @@ export { AudioRenderer } from './AudioRenderer.js';
25
25
  export * from '../core/types.js';
26
26
  export { parseInlineMarkdown, mediaKindForUrl, isSafeHref, compactUrl } from '../utils/inlineMarkdown.js';
27
27
  export type { InlineNode, MediaKind } from '../utils/inlineMarkdown.js';
28
+ export { parseMarkdownBlocks, parseMarkdownInline } from '../utils/markdownBlocks.js';
29
+ export type { MarkdownBlock, MarkdownInline } from '../utils/markdownBlocks.js';
28
30
  export { linkKindForUrl, describeUrl } from '../utils/linkPresentation.js';
29
31
  export type { LinkKind } from '../utils/linkPresentation.js';
30
32
  export { resolveLinkPreviewCached, isCardWorthy, LINK_PREVIEW_TIMEOUT_MS } from '../utils/linkPreview.js';
@@ -28,5 +28,6 @@ export { AudioRenderer } from './AudioRenderer.js';
28
28
  export * from '../core/types.js';
29
29
  // Inline markdown tokenizer, for building your own chat UI.
30
30
  export { parseInlineMarkdown, mediaKindForUrl, isSafeHref, compactUrl } from '../utils/inlineMarkdown.js';
31
+ export { parseMarkdownBlocks, parseMarkdownInline } from '../utils/markdownBlocks.js';
31
32
  export { linkKindForUrl, describeUrl } from '../utils/linkPresentation.js';
32
33
  export { resolveLinkPreviewCached, isCardWorthy, LINK_PREVIEW_TIMEOUT_MS } from '../utils/linkPreview.js';
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "2.1.0-beta.3";
1
+ export declare const SDK_VERSION = "2.2.0-beta.0";