@openclaw/tlon 2026.2.21 → 2026.5.2-beta.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 (63) hide show
  1. package/api.ts +16 -0
  2. package/channel-plugin-api.ts +1 -0
  3. package/doctor-contract-api.ts +1 -0
  4. package/index.ts +177 -11
  5. package/openclaw.plugin.json +194 -1
  6. package/package.json +57 -4
  7. package/runtime-api.ts +17 -0
  8. package/setup-api.ts +2 -0
  9. package/setup-entry.ts +9 -0
  10. package/src/account-fields.ts +9 -3
  11. package/src/channel.runtime.ts +248 -0
  12. package/src/channel.ts +153 -364
  13. package/src/config-schema.ts +22 -16
  14. package/src/core.test.ts +278 -0
  15. package/src/doctor-contract.ts +9 -0
  16. package/src/doctor.test.ts +40 -0
  17. package/src/doctor.ts +10 -0
  18. package/src/logger-runtime.ts +1 -0
  19. package/src/monitor/approval-runtime.ts +363 -0
  20. package/src/monitor/approval.test.ts +33 -0
  21. package/src/monitor/approval.ts +286 -0
  22. package/src/monitor/authorization.ts +30 -0
  23. package/src/monitor/cites.ts +54 -0
  24. package/src/monitor/discovery.ts +44 -54
  25. package/src/monitor/history.ts +155 -21
  26. package/src/monitor/index.ts +1290 -369
  27. package/src/monitor/media.test.ts +91 -0
  28. package/src/monitor/media.ts +172 -0
  29. package/src/monitor/processed-messages.test.ts +36 -1
  30. package/src/monitor/processed-messages.ts +62 -19
  31. package/src/monitor/settings-helpers.test.ts +113 -0
  32. package/src/monitor/settings-helpers.ts +158 -0
  33. package/src/monitor/utils.ts +311 -45
  34. package/src/runtime.ts +8 -13
  35. package/src/security.test.ts +622 -0
  36. package/src/session-route.ts +40 -0
  37. package/src/settings.ts +391 -0
  38. package/src/setup-core.ts +228 -0
  39. package/src/setup-surface.ts +103 -0
  40. package/src/targets.ts +29 -16
  41. package/src/tlon-api.test.ts +589 -0
  42. package/src/tlon-api.ts +402 -0
  43. package/src/types.ts +106 -45
  44. package/src/urbit/auth.ssrf.test.ts +3 -2
  45. package/src/urbit/auth.ts +2 -2
  46. package/src/urbit/base-url.test.ts +18 -11
  47. package/src/urbit/base-url.ts +9 -5
  48. package/src/urbit/channel-ops.ts +40 -59
  49. package/src/urbit/context.ts +13 -10
  50. package/src/urbit/errors.ts +2 -2
  51. package/src/urbit/fetch.ts +6 -3
  52. package/src/urbit/foreigns.ts +49 -0
  53. package/src/urbit/send.ts +53 -8
  54. package/src/urbit/sse-client.test.ts +184 -25
  55. package/src/urbit/sse-client.ts +123 -69
  56. package/src/urbit/story.ts +332 -0
  57. package/src/urbit/upload.test.ts +154 -0
  58. package/src/urbit/upload.ts +60 -0
  59. package/test-api.ts +1 -0
  60. package/tsconfig.json +16 -0
  61. package/src/config-schema.test.ts +0 -31
  62. package/src/onboarding.ts +0 -229
  63. package/src/urbit/channel-client.ts +0 -157
@@ -1,10 +1,11 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { Readable } from "node:stream";
2
- import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk";
3
+ import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
3
4
  import { ensureUrbitChannelOpen, pokeUrbitChannel, scryUrbitPath } from "./channel-ops.js";
4
5
  import { getUrbitContext, normalizeUrbitCookie } from "./context.js";
5
6
  import { urbitFetch } from "./fetch.js";
6
7
 
