@lightblues/jig 0.0.10 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,6 +9,7 @@ Planned parts (design: baton `.ea/log/2026-11-24-shared-agent-ui.md`, item #274)
9
9
  | `@lightblues/jig/agent-paseo` | server adapter: a Paseo agent's timeline as AG-UI events, with replay and recovery |
10
10
  | `@lightblues/jig/agent-pi` | server runtime for in-app pi agents: router models with tiers, sessions and runs in the host's own Postgres tables, one run as AG-UI events (run registry and SSE route: next) |
11
11
  | `@lightblues/jig/agent-chat` | a thin headless client: follow a thread over SSE, reconnect, fold events into messages |
12
- | `@lightblues/jig/markdown` | one markdown-it config for server and client: CJK, KaTeX, highlighting, safe for innerHTML, streaming-aware |
12
+ | `@lightblues/jig/markdown` | one markdown-it config for server and client: CJK, KaTeX, highlighting, safe for innerHTML, streaming-aware; fenced blocks with validated params, mermaid |
13
+ | `@lightblues/jig/markdown/react` | `FillSlots`: host components portalled into a document's block slots, mounted across streaming re-renders |
13
14
 
14
15
  The protocol is AG-UI (`@ag-ui/core`), used as is.
@@ -13,7 +13,11 @@ export interface Daemon {
13
13
  title: string;
14
14
  labels: Record<string, string>;
15
15
  }): Promise<string>;
16
- /** Sends `text` as a user message with our id (`clientMessageId` in the timeline): the turn it starts is found by it. */
16
+ /**
17
+ * Sends `text` as a user message with our id (`clientMessageId` in the timeline): the turn it starts is found by it.
18
+ * No `sourceAgentId`, so the daemon treats it as a human's: a running turn is interrupted, never queued (0.17 queues
19
+ * only messages from agents).
20
+ */
17
21
  send(id: string, text: string, messageId: string): Promise<void>;
18
22
  /** Live events of the agent's timeline until the returned function is called. Resolves once the subscription is up. */
19
23
  subscribe(id: string, on: (e: LiveEvent) => void): Promise<() => void>;
@@ -3,7 +3,7 @@ import { existsSync, readFileSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  // J004: public entry points only (`@getpaseo/client` and `@getpaseo/client/node`), no `internal/*` import.
6
- // This is the only file that imports `@getpaseo/client`; the version is pinned to the daemon's (0.16.1).
6
+ // This is the only file that imports `@getpaseo/client`; tested against 0.16.1 and 0.17.4, either client with either daemon (jig-008).
7
7
  import { createPaseoApi } from "@getpaseo/client";
8
8
  import { createHostClient } from "@getpaseo/client/node";
9
9
  export const paseoHome = (home) => home ?? process.env.PASEO_HOME ?? path.join(os.homedir(), ".paseo");
@@ -162,7 +162,7 @@ export function paseoDaemon(cfg) {
162
162
  };
163
163
  },
164
164
  async cancel(id) {
165
- // Agent handles have no cancel in 0.16.1; the client returned by `createHostClient` has.
165
+ // Agent handles have no cancel (0.16.1, 0.17.4); the client returned by `createHostClient` has.
166
166
  const { client } = await connect();
167
167
  await withTimeout(client.cancelAgent(id), TIMEOUT_MS, "stopping the agent");
168
168
  },
