@lightblues/jig 0.0.8 → 0.0.10

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.
@@ -0,0 +1,248 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { EventType } from "@ag-ui/core";
3
+ /** A thread already has a run in progress. Hosts answer it with 409. */
4
+ export class Busy extends Error {
5
+ threadId;
6
+ runId;
7
+ constructor(threadId, runId) {
8
+ super(`thread ${threadId} already has a run in progress (${runId})`);
9
+ this.name = "Busy";
10
+ this.threadId = threadId;
11
+ this.runId = runId;
12
+ }
13
+ }
14
+ /**
15
+ * What a listener needs to see the run so far: a replay of the text, reasoning, tool calls and cards, in the order
16
+ * they came. Folded from the run's own events, so it holds exactly what a listener from the start saw.
17
+ */
18
+ export class RunFolder {
19
+ order = [];
20
+ fold(e) {
21
+ const id = String(e.messageId ?? e.toolCallId ?? "");
22
+ switch (e.type) {
23
+ case EventType.TEXT_MESSAGE_START:
24
+ if (!this.find("text", id))
25
+ this.order.push({ kind: "text", id, text: "", open: true });
26
+ return;
27
+ case EventType.TEXT_MESSAGE_CONTENT: {
28
+ const x = this.find("text", id);
29
+ if (x)
30
+ x.text += String(e.delta ?? "");
31
+ return;
32
+ }
33
+ case EventType.TEXT_MESSAGE_END: {
34
+ const x = this.find("text", id);
35
+ if (x)
36
+ x.open = false;
37
+ return;
38
+ }
39
+ case EventType.REASONING_MESSAGE_START:
40
+ if (!this.find("reasoning", id))
41
+ this.order.push({ kind: "reasoning", id, text: "", open: true });
42
+ return;
43
+ case EventType.REASONING_MESSAGE_CONTENT: {
44
+ const x = this.find("reasoning", id);
45
+ if (x)
46
+ x.text += String(e.delta ?? "");
47
+ return;
48
+ }
49
+ case EventType.REASONING_MESSAGE_END: {
50
+ const x = this.find("reasoning", id);
51
+ if (x)
52
+ x.open = false;
53
+ return;
54
+ }
55
+ case EventType.TOOL_CALL_START:
56
+ if (!this.find("tool", id))
57
+ this.order.push({ kind: "tool", id, name: String(e.toolCallName ?? ""), ...(e.parentMessageId ? { parent: String(e.parentMessageId) } : {}), args: "", end: null });
58
+ return;
59
+ case EventType.TOOL_CALL_ARGS: {
60
+ const x = this.find("tool", id);
61
+ if (x)
62
+ x.args += String(e.delta ?? "");
63
+ return;
64
+ }
65
+ case EventType.TOOL_CALL_END: {
66
+ const x = this.find("tool", id);
67
+ if (x)
68
+ x.end = e;
69
+ return;
70
+ }
71
+ case EventType.ACTIVITY_SNAPSHOT: {
72
+ const x = this.find("activity", id);
73
+ if (x) {
74
+ if (e.replace !== false)
75
+ x.event = e;
76
+ }
77
+ else
78
+ this.order.push({ kind: "activity", id, event: e });
79
+ return;
80
+ }
81
+ }
82
+ }
83
+ /** The run so far as events: one CONTENT per message (the text so far), each START with its END if it ended. */
84
+ replay() {
85
+ const out = [];
86
+ for (const x of this.order) {
87
+ if (x.kind === "text") {
88
+ out.push({ type: EventType.TEXT_MESSAGE_START, messageId: x.id, role: "assistant" });
89
+ if (x.text)
90
+ out.push({ type: EventType.TEXT_MESSAGE_CONTENT, messageId: x.id, delta: x.text });
91
+ if (!x.open)
92
+ out.push({ type: EventType.TEXT_MESSAGE_END, messageId: x.id });
93
+ }
94
+ else if (x.kind === "reasoning") {
95
+ out.push({ type: EventType.REASONING_START, messageId: x.id });
96
+ out.push({ type: EventType.REASONING_MESSAGE_START, messageId: x.id, role: "reasoning" });
97
+ if (x.text)
98
+ out.push({ type: EventType.REASONING_MESSAGE_CONTENT, messageId: x.id, delta: x.text });
99
+ if (!x.open)
100
+ out.push({ type: EventType.REASONING_MESSAGE_END, messageId: x.id }, { type: EventType.REASONING_END, messageId: x.id });
101
+ }
102
+ else if (x.kind === "tool") {
103
+ out.push({ type: EventType.TOOL_CALL_START, toolCallId: x.id, toolCallName: x.name, ...(x.parent ? { parentMessageId: x.parent } : {}) });
104
+ if (x.args)
105
+ out.push({ type: EventType.TOOL_CALL_ARGS, toolCallId: x.id, delta: x.args });
106
+ if (x.end)
107
+ out.push(x.end);
108
+ }
109
+ else
110
+ out.push(x.event);
111
+ }
112
+ return out;
113
+ }
114
+ find(kind, id) {
115
+ return this.order.find((x) => x.kind === kind && x.id === id);
116
+ }
117
+ }
118
+ const isEnd = (e) => e.type === EventType.RUN_FINISHED || e.type === EventType.RUN_ERROR;
119
+ /**
120
+ * One run per thread in this process, which outlives the HTTP request that started it, and its events to any number
121
+ * of listeners. A listener that joins mid-run (a reload, a second tab, a reconnect) gets `READY`, `RUN_STARTED` and a
122
+ * replay of the run so far, then the live events: the follower contract agent-paseo's runner keeps
123
+ * (`.ea/docs/agent-chat.md`). Nothing is persisted here; the run's store has the session and the run row.
124
+ */
125
+ export class RunRegistry {
126
+ runs = new Map();
127
+ listeners = new Map();
128
+ warn;
129
+ constructor(o = {}) {
130
+ this.warn = o.warn ?? ((m, d) => console.warn(`agent-pi: ${m}`, d ?? ""));
131
+ }
132
+ running(threadId) {
133
+ return this.runs.has(threadId);
134
+ }
135
+ current(threadId) {
136
+ const r = this.runs.get(threadId);
137
+ return r ? { runId: r.runId } : null;
138
+ }
139
+ /**
140
+ * Starts a run on a thread; throws `Busy` when the thread has one. `fn` gets the run's id, thread, stop signal and
141
+ * event sink (`runAgent({ ...options, ...run })`). The registry guarantees each run one terminal event: when `fn`
142
+ * throws or settles without one, it sends `RUN_ERROR` / `RUN_FINISHED` itself. The run leaves the registry with its
143
+ * terminal event; events after it are dropped. `result` is `fn`'s promise (already handled: not awaiting it is fine).
144
+ */
145
+ start(threadId, fn, o = {}) {
146
+ const cur = this.runs.get(threadId);
147
+ if (cur)
148
+ throw new Busy(threadId, cur.runId);
149
+ const run = { runId: o.runId ?? `run_${randomBytes(9).toString("base64url")}`, threadId, metadata: o.metadata, abort: new AbortController(), folder: new RunFolder(), started: null, ended: false };
150
+ this.runs.set(threadId, run);
151
+ let result;
152
+ try {
153
+ result = Promise.resolve(fn({ runId: run.runId, threadId, signal: run.abort.signal, onEvent: (e) => this.onEvent(run, e) }));
154
+ }
155
+ catch (err) {
156
+ result = Promise.reject(err);
157
+ }
158
+ result.then(() => this.end(run, { type: EventType.RUN_FINISHED, threadId, runId: run.runId }), (err) => this.end(run, { type: EventType.RUN_ERROR, message: err instanceof Error ? err.message : String(err), metadata: { threadId, runId: run.runId } }));
159
+ return { runId: run.runId, result };
160
+ }
161
+ /** Aborts the thread's run (only `runId`'s, when given). False when there is no such run. */
162
+ stop(threadId, runId) {
163
+ const r = this.runs.get(threadId);
164
+ if (!r || (runId && r.runId !== runId))
165
+ return false;
166
+ r.abort.abort();
167
+ return true;
168
+ }
169
+ /**
170
+ * Follows a thread: `CUSTOM READY {threadId, runId, running}` at once; when a run is in progress, `RUN_STARTED` and
171
+ * the replay of the run so far (once the run has started); then live events. Returns the unsubscribe.
172
+ */
173
+ listen(threadId, fn) {
174
+ let set = this.listeners.get(threadId);
175
+ if (!set)
176
+ this.listeners.set(threadId, (set = new Set()));
177
+ const r = this.runs.get(threadId);
178
+ const value = { threadId, runId: r?.runId ?? null, running: Boolean(r) };
179
+ this.call(fn, { type: EventType.CUSTOM, name: "READY", value });
180
+ if (r?.started) {
181
+ this.call(fn, r.started);
182
+ for (const e of r.folder.replay())
183
+ this.call(fn, e);
184
+ }
185
+ set.add(fn);
186
+ return () => {
187
+ set.delete(fn);
188
+ if (!set.size && this.listeners.get(threadId) === set)
189
+ this.listeners.delete(threadId);
190
+ };
191
+ }
192
+ /** Aborts every run (shutdown). */
193
+ close() {
194
+ for (const r of this.runs.values())
195
+ r.abort.abort();
196
+ }
197
+ onEvent(run, e) {
198
+ if (run.ended)
199
+ return;
200
+ if (e.type === EventType.RUN_STARTED) {
201
+ if (run.started)
202
+ return;
203
+ e = run.metadata ? { ...e, metadata: { ...(e.metadata ?? {}), ...run.metadata } } : e;
204
+ run.started = e;
205
+ }
206
+ else if (isEnd(e))
207
+ return this.end(run, e);
208
+ else if (!run.started) {
209
+ // A run that skipped RUN_STARTED (a host fn, not runAgent) gets one before its first event.
210
+ run.started = { type: EventType.RUN_STARTED, threadId: run.threadId, runId: run.runId, ...(run.metadata ? { metadata: run.metadata } : {}) };
211
+ this.send(run, run.started);
212
+ }
213
+ run.folder.fold(e);
214
+ this.send(run, e);
215
+ }
216
+ end(run, e) {
217
+ if (run.ended)
218
+ return;
219
+ run.ended = true;
220
+ if (this.runs.get(run.threadId) === run)
221
+ this.runs.delete(run.threadId);
222
+ this.send(run, e);
223
+ }
224
+ /** Delivers to the listeners there are now: one that joins during delivery got this event in its replay already. */
225
+ send(run, e) {
226
+ for (const fn of [...(this.listeners.get(run.threadId) ?? [])])
227
+ this.call(fn, e);
228
+ }
229
+ call(fn, e) {
230
+ try {
231
+ fn(e);
232
+ }
233
+ catch (err) {
234
+ this.warn("listener failed", err);
235
+ }
236
+ }
237
+ }
238
+ export function runRegistry(o) {
239
+ return new RunRegistry(o);
240
+ }
241
+ /**
242
+ * At startup, before serving: runs the store still shows `running` were never finished (the process that ran them is
243
+ * gone, and with it their registry), so they are marked failed. Returns how many. Hosts with their own visible-thread
244
+ * rows (`rudi_messages`, a chat message `streaming`) fail those in the same place.
245
+ */
246
+ export function failOrphans(store) {
247
+ return store.failStaleRuns();
248
+ }
@@ -1,7 +1,7 @@
1
1
  import { type BaseEvent } from "@ag-ui/core";