7
- export type UrbitSseLogger = {
8
+ type UrbitSseLogger = {
8
9
  log?: (message: string) => void;
9
10
  error?: (message: string) => void;
10
11
  };
@@ -54,12 +55,17 @@ export class UrbitSSEClient {
54
55
  fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
55
56
  streamRelease: (() => Promise<void>) | null = null;
56
57
 
58
+ // Event ack tracking - must ack every ~50 events to keep channel healthy
59
+ private lastHeardEventId = -1;
60
+ private lastAcknowledgedEventId = -1;
61
+ private readonly ackThreshold = 20;
62
+
57
63
  constructor(url: string, cookie: string, options: UrbitSseOptions = {}) {
58
64
  const ctx = getUrbitContext(url, options.ship);
59
65
  this.url = ctx.baseUrl;
60
66
  this.cookie = normalizeUrbitCookie(cookie);
61
67
  this.ship = ctx.ship;
62
- this.channelId = `${Math.floor(Date.now() / 1000)}-${Math.random().toString(36).substring(2, 8)}`;
68
+ this.channelId = `${Math.floor(Date.now() / 1000)}-${randomUUID()}`;
63
69
  this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
64
70
  this.onReconnect = options.onReconnect ?? null;
65
71
  this.autoReconnect = options.autoReconnect !== false;
@@ -72,6 +78,18 @@ export class UrbitSSEClient {
72
78
  this.fetchImpl = options.fetchImpl;
73
79
  }
74
80
 
81
+ private channelRequestContext() {
82
+ return {
83
+ baseUrl: this.url,
84
+ cookie: this.cookie,
85
+ ship: this.ship,
86
+ channelId: this.channelId,
87
+ ssrfPolicy: this.ssrfPolicy,
88
+ lookupFn: this.lookupFn,
89
+ fetchImpl: this.fetchImpl,
90
+ };
91
+ }
92
+
75
93
  async subscribe(params: {
76
94
  app: string;
77
95
  path: string;
@@ -109,20 +127,7 @@ export class UrbitSSEClient {
109
127
  app: string;
110
128
  path: string;
111
129
  }) {
112
- const { response, release } = await urbitFetch({
113
- baseUrl: this.url,
114
- path: `/~/channel/${this.channelId}`,
115
- init: {
116
- method: "PUT",
117
- headers: {
118
- "Content-Type": "application/json",
119
- Cookie: this.cookie,
120
- },
121
- body: JSON.stringify([subscription]),
122
- },
123
- ssrfPolicy: this.ssrfPolicy,
124
- lookupFn: this.lookupFn,
125
- fetchImpl: this.fetchImpl,
130
+ const { response, release } = await this.putChannelPayload([subscription], {
126
131
  timeoutMs: 30_000,
127
132
  auditContext: "tlon-urbit-subscribe",
128
133
  });
@@ -140,21 +145,10 @@ export class UrbitSSEClient {
140
145
  }
141
146
 
142
147
  async connect() {
143
- await ensureUrbitChannelOpen(
144
- {
145
- baseUrl: this.url,
146
- cookie: this.cookie,
147
- ship: this.ship,
148
- channelId: this.channelId,
149
- ssrfPolicy: this.ssrfPolicy,
150
- lookupFn: this.lookupFn,
151
- fetchImpl: this.fetchImpl,
152
- },
153
- {
154
- createBody: this.subscriptions,
155
- createAuditContext: "tlon-urbit-channel-create",
156
- },
157
- );
148
+ await ensureUrbitChannelOpen(this.channelRequestContext(), {
149
+ createBody: this.subscriptions,
150
+ createAuditContext: "tlon-urbit-channel-create",
151
+ });
158
152
 
159
153
  await this.openStream();
160
154
  this.isConnected = true;
@@ -209,12 +203,15 @@ export class UrbitSSEClient {
209
203
  });
210
204
  }
211
205
 
212
- async processStream(body: ReadableStream<Uint8Array> | Readable | null) {
206
+ async processStream(body: unknown) {
213
207
  if (!body) {
214
208
  return;
215
209
  }
216
- // oxlint-disable-next-line typescript/no-explicit-any
217
- const stream = body instanceof ReadableStream ? Readable.fromWeb(body as any) : body;
210
+ // Bridge DOM fetch stream types to Node's stream/web declaration on newer TS/node combos.
211
+ const stream =
212
+ body instanceof ReadableStream
213
+ ? Readable.fromWeb(body as never)
214
+ : (body as NodeJS.ReadableStream);
218
215
  let buffer = "";
219
216
 
220
217
  try {
@@ -225,8 +222,8 @@ export class UrbitSSEClient {
225
222
  buffer += chunk.toString();
226
223
  let eventEnd;
227
224
  while ((eventEnd = buffer.indexOf("\n\n")) !== -1) {
228
- const eventData = buffer.substring(0, eventEnd);
229
- buffer = buffer.substring(eventEnd + 2);
225
+ const eventData = buffer.slice(0, eventEnd);
226
+ buffer = buffer.slice(eventEnd + 2);
230
227
  this.processEvent(eventData);
231
228
  }
232
229
  }
@@ -248,10 +245,14 @@ export class UrbitSSEClient {
248
245
  processEvent(eventData: string) {
249
246
  const lines = eventData.split("\n");
250
247
  let data: string | null = null;
248
+ let eventId: number | null = null;
251
249
 
252
250
  for (const line of lines) {
251
+ if (line.startsWith("id: ")) {
252
+ eventId = Number.parseInt(line.slice(4), 10);
253
+ }
253
254
  if (line.startsWith("data: ")) {
254
- data = line.substring(6);
255
+ data = line.slice(6);
255
256
  }
256
257
  }
257
258
 
@@ -259,6 +260,21 @@ export class UrbitSSEClient {
259
260
  return;
260
261
  }
261
262
 
263
+ // Track event ID and send ack if needed
264
+ if (eventId !== null && !Number.isNaN(eventId)) {
265
+ if (eventId > this.lastHeardEventId) {
266
+ this.lastHeardEventId = eventId;
267
+ if (eventId - this.lastAcknowledgedEventId > this.ackThreshold) {
268
+ this.logger.log?.(
269
+ `[SSE] Acking event ${eventId} (last acked: ${this.lastAcknowledgedEventId})`,
270
+ );
271
+ this.ack(eventId).catch((err) => {
272
+ this.logger.error?.(`Failed to ack event ${eventId}: ${String(err)}`);
273
+ });
274
+ }
275
+ }
276
+ }
277
+
262
278
  try {
263
279
  const parsed = JSON.parse(data) as { id?: number; json?: unknown; response?: string };
264
280
 
@@ -290,18 +306,10 @@ export class UrbitSSEClient {
290
306
  }
291
307
 
292
308
  async poke(params: { app: string; mark: string; json: unknown }) {
293
- return await pokeUrbitChannel(
294
- {
295
- baseUrl: this.url,
296
- cookie: this.cookie,
297
- ship: this.ship,
298
- channelId: this.channelId,
299
- ssrfPolicy: this.ssrfPolicy,
300
- lookupFn: this.lookupFn,
301
- fetchImpl: this.fetchImpl,
302
- },
303
- { ...params, auditContext: "tlon-urbit-poke" },
304
- );
309
+ return await pokeUrbitChannel(this.channelRequestContext(), {
310
+ ...params,
311
+ auditContext: "tlon-urbit-poke",
312
+ });
305
313
  }
306
314
 
307
315
  async scry(path: string) {
@@ -317,22 +325,58 @@ export class UrbitSSEClient {
317
325
  );
318
326
  }
319
327
 
328
+ /**
329
+ * Update the cookie used for authentication.
330
+ * Call this when re-authenticating after session expiry.
331
+ */
332
+ updateCookie(newCookie: string): void {
333
+ this.cookie = normalizeUrbitCookie(newCookie);
334
+ }
335
+
336
+ private async ack(eventId: number): Promise<void> {
337
+ this.lastAcknowledgedEventId = eventId;
338
+
339
+ const ackData = {
340
+ id: Date.now(),
341
+ action: "ack",
342
+ "event-id": eventId,
343
+ };
344
+
345
+ const { response, release } = await this.putChannelPayload([ackData], {
346
+ timeoutMs: 10_000,
347
+ auditContext: "tlon-urbit-ack",
348
+ });
349
+
350
+ try {
351
+ if (!response.ok) {
352
+ throw new Error(`Ack failed with status ${response.status}`);
353
+ }
354
+ } finally {
355
+ await release();
356
+ }
357
+ }
358
+
320
359
  async attemptReconnect() {
321
360
  if (this.aborted || !this.autoReconnect) {
322
361
  this.logger.log?.("[SSE] Reconnection aborted or disabled");
323
362
  return;
324
363
  }
325
364
 
365
+ // If we've hit max attempts, wait longer then reset and keep trying
326
366
  if (this.reconnectAttempts >= this.maxReconnectAttempts) {
327
- this.logger.error?.(
328
- `[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`,
367
+ this.logger.log?.(
368
+ `[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached. Waiting 10s before resetting...`,
329
369
  );
330
- return;
370
+ // Wait 10 seconds before resetting and trying again
371
+ const extendedBackoff = 10000; // 10 seconds
372
+ await new Promise((resolve) => setTimeout(resolve, extendedBackoff));
373
+ this.reconnectAttempts = 0; // Reset counter to continue trying
374
+ this.logger.log?.("[SSE] Reconnection attempts reset, resuming reconnection...");
331
375
  }
332
376
 
333
377
  this.reconnectAttempts += 1;
334
378
  const delay = Math.min(
335
- this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1),
379
+ this.reconnectDelay * 2 ** (this.reconnectAttempts - 1),
336
380
  this.maxReconnectDelay,
337
381
  );
338
382
 
@@ -343,7 +387,7 @@ export class UrbitSSEClient {
343
387
  await new Promise((resolve) => setTimeout(resolve, delay));
344
388
 
345
389
  try {
346
- this.channelId = `${Math.floor(Date.now() / 1000)}-${Math.random().toString(36).substring(2, 8)}`;
390
+ this.channelId = `${Math.floor(Date.now() / 1000)}-${randomUUID()}`;
347
391
  this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
348
392
 
349
393
  if (this.onReconnect) {
@@ -371,20 +415,7 @@ export class UrbitSSEClient {
371
415
  }));
372
416
 
373
417
  {
374
- const { response, release } = await urbitFetch({
375
- baseUrl: this.url,
376
- path: `/~/channel/${this.channelId}`,
377
- init: {
378
- method: "PUT",
379
- headers: {
380
- "Content-Type": "application/json",
381
- Cookie: this.cookie,
382
- },
383
- body: JSON.stringify(unsubscribes),
384
- },
385
- ssrfPolicy: this.ssrfPolicy,
386
- lookupFn: this.lookupFn,
387
- fetchImpl: this.fetchImpl,
418
+ const { response, release } = await this.putChannelPayload(unsubscribes, {
388
419
  timeoutMs: 30_000,
389
420
  auditContext: "tlon-urbit-unsubscribe",
390
421
  });
@@ -427,4 +458,27 @@ export class UrbitSSEClient {
427
458
  await release();
428
459
  }
429
460
  }
461
+
462
+ private async putChannelPayload(
463
+ payload: unknown,
464
+ params: { timeoutMs: number; auditContext: string },
465
+ ) {
466
+ return await urbitFetch({
467
+ baseUrl: this.url,
468
+ path: `/~/channel/${this.channelId}`,
469
+ init: {
470
+ method: "PUT",
471
+ headers: {
472
+ "Content-Type": "application/json",
473
+ Cookie: this.cookie,
474
+ },
475
+ body: JSON.stringify(payload),
476
+ },
477
+ ssrfPolicy: this.ssrfPolicy,
478
+ lookupFn: this.lookupFn,
479
+ fetchImpl: this.fetchImpl,
480
+ timeoutMs: params.timeoutMs,
481
+ auditContext: params.auditContext,
482
+ });
483
+ }
430
484
  }
@@ -0,0 +1,332 @@
1
+ /**
2
+ * Tlon Story Format - Rich text converter
3
+ *
4
+ * Converts markdown-like text to Tlon's story format.
5
+ */
6
+
7
+ // Inline content types
8
+ type StoryInline =
9
+ | string
10
+ | { bold: StoryInline[] }
11
+ | { italics: StoryInline[] }
12
+ | { strike: StoryInline[] }
13
+ | { blockquote: StoryInline[] }
14
+ | { "inline-code": string }
15
+ | { code: string }
16
+ | { ship: string }
17
+ | { link: { href: string; content: string } }
18
+ | { break: null }
19
+ | { tag: string };
20
+
21
+ // Block content types
22
+ type StoryBlock =
23
+ | { header: { tag: "h1" | "h2" | "h3" | "h4" | "h5" | "h6"; content: StoryInline[] } }
24
+ | { code: { code: string; lang: string } }
25
+ | { image: { src: string; height: number; width: number; alt: string } }
26
+ | { rule: null }
27
+ | { listing: StoryListing };
28
+
29
+ type StoryListing =
30
+ | {
31
+ list: {
32
+ type: "ordered" | "unordered" | "tasklist";
33
+ items: StoryListing[];
34
+ contents: StoryInline[];
35
+ };
36
+ }
37
+ | { item: StoryInline[] };
38
+
39
+ // A verse is either a block or inline content
40
+ type StoryVerse = { block: StoryBlock } | { inline: StoryInline[] };
41
+
42
+ // A story is a list of verses
43
+ export type Story = StoryVerse[];
44
+
45
+ /**
46
+ * Parse inline markdown formatting (bold, italic, code, links, mentions)
47
+ */
48
+ function parseInlineMarkdown(text: string): StoryInline[] {
49
+ const result: StoryInline[] = [];
50
+ let remaining = text;
51
+
52
+ while (remaining.length > 0) {
53
+ // Ship mentions: ~sampel-palnet
54
+ const shipMatch = remaining.match(/^(~[a-z][-a-z0-9]*)/);
55
+ if (shipMatch) {
56
+ result.push({ ship: shipMatch[1] });
57
+ remaining = remaining.slice(shipMatch[0].length);
58
+ continue;
59
+ }
60
+
61
+ // Bold: **text** or __text__
62
+ const boldMatch = remaining.match(/^\*\*(.+?)\*\*|^__(.+?)__/);
63
+ if (boldMatch) {
64
+ const content = boldMatch[1] || boldMatch[2];
65
+ result.push({ bold: parseInlineMarkdown(content) });
66
+ remaining = remaining.slice(boldMatch[0].length);
67
+ continue;
68
+ }
69
+
70
+ // Italics: *text* or _text_ (but not inside words for _)
71
+ const italicsMatch = remaining.match(/^\*([^*]+?)\*|^_([^_]+?)_(?![a-zA-Z0-9])/);
72
+ if (italicsMatch) {
73
+ const content = italicsMatch[1] || italicsMatch[2];
74
+ result.push({ italics: parseInlineMarkdown(content) });
75
+ remaining = remaining.slice(italicsMatch[0].length);
76
+ continue;
77
+ }
78
+
79
+ // Strikethrough: ~~text~~
80
+ const strikeMatch = remaining.match(/^~~(.+?)~~/);
81
+ if (strikeMatch) {
82
+ result.push({ strike: parseInlineMarkdown(strikeMatch[1]) });
83
+ remaining = remaining.slice(strikeMatch[0].length);
84
+ continue;
85
+ }
86
+
87
+ // Inline code: `code`
88
+ const codeMatch = remaining.match(/^`([^`]+)`/);
89
+ if (codeMatch) {
90
+ result.push({ "inline-code": codeMatch[1] });
91
+ remaining = remaining.slice(codeMatch[0].length);
92
+ continue;
93
+ }
94
+
95
+ // Links: [text](url)
96
+ const linkMatch = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);
97
+ if (linkMatch) {
98
+ result.push({ link: { href: linkMatch[2], content: linkMatch[1] } });
99
+ remaining = remaining.slice(linkMatch[0].length);
100
+ continue;
101
+ }
102
+
103
+ // Markdown images: ![alt](url)
104
+ const imageMatch = remaining.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
105
+ if (imageMatch) {
106
+ // Return a special marker that will be hoisted to a block
107
+ result.push({
108
+ __image: { src: imageMatch[2], alt: imageMatch[1] },
109
+ } as unknown as StoryInline);
110
+ remaining = remaining.slice(imageMatch[0].length);
111
+ continue;
112
+ }
113
+
114
+ // Plain URL detection
115
+ const urlMatch = remaining.match(/^(https?:\/\/[^\s<>"\]]+)/);
116
+ if (urlMatch) {
117
+ result.push({ link: { href: urlMatch[1], content: urlMatch[1] } });
118
+ remaining = remaining.slice(urlMatch[0].length);
119
+ continue;
120
+ }
121
+
122
+ // Hashtags: #tag - disabled, chat UI doesn't render them
123
+ // const tagMatch = remaining.match(/^#([a-zA-Z][a-zA-Z0-9_-]*)/);
124
+ // if (tagMatch) {
125
+ // result.push({ tag: tagMatch[1] });
126
+ // remaining = remaining.slice(tagMatch[0].length);
127
+ // continue;
128
+ // }
129
+
130
+ // Plain text: consume until next special character or URL start
131
+ // Exclude : and / to allow URL detection to work (stops before https://)
132
+ const plainMatch = remaining.match(/^[^*_`~[#~\n:/]+/);
133
+ if (plainMatch) {
134
+ result.push(plainMatch[0]);
135
+ remaining = remaining.slice(plainMatch[0].length);
136
+ continue;
137
+ }
138
+
139
+ // Single special char that didn't match a pattern
140
+ result.push(remaining[0]);
141
+ remaining = remaining.slice(1);
142
+ }
143
+
144
+ // Merge adjacent strings
145
+ return mergeAdjacentStrings(result);
146
+ }
147
+
148
+ /**
149
+ * Merge adjacent string elements in an inline array
150
+ */
151
+ function mergeAdjacentStrings(inlines: StoryInline[]): StoryInline[] {
152
+ const result: StoryInline[] = [];
153
+ for (const item of inlines) {
154
+ if (typeof item === "string" && typeof result[result.length - 1] === "string") {
155
+ result[result.length - 1] = (result[result.length - 1] as string) + item;
156
+ } else {
157
+ result.push(item);
158
+ }
159
+ }
160
+ return result;
161
+ }
162
+
163
+ /**
164
+ * Create an image block
165
+ */
166
+ export function createImageBlock(
167
+ src: string,
168
+ alt: string = "",
169
+ height: number = 0,
170
+ width: number = 0,
171
+ ): StoryVerse {
172
+ return {
173
+ block: {
174
+ image: { src, height, width, alt },
175
+ },
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Check if URL looks like an image
181
+ */
182
+ export function isImageUrl(url: string): boolean {
183
+ const imageExtensions = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)(\?.*)?$/i;
184
+ return imageExtensions.test(url);
185
+ }
186
+
187
+ /**
188
+ * Process inlines and extract any image markers into blocks
189
+ */
190
+ function processInlinesForImages(inlines: StoryInline[]): {
191
+ inlines: StoryInline[];
192
+ imageBlocks: StoryVerse[];
193
+ } {
194
+ const cleanInlines: StoryInline[] = [];
195
+ const imageBlocks: StoryVerse[] = [];
196
+
197
+ for (const inline of inlines) {
198
+ if (typeof inline === "object" && "__image" in inline) {
199
+ const img = (inline as unknown as { __image: { src: string; alt: string } }).__image;
200
+ imageBlocks.push(createImageBlock(img.src, img.alt));
201
+ } else {
202
+ cleanInlines.push(inline);
203
+ }
204
+ }
205
+
206
+ return { inlines: cleanInlines, imageBlocks };
207
+ }
208
+
209
+ /**
210
+ * Convert markdown text to Tlon story format
211
+ */
212
+ export function markdownToStory(markdown: string): Story {
213
+ const story: Story = [];
214
+ const lines = markdown.split("\n");
215
+ let i = 0;
216
+
217
+ while (i < lines.length) {
218
+ const line = lines[i];
219
+
220
+ // Code block: ```lang\ncode\n```
221
+ if (line.startsWith("```")) {
222
+ const lang = line.slice(3).trim() || "plaintext";
223
+ const codeLines: string[] = [];
224
+ i++;
225
+ while (i < lines.length && !lines[i].startsWith("```")) {
226
+ codeLines.push(lines[i]);
227
+ i++;
228
+ }
229
+ story.push({
230
+ block: {
231
+ code: {
232
+ code: codeLines.join("\n"),
233
+ lang,
234
+ },
235
+ },
236
+ });
237
+ i++; // skip closing ```
238
+ continue;
239
+ }
240
+
241
+ // Headers: # H1, ## H2, etc.
242
+ const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
243
+ if (headerMatch) {
244
+ const level = headerMatch[1].length as 1 | 2 | 3 | 4 | 5 | 6;
245
+ const tag = `h${level}` as const;
246
+ story.push({
247
+ block: {
248
+ header: {
249
+ tag,
250
+ content: parseInlineMarkdown(headerMatch[2]),
251
+ },
252
+ },
253
+ });
254
+ i++;
255
+ continue;
256
+ }
257
+
258
+ // Horizontal rule: --- or ***
259
+ if (/^(-{3,}|\*{3,})$/.test(line.trim())) {
260
+ story.push({ block: { rule: null } });
261
+ i++;
262
+ continue;
263
+ }
264
+
265
+ // Blockquote: > text
266
+ if (line.startsWith("> ")) {
267
+ const quoteLines: string[] = [];
268
+ while (i < lines.length && lines[i].startsWith("> ")) {
269
+ quoteLines.push(lines[i].slice(2));
270
+ i++;
271
+ }
272
+ const quoteText = quoteLines.join("\n");
273
+ story.push({
274
+ inline: [{ blockquote: parseInlineMarkdown(quoteText) }],
275
+ });
276
+ continue;
277
+ }
278
+
279
+ // Empty line - skip
280
+ if (line.trim() === "") {
281
+ i++;
282
+ continue;
283
+ }
284
+
285
+ // Regular paragraph - collect consecutive non-empty lines
286
+ const paragraphLines: string[] = [];
287
+ while (
288
+ i < lines.length &&
289
+ lines[i].trim() !== "" &&
290
+ !lines[i].startsWith("#") &&
291
+ !lines[i].startsWith("```") &&
292
+ !lines[i].startsWith("> ") &&
293
+ !/^(-{3,}|\*{3,})$/.test(lines[i].trim())
294
+ ) {
295
+ paragraphLines.push(lines[i]);
296
+ i++;
297
+ }
298
+
299
+ if (paragraphLines.length > 0) {
300
+ const paragraphText = paragraphLines.join("\n");
301
+ // Convert newlines within paragraph to break elements
302
+ const inlines = parseInlineMarkdown(paragraphText);
303
+ // Replace \n in strings with break elements
304
+ const withBreaks: StoryInline[] = [];
305
+ for (const inline of inlines) {
306
+ if (typeof inline === "string" && inline.includes("\n")) {
307
+ const parts = inline.split("\n");
308
+ for (let j = 0; j < parts.length; j++) {
309
+ if (parts[j]) {
310
+ withBreaks.push(parts[j]);
311
+ }
312
+ if (j < parts.length - 1) {
313
+ withBreaks.push({ break: null });
314
+ }
315
+ }
316
+ } else {
317
+ withBreaks.push(inline);
318
+ }
319
+ }
320
+
321
+ // Extract any images from inlines and add as separate blocks
322
+ const { inlines: cleanInlines, imageBlocks } = processInlinesForImages(withBreaks);
323
+
324
+ if (cleanInlines.length > 0) {
325
+ story.push({ inline: cleanInlines });
326
+ }
327
+ story.push(...imageBlocks);
328
+ }
329
+ }
330
+
331
+ return story;
332
+ }