@@ -0,0 +1,123 @@
1
+ /** What a block's `parse` returns. */
2
+ export type BlockResult<T = unknown> = {
3
+ ok: true;
4
+ value: T;
5
+ } | {
6
+ ok: false;
7
+ errors: string[];
8
+ };
9
+ /** The part of a Standard Schema (zod ≥ 3.24, valibot, arktype) `blocks` uses. https://standardschema.dev */
10
+ export type StandardSchemaLike<T = unknown> = {
11
+ readonly '~standard': {
12
+ readonly version: 1;
13
+ readonly validate: (value: unknown) => {
14
+ readonly value: T;
15
+ readonly issues?: undefined;
16
+ } | {
17
+ readonly issues: readonly {
18
+ readonly message: string;
19
+ readonly path?: readonly unknown[];
20
+ }[];
21
+ } | Promise<unknown>;
22
+ };
23
+ };
24
+ export type BlockSpec<T = unknown> = {
25
+ /** Validates the parsed body: a `{ok, value} | {ok: false, errors}` function, or a Standard Schema object. It should be strict (unknown fields are errors). */
26
+ parse: ((raw: unknown) => BlockResult<T>) | StandardSchemaLike<T>;
27
+ /**
28
+ * Body format. `yaml` (the default when `createMarkdown` has a `yaml` parser) also reads JSON; `json` without one;
29
+ * `text`: the body as a string, unparsed.
30
+ */
31
+ format?: 'yaml' | 'json' | 'text';
32
+ /** Fields holding Markdown, as paths (`caption`, `steps[].note`, `a.b`): rendered after validation through the safe instance, the value becomes HTML. */
33
+ md?: string[];
34
+ /** The same, rendered inline (no `<p>`). */
35
+ mdInline?: string[];
36
+ /** Fields holding URLs, by path: checked with `urlAllowed(url, kind, links.allow)`; one refused URL makes the block invalid. */
37
+ urls?: Record<string, 'link' | 'image'>;
38
+ };
39
+ export type BlockLimits = {
40
+ /** Longest block body (characters). Default 20,000. */
41
+ maxBody?: number;
42
+ /** Blocks per document; later ones are invalid. Default 50 (a host may pass 10 for a chat answer). */
43
+ maxBlocks?: number;
44
+ /** Deepest nesting of objects and arrays in a parsed body. Default 20. */
45
+ maxDepth?: number;
46
+ /** Most values (objects, arrays, scalars) in a parsed body. Default 10,000. */
47
+ maxNodes?: number;
48
+ };
49
+ export declare const BLOCK_LIMITS: Required<BlockLimits>;
50
+ /** Aliases a YAML body may use (`yaml`'s `maxAliasCount`): a billion-laughs body stops at once. */
51
+ export declare const YAML_MAX_ALIASES = 50;
52
+ export declare const BLOCK_NAME: RegExp;
53
+ /** The part of the `yaml` package (`import * as YAML from 'yaml'`) used: `parseDocument(src, options)`. */
54
+ export type YamlLike = {
55
+ parseDocument(src: string, options?: Record<string, unknown>): {
56
+ errors: readonly {
57
+ message: string;
58
+ }[];
59
+ warnings: readonly {
60
+ message: string;
61
+ }[];
62
+ toJS(options?: Record<string, unknown>): unknown;
63
+ };
64
+ };
65
+ /** A block that parsed and validated. `source` is its body as written: equal sources mean equal values. */
66
+ export type Block<T = unknown> = {
67
+ key: string;
68
+ name: string;
69
+ value: T;
70
+ source: string;
71
+ line: number;
72
+ };
73
+ /** A registered fence still open while streaming: a placeholder slot, no value yet. */
74
+ export type PendingBlock = {
75
+ key: string;
76
+ name: string;
77
+ line: number;
78
+ };
79
+ /** A registered fence that failed: it renders as its escaped source with the errors. */
80
+ export type BlockError = {
81
+ key: string;
82
+ name: string;
83
+ line: number;
84
+ errors: string[];
85
+ };
86
+ export type BlockEnv = {
87
+ blocks: Block[];
88
+ pending: PendingBlock[];
89
+ errors: BlockError[];
90
+ };
91
+ /** Runs a block's validator: a function or a Standard Schema. A throw or an async schema is an error. */
92
+ export declare function validate<T>(parse: BlockSpec<T>['parse'], raw: unknown): BlockResult<T>;
93
+ /** Depth, size and key checks on a parsed body (aliases already bounded by the parser). */
94
+ export declare function checkShape(v: unknown, limits: Required<BlockLimits>): string | null;
95
+ /** Parses a body by format. `yaml` with jig's safety options: core schema, unknown tags refused, aliases bounded, unique keys. */
96
+ export declare function parseBody(body: string, format: 'yaml' | 'json' | 'text', yaml?: YamlLike): BlockResult<unknown>;
97
+ /**
98
+ * Replaces each value at `path` (`a.b`, `list[].x`) with `f(value)`; returns an error string from `f`, or null.
99
+ * The value is copied along the path so the caller's object is not changed.
100
+ */
101
+ export declare function mapPath(root: unknown, path: string, f: (v: unknown, at: string) => {
102
+ value: unknown;
103
+ } | string): {
104
+ value: unknown;
105
+ } | string;
106
+ /**
107
+ * A card as a block: ```` ```<name>\n<JSON>\n``` ````. JSON is also YAML, so a host that reads blocks as YAML reads it
108
+ * too. The fence is longer than any backtick run in the body. `name` must match `[a-z][a-z0-9-]*`.
109
+ */
110
+ export declare function toBlock(name: string, value: unknown): string;
111
+ /**
112
+ * The first fenced block in `text` back as `{ name, value }` (the body read as JSON, or with `yaml` when given), or
113
+ * `null` when there is no closed fence. Validation is the caller's (`createMarkdown`'s `blocks`, or the card's schema).
114
+ */
115
+ export declare function fromBlock(text: string, yaml?: YamlLike): {
116
+ name: string;
117
+ value: unknown;
118
+ } | null;
119
+ /** `ACTIVITY_SNAPSHOT` `card.<kind>` content → a block (`toBlock(kind, content)`). */
120
+ export declare function cardToBlock(card: {
121
+ activityType: string;
122
+ content: unknown;
123
+ }): string;
@@ -0,0 +1,166 @@
1
+ // Fenced blocks with validated params (J008 tier A): ```name fences whose name the host registered become slots
2
+ // `<div data-jig-block="name" data-jig-key="name-0"></div>`; the parsed params come back beside the HTML, never in it.
3
+ // No imports: the YAML parser and the validators are the host's.
4
+ export const BLOCK_LIMITS = { maxBody: 20_000, maxBlocks: 50, maxDepth: 20, maxNodes: 10_000 };
5
+ /** Aliases a YAML body may use (`yaml`'s `maxAliasCount`): a billion-laughs body stops at once. */
6
+ export const YAML_MAX_ALIASES = 50;
7
+ export const BLOCK_NAME = /^[a-z][a-z0-9-]*$/;
8
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
9
+ function isStandard(p) {
10
+ return typeof p === 'object' && p !== null && '~standard' in p;
11
+ }
12
+ /** Runs a block's validator: a function or a Standard Schema. A throw or an async schema is an error. */
13
+ export function validate(parse, raw) {
14
+ try {
15
+ if (isStandard(parse)) {
16
+ const r = parse['~standard'].validate(raw);
17
+ if (r instanceof Promise) {
18
+ r.catch(() => { });
19
+ return { ok: false, errors: ['async schemas are not supported'] };
20
+ }
21
+ if (r.issues)
22
+ return { ok: false, errors: r.issues.map((i) => (i.path?.length ? `${i.path.map((p) => (typeof p === 'object' && p && 'key' in p ? String(p.key) : String(p))).join('.')}: ` : '') + i.message) };
23
+ return { ok: true, value: r.value };
24
+ }
25
+ const r = parse(raw);
26
+ if (r && r.ok === true)
27
+ return r;
28
+ if (r && r.ok === false)
29
+ return { ok: false, errors: r.errors?.length ? r.errors.map(String) : ['invalid'] };
30
+ return { ok: false, errors: ['parse returned neither {ok: true} nor {ok: false}'] };
31
+ }
32
+ catch (err) {
33
+ return { ok: false, errors: [String(err?.message ?? err)] };
34
+ }
35
+ }
36
+ /** Depth, size and key checks on a parsed body (aliases already bounded by the parser). */
37
+ export function checkShape(v, limits) {
38
+ let nodes = 0;
39
+ const seen = new Set();
40
+ const walk = (x, depth) => {
41
+ if (++nodes > limits.maxNodes)
42
+ return `more than ${limits.maxNodes} values`;
43
+ if (typeof x !== 'object' || x === null)
44
+ return null;
45
+ if (depth >= limits.maxDepth)
46
+ return `nested deeper than ${limits.maxDepth}`;
47
+ if (seen.has(x))
48
+ return 'repeated (aliased) values are not allowed'; // a tree: one object in one place
49
+ seen.add(x);
50
+ if (Array.isArray(x)) {
51
+ for (const y of x) {
52
+ const e = walk(y, depth + 1);
53
+ if (e)
54
+ return e;
55
+ }
56
+ }
57
+ else {
58
+ const proto = Object.getPrototypeOf(x);
59
+ if (proto !== Object.prototype && proto !== null)
60
+ return 'only plain objects, arrays and scalars';
61
+ for (const k of Object.keys(x)) {
62
+ if (FORBIDDEN_KEYS.has(k))
63
+ return `key "${k}" is not allowed`;
64
+ const e = walk(x[k], depth + 1);
65
+ if (e)
66
+ return e;
67
+ }
68
+ }
69
+ return null;
70
+ };
71
+ return walk(v, 0);
72
+ }
73
+ /** Parses a body by format. `yaml` with jig's safety options: core schema, unknown tags refused, aliases bounded, unique keys. */
74
+ export function parseBody(body, format, yaml) {
75
+ if (format === 'text')
76
+ return { ok: true, value: body };
77
+ try {
78
+ if (format === 'json')
79
+ return { ok: true, value: JSON.parse(body) };
80
+ const doc = yaml.parseDocument(body, { schema: 'core', customTags: [], uniqueKeys: true, merge: false, prettyErrors: false, strict: true, logLevel: 'silent' });
81
+ // A warning is an unknown tag (`!custom`, `!!js/function`): refused, not read as a string.
82
+ const bad = doc.errors[0] ?? doc.warnings[0];
83
+ if (bad)
84
+ throw new Error(bad.message);
85
+ return { ok: true, value: doc.toJS({ maxAliasCount: YAML_MAX_ALIASES }) };
86
+ }
87
+ catch (err) {
88
+ return { ok: false, errors: [`${format === 'json' ? 'JSON' : 'YAML'}: ${String(err?.message ?? err).split('\n')[0]}`] };
89
+ }
90
+ }
91
+ const parsePath = (p) => p.split('.').map((s) => (s.endsWith('[]') ? { key: s.slice(0, -2), each: true } : { key: s, each: false }));
92
+ /**
93
+ * Replaces each value at `path` (`a.b`, `list[].x`) with `f(value)`; returns an error string from `f`, or null.
94
+ * The value is copied along the path so the caller's object is not changed.
95
+ */
96
+ export function mapPath(root, path, f) {
97
+ const steps = parsePath(path);
98
+ const go = (v, i, at) => {
99
+ if (i === steps.length)
100
+ return f(v, at);
101
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
102
+ return { value: v };
103
+ const { key, each } = steps[i];
104
+ if (!Object.hasOwn(v, key))
105
+ return { value: v };
106
+ const child = v[key];
107
+ const here = at ? `${at}.${key}` : key;
108
+ let next;
109
+ if (each) {
110
+ if (child === undefined || child === null)
111
+ return { value: v };
112
+ if (!Array.isArray(child))
113
+ return `${here}: expected a list`;
114
+ const out = [];
115
+ for (let j = 0; j < child.length; j++) {
116
+ const r = go(child[j], i + 1, `${here}[${j}]`);
117
+ if (typeof r === 'string')
118
+ return r;
119
+ out.push(r.value);
120
+ }
121
+ next = out;
122
+ }
123
+ else {
124
+ const r = go(child, i + 1, here);
125
+ if (typeof r === 'string')
126
+ return r;
127
+ next = r.value;
128
+ }
129
+ return { value: { ...v, [key]: next } };
130
+ };
131
+ return go(root, 0, '');
132
+ }
133
+ /**
134
+ * A card as a block: ```` ```<name>\n<JSON>\n``` ````. JSON is also YAML, so a host that reads blocks as YAML reads it
135
+ * too. The fence is longer than any backtick run in the body. `name` must match `[a-z][a-z0-9-]*`.
136
+ */
137
+ export function toBlock(name, value) {
138
+ if (!BLOCK_NAME.test(name))
139
+ throw new Error(`block name must match ${BLOCK_NAME}: ${JSON.stringify(name)}`);
140
+ const body = JSON.stringify(value, null, 2);
141
+ if (body === undefined)
142
+ throw new Error('toBlock: value is not JSON');
143
+ const longest = Math.max(0, ...[...body.matchAll(/`+/g)].map((m) => m[0].length));
144
+ const fence = '`'.repeat(Math.max(3, longest + 1));
145
+ return `${fence}${name}\n${body}\n${fence}\n`;
146
+ }
147
+ /**
148
+ * The first fenced block in `text` back as `{ name, value }` (the body read as JSON, or with `yaml` when given), or
149
+ * `null` when there is no closed fence. Validation is the caller's (`createMarkdown`'s `blocks`, or the card's schema).
150
+ */
151
+ export function fromBlock(text, yaml) {
152
+ const m = /^ {0,3}(`{3,}|~{3,})[ \t]*([a-z][a-z0-9-]*)[^\n]*\n([\s\S]*?)\n? {0,3}\1[ \t]*$/m.exec(text);
153
+ if (!m)
154
+ return null;
155
+ const r = parseBody(m[3], yaml ? 'yaml' : 'json', yaml);
156
+ if (!r.ok)
157
+ throw new Error(r.errors.join('; '));
158
+ return { name: m[2], value: r.value };
159
+ }
160
+ /** `ACTIVITY_SNAPSHOT` `card.<kind>` content → a block (`toBlock(kind, content)`). */
161
+ export function cardToBlock(card) {
162
+ const m = /^card\.(.+)$/.exec(card.activityType);
163
+ if (!m)
164
+ throw new Error(`not a card activity: ${card.activityType}`);
165
+ return toBlock(m[1], card.content);
166
+ }
@@ -1,6 +1,9 @@
1
1
  import MarkdownIt from 'markdown-it';
2
2
  import { closeOpenMarkdown, type CloseOpenMarkdownOptions } from './close.ts';
3
+ import { type BlockEnv, type BlockLimits, type BlockSpec, type YamlLike } from './blocks.ts';
3
4
  export { closeOpenMarkdown, type CloseOpenMarkdownOptions };
5
+ export { BLOCK_LIMITS, BLOCK_NAME, YAML_MAX_ALIASES, cardToBlock, fromBlock, toBlock, type Block, type BlockError, type BlockLimits, type BlockResult, type BlockSpec, type PendingBlock, type StandardSchemaLike, type YamlLike, } from './blocks.ts';
6
+ export { drawMermaid, MERMAID_CONFIG, type MermaidLike, type DrawMermaidOptions } from './mermaid.ts';
4
7
  type Md = InstanceType<typeof MarkdownIt>;
5
8
  /** The part of the `katex` module texmath uses. */
6
9
  export type KatexLike = {
@@ -83,13 +86,34 @@ export type MarkdownOptions = {
83
86
  plugins?: (Plugin | [Plugin, ...unknown[]])[];
84
87
  /** Passed to `closeOpenMarkdown` as `strip` when rendering with `streaming: true` (a half-written host marker). */
85
88
  streamingStrip?: RegExp;
89
+ /**
90
+ * Fenced blocks: a fence ```` ```name ```` whose name (`[a-z][a-z0-9-]*`, the first word of the info string) is
91
+ * registered renders as an empty slot `<div data-jig-block="name" data-jig-key="name-0"></div>`; its validated params
92
+ * come back from `renderDocument` beside the HTML. An invalid one renders as its escaped source with the errors.
93
+ */
94
+ blocks?: Record<string, BlockSpec<any>>;
95
+ /** The `yaml` package (`import * as YAML from 'yaml'`), for YAML block bodies. Without it, bodies are JSON. */
96
+ yaml?: YamlLike;
97
+ /** Limits on blocks (body size, count, depth, values); the host may tighten them. */
98
+ blockLimits?: BlockLimits;
99
+ /**
100
+ * ```` ```mermaid ```` fences become `mermaid` blocks (value `{ source }`) whose slot holds the escaped source until
101
+ * the host draws it (`drawMermaid`). Off by default.
102
+ */
103
+ mermaid?: boolean;
86
104
  };
87
105
  export type RenderOptions = {
88
106
  /** The text is a partial answer: close what it left open first (`closeOpenMarkdown`). */
89
107
  streaming?: boolean;
90
108
  };
109
+ /** `renderDocument`'s result: the HTML with its slots, and what goes in them. */
110
+ export type MarkdownDocument = BlockEnv & {
111
+ html: string;
112
+ };
91
113
  export type Markdown = {
92
114
  render(text: string, opts?: RenderOptions): string;
115
+ /** `render`, plus the blocks: `{ html, blocks: [{key, name, value, source, line}], pending, errors }`. */
116
+ renderDocument(text: string, opts?: RenderOptions): MarkdownDocument;
93
117
  /** The markdown-it instance, for `md.use(...)` and render rules; the same rules as `plugins` apply. */
94
118
  md: Md;
95
119
  };
@@ -3,7 +3,10 @@
3
3
  // so a host that does not use one does not install it, and no bundler has to resolve a missing optional peer.
4
4
  import MarkdownIt from 'markdown-it';
5
5
  import { closeOpenMarkdown } from "./close.js";
6
+ import { BLOCK_LIMITS, BLOCK_NAME, checkShape, mapPath, parseBody, validate, } from "./blocks.js";
6
7
  export { closeOpenMarkdown };
8
+ export { BLOCK_LIMITS, BLOCK_NAME, YAML_MAX_ALIASES, cardToBlock, fromBlock, toBlock, } from "./blocks.js";
9
+ export { drawMermaid, MERMAID_CONFIG } from "./mermaid.js";
7
10
  /** Longest inline `$…$` read as math. texmath's own rule has no bound, so a long line of `$a ` is quadratic. */
8
11
  export const MAX_INLINE_MATH = 1000;
9
12
  export const DEFAULT_REL = 'noopener noreferrer nofollow';
@@ -84,11 +87,189 @@ export function createMarkdown(opts = {}) {
84
87
  else
85
88
  md.use(p);
86
89
  }
90
+ const blocks = useBlocks(md, opts);
87
91
  const strip = opts.streamingStrip;
92
+ const doc = (text, r, out) => {
93
+ if (!r.streaming)
94
+ return md.render(text, blocks ? { [ENV]: out } : {});
95
+ if (!blocks)
96
+ return md.render(closeOpenMarkdown(text, strip ? { strip } : {}));
97
+ // Which fence, if any, the closer added: that block is still being written.
98
+ const s = strip ? stripTail(text, strip) : text;
99
+ const closed = closeOpenMarkdown(s);
100
+ const tail = closed.slice(s.length);
101
+ const open = closed.startsWith(s) && /^\n?(`{3,}|~{3,})$/.test(tail);
102
+ return md.render(closed, { [ENV]: out, [OPEN]: open });
103
+ };
88
104
  return {
89
105
  md,
90
- render: (text, r = {}) => md.render(r.streaming ? closeOpenMarkdown(text, strip ? { strip } : {}) : text),
106
+ render: (text, r = {}) => doc(text, r, undefined),
107
+ renderDocument: (text, r = {}) => {
108
+ const out = { blocks: [], pending: [], errors: [] };
109
+ const html = doc(text, r, out);
110
+ return { html, ...out };
111
+ },
112
+ };
113
+ }
114
+ function stripTail(text, strip) {
115
+ const m = new RegExp(`(?:${strip.source})$`, strip.flags.replace(/[gym]/g, '')).exec(text);
116
+ return m ? text.slice(0, m.index) : text;
117
+ }
118
+ const ENV = Symbol('jig.blocks');
119
+ const OPEN = Symbol('jig.open');
120
+ const NONE = Symbol('jig.noBlocks');
121
+ const MERMAID = { format: 'text', parse: (s) => ({ ok: true, value: { source: String(s) } }) };
122
+ /**
123
+ * Did markdown-it find the fence's closing line? Its range is the opener, the content lines, and the closer if any;
124
+ * closed content ends with a newline (or is empty), so it holds exactly one newline per line between the fences.
125
+ */
126
+ const closedFence = (t) => (t.content === '' || t.content.endsWith('\n')) && (t.content.match(/\n/g)?.length ?? 0) === t.map[1] - t.map[0] - 2;
127
+ /**
128
+ * The block layer: a core rule after block parsing turns each registered fence token into a `jig_block` token
129
+ * (slot, pending slot, hidden, or error), and a render rule writes it. Params never enter the HTML.
130
+ */
131
+ function useBlocks(md, opts) {
132
+ const specs = new Map(Object.entries(opts.blocks ?? {}));
133
+ for (const name of specs.keys())
134
+ if (!BLOCK_NAME.test(name))
135
+ throw new Error(`block name must match ${BLOCK_NAME}: ${JSON.stringify(name)}`);
136
+ if (opts.mermaid) {
137
+ if (specs.has('mermaid'))
138
+ throw new Error('blocks: "mermaid" is registered twice (blocks and the mermaid option)');
139
+ specs.set('mermaid', MERMAID);
140
+ }
141
+ if (!specs.size)
142
+ return false;
143
+ for (const [name, spec] of specs) {
144
+ if ((spec.format ?? (opts.yaml ? 'yaml' : 'json')) === 'yaml' && !opts.yaml)
145
+ throw new Error(`block "${name}": format yaml needs the yaml option`);
146
+ }
147
+ const limits = { ...BLOCK_LIMITS, ...opts.blockLimits };
148
+ const allow = opts.links?.allow;
149
+ const names = [...specs.keys()];
150
+ // Markdown inside params goes through a safe instance: this one, or (with trustedHtml) the same options without it.
151
+ let safe = null;
152
+ const safeMd = () => (safe ??= opts.trustedHtml ? createMarkdown({ ...opts, trustedHtml: false, blocks: undefined, mermaid: false }).md : md);
153
+ const noBlocks = { [NONE]: true };
154
+ const settle = (spec, body) => {
155
+ if (body.length > limits.maxBody)
156
+ return [`body longer than ${limits.maxBody} characters`];
157
+ const format = spec.format ?? (opts.yaml ? 'yaml' : 'json');
158
+ const raw = parseBody(body, format, opts.yaml);
159
+ if (!raw.ok)
160
+ return raw.errors;
161
+ const shape = format === 'text' ? null : checkShape(raw.value, limits);
162
+ if (shape)
163
+ return [shape];
164
+ const r = validate(spec.parse, raw.value);
165
+ if (!r.ok)
166
+ return r.errors;
167
+ let value = r.value;
168
+ for (const [path, kind] of Object.entries(spec.urls ?? {})) {
169
+ const m = mapPath(value, path, (v, at) => {
170
+ if (v === undefined || v === null)
171
+ return { value: v };
172
+ if (typeof v !== 'string')
173
+ return `${at}: expected a URL`;
174
+ return urlAllowed(v, kind, allow) ? { value: v } : `${at}: URL not allowed`;
175
+ });
176
+ if (typeof m === 'string')
177
+ return [m];
178
+ value = m.value;
179
+ }
180
+ for (const [paths, inline] of [[spec.md, false], [spec.mdInline, true]]) {
181
+ for (const path of paths ?? []) {
182
+ const m = mapPath(value, path, (v, at) => {
183
+ if (v === undefined || v === null)
184
+ return { value: v };
185
+ if (typeof v !== 'string')
186
+ return `${at}: expected Markdown text`;
187
+ return { value: inline ? safeMd().renderInline(v, { ...noBlocks }) : safeMd().render(v, { ...noBlocks }) };
188
+ });
189
+ if (typeof m === 'string')
190
+ return [m];
191
+ value = m.value;
192
+ }
193
+ }
194
+ return { value };
195
+ };
196
+ md.core.ruler.after('block', 'jig_blocks', (state) => {
197
+ const env = (state.env ?? {});
198
+ if (env[NONE])
199
+ return;
200
+ const out = env[ENV];
201
+ const open = env[OPEN] === true;
202
+ const streaming = OPEN in env;
203
+ let lines = null;
204
+ let last = -1;
205
+ const counts = new Map();
206
+ let total = 0;
207
+ for (const t of state.tokens) {
208
+ if (t.type !== 'fence' || !t.map)
209
+ continue;
210
+ const name = t.info.trim().split(/\s+/)[0] ?? '';
211
+ const spec = specs.get(name);
212
+ if (!lines) {
213
+ lines = state.src.split('\n');
214
+ last = lines.length - 1;
215
+ while (last > 0 && !lines[last].trim())
216
+ last--;
217
+ }
218
+ const closed = closedFence(t);
219
+ // Streaming: a fence the closer just closed (it ends the text), or one it could not see (inside a quote), is open.
220
+ const pending = streaming && (!closed || (open && t.map[1] - 1 === last));
221
+ if (!spec) {
222
+ // A fence being opened whose name is still being typed (```fig of ```figure): nothing yet, not a code flash.
223
+ if (pending && !t.content && names.some((n) => n.startsWith(name))) {
224
+ t.type = 'jig_block';
225
+ t.meta = { kind: 'hidden' };
226
+ }
227
+ continue;
228
+ }
229
+ const n = counts.get(name) ?? 0;
230
+ counts.set(name, n + 1);
231
+ const key = `${name}-${n}`;
232
+ const line = t.map[0] + 1;
233
+ t.type = 'jig_block';
234
+ if (pending) {
235
+ t.meta = { kind: 'pending', name, key };
236
+ out?.pending.push({ key, name, line });
237
+ continue;
238
+ }
239
+ const body = t.content;
240
+ let r;
241
+ if (!closed)
242
+ r = ['block not closed'];
243
+ else if (++total > limits.maxBlocks)
244
+ r = [`more than ${limits.maxBlocks} blocks`];
245
+ else
246
+ r = settle(spec, body);
247
+ if (Array.isArray(r)) {
248
+ t.meta = { kind: 'error', name, key, source: body, errors: r };
249
+ out?.errors.push({ key, name, line, errors: r });
250
+ }
251
+ else {
252
+ t.meta = { kind: 'slot', name, key, source: spec === MERMAID ? body : undefined };
253
+ out?.blocks.push({ key, name, value: r.value, source: body, line });
254
+ }
255
+ }
256
+ });
257
+ const esc = md.utils.escapeHtml;
258
+ md.renderer.rules.jig_block = (tokens, idx) => {
259
+ const m = tokens[idx].meta;
260
+ if (m.kind === 'hidden')
261
+ return '';
262
+ const attrs = `data-jig-block="${esc(m.name)}" data-jig-key="${esc(m.key)}"`;
263
+ if (m.kind === 'pending')
264
+ return `<div ${attrs} data-jig-pending></div>\n`;
265
+ if (m.kind === 'error') {
266
+ return `<div class="jig-block-invalid" ${attrs}><pre><code class="language-${esc(m.name)}">${esc(m.source)}</code></pre>`
267
+ + `<div class="jig-block-errors">${m.errors.map((e) => `<p>${esc(e)}</p>`).join('')}</div></div>\n`;
268
+ }
269
+ const inner = m.source === undefined ? '' : `<pre><code class="language-${esc(m.name)}">${esc(m.source)}</code></pre>`;
270
+ return `<div ${attrs}>${inner}</div>\n`;
91
271
  };
272
+ return true;
92
273
  }
93
274
  /** Formulas kept per instance. While streaming, every frame re-renders the same formulas; KaTeX is ~80% of the cost. */
94
275
  export const MATH_CACHE_SIZE = 500;
@@ -0,0 +1,34 @@
1
+ /** The part of the `mermaid` module used. */
2
+ export type MermaidLike = {
3
+ initialize(config: Record<string, unknown>): void;
4
+ render(id: string, text: string): Promise<{
5
+ svg: string;
6
+ }>;
7
+ };
8
+ type MermaidModule = MermaidLike | {
9
+ default: MermaidLike;
10
+ };
11
+ export type MermaidSource = MermaidModule | (() => Promise<MermaidModule>);
12
+ export type DrawMermaidOptions = {
13
+ /** The host's mermaid config (theme, layout, fontFamily…). The keys of `MERMAID_CONFIG` are always jig's. */
14
+ config?: Record<string, unknown>;
15
+ };
16
+ /**
17
+ * Always applied over the host's config. `securityLevel: "strict"`: labels sanitised (DOMPurify), click handlers off.
18
+ * `secure` lists the keys a diagram's own `%%{init: …}%%` directive cannot set.
19
+ */
20
+ export declare const MERMAID_CONFIG: {
21
+ readonly startOnLoad: false;
22
+ readonly securityLevel: "strict";
23
+ readonly suppressErrorRendering: true;
24
+ readonly maxTextSize: 50000;
25
+ readonly maxEdges: 500;
26
+ readonly secure: readonly ["secure", "securityLevel", "startOnLoad", "maxTextSize", "suppressErrorRendering", "maxEdges", "dompurifyConfig", "themeCSS", "htmlLabels"];
27
+ };
28
+ /**
29
+ * Draws `source` into `el` (its children replaced by `<div class="jig-mermaid">svg</div>`), or, if mermaid fails,
30
+ * shows the source as escaped code with class `jig-mermaid-error`. Resolves to whether it drew. `mermaid` is the module,
31
+ * or a loader (`() => import('mermaid')`) called on first use.
32
+ */
33
+ export declare function drawMermaid(el: Element, source: string, mermaid: MermaidSource, o?: DrawMermaidOptions): Promise<boolean>;
34
+ export {};
@@ -0,0 +1,84 @@
1
+ // drawMermaid: a `mermaid` block's slot drawn with the host's mermaid module, locked down. Browser only (DOM globals),
2
+ // no imports: mermaid (~159 KB gzipped plus chunks) is the host's, passed in or loaded lazily.
3
+ /**
4
+ * Always applied over the host's config. `securityLevel: "strict"`: labels sanitised (DOMPurify), click handlers off.
5
+ * `secure` lists the keys a diagram's own `%%{init: …}%%` directive cannot set.
6
+ */
7
+ export const MERMAID_CONFIG = {
8
+ startOnLoad: false,
9
+ securityLevel: 'strict',
10
+ suppressErrorRendering: true,
11
+ maxTextSize: 50_000,
12
+ maxEdges: 500,
13
+ secure: ['secure', 'securityLevel', 'startOnLoad', 'maxTextSize', 'suppressErrorRendering', 'maxEdges', 'dompurifyConfig', 'themeCSS', 'htmlLabels'],
14
+ };
15
+ const DROP = new Set(['script', 'iframe', 'object', 'embed', 'link', 'meta', 'base', 'form', 'input', 'textarea', 'button', 'select', 'frame', 'frameset', 'audio', 'video', 'img', 'image', 'animate', 'set', 'animatemotion', 'animatetransform', 'handler', 'listener', 'feimage']);
16
+ const URL_ATTRS = /^(href|xlink:href|src|srcset|action|formaction|data|poster|background|ping)$/i;
17
+ const FRAGMENT = /^\s*#[\w.:-]*$/;
18
+ /** CSS that loads or runs: `@import` statements, non-fragment `url()`, `expression()`, `javascript:`. */
19
+ function cleanCss(css) {
20
+ return css.replace(/@import[^;]*;?/gi, '').replace(/url\(\s*(?!['"]?#)[^)]*\)/gi, 'url(#)').replace(/expression\s*\(/gi, '(').replace(/javascript:/gi, '');
21
+ }
22
+ let seq = 0;
23
+ /**
24
+ * Strips what strict mode should already have: dangerous elements and handlers, URLs that are not fragment references
25
+ * (except `image`, dropped), CSS that loads. `foreignObject` (mermaid's HTML labels) stays: its content is an inert,
26
+ * scrubbed HTML subtree.
27
+ */
28
+ function scrub(root) {
29
+ for (const el of [...root.querySelectorAll('*')]) {
30
+ const name = el.localName.toLowerCase();
31
+ if (DROP.has(name) || (name === 'use' && !FRAGMENT.test(el.getAttribute('href') ?? el.getAttribute('xlink:href') ?? ''))) {
32
+ el.remove();
33
+ continue;
34
+ }
35
+ for (const a of [...el.attributes]) {
36
+ const n = a.name.toLowerCase();
37
+ if (n.startsWith('on'))
38
+ el.removeAttribute(a.name);
39
+ else if (URL_ATTRS.test(n) && !FRAGMENT.test(a.value))
40
+ el.removeAttribute(a.name);
41
+ else if (n === 'style')
42
+ el.setAttribute(a.name, cleanCss(a.value));
43
+ }
44
+ if (name === 'style' && el.textContent)
45
+ el.textContent = cleanCss(el.textContent);
46
+ }
47
+ }
48
+ /**
49
+ * Draws `source` into `el` (its children replaced by `<div class="jig-mermaid">svg</div>`), or, if mermaid fails,
50
+ * shows the source as escaped code with class `jig-mermaid-error`. Resolves to whether it drew. `mermaid` is the module,
51
+ * or a loader (`() => import('mermaid')`) called on first use.
52
+ */
53
+ export async function drawMermaid(el, source, mermaid, o = {}) {
54
+ const id = `jig-mmd-${++seq}`;
55
+ const doc = el.ownerDocument;
56
+ try {
57
+ const mod = typeof mermaid === 'function' ? await mermaid() : mermaid;
58
+ const m = 'default' in mod && mod.default ? mod.default : mod;
59
+ m.initialize({ ...o.config, ...MERMAID_CONFIG, secure: [...MERMAID_CONFIG.secure] });
60
+ const { svg } = await m.render(id, source);
61
+ const tpl = doc.createElement('template');
62
+ tpl.innerHTML = svg; // inert: nothing in a template loads or runs
63
+ scrub(tpl.content);
64
+ const view = doc.createElement('div');
65
+ view.className = 'jig-mermaid';
66
+ view.append(tpl.content);
67
+ el.replaceChildren(view);
68
+ return true;
69
+ }
70
+ catch {
71
+ const pre = doc.createElement('pre');
72
+ pre.className = 'jig-mermaid-error';
73
+ const code = doc.createElement('code');
74
+ code.className = 'language-mermaid';
75
+ code.textContent = source;
76
+ pre.append(code);
77
+ el.replaceChildren(pre);
78
+ return false;
79
+ }
80
+ finally {
81
+ doc.getElementById(id)?.remove();
82
+ doc.getElementById(`d${id}`)?.remove();
83
+ }
84
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `@lightblues/jig/markdown/react`: `FillSlots` puts host components into the slots of a `renderDocument` result.
3
+ * The HTML is set as is (once per string); each block's component is portalled into a holder element that moves into
4
+ * the current slot after each commit, so a component stays mounted (state, effects, a drawn chart) while the text
5
+ * streams and the HTML around it is replaced. React DOM only.
6
+ */
7
+ import { type ReactNode } from 'react';
8
+ import type { Block, PendingBlock } from './blocks.ts';
9
+ /** Draws one block: framework-escaped (React text), never HTML from a param except the `md` fields jig rendered. */
10
+ export type BlockRenderer = (value: any, ctx: {
11
+ key: string;
12
+ name: string;
13
+ }) => ReactNode;
14
+ export type FillSlotsProps = {
15
+ /** `renderDocument`'s result (or the server's, sent as JSON). */
16
+ doc: {
17
+ html: string;
18
+ blocks: Block[];
19
+ pending?: PendingBlock[];
20
+ };
21
+ /** Components by block name. A slot whose name has none keeps its own HTML (mermaid: its source). */
22
+ registry: Record<string, BlockRenderer | undefined>;
23
+ /** What a still-open block shows while streaming (default: nothing). */
24
+ pending?: (ctx: {
25
+ key: string;
26
+ name: string;
27
+ }) => ReactNode;
28
+ className?: string;
29
+ };
30
+ export declare function FillSlots({ doc, registry, pending, className }: FillSlotsProps): import("react").FunctionComponentElement<import("react").FragmentProps>;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * `@lightblues/jig/markdown/react`: `FillSlots` puts host components into the slots of a `renderDocument` result.
3
+ * The HTML is set as is (once per string); each block's component is portalled into a holder element that moves into
4
+ * the current slot after each commit, so a component stays mounted (state, effects, a drawn chart) while the text
5
+ * streams and the HTML around it is replaced. React DOM only.
6
+ */
7
+ import { createElement, Fragment, memo, useLayoutEffect, useRef } from 'react';
8
+ import { createPortal } from 'react-dom';
9
+ /** The HTML, set by React only when the string changes. */
10
+ const Html = memo(function Html({ html, className, root }) {
11
+ return createElement('div', { ref: root, className, dangerouslySetInnerHTML: { __html: html } });
12
+ });
13
+ /** Re-renders only when the block's source (so its value), its renderer or its state (pending → done) changes. */
14
+ const Fill = memo(function Fill({ render, value, source, name, k }) {
15
+ return createElement(Fragment, null, source === null ? render({ key: k, name }) : render(value, { key: k, name }));
16
+ }, (a, b) => a.render === b.render && a.source === b.source && a.name === b.name && a.k === b.k);
17
+ export function FillSlots({ doc, registry, pending, className }) {
18
+ const root = useRef(null);
19
+ const holders = useRef(new Map());
20
+ const dom = typeof document !== 'undefined';
21
+ const items = [];
22
+ for (const b of doc.blocks) {
23
+ const r = registry[b.name];
24
+ if (r)
25
+ items.push({ key: b.key, name: b.name, value: b.value, source: b.source, render: r });
26
+ }
27
+ if (pending)
28
+ for (const p of doc.pending ?? [])
29
+ if (registry[p.name])
30
+ items.push({ key: p.key, name: p.name, value: undefined, source: null, render: pending });
31
+ const live = new Set(items.map((i) => i.key));
32
+ const holder = (key) => {
33
+ let h = holders.current.get(key);
34
+ if (!h) {
35
+ h = document.createElement('div');
36
+ h.className = 'jig-slot';
37
+ holders.current.set(key, h);
38
+ }
39
+ return h;
40
+ };
41
+ useLayoutEffect(() => {
42
+ const el = root.current;
43
+ if (!el)
44
+ return;
45
+ for (const slot of el.querySelectorAll('[data-jig-key]')) {
46
+ const h = holders.current.get(slot.dataset.jigKey ?? '');
47
+ if (h && live.has(slot.dataset.jigKey) && (h.parentNode !== slot || slot.childNodes.length !== 1))
48
+ slot.replaceChildren(h);
49
+ }
50
+ for (const k of [...holders.current.keys()])
51
+ if (!live.has(k)) {
52
+ holders.current.get(k).remove();
53
+ holders.current.delete(k);
54
+ }
55
+ });
56
+ return createElement(Fragment, null, createElement(Html, { html: doc.html, className, root }), dom ? items.map((i) => createPortal(createElement(Fill, { render: i.render, value: i.value, source: i.source, name: i.name, k: i.key }), holder(i.key), i.key)) : null);
57
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightblues/jig",
3
- "version": "0.0.10",
3
+ "version": "0.1.0",
4
4
  "description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, one markdown renderer, and more as they prove reusable.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -44,6 +44,10 @@
44
44
  "types": "./dist/markdown/index.d.ts",
45
45
  "default": "./dist/markdown/index.js"
46
46
  },
47
+ "./markdown/react": {
48
+ "types": "./dist/markdown/react.d.ts",
49
+ "default": "./dist/markdown/react.js"
50
+ },
47
51
  "./package.json": "./package.json"
48
52
  },
49
53
  "scripts": {
@@ -58,35 +62,45 @@
58
62
  "@earendil-works/pi-agent-core": "1.4.0",
59
63
  "@earendil-works/pi-ai": "1.4.0",
60
64
  "@earendil-works/pi-coding-agent": "1.4.0",
61
- "@getpaseo/client": "0.16.1",
65
+ "@getpaseo/client": "0.17.4",
62
66
  "@types/node": "^24.0.0",
63
67
  "@types/pg": "8.23.1",
64
68
  "@types/react": "19.3.0",
69
+ "@types/react-dom": "19.3.0",
65
70
  "@types/react-test-renderer": "19.3.1",
66
71
  "esbuild": "0.28.2",
72
+ "happy-dom": "21.0.4",
67
73
  "highlight.js": "11.12.0",
68
74
  "katex": "0.19.1",
69
75
  "markdown-it": "15.0.3",
70
76
  "markdown-it-cjk-friendly": "3.0.0",
71
77
  "markdown-it-texmath": "1.0.0",
78
+ "mermaid": "12.3.0",
72
79
  "pg": "8.23.1",
80
+ "playwright-core": "1.64.1",
73
81
  "postgres": "3.4.9",
74
82
  "react": "19.3.1",
83
+ "react-dom": "19.3.1",
75
84
  "react-test-renderer": "19.3.1",
76
- "typescript": "^5.9.0"
85
+ "typescript": "^5.9.0",
86
+ "yaml": "2.9.0",
87
+ "zod": "4.6.7"
77
88
  },
78
89
  "peerDependencies": {
79
90
  "@ag-ui/core": "^1.0.5",
80
91
  "@earendil-works/pi-agent-core": "~1.4.0",
81
92
  "@earendil-works/pi-ai": "~1.4.0",
82
93
  "@earendil-works/pi-coding-agent": "~1.4.0",
83
- "@getpaseo/client": "0.16.1",
94
+ "@getpaseo/client": "0.16.1 || 0.17.4",
84
95
  "highlight.js": "^11.0.0",
85
96
  "katex": ">=0.16.21",
86
97
  "markdown-it": "^15.0.0",
87
98
  "markdown-it-cjk-friendly": "^3.0.0",
88
99
  "markdown-it-texmath": "~1.0.0",
89
- "react": ">=18"
100
+ "mermaid": "^12.0.0",
101
+ "react": ">=18",
102
+ "react-dom": ">=18",
103
+ "yaml": "^2.0.0"
90
104
  },
91
105
  "peerDependenciesMeta": {
92
106
  "@ag-ui/core": {
@@ -119,8 +133,17 @@
119
133
  "markdown-it-texmath": {
120
134
  "optional": true
121
135
  },
136
+ "mermaid": {
137
+ "optional": true
138
+ },
122
139
  "react": {
123
140
  "optional": true
141
+ },
142
+ "react-dom": {
143
+ "optional": true
144
+ },
145
+ "yaml": {
146
+ "optional": true
124
147
  }
125
148
  }
126
149
  }