2
2
  import type { ImageContent, TSchema } from "@earendil-works/pi-ai";
3
3
  import { type FileEntry, type ToolDefinition } from "@earendil-works/pi-coding-agent";
4
- import { type PiModels } from "./models.ts";
4
+ import { type PiModels, type Thinking } from "./models.ts";
5
5
  import { type RunStatus, type RunUsage, type SessionStore } from "./store.ts";
6
6
  /**
7
7
  * Limits per run. `toolCalls` and `ms` stop a run that went wrong (a loop, a hung tool), not a normal one;
@@ -48,6 +48,13 @@ export interface RunAgentOptions {
48
48
  ownerId: string;
49
49
  /** Which kind of run: picks the tier and thinking (`models`), recorded on the run. */
50
50
  purpose: string;
51
+ /**
52
+ * This run's tier instead of the purpose's (lemma: the learner picks Fast / Balanced / Deep per ask); needs
53
+ * `models.byTier`. Recorded on the run. An unknown tier throws before anything runs or is stored.
54
+ */
55
+ tier?: string;
56
+ /** This run's thinking instead of the purpose's; recorded on the run. A model that does not reason runs `off` whatever this says. */
57
+ thinking?: Thinking;
51
58
  system: string;
52
59
  tools?: RunTool[];
53
60
  /** pi tool definitions used as they are (lemma's read-only file tools); counted against `toolCalls` like the others. */
