@runappsai/agent 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -2
  3. package/dist/agent-core.umd.js +266 -0
  4. package/dist/agent.d.ts +222 -0
  5. package/dist/agent.js +1331 -0
  6. package/dist/agent.umd.js +732 -0
  7. package/dist/browser.d.ts +2 -0
  8. package/dist/browser.js +4 -0
  9. package/dist/chat-theme.d.ts +24 -0
  10. package/dist/chat-theme.js +101 -0
  11. package/dist/chat.d.ts +271 -0
  12. package/dist/chat.js +4099 -0
  13. package/dist/compaction.d.ts +48 -0
  14. package/dist/compaction.js +208 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.js +88 -0
  17. package/dist/context.d.ts +44 -0
  18. package/dist/context.js +177 -0
  19. package/dist/debug-panel.d.ts +40 -0
  20. package/dist/debug-panel.js +262 -0
  21. package/dist/dialogs.d.ts +7 -0
  22. package/dist/dialogs.js +231 -0
  23. package/dist/directory-fs.d.ts +5 -0
  24. package/dist/directory-fs.js +118 -0
  25. package/dist/dom.d.ts +83 -0
  26. package/dist/dom.js +163 -0
  27. package/dist/edit.d.ts +22 -0
  28. package/dist/edit.js +133 -0
  29. package/dist/file-guard.d.ts +46 -0
  30. package/dist/file-guard.js +153 -0
  31. package/dist/file-tools.d.ts +16 -0
  32. package/dist/file-tools.js +339 -0
  33. package/dist/files-panel.d.ts +60 -0
  34. package/dist/files-panel.js +613 -0
  35. package/dist/index.cjs +4848 -0
  36. package/dist/index.d.ts +37 -0
  37. package/dist/index.js +44 -0
  38. package/dist/json-schema.d.ts +3 -0
  39. package/dist/json-schema.js +141 -0
  40. package/dist/llm.d.ts +95 -0
  41. package/dist/llm.js +5 -0
  42. package/dist/markdown.d.ts +4 -0
  43. package/dist/markdown.js +265 -0
  44. package/dist/mcp.d.ts +82 -0
  45. package/dist/mcp.js +325 -0
  46. package/dist/node.cjs +402 -0
  47. package/dist/node.d.ts +78 -0
  48. package/dist/node.js +432 -0
  49. package/dist/pdf.d.ts +52 -0
  50. package/dist/pdf.js +77 -0
  51. package/dist/provider.d.ts +135 -0
  52. package/dist/provider.js +181 -0
  53. package/dist/sandbox.d.ts +33 -0
  54. package/dist/sandbox.js +219 -0
  55. package/dist/select.d.ts +30 -0
  56. package/dist/select.js +185 -0
  57. package/dist/skill-zips.d.ts +28 -0
  58. package/dist/skill-zips.js +123 -0
  59. package/dist/skills.d.ts +20 -0
  60. package/dist/skills.js +111 -0
  61. package/dist/templates.d.ts +24 -0
  62. package/dist/templates.js +136 -0
  63. package/dist/tool.d.ts +28 -0
  64. package/dist/tool.js +102 -0
  65. package/dist/types.d.ts +571 -0
  66. package/dist/types.js +7 -0
  67. package/dist/ui.cjs +6247 -0
  68. package/dist/ui.d.ts +6 -0
  69. package/dist/ui.js +11 -0
  70. package/dist/vlist.d.ts +80 -0
  71. package/dist/vlist.js +277 -0
  72. package/dist/workspace.d.ts +343 -0
  73. package/dist/workspace.js +1203 -0
  74. package/dist/zip.d.ts +26 -0
  75. package/dist/zip.js +204 -0
  76. package/docs/agent.md +228 -0
  77. package/docs/chat-ui.md +307 -0
  78. package/docs/node.md +135 -0
  79. package/docs/providers.md +176 -0
  80. package/docs/reference.md +143 -0
  81. package/docs/skills.md +131 -0
  82. package/docs/tools.md +254 -0
  83. package/docs/workspace.md +198 -0
  84. package/package.json +59 -4
