@seclai/react 0.0.16 → 0.0.18
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/README.md +138 -13
- package/dist/chunk-OFKVHNZ6.js +117 -0
- package/dist/chunk-VRNPDCWI.js +134 -0
- package/dist/extensions-D2MHwNt1.d.ts +49 -0
- package/dist/html.d.ts +22 -0
- package/dist/html.js +11 -0
- package/dist/index.d.ts +39 -10
- package/dist/index.js +584 -258
- package/dist/math.d.ts +22 -0
- package/dist/math.js +106 -0
- package/dist/mermaid.d.ts +30 -0
- package/dist/mermaid.js +126 -0
- package/dist/styles.css +175 -5
- package/package.json +49 -12
- package/dist/index.cjs +0 -1456
- package/dist/index.d.cts +0 -474
package/README.md
CHANGED
|
@@ -10,6 +10,14 @@ npm install @seclai/react
|
|
|
10
10
|
|
|
11
11
|
`react` and `react-dom` 18 or later are peer dependencies. Mount the handlers on your server first: see the [`@seclai/handlers` README](https://www.npmjs.com/package/@seclai/handlers#usage).
|
|
12
12
|
|
|
13
|
+
### Module format
|
|
14
|
+
|
|
15
|
+
`@seclai/react` ships as ES modules only. Bundlers and `import` work as usual. CommonJS code, such as a server-rendering setup, can `require` it on Node 22.12 or later; Node 22.12 and Node 23.0 to 23.4 print an `ExperimentalWarning` the first time, and Node 22.13+ and 23.5+ don't.
|
|
16
|
+
|
|
17
|
+
In a TypeScript CommonJS project, set `module` to `nodenext` (TypeScript 5.8+) or `node20` (TypeScript 5.9+), so the compiler allows that `require`. With `node16` or `node18` it reports error TS1479 on the import. `commonjs` with `moduleResolution` `node10` and the `bundler` setting work as they are.
|
|
18
|
+
|
|
19
|
+
Jest's default CommonJS mode doesn't transform packages in `node_modules`, so tell it to transform this one, for example with `transformIgnorePatterns: ["/node_modules/(?!(\\.pnpm/)?@seclai[/+])"]` (the `.pnpm` part covers pnpm's layout), using a transform that converts ES modules to CommonJS, such as `babel-jest` with `@babel/preset-env`. Vitest needs no setup.
|
|
20
|
+
|
|
13
21
|
## Usage
|
|
14
22
|
|
|
15
23
|
```tsx
|
|
@@ -33,6 +41,7 @@ export function App() {
|
|
|
33
41
|
- **`AgentChat`** sends each message as a run with a shared session id and streams the reply.
|
|
34
42
|
- **`SeclaiAgent`** renders one of the two based on `mode`.
|
|
35
43
|
- **`RunProgress`** shows a running run's steps and elapsed time. See [below](#runprogress).
|
|
44
|
+
- **`MarkdownContent`** renders the agent's replies, including while they stream. See [Markdown](#markdown).
|
|
36
45
|
|
|
37
46
|
### Files in `AgentChat`
|
|
38
47
|
|
|
@@ -289,25 +298,141 @@ Here `toJpeg` is your own code that draws the image on a canvas and returns `can
|
|
|
289
298
|
- **`saveFile(urlOrBlob, filename)`** saves a URL or a `Blob` through a temporary `<a download>`. A URL that isn't `http:`, `https:`, `blob:` or relative (such as `javascript:`) is skipped with a warning. For a `Blob` it makes an object URL and revokes it 40 seconds later, once the browser has had time to start the download. Without a `document`, as in server rendering, it does nothing.
|
|
290
299
|
- **`saveFiles(files, { delayMs, signal })`** saves `{ source, filename }` files one at a time with `saveFile`, waiting `delayMs` (400 ms) between them, as "Download all" does. A `source` is a URL or a `Blob`. It stops when `signal` aborts.
|
|
291
300
|
|
|
292
|
-
##
|
|
301
|
+
## Markdown
|
|
302
|
+
|
|
303
|
+
`AgentRunForm` and `AgentChat` show the agent's replies, and the user's messages, with `MarkdownContent`. It's exported for your own UI too:
|
|
304
|
+
|
|
305
|
+
```tsx
|
|
306
|
+
import { MarkdownContent } from "@seclai/react";
|
|
307
|
+
|
|
308
|
+
<MarkdownContent content={run.text} streaming={run.status === "running"} />
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
| Prop | |
|
|
312
|
+
|---|---|
|
|
313
|
+
| `content` | Required. The Markdown |
|
|
314
|
+
| `streaming` | The text is still arriving. See [Streaming](#streaming) |
|
|
315
|
+
| `extensions` | Extensions such as `math()`, in place of the ones from `SeclaiMarkdownProvider` |
|
|
316
|
+
|
|
317
|
+
It renders [GitHub Flavored Markdown](https://github.github.com/gfm/):
|
|
318
|
+
|
|
319
|
+
- paragraphs, headings, **bold**, *emphasis*, ~~strikethrough~~, block quotes and rules;
|
|
320
|
+
- links, and bare URLs and emails, which become links;
|
|
321
|
+
- inline code and code blocks, fenced or indented, in a monospace font. Code blocks scroll sideways rather than wrap;
|
|
322
|
+
- lists, nested by indenting an item to the text of the item above, with paragraphs and code blocks inside items;
|
|
323
|
+
- tables, which scroll sideways when they're too wide;
|
|
324
|
+
- task lists (`- [ ]`, `- [x]`), as disabled checkboxes, and footnotes.
|
|
325
|
+
|
|
326
|
+
Agent replies get a few extras:
|
|
327
|
+
|
|
328
|
+
- **Numbered items keep the number the agent wrote.** Markdown only keeps a list's first number and counts on from it, so `1. 1. 1.` would read 1, 2, 3. Each number shows in a badge like `MediaPreview`'s, so "2." in the text matches image 2. The list is still an `<ol>` with `start` and `value` set.
|
|
329
|
+
- **A single newline is a line break**, as in chat apps, rather than a space. `<br>` is one too, as agents write it in table cells.
|
|
330
|
+
- **`•` works as a bullet**, as well as `-`, `*` and `+`.
|
|
331
|
+
|
|
332
|
+
Maths, Mermaid diagrams and HTML are opt-in: see [Extensions](#extensions).
|
|
333
|
+
|
|
334
|
+
### Streaming
|
|
335
|
+
|
|
336
|
+
`MarkdownContent` re-renders on every token. To stay fast on long replies, it splits the text into top-level blocks, such as paragraphs, lists, tables and code blocks, and only parses the last one again: about 2 ms per token on a 50 KB reply, where parsing the whole reply takes over 100 ms. Blocks are split where the parser ended one, so a list with blank lines between its items, or a code block holding a blank line, stays whole. A reply with a link reference definition (`[docs]: https://…`) or a footnote is parsed whole, as those change text elsewhere in it.
|
|
337
|
+
|
|
338
|
+
Partial text renders as what it is so far, without errors or garbage:
|
|
339
|
+
|
|
340
|
+
- An unclosed code fence is a code block to the end.
|
|
341
|
+
- A table's header row is text until its delimiter row arrives.
|
|
342
|
+
- An unclosed `**`, `` ` `` or `[link](` is text until it closes.
|
|
343
|
+
- Maths and diagrams render once they're complete: see [Extensions](#extensions).
|
|
344
|
+
|
|
345
|
+
With `streaming` set (`AgentRunForm` and `AgentChat` set it while a reply streams), an unfinished last line that could still turn into something else is held back until more of it arrives: a bare list marker (`-`, `2.`), the start of a rule or heading underline (`-`, `--`, `* *`), a fence (```` ``` ````, `$$`), a table's delimiter row (`| --- |`) or a bare `#`. Shown as they are, these would flash as an empty list item, or turn the line above into a heading, for a token or two.
|
|
346
|
+
|
|
347
|
+
### Extensions
|
|
348
|
+
|
|
349
|
+
HTML, maths and Mermaid diagrams are extensions, each in an entry of its own, so an app that doesn't use one doesn't bundle it. Pass them to every `MarkdownContent` at once, including the ones `AgentRunForm` and `AgentChat` render, with `SeclaiMarkdownProvider`:
|
|
350
|
+
|
|
351
|
+
```tsx
|
|
352
|
+
import { AgentChat, SeclaiMarkdownProvider } from "@seclai/react";
|
|
353
|
+
import { html } from "@seclai/react/html";
|
|
354
|
+
import { math } from "@seclai/react/math";
|
|
355
|
+
import { mermaid } from "@seclai/react/mermaid";
|
|
356
|
+
import "katex/dist/katex.min.css"; // for math()
|
|
357
|
+
|
|
358
|
+
const extensions = [html(), math(), mermaid()];
|
|
293
359
|
|
|
294
|
-
|
|
360
|
+
export function App() {
|
|
361
|
+
return (
|
|
362
|
+
<SeclaiMarkdownProvider extensions={extensions}>
|
|
363
|
+
<AgentChat />
|
|
364
|
+
</SeclaiMarkdownProvider>
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
Or pass them to one `MarkdownContent` with its `extensions` prop, which replaces the provider's. Each factory returns the same extension every time, so calling them inline is fine.
|
|
295
370
|
|
|
296
|
-
|
|
|
371
|
+
| Extension | Install | Renders |
|
|
297
372
|
|---|---|---|
|
|
298
|
-
| `
|
|
299
|
-
| `
|
|
373
|
+
| `html()` from `@seclai/react/html` | Nothing more | HTML in the Markdown, such as `<sub>`, `<kbd>`, `<details>` and inline `<svg>` charts, sanitized (see [Security](#security)). Without it, HTML shows as the text it is. It bundles an HTML parser, about 50 KB gzipped |
|
|
374
|
+
| `math()` from `@seclai/react/math` | `katex` and `remark-math` | `$…$` and `\(…\)` inline, `$$…$$` and `\[…\]` as a block, and ```` ```math ```` fences, with [KaTeX](https://katex.org). Import KaTeX's stylesheet, `katex/dist/katex.min.css`, once in your app: without it the maths shows twice, as text and as MathML |
|
|
375
|
+
| `mermaid()` from `@seclai/react/mermaid` | `mermaid` | ```` ```mermaid ```` code blocks as [Mermaid](https://mermaid.js.org) diagrams. Mermaid is loaded on demand the first time a diagram shows, so bundlers split it into chunks of its own |
|
|
376
|
+
|
|
377
|
+
**Before turning on `html()`:** with it, angle brackets in prose are read as HTML tags, and a tag that isn't on the allowlist is removed. Agents write such text all the time outside backticks, and the reader sees words go missing with no sign of why:
|
|
378
|
+
|
|
379
|
+
| The agent writes | Shows with `html()` |
|
|
380
|
+
|---|---|
|
|
381
|
+
| `Return a List<String> of names` | Return a List of names |
|
|
382
|
+
| `Pass the <filename> argument` | Pass the argument |
|
|
383
|
+
| `If a<b and c>d then swap.` | If a**d then swap.** (read as a `<b>` tag) |
|
|
384
|
+
|
|
385
|
+
Text in backticks, such as `` `List<String>` ``, is safe. So turn `html()` on only for agents that are meant to produce HTML or SVG, and prompt them to put code, types and placeholders in backticks. A tag left open also makes the rest of the reply re-parse whole on every streamed token, which slows long replies down.
|
|
386
|
+
|
|
387
|
+
`katex`, `remark-math` and `mermaid` are optional peer dependencies: install them only for the extensions you use.
|
|
388
|
+
|
|
389
|
+
```sh
|
|
390
|
+
npm install katex remark-math # for math()
|
|
391
|
+
npm install mermaid # for mermaid()
|
|
392
|
+
```
|
|
300
393
|
|
|
301
|
-
|
|
394
|
+
How they handle partial and invalid input:
|
|
302
395
|
|
|
303
|
-
-
|
|
304
|
-
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
396
|
+
- **Maths** renders once its closing delimiter arrives. Until then, `$…` is text, and a `$$` block or ```` ```math ```` fence shows its source as a code block. Invalid LaTeX shows as its source in code, not as a KaTeX error. `\(…\)` and `\[…\]` are rewritten to `$…$` and `$$…$$` before parsing, except in code. As in most Markdown maths, `$5 and $10` on one line is read as maths.
|
|
397
|
+
- **A Mermaid diagram** is drawn once its closing fence arrives. Until then, while Mermaid loads, and if the diagram has a syntax error, its source shows as a code block. `mermaid({ theme: "dark" })` picks Mermaid's theme (`"default"`, on a white background, unless set). Mermaid has one configuration per page, so the first theme used applies to every diagram.
|
|
398
|
+
|
|
399
|
+
To write your own, a `MarkdownExtension` is an object with any of `remarkPlugins`, `rehypePluginsBeforeSanitize`, `rehypePlugins`, `components` and `transform`. `rehypePlugins` run after sanitizing, so they must only add HTML they built. `components` replace the built-in ones, as in [react-markdown](https://github.com/remarkjs/react-markdown#components). Create an extension once, outside your components, rather than on every render: a new object is a new set of plugins, which renders every block again. For example, to show images inline rather than as links (see [Security](#security)):
|
|
400
|
+
|
|
401
|
+
```tsx
|
|
402
|
+
const images: MarkdownExtension = {
|
|
403
|
+
components: { img: ({ node: _, ...props }) => <img {...props} loading="lazy" /> },
|
|
404
|
+
};
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
### Security
|
|
408
|
+
|
|
409
|
+
Agent output is untrusted: a reply can be steered by whatever the agent read. So:
|
|
410
|
+
|
|
411
|
+
- **Links** keep only `http:`, `https:` and `mailto:` URLs, and relative ones (`/path`, `#id`). Anything else, such as `javascript:` or `data:`, is removed, and the link shows as its text. `http:` and `https:` links open in a new tab with `rel="noopener noreferrer"`.
|
|
412
|
+
- **Images show as links** to the image (with its alt text, or else its URL), rather than loading. A reply could otherwise use an image URL to send data from the conversation to another server, or to track that it was viewed. An image inside a link shows as its alt text. To show images anyway, replace the `img` component with an extension, as above; the URL rules still apply, so only `http:`, `https:` and relative image URLs load.
|
|
413
|
+
- **HTML shows as text** unless `html()` is on. With it, HTML is sanitized to an allowlist: [GitHub's](https://github.com/syntax-tree/hast-util-sanitize#defaultschema), plus SVG shapes, text, gradients, markers, masks and filters. `<script>`, `<style>`, `<iframe>`, `<foreignObject>`, `<template>` and `<noscript>` are removed with their content; other elements not on the list, such as `<form>` or `<object>`, are removed but keep their text. `on*` event handlers, `style`, `class`, `accesskey` and `tabindex` attributes are removed. Every `id` is prefixed with `user-content-`, so a reply can't clobber the app's own ids, and in-page links (`#id`) follow the prefix. In SVG, `href` and `url(…)` can only point at an id in the same reply.
|
|
414
|
+
- **KaTeX** runs with `trust: false`, so `\href`, `\url`, `\includegraphics` and the `\html…` commands don't produce links, images or attributes.
|
|
415
|
+
- **Mermaid** runs with `securityLevel: "strict"` and `startOnLoad: false`, and syntax errors show the source rather than Mermaid's error diagram. Labels can't hold images or `style` attributes, and a diagram's `%%{init: …}%%` directive can't set `themeCSS`, `fontFamily`, `altFontFamily` or the label sanitizing, which Mermaid copies into the diagram as they are, so a diagram can't load outside URLs or restyle the page.
|
|
416
|
+
|
|
417
|
+
### Styling Markdown
|
|
418
|
+
|
|
419
|
+
The stylesheet styles Markdown with the same `--seclai-*` variables, in light and dark colour schemes. The root is a `div.seclai-markdown`, and its elements are plain HTML (`p`, `h1` to `h6`, `pre > code`, `table`, `blockquote` and so on), so `.seclai-markdown h2` and the like work for your own styles. It also uses:
|
|
420
|
+
|
|
421
|
+
| Class | |
|
|
422
|
+
|---|---|
|
|
423
|
+
| `.seclai-markdown-number` | A numbered item's badge, the first child of its `li`. The item's content is in a `div` after it |
|
|
424
|
+
| `.seclai-markdown-table` | The scrolling wrapper around a table |
|
|
425
|
+
| `.seclai-markdown-image` | The link an image shows as |
|
|
426
|
+
| `.seclai-markdown-math` | KaTeX's output: a `span` inline, a `div` for a block |
|
|
427
|
+
| `.seclai-markdown-mermaid` | A drawn diagram, with `data-theme` set to its Mermaid theme |
|
|
428
|
+
| `.task-list-item`, `.contains-task-list` | A task list's items, and the list |
|
|
429
|
+
| `section.footnotes` | The footnotes, at the end |
|
|
430
|
+
|
|
431
|
+
Two more variables: `--seclai-code-font` (the monospace font for code) and `--seclai-code-surface` (the background of code blocks and inline code).
|
|
432
|
+
|
|
433
|
+
## Placeholders
|
|
309
434
|
|
|
310
|
-
|
|
435
|
+
`MediaPreview` is exported so the API is in place, but it's minimal until it's ported from the main Seclai app: it shows image cards (see [Media](#media)) and a download link for everything else. Audio, video and PDF previews are still to come.
|
|
311
436
|
|
|
312
437
|
## License
|
|
313
438
|
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// src/markdown/text.ts
|
|
4
|
+
function normalizeNewlines(text) {
|
|
5
|
+
return text.includes("\r") ? text.replace(/\r\n?/g, "\n") : text;
|
|
6
|
+
}
|
|
7
|
+
var CONTAINER_PREFIX = /^[\s>]*/;
|
|
8
|
+
var PENDING_LINE = /^(?:\d{1,9}[.)]?)?[-*+_=•|:`~$#\s]*$/;
|
|
9
|
+
function holdBackPendingLine(text) {
|
|
10
|
+
const start = text.lastIndexOf("\n") + 1;
|
|
11
|
+
const line = text.slice(start).replace(CONTAINER_PREFIX, "");
|
|
12
|
+
return PENDING_LINE.test(line) ? text.slice(0, start) : text;
|
|
13
|
+
}
|
|
14
|
+
var FENCE_OPEN = /^[ \t>]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)*(`{3,}(?=[^`]*$)|~{3,})/;
|
|
15
|
+
var FENCE_CLOSE = /^[ \t>]*(`{3,}|~{3,})[ \t]*$/;
|
|
16
|
+
function codeRanges(text) {
|
|
17
|
+
const ranges = [];
|
|
18
|
+
let fence = null;
|
|
19
|
+
let runStart = -1;
|
|
20
|
+
const spans = (start, end) => {
|
|
21
|
+
let at = start;
|
|
22
|
+
while (at < end) {
|
|
23
|
+
const tick = text.indexOf("`", at);
|
|
24
|
+
if (tick === -1 || tick >= end) break;
|
|
25
|
+
let length = 1;
|
|
26
|
+
while (text[tick + length] === "`") length++;
|
|
27
|
+
let slashes = 0;
|
|
28
|
+
while (text[tick - 1 - slashes] === "\\") slashes++;
|
|
29
|
+
if (slashes % 2 === 1) {
|
|
30
|
+
at = tick + 1;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
let close = tick + length;
|
|
34
|
+
let found = -1;
|
|
35
|
+
while (close < end) {
|
|
36
|
+
const next = text.indexOf("`", close);
|
|
37
|
+
if (next === -1 || next >= end) break;
|
|
38
|
+
let run = 1;
|
|
39
|
+
while (text[next + run] === "`") run++;
|
|
40
|
+
if (run === length) {
|
|
41
|
+
found = next;
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
close = next + run;
|
|
45
|
+
}
|
|
46
|
+
if (found === -1) {
|
|
47
|
+
at = tick + length;
|
|
48
|
+
} else {
|
|
49
|
+
ranges.push([tick, found + length]);
|
|
50
|
+
at = found + length;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
let lineStart = 0;
|
|
55
|
+
while (lineStart <= text.length) {
|
|
56
|
+
const newline = text.indexOf("\n", lineStart);
|
|
57
|
+
const lineEnd = newline === -1 ? text.length : newline;
|
|
58
|
+
const line = text.slice(lineStart, lineEnd);
|
|
59
|
+
if (fence) {
|
|
60
|
+
const closing = FENCE_CLOSE.exec(line)?.[1];
|
|
61
|
+
if (closing && closing[0] === fence.char && closing.length >= fence.length) {
|
|
62
|
+
ranges.push([fence.start, lineEnd]);
|
|
63
|
+
fence = null;
|
|
64
|
+
}
|
|
65
|
+
} else {
|
|
66
|
+
const opening = FENCE_OPEN.exec(line)?.[1];
|
|
67
|
+
const blank = !line.trim();
|
|
68
|
+
if (opening || blank) {
|
|
69
|
+
if (runStart !== -1) spans(runStart, lineStart);
|
|
70
|
+
runStart = -1;
|
|
71
|
+
} else if (runStart === -1) {
|
|
72
|
+
runStart = lineStart;
|
|
73
|
+
}
|
|
74
|
+
if (opening) fence = { char: opening[0], length: opening.length, start: lineStart };
|
|
75
|
+
}
|
|
76
|
+
if (newline === -1) break;
|
|
77
|
+
lineStart = newline + 1;
|
|
78
|
+
}
|
|
79
|
+
if (fence) ranges.push([fence.start, text.length]);
|
|
80
|
+
else if (runStart !== -1) spans(runStart, text.length);
|
|
81
|
+
return ranges.sort((a, b) => a[0] - b[0]);
|
|
82
|
+
}
|
|
83
|
+
function replaceOutsideCode(text, pattern, replace) {
|
|
84
|
+
const ranges = codeRanges(text);
|
|
85
|
+
if (ranges.length === 0) {
|
|
86
|
+
return text.replace(pattern, (match, ...rest) => replace(match, rest.at(-2), text));
|
|
87
|
+
}
|
|
88
|
+
let masked = "";
|
|
89
|
+
let at = 0;
|
|
90
|
+
for (const [start, end] of ranges) {
|
|
91
|
+
masked += text.slice(at, start) + "\0".repeat(end - start);
|
|
92
|
+
at = end;
|
|
93
|
+
}
|
|
94
|
+
masked += text.slice(at);
|
|
95
|
+
let out = "";
|
|
96
|
+
at = 0;
|
|
97
|
+
for (const match of masked.matchAll(pattern)) {
|
|
98
|
+
const start = match.index;
|
|
99
|
+
const end = start + match[0].length;
|
|
100
|
+
out += text.slice(at, start) + replace(text.slice(start, end), start, text);
|
|
101
|
+
at = end;
|
|
102
|
+
}
|
|
103
|
+
return out + text.slice(at);
|
|
104
|
+
}
|
|
105
|
+
var BULLET = /^([ \t>]*)•(?=[ \t])/gm;
|
|
106
|
+
function normalizeBullets(text) {
|
|
107
|
+
return text.includes("\u2022") ? replaceOutsideCode(text, BULLET, (match) => `${match.slice(0, -1)}-`) : text;
|
|
108
|
+
}
|
|
109
|
+
var MAY_DEFINE = /^[ \t]*(?:(?:>|(?:[-*+]|\d{1,9}[.)])[ \t])[ \t]*)*\[(?:[^\\\]]|\\[\s\S]){1,999}\]:/m;
|
|
110
|
+
|
|
111
|
+
export {
|
|
112
|
+
normalizeNewlines,
|
|
113
|
+
holdBackPendingLine,
|
|
114
|
+
replaceOutsideCode,
|
|
115
|
+
normalizeBullets,
|
|
116
|
+
MAY_DEFINE
|
|
117
|
+
};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// src/markdown/plugins.ts
|
|
4
|
+
function visit(node, test, fn, parent) {
|
|
5
|
+
if (node.type === test) fn(node, parent);
|
|
6
|
+
if ("children" in node) for (const child of node.children) visit(child, test, fn, node);
|
|
7
|
+
}
|
|
8
|
+
function remarkListNumbers() {
|
|
9
|
+
return (tree, file) => {
|
|
10
|
+
const source = String(file.value);
|
|
11
|
+
visit(tree, "list", (list) => {
|
|
12
|
+
if (list.type !== "list" || !list.ordered) return;
|
|
13
|
+
for (const item of list.children) {
|
|
14
|
+
const offset = item.position?.start.offset;
|
|
15
|
+
if (offset === void 0) continue;
|
|
16
|
+
const number = /^[ \t]*(\d{1,9})[.)]/.exec(source.slice(offset, offset + 16))?.[1];
|
|
17
|
+
if (number === void 0) continue;
|
|
18
|
+
item.data = { ...item.data, hProperties: { ...item.data?.hProperties, value: number } };
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
var LINE_ENDING = /[ \t]*\n[ \t]*/;
|
|
24
|
+
function remarkLineBreaks() {
|
|
25
|
+
const split = (parent) => {
|
|
26
|
+
const children = [];
|
|
27
|
+
let changed = false;
|
|
28
|
+
for (const child of parent.children) {
|
|
29
|
+
if (child.type === "text" && child.value.includes("\n")) {
|
|
30
|
+
changed = true;
|
|
31
|
+
child.value.split(LINE_ENDING).forEach((value, i) => {
|
|
32
|
+
if (i > 0) children.push({ type: "break" });
|
|
33
|
+
if (value) children.push({ type: "text", value });
|
|
34
|
+
});
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if ("children" in child) split(child);
|
|
38
|
+
children.push(child);
|
|
39
|
+
}
|
|
40
|
+
if (changed) parent.children = children;
|
|
41
|
+
};
|
|
42
|
+
return (tree) => split(tree);
|
|
43
|
+
}
|
|
44
|
+
var BR = /^<br\s*\/?>$/i;
|
|
45
|
+
function remarkHtmlBreaks() {
|
|
46
|
+
return (tree) => visit(tree, "html", (node, parent) => {
|
|
47
|
+
if (node.type !== "html" || !parent || parent.type === "root" || !BR.test(node.value)) return;
|
|
48
|
+
const index = parent.children.indexOf(node);
|
|
49
|
+
parent.children[index] = { type: "break" };
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function isClosedFence(node, source) {
|
|
53
|
+
const start = node.position?.start.offset;
|
|
54
|
+
const end = node.position?.end.offset;
|
|
55
|
+
if (start === void 0 || end === void 0) return true;
|
|
56
|
+
const text = source.slice(start, end);
|
|
57
|
+
const opening = /^[ \t]*(`{3,}|~{3,}|\${2,})/.exec(text)?.[1];
|
|
58
|
+
if (!opening) return true;
|
|
59
|
+
const newline = text.lastIndexOf("\n");
|
|
60
|
+
if (newline === -1) return false;
|
|
61
|
+
const closing = /^[ \t>]*(`+|~+|\$+)[ \t]*$/.exec(text.slice(newline + 1))?.[1];
|
|
62
|
+
return !!closing && closing[0] === opening[0] && closing.length >= opening.length;
|
|
63
|
+
}
|
|
64
|
+
function remarkOpenFencesAsCode(languages) {
|
|
65
|
+
return () => (tree, file) => {
|
|
66
|
+
const source = String(file.value);
|
|
67
|
+
visit(tree, "code", (node) => {
|
|
68
|
+
const code = node;
|
|
69
|
+
if (code.lang && languages.includes(code.lang.toLowerCase()) && !isClosedFence(code, source)) {
|
|
70
|
+
code.lang = null;
|
|
71
|
+
code.meta = null;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
var isElement = (node) => node.type === "element";
|
|
77
|
+
function rehypeRawAsText() {
|
|
78
|
+
const walk = (node) => {
|
|
79
|
+
node.children.forEach((child, index) => {
|
|
80
|
+
const raw = child;
|
|
81
|
+
if (raw.type === "raw") node.children[index] = { type: "text", value: raw.value };
|
|
82
|
+
else if (child.type === "element") walk(child);
|
|
83
|
+
});
|
|
84
|
+
};
|
|
85
|
+
return (tree) => walk(tree);
|
|
86
|
+
}
|
|
87
|
+
function rehypeTrimBlocks() {
|
|
88
|
+
return (tree) => {
|
|
89
|
+
tree.children = tree.children.filter((child) => child.type !== "text" || child.value.trim() !== "");
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function rehypeListBadges() {
|
|
93
|
+
const walk = (node) => {
|
|
94
|
+
for (const child of node.children) {
|
|
95
|
+
if (child.type !== "element") continue;
|
|
96
|
+
walk(child);
|
|
97
|
+
if (child.tagName !== "ol") continue;
|
|
98
|
+
const start = Number(child.properties.start);
|
|
99
|
+
let next = Number.isInteger(start) ? start : 1;
|
|
100
|
+
let first;
|
|
101
|
+
for (const item of child.children) {
|
|
102
|
+
if (!isElement(item) || item.tagName !== "li") continue;
|
|
103
|
+
const value = Number(item.properties.value);
|
|
104
|
+
const number = Number.isInteger(value) && item.properties.value !== void 0 ? value : next;
|
|
105
|
+
first ??= number;
|
|
106
|
+
next = number + 1;
|
|
107
|
+
item.properties.value = number;
|
|
108
|
+
item.children = [
|
|
109
|
+
{
|
|
110
|
+
type: "element",
|
|
111
|
+
tagName: "span",
|
|
112
|
+
properties: { className: ["seclai-markdown-number"] },
|
|
113
|
+
children: [{ type: "text", value: String(number) }]
|
|
114
|
+
},
|
|
115
|
+
{ type: "element", tagName: "div", properties: {}, children: item.children }
|
|
116
|
+
];
|
|
117
|
+
}
|
|
118
|
+
if (first !== void 0) child.properties.start = first;
|
|
119
|
+
child.properties.role = "list";
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
return (tree) => walk(tree);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export {
|
|
126
|
+
remarkListNumbers,
|
|
127
|
+
remarkLineBreaks,
|
|
128
|
+
remarkHtmlBreaks,
|
|
129
|
+
isClosedFence,
|
|
130
|
+
remarkOpenFencesAsCode,
|
|
131
|
+
rehypeRawAsText,
|
|
132
|
+
rehypeTrimBlocks,
|
|
133
|
+
rehypeListBadges
|
|
134
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { Options, Components } from 'react-markdown';
|
|
4
|
+
|
|
5
|
+
type PluggableList = NonNullable<Options["remarkPlugins"]>;
|
|
6
|
+
/**
|
|
7
|
+
* Adds to what `MarkdownContent` renders: HTML with `html()` from
|
|
8
|
+
* `@seclai/react/html`, maths with `math()` from `@seclai/react/math`, or
|
|
9
|
+
* diagrams with `mermaid()` from `@seclai/react/mermaid`.
|
|
10
|
+
*/
|
|
11
|
+
interface MarkdownExtension {
|
|
12
|
+
/** remark plugins, run on the Markdown tree after the built-in syntax (GFM). */
|
|
13
|
+
remarkPlugins?: PluggableList;
|
|
14
|
+
/**
|
|
15
|
+
* rehype plugins, run on the HTML tree before it's sanitized, such as
|
|
16
|
+
* `rehype-raw` in `html()`. What they add is sanitized.
|
|
17
|
+
*/
|
|
18
|
+
rehypePluginsBeforeSanitize?: PluggableList;
|
|
19
|
+
/**
|
|
20
|
+
* rehype plugins, run on the HTML tree after it's sanitized. What they add
|
|
21
|
+
* isn't sanitized, so they must only add HTML they built themselves.
|
|
22
|
+
*/
|
|
23
|
+
rehypePlugins?: PluggableList;
|
|
24
|
+
/**
|
|
25
|
+
* Components for elements, as in `react-markdown`. They replace the built-in
|
|
26
|
+
* ones for the same element, such as `a`, `img` or `table`.
|
|
27
|
+
*/
|
|
28
|
+
components?: Components;
|
|
29
|
+
/** Rewrites the whole text before it's parsed, for syntax Markdown doesn't have. */
|
|
30
|
+
transform?: (markdown: string) => string;
|
|
31
|
+
}
|
|
32
|
+
interface SeclaiMarkdownProviderProps {
|
|
33
|
+
/** The extensions for every `MarkdownContent` inside, including the ones `AgentChat` and `AgentRunForm` render. */
|
|
34
|
+
extensions: readonly MarkdownExtension[];
|
|
35
|
+
children?: ReactNode;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Sets the Markdown extensions for every `MarkdownContent` inside it, such as
|
|
39
|
+
* the ones `AgentChat` and `AgentRunForm` render:
|
|
40
|
+
*
|
|
41
|
+
* ```tsx
|
|
42
|
+
* <SeclaiMarkdownProvider extensions={[math(), mermaid()]}>
|
|
43
|
+
* <AgentChat />
|
|
44
|
+
* </SeclaiMarkdownProvider>
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
declare function SeclaiMarkdownProvider({ extensions, children }: SeclaiMarkdownProviderProps): react.JSX.Element;
|
|
48
|
+
|
|
49
|
+
export { type MarkdownExtension as M, SeclaiMarkdownProvider as S, type SeclaiMarkdownProviderProps as a };
|
package/dist/html.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { M as MarkdownExtension } from './extensions-D2MHwNt1.js';
|
|
2
|
+
import 'react';
|
|
3
|
+
import 'react-markdown';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* HTML written in the Markdown, such as `<sub>`, `<kbd>`, `<details>` or an
|
|
7
|
+
* inline `<svg>` chart, rendered rather than shown as text. It's sanitized to
|
|
8
|
+
* an allowlist: GitHub's, plus SVG shapes, text, gradients and filters. Scripts,
|
|
9
|
+
* styles, event handlers, `<iframe>`, `<foreignObject>`, forms and URLs other
|
|
10
|
+
* than http, https and mailto are removed, and SVG can only reference ids in
|
|
11
|
+
* the same reply.
|
|
12
|
+
*
|
|
13
|
+
* ```tsx
|
|
14
|
+
* import { SeclaiMarkdownProvider } from "@seclai/react";
|
|
15
|
+
* import { html } from "@seclai/react/html";
|
|
16
|
+
*
|
|
17
|
+
* <SeclaiMarkdownProvider extensions={[html()]}>…</SeclaiMarkdownProvider>
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
declare function html(): MarkdownExtension;
|
|
21
|
+
|
|
22
|
+
export { html };
|
package/dist/html.js
ADDED
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
+
import { M as MarkdownExtension } from './extensions-D2MHwNt1.js';
|
|
4
|
+
export { S as SeclaiMarkdownProvider, a as SeclaiMarkdownProviderProps } from './extensions-D2MHwNt1.js';
|
|
5
|
+
import 'react-markdown';
|
|
3
6
|
|
|
4
7
|
/**
|
|
5
8
|
* The handlers' wire format, declared here rather than imported from
|
|
@@ -457,18 +460,44 @@ interface SaveFilesOptions {
|
|
|
457
460
|
declare function saveFiles(files: readonly SaveFilesEntry[], { delayMs, signal }?: SaveFilesOptions): Promise<void>;
|
|
458
461
|
|
|
459
462
|
interface MarkdownContentProps {
|
|
463
|
+
/** The Markdown to show. */
|
|
460
464
|
content: string;
|
|
465
|
+
/**
|
|
466
|
+
* The text is still streaming in. An unfinished last line that could still
|
|
467
|
+
* become something else, such as a bare `-` or `2.`, is held back until more
|
|
468
|
+
* arrives. Leave it off for finished text.
|
|
469
|
+
*/
|
|
470
|
+
streaming?: boolean;
|
|
471
|
+
/**
|
|
472
|
+
* Extensions, such as `math()` and `mermaid()`. When set, they replace the
|
|
473
|
+
* ones from `SeclaiMarkdownProvider`.
|
|
474
|
+
*/
|
|
475
|
+
extensions?: readonly MarkdownExtension[];
|
|
461
476
|
}
|
|
462
477
|
/**
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
*
|
|
466
|
-
*
|
|
467
|
-
*
|
|
468
|
-
*
|
|
469
|
-
*
|
|
470
|
-
*
|
|
478
|
+
* Renders Markdown, such as an agent's reply, including while it streams in.
|
|
479
|
+
* `AgentRunForm` and `AgentChat` use it for the agent's output and the user's
|
|
480
|
+
* messages.
|
|
481
|
+
*
|
|
482
|
+
* It renders GitHub Flavored Markdown: headings, emphasis, links (and bare
|
|
483
|
+
* URLs), inline code and code blocks, block quotes, lists (nested, and with
|
|
484
|
+
* block content in items), tables, task lists, strikethrough, footnotes and
|
|
485
|
+
* rules. Numbered items keep the number the agent wrote, shown in a badge that
|
|
486
|
+
* matches `MediaPreview`'s. A single newline is a line break, `<br>` is one
|
|
487
|
+
* too, and `•` works as a bullet.
|
|
488
|
+
*
|
|
489
|
+
* Agent output is untrusted: links are limited to http, https, mailto and
|
|
490
|
+
* relative URLs, and external ones open in a new tab; images show as links
|
|
491
|
+
* rather than loading; other HTML shows as text.
|
|
492
|
+
*
|
|
493
|
+
* HTML (sanitized), maths and Mermaid diagrams are opt-in extensions:
|
|
494
|
+
* `html()`, `math()` and `mermaid()` from `@seclai/react/html`,
|
|
495
|
+
* `@seclai/react/math` and `@seclai/react/mermaid`. Pass them in `extensions`,
|
|
496
|
+
* or to every `MarkdownContent` at once with `SeclaiMarkdownProvider`.
|
|
497
|
+
*
|
|
498
|
+
* While the text streams in, it's split into blocks and only the last one is
|
|
499
|
+
* parsed again as tokens arrive. Pass `streaming` until it's complete.
|
|
471
500
|
*/
|
|
472
|
-
declare
|
|
501
|
+
declare const MarkdownContent: react.NamedExoticComponent<MarkdownContentProps>;
|
|
473
502
|
|
|
474
|
-
export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, type AgentChatAttachButton, type AgentChatAttachment, type AgentChatFile, type AgentChatMessage, type AgentChatProps, type AgentChatTurn, type AgentEndpointOptions, type AgentEndpoints, type AgentRunEvent, AgentRunForm, type AgentRunFormProps, type AgentRunState, type AgentRunStatus, type AgentRunStep, type AgentUiMode, type AttachmentReferences, DEFAULT_BASE_PATH, type EndpointRequestOptions, MarkdownContent, type MarkdownContentProps, type MediaAspectRatio, MediaGallery, type MediaGalleryProps, MediaPreview, type MediaPreviewProps, MediaSkeleton, type MediaSkeletonProps, MediaViewer, type MediaViewerProps, RunProgress, type RunProgressProps, type RunProgressRun, type SaveFilesEntry, type SaveFilesOptions, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadFileOptions, type UploadResult, type UseAgentRunOptions, type UseAgentRunResult, attachmentFileName, createEndpoints, fetchAttachmentReferences, saveFile, saveFiles, uploadFile, useAgentRun, useElapsed };
|
|
503
|
+
export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, type AgentChatAttachButton, type AgentChatAttachment, type AgentChatFile, type AgentChatMessage, type AgentChatProps, type AgentChatTurn, type AgentEndpointOptions, type AgentEndpoints, type AgentRunEvent, AgentRunForm, type AgentRunFormProps, type AgentRunState, type AgentRunStatus, type AgentRunStep, type AgentUiMode, type AttachmentReferences, DEFAULT_BASE_PATH, type EndpointRequestOptions, MarkdownContent, type MarkdownContentProps, MarkdownExtension, type MediaAspectRatio, MediaGallery, type MediaGalleryProps, MediaPreview, type MediaPreviewProps, MediaSkeleton, type MediaSkeletonProps, MediaViewer, type MediaViewerProps, RunProgress, type RunProgressProps, type RunProgressRun, type SaveFilesEntry, type SaveFilesOptions, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadFileOptions, type UploadResult, type UseAgentRunOptions, type UseAgentRunResult, attachmentFileName, createEndpoints, fetchAttachmentReferences, saveFile, saveFiles, uploadFile, useAgentRun, useElapsed };
|