@@ -140,7 +140,7 @@ export function runAgent(o) {
140
140
  async function run(o) {
141
141
  const warn = o.warn ?? ((message, detail) => console.warn(`agent-pi: ${message}`, detail ?? ""));
142
142
  const placeholder = o.imagePlaceholder ?? DEFAULT_PLACEHOLDER;
143
- const pick = o.models.pick(o.purpose);
143
+ const pick = choose(o);
144
144
  const model = pick.model;
145
145
  const thinking = model.model.reasoning ? pick.thinking : "off";
146
146
  const base = { ...DEFAULT_LIMITS, ...o.limits };
@@ -178,6 +178,12 @@ async function run(o) {
178
178
  const threadId = o.threadId ?? scope ?? sessionId;
179
179
  await o.store.startRun({ runId, ownerId: o.ownerId, purpose: o.purpose, model: model.id, tier: pick.tier, thinking, sessionId: keep ? sessionId : null, columns: o.runColumns });
180
180
  const startedAt = Date.now();
181
+ /** When the first text or reasoning delta came (ms since `startedAt`). */
182
+ let ttfbMs = null;
183
+ const firstByte = () => {
184
+ if (ttfbMs === null)
185
+ ttfbMs = Date.now() - startedAt;
186
+ };
181
187
  // From here on nothing throws: every failure ends the run with a status.
182
188
  let ended = false;
183
189
  const emit = (event) => {
@@ -332,10 +338,13 @@ async function run(o) {
332
338
  const e = event.assistantMessageEvent;
333
339
  if (e.type === "text_delta") {
334
340
  closeReasoning();
341
+ if (e.delta)
342
+ firstByte();
335
343
  streaming += e.delta;
336
344
  emit({ type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta: e.delta });
337
345
  }
338
346
  if (e.type === "thinking_delta" && e.delta) {
347
+ firstByte();
339
348
  if (!reasoningId) {
340
349
  reasoningId = `${messageId}:reasoning`;
341
350
  emit({ type: EventType.REASONING_START, messageId: reasoningId });
@@ -434,19 +443,30 @@ async function run(o) {
434
443
  }
435
444
  closeMessage(stopped ? "aborted" : undefined);
436
445
  const durationMs = Date.now() - startedAt;
446
+ const timing = { ttfbMs, durationMs };
437
447
  if (status === "failed")
438
- emit({ type: EventType.RUN_ERROR, message: why ?? "the run failed", metadata: { threadId, runId } });
448
+ emit({ type: EventType.RUN_ERROR, message: why ?? "the run failed", metadata: { threadId, runId, timing } });
439
449
  else
440
450
  emit({
441
451
  type: EventType.RUN_FINISHED,
442
452
  threadId,
443
453
  runId,
444
- result: { messageId: final ? lastTextId : null, text: final, costUsd: usage.costUsd, durationMs },
445
- ...(status === "stopped" ? { outcome: { type: "cancelled" }, metadata: { stopped: true } } : status === "cut" ? { metadata: { stopped: "cut", reason: cut } } : {}),
454
+ result: { messageId: final ? lastTextId : null, text: final, costUsd: usage.costUsd, durationMs, ttfbMs },
455
+ metadata: { timing, ...(status === "stopped" ? { stopped: true } : status === "cut" ? { stopped: "cut", reason: cut } : {}) },
456
+ ...(status === "stopped" ? { outcome: { type: "cancelled" } } : {}),
446
457
  });
447
458
  ended = true;
448
459
  return { runId, status, text: parts.join("\n\n"), final, cards, usage, error: why, sessionId: keep ? sessionId : null };
449
460
  }
461
+ /** The model, tier and thinking of a run: the purpose's, with the run's own `tier` / `thinking` over them. */
462
+ function choose(o) {
463
+ const pick = o.models.pick(o.purpose);
464
+ if (o.tier === undefined)
465
+ return o.thinking === undefined ? pick : { ...pick, thinking: o.thinking };
466
+ if (!o.models.byTier)
467
+ throw new Error(`runAgent: tier ${o.tier} asked, but the models have no byTier`);
468
+ return { model: o.models.byTier(o.tier), tier: o.tier, thinking: o.thinking ?? pick.thinking };
469
+ }
450
470
  /**
451
471
  * Adds a user message to a thread's session without a run (an event the app recorded): the next run reads it in
452
472
  * order. Makes the session, with its etho entry, when the scope has none yet.
@@ -0,0 +1,27 @@
1
+ import type { PiRunEvent } from "./run.ts";
2
+ import type { RunListener } from "./registry.ts";
3
+ /** What `sseResponse` needs: anything with agent-paseo's / the registry's `listen` (so it serves either part). */
4
+ export interface Listenable {
5
+ listen(threadId: string, fn: RunListener): () => void;
6
+ }
7
+ export interface SseOptions {
8
+ /** The request's signal (Hono: `c.req.raw.signal`): the stream ends when the client goes. The run goes on. */
9
+ signal?: AbortSignal;
10
+ /** A `: ping` comment this often, so proxies keep the stream open. Default 15 000; 0 for none. */
11
+ pingMs?: number;
12
+ /**
13
+ * Close the stream after the run's terminal event (a POST that streams its own answer), or at once when `READY`
14
+ * says no run is in progress (it ended before the response was made). Default false: follow the thread.
15
+ */
16
+ endAfterRun?: boolean;
17
+ /** Extra response headers. */
18
+ headers?: Record<string, string>;
19
+ }
20
+ /** One event as SSE: `event: <type, or a CUSTOM event's name>` and `data: <json>` (JSON has no raw newline). */
21
+ export declare function sseFrame(e: PiRunEvent): string;
22
+ /**
23
+ * A thread's events as a web `Response` (`text/event-stream`), for any Fetch-API server (Hono: `return
24
+ * sseResponse(registry, id, { signal: c.req.raw.signal })`). The first events are the follower contract's `READY` and
25
+ * replay. Ends when `signal` aborts or the client cancels the body; the run is never stopped by it.
26
+ */
27
+ export declare function sseResponse(source: Listenable, threadId: string, o?: SseOptions): Response;
@@ -0,0 +1,75 @@
1
+ /** One event as SSE: `event: <type, or a CUSTOM event's name>` and `data: <json>` (JSON has no raw newline). */
2
+ export function sseFrame(e) {
3
+ const name = String(e.type === "CUSTOM" && typeof e.name === "string" ? e.name : e.type).replace(/[\r\n]/g, " ");
4
+ return `event: ${name}\ndata: ${JSON.stringify(e)}\n\n`;
5
+ }
6
+ /**
7
+ * A thread's events as a web `Response` (`text/event-stream`), for any Fetch-API server (Hono: `return
8
+ * sseResponse(registry, id, { signal: c.req.raw.signal })`). The first events are the follower contract's `READY` and
9
+ * replay. Ends when `signal` aborts or the client cancels the body; the run is never stopped by it.
10
+ */
11
+ export function sseResponse(source, threadId, o = {}) {
12
+ const encoder = new TextEncoder();
13
+ let finish = () => { };
14
+ const body = new ReadableStream({
15
+ start(controller) {
16
+ let done = false;
17
+ let off = null;
18
+ let ping = null;
19
+ const write = (text) => {
20
+ if (done)
21
+ return;
22
+ try {
23
+ controller.enqueue(encoder.encode(text));
24
+ }
25
+ catch {
26
+ finish();
27
+ }
28
+ };
29
+ finish = () => {
30
+ if (done)
31
+ return;
32
+ done = true;
33
+ off?.();
34
+ if (ping)
35
+ clearInterval(ping);
36
+ o.signal?.removeEventListener("abort", finish);
37
+ try {
38
+ controller.close();
39
+ }
40
+ catch { }
41
+ };
42
+ if (o.signal?.aborted)
43
+ return finish();
44
+ o.signal?.addEventListener("abort", finish);
45
+ write(": connected\n\n");
46
+ let ended = false;
47
+ off = source.listen(threadId, (e) => {
48
+ write(sseFrame(e));
49
+ if (o.endAfterRun && (e.type === "RUN_FINISHED" || e.type === "RUN_ERROR"))
50
+ ended = true;
51
+ if (o.endAfterRun && e.type === "CUSTOM" && e.name === "READY" && !e.value?.running)
52
+ ended = true;
53
+ if (ended)
54
+ queueMicrotask(finish);
55
+ });
56
+ if (done)
57
+ off();
58
+ const every = o.pingMs ?? 15_000;
59
+ if (every > 0 && !done)
60
+ ping = setInterval(() => write(": ping\n\n"), every);
61
+ },
62
+ cancel() {
63
+ finish();
64
+ },
65
+ });
66
+ return new Response(body, {
67
+ headers: {
68
+ "content-type": "text/event-stream; charset=utf-8",
69
+ "cache-control": "no-store",
70
+ connection: "keep-alive",
71
+ "x-accel-buffering": "no",
72
+ ...o.headers,
73
+ },
74
+ });
75
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const parts: readonly ["agent-paseo", "agent-pi", "agent-chat"];
1
+ export declare const parts: readonly ["agent-paseo", "agent-pi", "agent-chat", "markdown"];
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @lightblues/jig: reusable parts for my apps. Each part is its own subpath export; this root only names the parts.
2
- export const parts = ['agent-paseo', 'agent-pi', 'agent-chat'];
2
+ export const parts = ['agent-paseo', 'agent-pi', 'agent-chat', 'markdown'];
@@ -0,0 +1 @@
1
+ export { closeOpenMarkdown, type CloseOpenMarkdownOptions } from "../agent-chat/markdown.ts";
@@ -0,0 +1,3 @@
1
+ // The one implementation lives in agent-chat (dependency-free); markdown re-exports it so streaming renders and
2
+ // agent-chat's helper close text the same way.
3
+ export { closeOpenMarkdown } from "../agent-chat/markdown.js";
@@ -0,0 +1,108 @@
1
+ import MarkdownIt from 'markdown-it';
2
+ import { closeOpenMarkdown, type CloseOpenMarkdownOptions } from './close.ts';
3
+ export { closeOpenMarkdown, type CloseOpenMarkdownOptions };
4
+ type Md = InstanceType<typeof MarkdownIt>;
5
+ /** The part of the `katex` module texmath uses. */
6
+ export type KatexLike = {
7
+ renderToString(tex: string, options?: Record<string, unknown>): string;
8
+ };
9
+ /** `markdown-it-texmath`'s default export. */
10
+ export type TexmathPlugin = ((md: Md, options?: Record<string, unknown>) => void) & {
11
+ inline?: (rule: TexRule) => (state: any, silent: boolean) => boolean;
12
+ rules?: Record<string, {
13
+ inline: TexRule[];
14
+ }>;
15
+ };
16
+ type TexRule = {
17
+ name: string;
18
+ rex: RegExp;
19
+ } & Record<string, unknown>;
20
+ /** Longest inline `$…$` read as math. texmath's own rule has no bound, so a long line of `$a ` is quadratic. */
21
+ export declare const MAX_INLINE_MATH = 1000;
22
+ /** A markdown-it plugin, as `md.use` takes it. */
23
+ export type Plugin = (md: Md, ...params: any[]) => void;
24
+ /** The part of highlight.js `hljsHighlighter` uses (`highlight.js/lib/core` with the languages registered). */
25
+ export type HljsLike = {
26
+ getLanguage(name: string): unknown;
27
+ highlight(code: string, options: {
28
+ language: string;
29
+ ignoreIllegals?: boolean;
30
+ }): {
31
+ value: string;
32
+ };
33
+ };
34
+ export type LinkKind = 'link' | 'image';
35
+ export type MarkdownOptions = {
36
+ /**
37
+ * Math with markdown-it-texmath (`dollars`: `$…$`, `$$…$$`) and KaTeX. Off by default. KaTeX runs with
38
+ * `trust: false` always (no `\href`, `\url`, `\htmlClass`, `\includegraphics`), `maxExpand` at most 1000, `maxSize` at
39
+ * most 50 em (no `\rule` over the page), `throwOnError: false` and `strict: "ignore"` unless `katexOptions` says
40
+ * otherwise. Each formula renders with a fresh copy of `macros`, so a `\gdef` lasts one formula.
41
+ */
42
+ math?: false | {
43
+ katex: KatexLike;
44
+ texmath: TexmathPlugin;
45
+ katexOptions?: Record<string, unknown>;
46
+ /** Longest formula rendered (characters); a longer one shows as its escaped source. Default 5000, ~50 ms. */
47
+ maxLength?: number;
48
+ };
49
+ /** `markdown-it-cjk-friendly`'s default export (`**粗体。**后文` closes as bold). Off when absent. */
50
+ cjk?: false | Plugin;
51
+ /**
52
+ * Code highlighting: `(code, lang) => html` of the code's inside, or `''` to leave it escaped. Its output is inserted
53
+ * as is, so it must escape the code (highlight.js does; see `hljsHighlighter`). Off by default.
54
+ */
55
+ highlight?: false | ((code: string, lang: string) => string);
56
+ links?: {
57
+ /** `target` on external links (an absolute URL), e.g. `"_blank"`. None by default. */
58
+ target?: string;
59
+ /** `rel` on external links. Default `"noopener noreferrer nofollow"`. */
60
+ rel?: string;
61
+ /**
62
+ * Decide a URL the default rule would not, or overrule it: `true` admits, `false` refuses, `undefined` keeps the
63
+ * default (http, https, mailto and relative URLs for links; http, https and relative for images). `javascript:`,
64
+ * `vbscript:`, `file:` and `data:` (except raster `data:image/…` for images) are refused whatever it says.
65
+ */
66
+ allow?: (url: string, kind: LinkKind) => boolean | undefined;
67
+ };
68
+ /** Images (`![alt](src)`). Off by default: an image renders as its alt text. */
69
+ images?: boolean;
70
+ /** Single newlines become `<br>`. Default `true` (model and chat text). */
71
+ breaks?: boolean;
72
+ /** Bare URLs become links (through the same link rules). Default `true`. */
73
+ linkify?: boolean;
74
+ /**
75
+ * Pass raw HTML through (markdown-it `html: true`). NEVER for model or user text: only for content the host itself
76
+ * wrote (course pages). Off by default; links and images keep their URL rules either way.
77
+ */
78
+ trustedHtml?: boolean;
79
+ /**
80
+ * Host plugins, applied after jig's own rules: `[plugin, ...params]` or a bare plugin. A plugin that emits HTML is
81
+ * the host's responsibility for safety: jig escapes the text, not what a plugin writes.
82
+ */
83
+ plugins?: (Plugin | [Plugin, ...unknown[]])[];
84
+ /** Passed to `closeOpenMarkdown` as `strip` when rendering with `streaming: true` (a half-written host marker). */
85
+ streamingStrip?: RegExp;
86
+ };
87
+ export type RenderOptions = {
88
+ /** The text is a partial answer: close what it left open first (`closeOpenMarkdown`). */
89
+ streaming?: boolean;
90
+ };
91
+ export type Markdown = {
92
+ render(text: string, opts?: RenderOptions): string;
93
+ /** The markdown-it instance, for `md.use(...)` and render rules; the same rules as `plugins` apply. */
94
+ md: Md;
95
+ };
96
+ export declare const DEFAULT_REL = "noopener noreferrer nofollow";
97
+ /** Is `url` (as markdown-it normalized it) allowed as a link or an image source? */
98
+ export declare function urlAllowed(url: string, kind: LinkKind, allow?: (url: string, kind: LinkKind) => boolean | undefined): boolean;
99
+ export declare function createMarkdown(opts?: MarkdownOptions): Markdown;
100
+ /** Formulas kept per instance. While streaming, every frame re-renders the same formulas; KaTeX is ~80% of the cost. */
101
+ export declare const MATH_CACHE_SIZE = 500;
102
+ /** Default `math.maxLength`. */
103
+ export declare const MAX_MATH_LENGTH = 5000;
104
+ /**
105
+ * A `highlight` function from highlight.js (pass `highlight.js/lib/core` with the languages you register; the full
106
+ * bundle is ~314 KB gzipped). An unknown language stays escaped plain code.
107
+ */
108
+ export declare function hljsHighlighter(hljs: HljsLike): (code: string, lang: string) => string;