@@ -0,0 +1,37 @@
1
+ export { Agent, type PromptContent } from "./agent.js";
2
+ export { openAIProvider, runappsProvider, toProvider, ProviderError, sseData, modelAccepts, type ModelProvider, type ModelInfo, type ModelPrice, type InputKind, type OpenAIProviderOptions, type RunAppsClientLike } from "./provider.js";
3
+ export type { ChatMessage, ContentPart, ChatTool, ChatToolCall, ChatCompletionParams, ChatCompletionChunk, ChatCompletion, Usage } from "./llm.js";
4
+ import { Agent } from "./agent.js";
5
+ import type { AgentOptions } from "./types.js";
6
+ import { Workspace, type WorkspaceOptions } from "./workspace.js";
7
+ import { type ModelProvider, type RunAppsClientLike } from "./provider.js";
8
+ /**
9
+ * An agent on a model provider: `createAgent(openAIProvider({ baseURL, apiKey }), { tools, workspace, … })`,
10
+ * or on a RunApps SDK client directly (`createAgent(client, …)`).
11
+ */
12
+ export declare function createAgent(provider: ModelProvider | RunAppsClientLike, opts?: AgentOptions): Agent;
13
+ /**
14
+ * A workspace for agents, in the app's own IndexedDB database
15
+ * (`opts.project`, else the provider's `name`, e.g. the RunApps client's
16
+ * project); resolves once its skills are ready. The provider is only
17
+ * needed for `files:` skills sources; `null` is fine.
18
+ */
19
+ export declare function openWorkspace(provider: ModelProvider | RunAppsClientLike | null, opts?: WorkspaceOptions): Promise<Workspace>;
20
+ export { Workspace, memoryFS, normalizePath, guessType, decodeText, titleOf, UNTITLED, DEFAULT_SKILLS_DIR, DEFAULT_USER_SKILLS_DIR, type SkillSource, type LazySkill, type WorkspaceOptions, type WorkspaceRead, type WorkspaceChange, type SessionStore, type WorkspaceStore, type WorkspaceStoreFactory, type FileRecord } from "./workspace.js";
21
+ export { planCut, serializeConversation, splitForSummary, summaryOf, summaryMessage, type CompactionSettings, type CutPlan } from "./compaction.js";
22
+ export { parseCommandArgs, substituteArgs, listTemplates, expandSlash, type PromptTemplate } from "./templates.js";
23
+ export { applyEdits, normalizeForFuzzyMatch, type TextEdit } from "./edit.js";
24
+ export { defineTool, normalizeResult } from "./tool.js";
25
+ export { domUI, nullUI, askUserTool } from "./dialogs.js";
26
+ export { configurePdf, extractPdfText, formatPdfText, isPdf, type PdfLib } from "./pdf.js";
27
+ export { fileTools, type FileToolsOptions } from "./file-tools.js";
28
+ export { fileGuard, PartialReadError, type FileGuard } from "./file-guard.js";
29
+ export { connectMCP, MCPError, type MCPConnection, type MCPOptions, type MCPToolInfo } from "./mcp.js";
30
+ export { sandboxTool, runInSandbox, type SandboxOptions, type SandboxResult } from "./sandbox.js";
31
+ export { parseSkill, parseFrontmatter } from "./skills.js";
32
+ export { collectCompletion, type CollectedCompletion } from "./completion.js";
33
+ export { buildSystemPrompt, estimateTokens, fitBudget, groupTurns } from "./context.js";
34
+ export { validateSchema } from "./json-schema.js";
35
+ export { listZip, readZipEntry, buildZip, type ZipEntry, type Inflate } from "./zip.js";
36
+ export { skillZipFS, skillFoldersOf, subFS } from "./skill-zips.js";
37
+ export type { AgentEventMap, AgentEventName, AgentFS, AgentOptions, AgentUI, AgentUsage, FileStat, JSONSchema, Permissions, RunEnd, RunEndReason, RunResult, SelectOption, SessionData, SessionSummary, Skill, Tool, ToolCallHookEvent, ToolContext, ToolDefinition, ToolConfirm, ToolResultValue, ToolStatus, ToolDisplay, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,44 @@
1
+ // @runappsai/agent — the core: `Agent` (the loop), `Workspace` (files,
2
+ // skills, sessions), providers, tools. No DOM: it runs in browsers, Node,
3
+ // Deno and workers. The chat UI is `@runappsai/agent/ui`; Node helpers
4
+ // (a folder as the directory, storage on disk, terminal dialogs) are
5
+ // `@runappsai/agent/node`.
6
+ export { Agent } from "./agent.js";
7
+ export { openAIProvider, runappsProvider, toProvider, ProviderError, sseData, modelAccepts } from "./provider.js";
8
+ import { Agent } from "./agent.js";
9
+ import { Workspace } from "./workspace.js";
10
+ import { toProvider } from "./provider.js";
11
+ /**
12
+ * An agent on a model provider: `createAgent(openAIProvider({ baseURL, apiKey }), { tools, workspace, … })`,
13
+ * or on a RunApps SDK client directly (`createAgent(client, …)`).
14
+ */
15
+ export function createAgent(provider, opts = {}) {
16
+ return new Agent(provider, opts);
17
+ }
18
+ /**
19
+ * A workspace for agents, in the app's own IndexedDB database
20
+ * (`opts.project`, else the provider's `name`, e.g. the RunApps client's
21
+ * project); resolves once its skills are ready. The provider is only
22
+ * needed for `files:` skills sources; `null` is fine.
23
+ */
24
+ export function openWorkspace(provider, opts = {}) {
25
+ const p = provider ? toProvider(provider) : null;
26
+ return Workspace.open(p, { ...opts, project: opts.project ?? p?.name ?? undefined });
27
+ }
28
+ export { Workspace, memoryFS, normalizePath, guessType, decodeText, titleOf, UNTITLED, DEFAULT_SKILLS_DIR, DEFAULT_USER_SKILLS_DIR } from "./workspace.js";
29
+ export { planCut, serializeConversation, splitForSummary, summaryOf, summaryMessage } from "./compaction.js";
30
+ export { parseCommandArgs, substituteArgs, listTemplates, expandSlash } from "./templates.js";
31
+ export { applyEdits, normalizeForFuzzyMatch } from "./edit.js";
32
+ export { defineTool, normalizeResult } from "./tool.js";
33
+ export { domUI, nullUI, askUserTool } from "./dialogs.js";
34
+ export { configurePdf, extractPdfText, formatPdfText, isPdf } from "./pdf.js";
35
+ export { fileTools } from "./file-tools.js";
36
+ export { fileGuard, PartialReadError } from "./file-guard.js";
37
+ export { connectMCP, MCPError } from "./mcp.js";
38
+ export { sandboxTool, runInSandbox } from "./sandbox.js";
39
+ export { parseSkill, parseFrontmatter } from "./skills.js";
40
+ export { collectCompletion } from "./completion.js";
41
+ export { buildSystemPrompt, estimateTokens, fitBudget, groupTurns } from "./context.js";
42
+ export { validateSchema } from "./json-schema.js";
43
+ export { listZip, readZipEntry, buildZip } from "./zip.js";
44
+ export { skillZipFS, skillFoldersOf, subFS } from "./skill-zips.js";
@@ -0,0 +1,3 @@
1
+ import type { JSONSchema } from "./types.js";
2
+ /** Problems found, as `path: message` lines; empty when the value fits. */
3
+ export declare function validateSchema(schema: JSONSchema | undefined, value: unknown): string[];
@@ -0,0 +1,141 @@
1
+ // A small JSON Schema checker for tool arguments. Covers what tool schemas
2
+ // use in practice — type, required, properties, additionalProperties,
3
+ // enum, const, items, bounds, anyOf/oneOf — and returns readable messages
4
+ // that go back to the model as the tool result, so it can fix the call.
5
+ // (`validate.ts` speaks the gateway's option-schema vocabulary, not JSON
6
+ // Schema, so it does not apply here.)
7
+ /** Problems found, as `path: message` lines; empty when the value fits. */
8
+ export function validateSchema(schema, value) {
9
+ if (!schema)
10
+ return [];
11
+ const errors = [];
12
+ check(schema, value, "", errors, 0);
13
+ return errors;
14
+ }
15
+ function typeOf(v) {
16
+ if (v === null)
17
+ return "null";
18
+ if (Array.isArray(v))
19
+ return "array";
20
+ if (typeof v === "number")
21
+ return Number.isInteger(v) ? "integer" : "number";
22
+ return typeof v;
23
+ }
24
+ function matchesType(want, v) {
25
+ const t = typeOf(v);
26
+ if (want === "number")
27
+ return t === "number" || t === "integer";
28
+ if (want === "integer")
29
+ return t === "integer";
30
+ return want === t;
31
+ }
32
+ function check(schema, value, path, errors, depth) {
33
+ if (depth > 32)
34
+ return;
35
+ const at = path || "arguments";
36
+ // Combinators: anyOf needs one branch to pass, oneOf exactly one; the schema's other keywords still apply.
37
+ for (const key of ["anyOf", "oneOf"]) {
38
+ const branches = schema[key];
39
+ if (Array.isArray(branches) && branches.length) {
40
+ const passing = branches.filter((b) => {
41
+ const e = [];
42
+ check(b, value, path, e, depth + 1);
43
+ return e.length === 0;
44
+ }).length;
45
+ if (passing === 0) {
46
+ errors.push(`${at}: does not match any allowed form`);
47
+ return;
48
+ }
49
+ if (key === "oneOf" && passing > 1) {
50
+ errors.push(`${at}: matches more than one of the allowed forms`);
51
+ return;
52
+ }
53
+ }
54
+ }
55
+ if (Array.isArray(schema.allOf)) {
56
+ for (const b of schema.allOf)
57
+ check(b, value, path, errors, depth + 1);
58
+ }
59
+ if (schema.type !== undefined) {
60
+ const types = (Array.isArray(schema.type) ? schema.type : [schema.type]);
61
+ if (!types.some((t) => matchesType(t, value))) {
62
+ errors.push(`${at}: expected ${types.join(" or ")}, got ${typeOf(value)}`);
63
+ return;
64
+ }
65
+ }
66
+ if (Array.isArray(schema.enum) && !schema.enum.some((e) => deepEqual(e, value))) {
67
+ errors.push(`${at}: must be one of ${schema.enum.map((e) => JSON.stringify(e)).join(", ")}`);
68
+ return;
69
+ }
70
+ if ("const" in schema && !deepEqual(schema.const, value)) {
71
+ errors.push(`${at}: must be ${JSON.stringify(schema.const)}`);
72
+ return;
73
+ }
74
+ if (typeof value === "string") {
75
+ if (typeof schema.minLength === "number" && value.length < schema.minLength)
76
+ errors.push(`${at}: shorter than ${schema.minLength} characters`);
77
+ if (typeof schema.maxLength === "number" && value.length > schema.maxLength)
78
+ errors.push(`${at}: longer than ${schema.maxLength} characters`);
79
+ if (typeof schema.pattern === "string") {
80
+ try {
81
+ if (!new RegExp(schema.pattern, "u").test(value))
82
+ errors.push(`${at}: does not match pattern ${schema.pattern}`);
83
+ }
84
+ catch { /* bad pattern in the schema: ignore */ }
85
+ }
86
+ }
87
+ else if (typeof value === "number") {
88
+ if (typeof schema.minimum === "number" && value < schema.minimum)
89
+ errors.push(`${at}: below minimum ${schema.minimum}`);
90
+ if (typeof schema.maximum === "number" && value > schema.maximum)
91
+ errors.push(`${at}: above maximum ${schema.maximum}`);
92
+ if (typeof schema.exclusiveMinimum === "number" && value <= schema.exclusiveMinimum)
93
+ errors.push(`${at}: must be greater than ${schema.exclusiveMinimum}`);
94
+ if (typeof schema.exclusiveMaximum === "number" && value >= schema.exclusiveMaximum)
95
+ errors.push(`${at}: must be less than ${schema.exclusiveMaximum}`);
96
+ }
97
+ else if (Array.isArray(value)) {
98
+ if (typeof schema.minItems === "number" && value.length < schema.minItems)
99
+ errors.push(`${at}: needs at least ${schema.minItems} items`);
100
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems)
101
+ errors.push(`${at}: at most ${schema.maxItems} items`);
102
+ if (schema.items && typeof schema.items === "object" && !Array.isArray(schema.items)) {
103
+ value.forEach((v, i) => check(schema.items, v, `${path}[${i}]`, errors, depth + 1));
104
+ }
105
+ }
106
+ else if (value && typeof value === "object") {
107
+ const obj = value;
108
+ const props = (schema.properties && typeof schema.properties === "object" ? schema.properties : {});
109
+ if (Array.isArray(schema.required)) {
110
+ for (const r of schema.required) {
111
+ if (!(r in obj) || obj[r] === undefined)
112
+ errors.push(`${at}: missing required "${r}"`);
113
+ }
114
+ }
115
+ for (const [k, v] of Object.entries(obj)) {
116
+ const sub = props[k];
117
+ if (sub) {
118
+ check(sub, v, path ? `${path}.${k}` : k, errors, depth + 1);
119
+ }
120
+ else if (schema.additionalProperties === false) {
121
+ const known = Object.keys(props);
122
+ errors.push(`${at}: unknown field "${k}"${known.length ? ` (allowed: ${known.join(", ")})` : ""}`);
123
+ }
124
+ else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
125
+ check(schema.additionalProperties, v, path ? `${path}.${k}` : k, errors, depth + 1);
126
+ }
127
+ }
128
+ }
129
+ }
130
+ function deepEqual(a, b) {
131
+ if (a === b)
132
+ return true;
133
+ if (typeof a !== typeof b || a === null || b === null || typeof a !== "object")
134
+ return false;
135
+ if (Array.isArray(a) !== Array.isArray(b))
136
+ return false;
137
+ const ka = Object.keys(a), kb = Object.keys(b);
138
+ if (ka.length !== kb.length)
139
+ return false;
140
+ return ka.every((k) => deepEqual(a[k], b[k]));
141
+ }
package/dist/llm.d.ts ADDED
@@ -0,0 +1,95 @@
1
+ export interface ChatMessage {
2
+ role: "system" | "user" | "assistant" | "tool";
3
+ content: string | ContentPart[] | null;
4
+ name?: string;
5
+ tool_call_id?: string;
6
+ tool_calls?: ChatToolCall[];
7
+ /** A thinking model's reasoning (DeepSeek's field; sent back on tool-calling turns). */
8
+ reasoning_content?: string;
9
+ }
10
+ export type ContentPart = {
11
+ type: "text";
12
+ text: string;
13
+ } | {
14
+ type: "image_url";
15
+ image_url: {
16
+ url: string;
17
+ detail?: "auto" | "low" | "high";
18
+ };
19
+ } | {
20
+ type: "video_url";
21
+ video_url: {
22
+ url: string;
23
+ };
24
+ } | {
25
+ type: "audio_url";
26
+ audio_url: {
27
+ url: string;
28
+ };
29
+ };
30
+ export interface ChatTool {
31
+ type: "function";
32
+ function: {
33
+ name: string;
34
+ description?: string;
35
+ parameters?: Record<string, unknown>;
36
+ strict?: boolean;
37
+ };
38
+ }
39
+ export interface ChatToolCall {
40
+ index?: number;
41
+ id?: string;
42
+ type?: string;
43
+ function: {
44
+ name: string;
45
+ arguments: string;
46
+ };
47
+ }
48
+ /** One request. Fields a provider does not know it may drop. */
49
+ export interface ChatCompletionParams {
50
+ model: string;
51
+ messages: ChatMessage[];
52
+ tools?: ChatTool[];
53
+ max_tokens?: number;
54
+ stream?: boolean;
55
+ reasoning_effort?: string;
56
+ [extra: string]: unknown;
57
+ }
58
+ export interface Usage {
59
+ prompt_tokens?: number;
60
+ completion_tokens?: number;
61
+ total_tokens?: number;
62
+ /** What the call cost in USD, when the provider says (RunApps does). */
63
+ total_cost?: number;
64
+ }
65
+ /** A streamed piece of a reply (`chat.completion.chunk`). */
66
+ export interface ChatCompletionChunk {
67
+ choices: Array<{
68
+ index?: number;
69
+ delta?: {
70
+ role?: string;
71
+ content?: string | null;
72
+ tool_calls?: ChatToolCall[];
73
+ reasoning_content?: string;
74
+ reasoning?: string;
75
+ };
76
+ finish_reason?: string | null;
77
+ }>;
78
+ usage?: Usage | null;
79
+ }
80
+ /** A whole reply (`chat.completion`). */
81
+ export interface ChatCompletion {
82
+ choices: Array<{
83
+ index?: number;
84
+ message: {
85
+ role: string;
86
+ content: string | null;
87
+ tool_calls?: ChatToolCall[];
88
+ reasoning_content?: string;
89
+ reasoning?: string;
90
+ };
91
+ finish_reason: string;
92
+ }>;
93
+ usage?: Usage | null;
94
+ }
95
+ export type Unsubscribe = () => void;
package/dist/llm.js ADDED
@@ -0,0 +1,5 @@
1
+ // The model API the agent speaks: OpenAI's Chat Completions, as types of
2
+ // its own, so the package depends on no SDK. The RunApps SDK's types are
3
+ // the same shape (its client works as a provider unchanged), and so are
4
+ // those of any OpenAI-compatible endpoint.
5
+ export {};
@@ -0,0 +1,4 @@
1
+ export declare function escapeHTML(s: string): string;
2
+ /** Inline markup within one block (text already raw; escapes here). */
3
+ export declare function renderInline(text: string): string;
4
+ export declare function renderMarkdown(src: string): string;
@@ -0,0 +1,265 @@
1
+ // A small Markdown → HTML renderer for chat replies: fenced code, headings,
2
+ // lists, blockquotes, tables, rules, paragraphs; inline code, bold, italic,
3
+ // strikethrough and links. Everything is HTML-escaped; links are kept only
4
+ // for http(s)/mailto. Good enough for model output, with no dependency.
5
+ // A fence left open (a reply still streaming) renders as code.
6
+ const ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
7
+ export function escapeHTML(s) {
8
+ return s.replace(/[&<>"']/g, (c) => ESC[c]);
9
+ }
10
+ function safeHref(url) {
11
+ const u = url.trim();
12
+ if (/^(https?:\/\/|mailto:)/i.test(u))
13
+ return u;
14
+ if (/^(\/|\.\/|\.\.\/|#)/.test(u) && !/^\/\//.test(u))
15
+ return u;
16
+ return null;
17
+ }
18
+ const WORD = /[\p{L}\p{N}]/u;
19
+ const TICKS = /`+/y;
20
+ const LINK = /\[([^\]]*)\]\(((?:[^()\s]|\([^()\s]*\))+)(?:\s+"[^"]*")?\)/y;
21
+ const BARE = /https?:\/\/(?:[^\s<>()]|\([^\s<>()]*\))+/y;
22
+ /** Inline markup within one block (text already raw; escapes here). */
23
+ export function renderInline(text) {
24
+ let out = "";
25
+ let i = 0;
26
+ const n = text.length;
27
+ // Searches that already failed from an earlier position fail from any later one: remember them, so
28
+ // pathological input (many "*" or "[" with nothing to close them) stays linear.
29
+ const noClose = new Map();
30
+ let nextLink = -2;
31
+ while (i < n) {
32
+ const c = text[i];
33
+ // Inline code: `…` (any run of backticks, matched by the same run).
34
+ if (c === "`") {
35
+ TICKS.lastIndex = i;
36
+ const run = TICKS.exec(text)[0];
37
+ const close = text.indexOf(run, i + run.length);
38
+ if (close > 0) {
39
+ out += `<code>${escapeHTML(text.slice(i + run.length, close).trim())}</code>`;
40
+ i = close + run.length;
41
+ continue;
42
+ }
43
+ out += escapeHTML(run);
44
+ i += run.length;
45
+ continue;
46
+ }
47
+ // Links: [label](url) — the label may hold inline markup; the url may hold balanced parentheses.
48
+ if (c === "[") {
49
+ if (nextLink !== -1 && nextLink < i)
50
+ nextLink = text.indexOf("](", i);
51
+ if (nextLink !== -1) {
52
+ LINK.lastIndex = i;
53
+ const m = LINK.exec(text);
54
+ if (m) {
55
+ const href = safeHref(m[2]);
56
+ const label = renderInline(m[1]);
57
+ out += href ? `<a href="${escapeHTML(href)}" target="_blank" rel="noopener noreferrer">${label}</a>` : label;
58
+ i += m[0].length;
59
+ continue;
60
+ }
61
+ }
62
+ }
63
+ // Bare URLs (balanced parentheses kept, trailing punctuation left out).
64
+ if (c === "h" && text.startsWith("http", i) && (i === 0 || !WORD.test(text[i - 1]))) {
65
+ BARE.lastIndex = i;
66
+ const m = BARE.exec(text);
67
+ if (m) {
68
+ const url = m[0].replace(/[.,;:!?'"]+$/, "");
69
+ if (url.length > 8) {
70
+ out += `<a href="${escapeHTML(url)}" target="_blank" rel="noopener noreferrer">${escapeHTML(url)}</a>`;
71
+ i += url.length;
72
+ continue;
73
+ }
74
+ }
75
+ }
76
+ // Strong / emphasis / strikethrough. "_" never opens or closes inside a word (my_file_name).
77
+ if (c === "*" || c === "_" || c === "~") {
78
+ const run = text[i + 1] === c ? c + c : c;
79
+ const opens = (run.length === 2 || c !== "~")
80
+ && i + run.length < n && !/\s/.test(text[i + run.length])
81
+ && !(c === "_" && i > 0 && WORD.test(text[i - 1]));
82
+ if (opens && (noClose.get(run) ?? Infinity) > i) {
83
+ const close = findClose(text, i + run.length, run);
84
+ if (close > 0) {
85
+ const inner = renderInline(text.slice(i + run.length, close));
86
+ out += run === "~~" ? `<del>${inner}</del>` : run.length === 2 ? `<strong>${inner}</strong>` : `<em>${inner}</em>`;
87
+ i = close + run.length;
88
+ continue;
89
+ }
90
+ noClose.set(run, Math.min(noClose.get(run) ?? Infinity, i));
91
+ }
92
+ out += escapeHTML(run);
93
+ i += run.length;
94
+ continue;
95
+ }
96
+ if (c === "\\" && i + 1 < n && /[\\`*_{}\[\]()#+\-.!~|>]/.test(text[i + 1])) {
97
+ out += escapeHTML(text[i + 1]);
98
+ i += 2;
99
+ continue;
100
+ }
101
+ if (c === "\n") {
102
+ out += "<br>";
103
+ i++;
104
+ continue;
105
+ }
106
+ out += escapeHTML(c);
107
+ i++;
108
+ }
109
+ return out;
110
+ }
111
+ /** The closing delimiter of an emphasis run: not preceded by a space, not an empty span; "_" not followed by a letter. */
112
+ function findClose(text, from, run) {
113
+ let j = from;
114
+ while ((j = text.indexOf(run, j)) > 0) {
115
+ const ok = j > from && text[j - 1] !== " " && text[j - 1] !== "\n"
116
+ && !(run[0] === "_" && j + run.length < text.length && WORD.test(text[j + run.length]));
117
+ if (ok)
118
+ return j;
119
+ j += run.length;
120
+ }
121
+ return -1;
122
+ }
123
+ const FENCE = /^(\s{0,3})(`{3,}|~{3,})\s*([\w+#.-]*)/;
124
+ export function renderMarkdown(src) {
125
+ const lines = src.replace(/\r\n?/g, "\n").split("\n");
126
+ const html = [];
127
+ let i = 0;
128
+ const paragraph = [];
129
+ const flush = () => {
130
+ if (!paragraph.length)
131
+ return;
132
+ html.push(`<p>${renderInline(paragraph.join("\n"))}</p>`);
133
+ paragraph.length = 0;
134
+ };
135
+ while (i < lines.length) {
136
+ const line = lines[i];
137
+ // Fenced code (an unclosed fence runs to the end).
138
+ const fence = FENCE.exec(line);
139
+ if (fence && !(fence[2][0] === "`" && line.slice(fence[0].length).includes("`"))) {
140
+ flush();
141
+ const marker = fence[2];
142
+ const lang = fence[3] ?? "";
143
+ const body = [];
144
+ i++;
145
+ const closes = (l) => { const t = l.trim(); return t.length >= marker.length && t === marker[0].repeat(t.length); };
146
+ while (i < lines.length && !closes(lines[i])) {
147
+ body.push(lines[i]);
148
+ i++;
149
+ }
150
+ i++;
151
+ const cls = lang ? ` class="language-${escapeHTML(lang)}"` : "";
152
+ html.push(`<pre><code${cls}>${escapeHTML(body.join("\n"))}\n</code></pre>`);
153
+ continue;
154
+ }
155
+ if (!line.trim()) {
156
+ flush();
157
+ i++;
158
+ continue;
159
+ }
160
+ const heading = /^(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/.exec(line);
161
+ if (heading) {
162
+ flush();
163
+ html.push(`<h${heading[1].length}>${renderInline(heading[2])}</h${heading[1].length}>`);
164
+ i++;
165
+ continue;
166
+ }
167
+ if (/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(line)) {
168
+ flush();
169
+ html.push("<hr>");
170
+ i++;
171
+ continue;
172
+ }
173
+ if (/^\s{0,3}>/.test(line)) {
174
+ flush();
175
+ const inner = [];
176
+ while (i < lines.length && /^\s{0,3}>/.test(lines[i])) {
177
+ inner.push(lines[i].replace(/^\s{0,3}>\s?/, ""));
178
+ i++;
179
+ }
180
+ html.push(`<blockquote>${renderMarkdown(inner.join("\n"))}</blockquote>`);
181
+ continue;
182
+ }
183
+ // Table: a header row, a delimiter row, then rows.
184
+ if (line.includes("|") && i + 1 < lines.length && lines[i + 1].includes("|") && /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(lines[i + 1])) {
185
+ flush();
186
+ const cells = (l) => l.trim().replace(/^\|/, "").replace(/(?<!\\)\|$/, "").split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, "|"));
187
+ const aligns = cells(lines[i + 1]).map((d) => (d.startsWith(":") && d.endsWith(":") ? "center" : d.endsWith(":") ? "right" : d.startsWith(":") ? "left" : ""));
188
+ const row = (l, tag) => `<tr>${cells(l).map((c, k) => `<${tag}${aligns[k] ? ` style="text-align:${aligns[k]}"` : ""}>${renderInline(c)}</${tag}>`).join("")}</tr>`;
189
+ let t = `<table><thead>${row(line, "th")}</thead><tbody>`;
190
+ i += 2;
191
+ while (i < lines.length && lines[i].includes("|") && lines[i].trim()) {
192
+ t += row(lines[i], "td");
193
+ i++;
194
+ }
195
+ html.push(t + "</tbody></table>");
196
+ continue;
197
+ }
198
+ const list = /^(\s*)([-*+]|\d+[.)])\s+/.exec(line);
199
+ if (list) {
200
+ flush();
201
+ const { html: h, next } = renderList(lines, i, list[1].length);
202
+ html.push(h);
203
+ i = next;
204
+ continue;
205
+ }
206
+ paragraph.push(line);
207
+ i++;
208
+ }
209
+ flush();
210
+ return html.join("\n");
211
+ }
212
+ /** A list starting at `start` with items indented by `indent`; nested items follow deeper indentation. */
213
+ function renderList(lines, start, indent) {
214
+ const first = /^(\s*)([-*+]|\d+[.)])\s+/.exec(lines[start]);
215
+ const ordered = /\d/.test(first[2]);
216
+ const startNum = ordered ? parseInt(first[2], 10) : 1;
217
+ const items = [];
218
+ let i = start;
219
+ while (i < lines.length) {
220
+ const m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(lines[i]);
221
+ if (!m || m[1].length !== indent || /\d/.test(m[2]) !== ordered)
222
+ break;
223
+ const bodyLines = [m[3]];
224
+ i++;
225
+ // Continuation lines: deeper indentation (nested lists or wrapped text) until the next sibling / blank+dedent.
226
+ while (i < lines.length) {
227
+ const l = lines[i];
228
+ if (!l.trim()) {
229
+ // A blank line ends the item unless more indented content follows.
230
+ if (i + 1 < lines.length && /^\s+\S/.test(lines[i + 1]) && (lines[i + 1].match(/^\s*/)[0].length > indent)) {
231
+ bodyLines.push("");
232
+ i++;
233
+ continue;
234
+ }
235
+ break;
236
+ }
237
+ const ind = l.match(/^\s*/)[0].length;
238
+ if (ind > indent) {
239
+ bodyLines.push(l);
240
+ i++;
241
+ continue;
242
+ }
243
+ break;
244
+ }
245
+ const task = /^\[([ xX])\]\s+/.exec(bodyLines[0]);
246
+ if (task)
247
+ bodyLines[0] = `<input type="checkbox" disabled${task[1] === " " ? "" : " checked"}> ` + bodyLines[0].slice(task[0].length);
248
+ items.push(`<li>${renderItemBody(bodyLines, indent, !!task)}</li>`);
249
+ }
250
+ const tag = ordered ? "ol" : "ul";
251
+ const attr = ordered && startNum !== 1 ? ` start="${startNum}"` : "";
252
+ return { html: `<${tag}${attr}>${items.join("")}</${tag}>`, next: i };
253
+ }
254
+ function renderItemBody(bodyLines, indent, rawFirst) {
255
+ // First line inline; the rest (dedented) as nested markdown.
256
+ const firstLine = bodyLines[0];
257
+ const rest = bodyLines.slice(1).map((l) => l.replace(new RegExp(`^\\s{0,${indent + 2}}`), "")).join("\n").trim();
258
+ const head = rawFirst ? firstLine.replace(/^(<input[^>]*> )/, "$1") : "";
259
+ const first = rawFirst ? head.slice(0, head.indexOf("> ") + 2) + renderInline(head.slice(head.indexOf("> ") + 2)) : renderInline(firstLine);
260
+ if (!rest)
261
+ return first;
262
+ const nested = renderMarkdown(rest);
263
+ // A lone paragraph in a nested block stays inline with the item.
264
+ return first + (nested.startsWith("<p>") && !nested.includes("</p>\n") ? `<br>${nested.slice(3, -4)}` : nested);
265
+ }