dsh-share-html 0.0.0-stage → 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/lib/kernel.js ADDED
@@ -0,0 +1,2632 @@
1
+ /* dsh-share-html 内核(由 scripts/build.mjs 从 src/host 打包,勿手改)
2
+ * 打包而非直接 import .ts:npm 包不能依赖 Node 的类型剥离实验特性。
3
+ */
4
+
5
+ // src/host/model.ts
6
+ function emptyDropped() {
7
+ return { systemMessages: 0, injectedUserContext: 0, attachmentBytes: 0, unknownEvents: 0 };
8
+ }
9
+
10
+ // src/host/events.ts
11
+ function asRecord(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
13
+ }
14
+ function asString(value) {
15
+ return typeof value === "string" ? value : void 0;
16
+ }
17
+ function asNumber(value) {
18
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
19
+ }
20
+
21
+ // src/host/project.ts
22
+ var DEFAULT_TITLE = "Untitled session";
23
+ var USER_SOURCE_KINDS = /* @__PURE__ */ new Set(["user"]);
24
+ function project(events, options = {}) {
25
+ const dropped = emptyDropped();
26
+ const turns = [];
27
+ let current = null;
28
+ let sessionTitle;
29
+ let sessionId = options.sessionId;
30
+ let lastModel;
31
+ const pendingCalls = /* @__PURE__ */ new Map();
32
+ const callOwner = /* @__PURE__ */ new Map();
33
+ const openTurn = (user) => {
34
+ const turn = { index: turns.length + 1, user, assistants: [] };
35
+ turns.push(turn);
36
+ current = turn;
37
+ return turn;
38
+ };
39
+ const ensureTurn = () => current ?? openTurn(null);
40
+ const assistantSlot = /* @__PURE__ */ new Map();
41
+ const clearStepSlots = () => assistantSlot.clear();
42
+ const getAssistant = (turnNo, stepNo, at) => {
43
+ const key = `${turnNo}:${stepNo}`;
44
+ const existing = assistantSlot.get(key);
45
+ if (existing) return existing;
46
+ const turn = ensureTurn();
47
+ const msg = { id: `a-${turnNo}-${stepNo}-${turn.assistants.length}`, role: "assistant", blocks: [] };
48
+ if (at !== void 0) msg.at = at;
49
+ turn.assistants.push(msg);
50
+ assistantSlot.set(key, msg);
51
+ return msg;
52
+ };
53
+ for (const raw of events) {
54
+ const type = asString(raw.type) ?? "";
55
+ const data = asRecord(raw.data) ?? {};
56
+ const at = asNumber(raw.time);
57
+ switch (type) {
58
+ case "session/title": {
59
+ const title = asString(data.title);
60
+ if (title && title.trim()) sessionTitle = title.trim();
61
+ break;
62
+ }
63
+ case "request/context": {
64
+ const model2 = asString(data.model);
65
+ if (model2) lastModel = model2;
66
+ break;
67
+ }
68
+ // ---- 硬约束:直接丢弃 ------------------------------------------------
69
+ case "system/message":
70
+ case "developer/message": {
71
+ dropped.systemMessages += 1;
72
+ break;
73
+ }
74
+ // ---- 用户消息 -------------------------------------------------------
75
+ case "user/message": {
76
+ const msg = asRecord(data);
77
+ if (!msg) break;
78
+ const kind = asString(asRecord(msg.source)?.kind);
79
+ if (!kind || !USER_SOURCE_KINDS.has(kind)) {
80
+ dropped.injectedUserContext += 1;
81
+ break;
82
+ }
83
+ const user = projectUserMessage(msg, at, dropped);
84
+ if (!user) break;
85
+ openTurn(user);
86
+ clearStepSlots();
87
+ break;
88
+ }
89
+ // ---- 助手消息 -------------------------------------------------------
90
+ case "assistant/message": {
91
+ const msg = asRecord(data.message);
92
+ if (!msg) break;
93
+ const turnNo = asNumber(data.turn) ?? ensureTurn().index;
94
+ const stepNo = asNumber(data.step) ?? 1;
95
+ const target = getAssistant(turnNo, stepNo, at);
96
+ if (lastModel && !target.model) target.model = lastModel;
97
+ collectAssistantBlocks(msg, target, dropped);
98
+ break;
99
+ }
100
+ // ---- 工具调用 -------------------------------------------------------
101
+ case "tool/call": {
102
+ const callId = asString(data.callId);
103
+ const name = asString(data.name) ?? "tool";
104
+ const rawArgs = data.arguments;
105
+ const argsText = typeof rawArgs === "string" ? rawArgs : rawArgs === void 0 ? void 0 : JSON.stringify(rawArgs);
106
+ const turnNo = asNumber(data.turn) ?? ensureTurn().index;
107
+ const stepNo = asNumber(data.step) ?? 1;
108
+ const owner = getAssistant(turnNo, stepNo, at);
109
+ const block = { kind: "tool", name, status: "pending" };
110
+ if (callId) block.callId = callId;
111
+ if (argsText !== void 0) block.args = argsText;
112
+ const fields = argsToFields(rawArgs);
113
+ if (fields.length) block.argsFields = fields;
114
+ owner.blocks.push(block);
115
+ if (callId) {
116
+ pendingCalls.set(callId, block);
117
+ callOwner.set(callId, owner);
118
+ }
119
+ break;
120
+ }
121
+ // ---- 工具结果 -------------------------------------------------------
122
+ case "tool/result": {
123
+ const msg = asRecord(data.message);
124
+ if (!msg) break;
125
+ const callId = asString(msg.toolCallId) ?? asString(asRecord(msg.source)?.callId);
126
+ if (!callId) break;
127
+ const block = pendingCalls.get(callId);
128
+ const owner = callOwner.get(callId);
129
+ if (!block || !owner) break;
130
+ const text = partsToText(msg.content);
131
+ const isError = msg.isError === true || asRecord(data)?.isError === true;
132
+ applyResult(block, text, isError, options.maxToolResultChars);
133
+ break;
134
+ }
135
+ // ---- 轮次与步骤边界(只影响归并) -----------------------------------
136
+ case "turn/end": {
137
+ current = null;
138
+ clearStepSlots();
139
+ break;
140
+ }
141
+ case "step/end":
142
+ break;
143
+ default: {
144
+ break;
145
+ }
146
+ }
147
+ }
148
+ const model = {
149
+ id: sessionId ?? "",
150
+ title: options.title?.trim() || sessionTitle || DEFAULT_TITLE,
151
+ turns: pruneEmptyTurns(turns),
152
+ dropped
153
+ };
154
+ if (options.exportedAt !== void 0) model.exportedAt = options.exportedAt;
155
+ return model;
156
+ }
157
+ function projectUserMessage(msg, at, dropped) {
158
+ const blocks = [];
159
+ const files = [];
160
+ if (typeof msg.content === "string") {
161
+ if (msg.content.trim()) blocks.push({ kind: "text", md: msg.content });
162
+ } else if (Array.isArray(msg.content)) {
163
+ for (const part of msg.content) {
164
+ const p = asRecord(part);
165
+ if (!p) continue;
166
+ switch (p.type) {
167
+ case "text": {
168
+ const text = asString(p.text);
169
+ if (text && text.trim()) blocks.push({ kind: "text", md: text });
170
+ break;
171
+ }
172
+ case "image": {
173
+ dropped.attachmentBytes += 1;
174
+ files.push({ name: asString(p.name) ?? "image", type: "IMG" });
175
+ break;
176
+ }
177
+ case "file":
178
+ case "attachment": {
179
+ const name = asString(p.name) ?? asString(p.filename);
180
+ if (!name) {
181
+ dropped.attachmentBytes += 1;
182
+ break;
183
+ }
184
+ const meta = { name, type: fileType(name) };
185
+ const bytes = asNumber(p.bytes) ?? asNumber(p.size);
186
+ if (bytes !== void 0) meta.bytes = bytes;
187
+ files.push(meta);
188
+ break;
189
+ }
190
+ default:
191
+ break;
192
+ }
193
+ }
194
+ }
195
+ if (files.length) blocks.push({ kind: "files", files });
196
+ if (!blocks.length) return null;
197
+ const id = asString(msg.id) ?? `u-${at ?? 0}`;
198
+ const message = { id, role: "user", blocks };
199
+ if (at !== void 0) message.at = at;
200
+ return message;
201
+ }
202
+ function collectAssistantBlocks(msg, target, dropped) {
203
+ if (typeof msg.content === "string") {
204
+ if (msg.content.trim()) target.blocks.push({ kind: "text", md: msg.content });
205
+ return;
206
+ }
207
+ if (!Array.isArray(msg.content)) return;
208
+ for (const part of msg.content) {
209
+ const p = asRecord(part);
210
+ if (!p) continue;
211
+ switch (p.type) {
212
+ case "text": {
213
+ const text = asString(p.text);
214
+ if (text && text.trim()) target.blocks.push({ kind: "text", md: text });
215
+ break;
216
+ }
217
+ case "reasoning":
218
+ case "thinking": {
219
+ const text = asString(p.text) ?? asString(p.thinking);
220
+ if (text && text.trim()) target.blocks.push({ kind: "reasoning", text });
221
+ break;
222
+ }
223
+ case "image": {
224
+ dropped.attachmentBytes += 1;
225
+ break;
226
+ }
227
+ case "tool-call":
228
+ case "tool-call-delta":
229
+ break;
230
+ default:
231
+ break;
232
+ }
233
+ }
234
+ }
235
+ function applyResult(block, text, isError, maxChars) {
236
+ block.status = isError ? "error" : "ok";
237
+ let value = text;
238
+ if (maxChars !== void 0 && maxChars >= 0 && value.length > maxChars) {
239
+ value = value.slice(0, maxChars);
240
+ block.truncated = true;
241
+ }
242
+ block.result = value;
243
+ }
244
+ function partsToText(content) {
245
+ if (typeof content === "string") return content;
246
+ if (!Array.isArray(content)) return "";
247
+ const out = [];
248
+ for (const part of content) {
249
+ const p = asRecord(part);
250
+ if (!p) continue;
251
+ const text = asString(p.text);
252
+ if (text !== void 0) out.push(text);
253
+ else if (p.type === "image") out.push("[image]");
254
+ }
255
+ return out.join("\n");
256
+ }
257
+ function argsToFields(rawArgs) {
258
+ let parsed = rawArgs;
259
+ if (typeof rawArgs === "string") {
260
+ try {
261
+ parsed = JSON.parse(rawArgs);
262
+ } catch {
263
+ return rawArgs.trim() ? [{ key: "", value: rawArgs }] : [];
264
+ }
265
+ }
266
+ const rec = asRecord(parsed);
267
+ if (!rec) return [];
268
+ const fields = [];
269
+ for (const [key, value] of Object.entries(rec)) {
270
+ fields.push({ key, value: stringifyArg(value) });
271
+ }
272
+ return fields;
273
+ }
274
+ function stringifyArg(value) {
275
+ if (typeof value === "string") return value;
276
+ if (value === null || value === void 0) return String(value);
277
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
278
+ try {
279
+ return JSON.stringify(value);
280
+ } catch {
281
+ return String(value);
282
+ }
283
+ }
284
+ var EXT_TYPE = {
285
+ png: "PNG",
286
+ jpg: "JPG",
287
+ jpeg: "JPG",
288
+ gif: "GIF",
289
+ webp: "WEBP",
290
+ svg: "SVG",
291
+ bmp: "BMP",
292
+ ico: "ICO",
293
+ pdf: "PDF",
294
+ doc: "DOC",
295
+ docx: "DOCX",
296
+ xls: "XLS",
297
+ xlsx: "XLSX",
298
+ ppt: "PPT",
299
+ pptx: "PPTX",
300
+ csv: "CSV",
301
+ tsv: "TSV",
302
+ json: "JSON",
303
+ jsonl: "JSONL",
304
+ xml: "XML",
305
+ yaml: "YAML",
306
+ yml: "YAML",
307
+ txt: "TXT",
308
+ md: "MD",
309
+ html: "HTML",
310
+ htm: "HTML",
311
+ css: "CSS",
312
+ scss: "SCSS",
313
+ less: "LESS",
314
+ js: "JS",
315
+ mjs: "MJS",
316
+ cjs: "CJS",
317
+ ts: "TS",
318
+ tsx: "TSX",
319
+ jsx: "JSX",
320
+ vue: "VUE",
321
+ py: "PY",
322
+ go: "GO",
323
+ rs: "RS",
324
+ java: "JAVA",
325
+ kt: "KT",
326
+ c: "C",
327
+ h: "H",
328
+ cpp: "CPP",
329
+ hpp: "HPP",
330
+ cs: "CS",
331
+ rb: "RB",
332
+ php: "PHP",
333
+ sh: "SH",
334
+ bash: "SH",
335
+ zsh: "SH",
336
+ ps1: "PS1",
337
+ sql: "SQL",
338
+ sqlite: "SQLITE",
339
+ db: "DB",
340
+ zip: "ZIP",
341
+ gz: "GZ",
342
+ tar: "TAR",
343
+ rar: "RAR",
344
+ "7z": "7Z",
345
+ ipynb: "IPYNB",
346
+ toml: "TOML",
347
+ ini: "INI",
348
+ log: "LOG",
349
+ env: "ENV"
350
+ };
351
+ function fileType(name) {
352
+ const base = name.split(/[\\/]/).pop() ?? name;
353
+ const dot = base.lastIndexOf(".");
354
+ if (dot <= 0 || dot === base.length - 1) return "FILE";
355
+ const ext = base.slice(dot + 1).toLowerCase();
356
+ return EXT_TYPE[ext] ?? ext.toUpperCase().slice(0, 8);
357
+ }
358
+ function pruneEmptyTurns(turns) {
359
+ const kept = turns.filter((t) => t.user !== null || t.assistants.some((m) => m.blocks.length > 0));
360
+ return kept.map((t, i) => ({ ...t, index: i + 1 }));
361
+ }
362
+
363
+ // src/host/policy.ts
364
+ function presetInclude(preset) {
365
+ switch (preset) {
366
+ case "conversation":
367
+ return {
368
+ reasoning: false,
369
+ retrieval: false,
370
+ toolCalls: false,
371
+ toolResults: false,
372
+ toolArgumentChars: 0,
373
+ toolResultChars: 0,
374
+ files: false,
375
+ fileBytes: false,
376
+ deepResearch: false,
377
+ modelMeta: false
378
+ };
379
+ case "process":
380
+ return {
381
+ reasoning: true,
382
+ retrieval: true,
383
+ toolCalls: true,
384
+ // 过程档只给结果摘要,不给全文
385
+ toolResults: false,
386
+ toolArgumentChars: 200,
387
+ toolResultChars: 400,
388
+ files: true,
389
+ fileBytes: false,
390
+ deepResearch: true,
391
+ modelMeta: false
392
+ };
393
+ case "full":
394
+ return {
395
+ reasoning: true,
396
+ retrieval: true,
397
+ toolCalls: true,
398
+ toolResults: true,
399
+ toolArgumentChars: 0,
400
+ toolResultChars: 0,
401
+ files: true,
402
+ fileBytes: false,
403
+ deepResearch: true,
404
+ modelMeta: true
405
+ };
406
+ }
407
+ }
408
+ function shareOptions(preset, overrides = {}) {
409
+ const base = {
410
+ preset,
411
+ turns: null,
412
+ include: presetInclude(preset),
413
+ redact: true
414
+ };
415
+ const include = { ...base.include, ...overrides.include ?? {} };
416
+ delete include.fileBytes;
417
+ include.fileBytes = false;
418
+ return { ...base, ...overrides, preset, include };
419
+ }
420
+ function applySharePolicy(model, options) {
421
+ const include = normalizeInclude(options.include);
422
+ const stats = { messages: 0, messagesDropped: 0, blocksDropped: {}, truncated: 0 };
423
+ const wanted = options.turns === null ? null : new Set(options.turns);
424
+ const turns = [];
425
+ for (const turn of model.turns) {
426
+ if (wanted && !wanted.has(turn.index)) {
427
+ countDropped(stats, "turn", turn.user ? 1 + turn.assistants.length : turn.assistants.length);
428
+ continue;
429
+ }
430
+ const user = turn.user ? pruneMessage(turn.user, include, stats) : null;
431
+ if (turn.user && !user) countDropped(stats, "message", 1);
432
+ if (user) stats.messages += 1;
433
+ const assistants = [];
434
+ for (const msg of turn.assistants) {
435
+ const pruned = pruneMessage(msg, include, stats);
436
+ if (!pruned) {
437
+ countDropped(stats, "message", 1);
438
+ continue;
439
+ }
440
+ assistants.push(pruned);
441
+ stats.messages += 1;
442
+ }
443
+ if (!user && !assistants.length) {
444
+ turns.push({ ...turn, user: null, assistants: [] });
445
+ continue;
446
+ }
447
+ turns.push({ ...turn, user, assistants });
448
+ }
449
+ const keptTurns = turns.filter((t) => t.user !== null || t.assistants.length > 0);
450
+ const renumbered = keptTurns.map((t, i) => ({ ...t, index: i + 1 }));
451
+ stats.messagesDropped = countMessages(model) - stats.messages;
452
+ return {
453
+ model: { ...model, turns: renumbered, dropped: model.dropped },
454
+ stats
455
+ };
456
+ }
457
+ function normalizeInclude(include) {
458
+ return { ...include, fileBytes: false };
459
+ }
460
+ function pruneMessage(msg, include, stats) {
461
+ const blocks = [];
462
+ for (const block of msg.blocks) {
463
+ const kept = pruneBlock(block, include, stats);
464
+ if (kept === null) {
465
+ countDropped(stats, block.kind, 1);
466
+ continue;
467
+ }
468
+ blocks.push(kept);
469
+ }
470
+ if (!blocks.length) return null;
471
+ const out = { ...msg, blocks };
472
+ if (!include.modelMeta) delete out.model;
473
+ return out;
474
+ }
475
+ function pruneBlock(block, include, stats) {
476
+ switch (block.kind) {
477
+ case "text":
478
+ return block.md.trim() ? block : null;
479
+ case "reasoning":
480
+ return include.reasoning ? block : null;
481
+ case "retrieval":
482
+ return include.retrieval ? block : null;
483
+ case "files":
484
+ if (!include.files) return null;
485
+ return { kind: "files", files: block.files };
486
+ case "research":
487
+ return include.deepResearch ? block : null;
488
+ case "tool": {
489
+ if (!include.toolCalls) return null;
490
+ const out = { kind: "tool", name: block.name, status: block.status };
491
+ if (block.callId) out.callId = block.callId;
492
+ if (block.args !== void 0) {
493
+ const cut = clip(block.args, include.toolArgumentChars);
494
+ out.args = cut.text;
495
+ if (cut.truncated) stats.truncated += 1;
496
+ }
497
+ if (block.argsFields?.length) {
498
+ out.argsFields = block.argsFields.map((f) => ({
499
+ key: f.key,
500
+ value: clip(f.value, include.toolArgumentChars).text
501
+ }));
502
+ }
503
+ if (block.result !== void 0) {
504
+ if (include.toolResults) {
505
+ const cut = clip(block.result, include.toolResultChars);
506
+ out.result = cut.text;
507
+ if (cut.truncated) {
508
+ out.truncated = true;
509
+ stats.truncated += 1;
510
+ }
511
+ } else {
512
+ out.result = summarize(block.result);
513
+ out.truncated = true;
514
+ }
515
+ }
516
+ if (block.truncated && !include.toolResults) out.truncated = true;
517
+ return out;
518
+ }
519
+ }
520
+ }
521
+ function clip(text, maxChars) {
522
+ if (maxChars <= 0 || text.length <= maxChars) return { text, truncated: false };
523
+ return { text: text.slice(0, maxChars), truncated: true };
524
+ }
525
+ function summarize(text) {
526
+ const lines = text ? text.split("\n").length : 0;
527
+ const firstLine2 = text.split("\n").find((l) => l.trim())?.trim() ?? "";
528
+ const head = firstLine2.length > 120 ? `${firstLine2.slice(0, 120)}\u2026` : firstLine2;
529
+ return lines > 1 ? `${head}\uFF08\u5171 ${lines} \u884C / ${text.length} \u5B57\u7B26\uFF09` : head;
530
+ }
531
+ function countDropped(stats, kind, n) {
532
+ stats.blocksDropped[kind] = (stats.blocksDropped[kind] ?? 0) + n;
533
+ }
534
+ function countMessages(model) {
535
+ let n = 0;
536
+ for (const turn of model.turns) n += (turn.user ? 1 : 0) + turn.assistants.length;
537
+ return n;
538
+ }
539
+
540
+ // src/host/redact.ts
541
+ var HASH_TAG = "#";
542
+ function fnv1aHex(input) {
543
+ let hash = 2166136261;
544
+ for (let i = 0; i < input.length; i++) {
545
+ hash ^= input.charCodeAt(i);
546
+ hash = Math.imul(hash, 16777619) >>> 0;
547
+ }
548
+ return hash.toString(16).padStart(8, "0");
549
+ }
550
+ var LONG_HEX = /(?<![0-9a-zA-Z])(?:[0-9a-fA-F]{32,})(?![0-9a-zA-Z])/g;
551
+ var RULES = [
552
+ // ---- 私钥块:必须最先,否则块内的 base64 会被别的规则切碎 ----
553
+ {
554
+ name: "private-key",
555
+ re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
556
+ enabled: () => true
557
+ },
558
+ // ---- Authorization 头 ----
559
+ { name: "authorization", re: /\b(Authorization\s*:\s*)((?:Bearer|Basic|Token)\s+[^\s"'\\]+)/gi, enabled: () => true },
560
+ { name: "bearer", re: /\b(Bearer\s+)([A-Za-z0-9._~+/-]{12,}=*)/g, enabled: () => true },
561
+ // ---- 各类 API Key ----
562
+ { name: "openai-key", re: /\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{16,}/g, enabled: () => true },
563
+ { name: "anthropic-key", re: /\bsk-ant-[A-Za-z0-9_-]{16,}/g, enabled: () => true },
564
+ { name: "github-pat", re: /\bgh[pousr]_[A-Za-z0-9]{20,}/g, enabled: () => true },
565
+ { name: "aws-key", re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, enabled: () => true },
566
+ { name: "google-key", re: /\bAIza[0-9A-Za-z_-]{30,}/g, enabled: () => true },
567
+ { name: "slack-token", re: /\bxox[baprs]-[0-9A-Za-z-]{10,}/g, enabled: () => true },
568
+ { name: "jwt", re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, enabled: () => true },
569
+ // ---- 数据库 URL 中的凭证 ----
570
+ {
571
+ name: "db-url-credential",
572
+ re: /\b((?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|amqp|mssql):\/\/)[^\s:/@]+:[^\s@/]+@/gi,
573
+ enabled: () => true
574
+ },
575
+ // ---- 长 hex(凭证常见形态)----
576
+ { name: "long-hex", re: LONG_HEX, enabled: () => true },
577
+ // ---- 邮箱 ----
578
+ {
579
+ name: "email",
580
+ re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
581
+ enabled: (o) => o.email
582
+ },
583
+ // ---- 内网 IP(10/8、172.16/12、192.168/16、127/8、169.254/16)----
584
+ {
585
+ name: "internal-ip",
586
+ re: /\b(?:10\.\d{1,3}|127\.\d{1,3}|192\.168|169\.254|172\.(?:1[6-9]|2\d|3[01]))\.\d{1,3}\.\d{1,3}\b/g,
587
+ enabled: (o) => o.internalIp
588
+ }
589
+ ];
590
+ var ABS_PATH = /(?<![\w:/\\])(?:\/(?:home|Users|root|private\/var)\/[^\s"'`<>()[\],;|]*|[A-Za-z]:\\Users\\[^\s"'`<>()[\],;|]*)/g;
591
+ function record(hits, name) {
592
+ hits[name] = (hits[name] ?? 0) + 1;
593
+ }
594
+ function redactText(text, options = {}, hits) {
595
+ const opts = {
596
+ mode: options.mode ?? "mask",
597
+ internalIp: options.internalIp ?? true,
598
+ email: options.email ?? true,
599
+ stripAbsolutePaths: options.stripAbsolutePaths ?? true
600
+ };
601
+ const bucket = hits ?? {};
602
+ const mark = (value) => opts.mode === "mask-hash" ? `${HASH_TAG}${fnv1aHex(value)}` : "[REDACTED]";
603
+ let out = text;
604
+ for (const rule of RULES) {
605
+ if (!rule.enabled(opts)) continue;
606
+ out = out.replace(rule.re, (match, ...groups) => {
607
+ const g1 = typeof groups[0] === "string" ? groups[0] : void 0;
608
+ const g2 = typeof groups[1] === "string" ? groups[1] : void 0;
609
+ record(bucket, rule.name);
610
+ if (g1 !== void 0 && g2 !== void 0) {
611
+ return g1 + mark(g2);
612
+ }
613
+ return mark(match);
614
+ });
615
+ }
616
+ if (opts.stripAbsolutePaths) {
617
+ out = out.replace(ABS_PATH, (match) => {
618
+ record(bucket, "absolute-path");
619
+ const base = match.split(/[\\/]/).filter(Boolean).pop() ?? match;
620
+ return `\u2026/${base}`;
621
+ });
622
+ }
623
+ return out;
624
+ }
625
+ function redact(model, options = {}) {
626
+ const hits = {};
627
+ const turns = model.turns.map((turn) => {
628
+ const user = turn.user ? redactMessage(turn.user, options, hits) : null;
629
+ const assistants = turn.assistants.map((m) => redactMessage(m, options, hits));
630
+ return { ...turn, user, assistants };
631
+ });
632
+ const total = Object.values(hits).reduce((a, b) => a + b, 0);
633
+ return {
634
+ model: { ...model, turns },
635
+ stats: { hits, total, mode: options.mode ?? "mask" }
636
+ };
637
+ }
638
+ function redactMessage(msg, options, hits) {
639
+ return { ...msg, blocks: msg.blocks.map((b) => redactBlock(b, options, hits)) };
640
+ }
641
+ function redactBlock(block, options, hits) {
642
+ switch (block.kind) {
643
+ case "text":
644
+ return { ...block, md: redactText(block.md, options, hits) };
645
+ case "reasoning":
646
+ return { ...block, text: redactText(block.text, options, hits) };
647
+ case "research":
648
+ return {
649
+ ...block,
650
+ title: redactText(block.title, options, hits),
651
+ text: redactText(block.text, options, hits)
652
+ };
653
+ case "retrieval": {
654
+ const items = block.items.map((it) => {
655
+ const next = { title: redactText(it.title, options, hits) };
656
+ if (it.snippet !== void 0) next.snippet = redactText(it.snippet, options, hits);
657
+ if (it.site !== void 0) next.site = redactText(it.site, options, hits);
658
+ if (it.url !== void 0) next.url = it.url;
659
+ return next;
660
+ });
661
+ const out = { kind: "retrieval", items };
662
+ if (block.query !== void 0) out.query = redactText(block.query, options, hits);
663
+ if (block.raw !== void 0) out.raw = redactText(block.raw, options, hits);
664
+ return out;
665
+ }
666
+ case "files":
667
+ return {
668
+ kind: "files",
669
+ files: block.files.map((f) => ({ ...f, name: redactText(f.name, options, hits) }))
670
+ };
671
+ case "tool": {
672
+ const out = { ...block };
673
+ if (block.args !== void 0) out.args = redactText(block.args, options, hits);
674
+ if (block.argsFields) {
675
+ out.argsFields = block.argsFields.map((f) => ({ key: f.key, value: redactText(f.value, options, hits) }));
676
+ }
677
+ if (block.result !== void 0) out.result = redactText(block.result, options, hits);
678
+ return out;
679
+ }
680
+ }
681
+ }
682
+
683
+ // src/host/highlight.ts
684
+ var LANG_LABEL = {
685
+ js: "JavaScript",
686
+ javascript: "JavaScript",
687
+ mjs: "JavaScript",
688
+ cjs: "JavaScript",
689
+ jsx: "JSX",
690
+ ts: "TypeScript",
691
+ typescript: "TypeScript",
692
+ tsx: "TSX",
693
+ py: "Python",
694
+ python: "Python",
695
+ json: "JSON",
696
+ jsonc: "JSON",
697
+ json5: "JSON",
698
+ bash: "Bash",
699
+ sh: "Shell",
700
+ shell: "Shell",
701
+ zsh: "Shell",
702
+ console: "Console",
703
+ html: "HTML",
704
+ xml: "XML",
705
+ svg: "SVG",
706
+ css: "CSS",
707
+ scss: "SCSS",
708
+ less: "Less",
709
+ go: "Go",
710
+ golang: "Go",
711
+ rust: "Rust",
712
+ rs: "Rust",
713
+ java: "Java",
714
+ kotlin: "Kotlin",
715
+ kt: "Kotlin",
716
+ c: "C",
717
+ h: "C",
718
+ cpp: "C++",
719
+ "c++": "C++",
720
+ hpp: "C++",
721
+ cs: "C#",
722
+ csharp: "C#",
723
+ rb: "Ruby",
724
+ ruby: "Ruby",
725
+ php: "PHP",
726
+ swift: "Swift",
727
+ sql: "SQL",
728
+ yaml: "YAML",
729
+ yml: "YAML",
730
+ toml: "TOML",
731
+ ini: "INI",
732
+ md: "Markdown",
733
+ markdown: "Markdown",
734
+ diff: "Diff",
735
+ patch: "Diff",
736
+ dockerfile: "Dockerfile",
737
+ docker: "Dockerfile",
738
+ makefile: "Makefile",
739
+ make: "Makefile",
740
+ lua: "Lua",
741
+ perl: "Perl",
742
+ r: "R",
743
+ scala: "Scala",
744
+ dart: "Dart",
745
+ vue: "Vue",
746
+ svelte: "Svelte",
747
+ text: "Text",
748
+ txt: "Text",
749
+ plain: "Text",
750
+ plaintext: "Text",
751
+ log: "Log",
752
+ powershell: "PowerShell",
753
+ ps1: "PowerShell",
754
+ psm1: "PowerShell",
755
+ bat: "Batch",
756
+ cmd: "Batch"
757
+ };
758
+ var KEYWORDS = {
759
+ c: `auto break case char const continue default do double else enum extern float for goto if inline int long register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while _Bool _Complex _Imaginary`.split(" "),
760
+ cpp: `alignas alignof and and_eq asm auto bitand bitor bool break case catch char char16_t char32_t class compl const constexpr const_cast continue decltype default delete do double dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace new noexcept not not_eq nullptr operator or or_eq private protected public register reinterpret_cast return short signed sizeof static static_assert static_cast struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while xor xor_eq override final`.split(" "),
761
+ js: `async await break case catch class const continue debugger default delete do else export extends false finally for from function get if implements import in instanceof interface let new null of return set static super switch this throw true try typeof undefined var void while with yield`.split(" "),
762
+ ts: `abstract any as asserts async await bigint boolean break case catch class const constructor continue declare default delete do else enum export extends false finally for from function get global if implements import in infer instanceof interface is keyof let namespace never new null number object of override private protected public readonly record return satisfies set static string super switch symbol this throw true try type typeof undefined unique unknown var void while yield`.split(" "),
763
+ py: `and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield match case self`.split(" "),
764
+ go: `break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var nil true false iota`.split(" "),
765
+ rust: `as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while`.split(" "),
766
+ java: `abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while var record sealed permits yield true false null`.split(" "),
767
+ sh: `if then else elif fi for while until do done case esac function in select return exit local export readonly declare unset shift source eval exec trap set echo cd`.split(" "),
768
+ sql: `select from where insert into values update set delete create table alter drop index view join left right inner outer full on group by order having limit offset union all distinct as and or not null is in like between exists case when then else end primary key foreign references default constraint unique check begin commit rollback transaction`.split(" "),
769
+ css: `important media supports keyframes font-face import charset`.split(" "),
770
+ ruby: `alias and begin break case class def defined do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield`.split(" "),
771
+ php: `abstract and array as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile eval exit extends final finally fn for foreach function global goto if implements include include_once instanceof insteadof interface isset list match namespace new null or print private protected public readonly require require_once return static switch throw trait true false try unset use var while xor yield`.split(" "),
772
+ lua: `and break do else elseif end false for function goto if in local nil not or repeat return then true until while`.split(" "),
773
+ r: `if else repeat while function for in next break TRUE FALSE NULL Inf NaN NA`.split(" "),
774
+ kotlin: `as break class continue do else false for fun if in interface is null object package return super this throw true try typealias typeof val var when while by catch constructor delegate dynamic field file finally get import init param property receiver set setparam where actual abstract annotation companion const crossinline data enum expect external final infix inline inner internal lateinit noinline open operator out override private protected public reified sealed suspend tailrec vararg`.split(" "),
775
+ swift: `associatedtype class deinit enum extension fileprivate func import init inout internal let open operator private protocol public static struct subscript typealias var break case continue default defer do else fallthrough for guard if in repeat return switch where while as catch false is nil rethrows super self Self throw throws true try`.split(" "),
776
+ dart: `abstract as assert async await break case catch class const continue covariant default deferred do dynamic else enum export extends extension external factory false final finally for Function get hide if implements import in interface is late library mixin new null on operator part required rethrow return set show static super switch sync this throw true try typedef var void while with yield`.split(" "),
777
+ diff: []
778
+ };
779
+ var FAMILY = {
780
+ js: "js",
781
+ javascript: "js",
782
+ mjs: "js",
783
+ cjs: "js",
784
+ jsx: "js",
785
+ ts: "ts",
786
+ typescript: "ts",
787
+ tsx: "ts",
788
+ py: "py",
789
+ python: "py",
790
+ go: "go",
791
+ golang: "go",
792
+ rust: "rust",
793
+ rs: "rust",
794
+ java: "java",
795
+ kotlin: "kotlin",
796
+ kt: "kotlin",
797
+ c: "c",
798
+ h: "c",
799
+ cpp: "cpp",
800
+ "c++": "cpp",
801
+ hpp: "cpp",
802
+ cc: "cpp",
803
+ cs: "java",
804
+ csharp: "java",
805
+ rb: "ruby",
806
+ ruby: "ruby",
807
+ php: "php",
808
+ swift: "swift",
809
+ dart: "dart",
810
+ sh: "sh",
811
+ bash: "sh",
812
+ shell: "sh",
813
+ zsh: "sh",
814
+ console: "sh",
815
+ sql: "sql",
816
+ css: "css",
817
+ scss: "css",
818
+ less: "css",
819
+ lua: "lua",
820
+ r: "r"
821
+ };
822
+ var STRING_LANGS = /* @__PURE__ */ new Set(["js", "ts", "py", "go", "rust", "java", "kotlin", "c", "cpp", "ruby", "php", "swift", "dart", "lua", "r", "sh", "css"]);
823
+ var Out = class {
824
+ parts = [];
825
+ push(text) {
826
+ this.parts.push(text);
827
+ }
828
+ text(raw) {
829
+ this.parts.push(esc(raw));
830
+ }
831
+ span(cls, raw) {
832
+ if (!raw) return;
833
+ this.parts.push(`<span class="tok-${cls}">${esc(raw)}</span>`);
834
+ }
835
+ toString() {
836
+ return this.parts.join("");
837
+ }
838
+ };
839
+ function highlightCode(code, lang) {
840
+ const key = lang.toLowerCase().replace(/^language-/, "");
841
+ if (!key) return esc(code);
842
+ if (key === "diff" || key === "patch") return highlightDiff(code);
843
+ if (key === "html" || key === "xml" || key === "svg" || key === "vue" || key === "svelte") return highlightMarkup(code);
844
+ if (key === "json" || key === "jsonc" || key === "json5") return highlightJson(code);
845
+ if (key === "yaml" || key === "yml" || key === "toml" || key === "ini") return highlightKeyValue(code);
846
+ if (key === "md" || key === "markdown") return esc(code);
847
+ const family = FAMILY[key];
848
+ if (!family) return esc(code);
849
+ return highlightGeneric(code, family, key);
850
+ }
851
+ function highlightDiff(code) {
852
+ const out = new Out();
853
+ for (const line of code.split("\n")) {
854
+ const cls = line.startsWith("+++") || line.startsWith("---") ? "diff-meta" : line.startsWith("+") ? "diff-add" : line.startsWith("-") ? "diff-del" : line.startsWith("@@") ? "diff-hunk" : "";
855
+ if (cls) out.span(cls, line);
856
+ else out.text(line);
857
+ out.push("\n");
858
+ }
859
+ const html = out.toString();
860
+ return html.endsWith("\n") ? html.slice(0, -1) : html;
861
+ }
862
+ function highlightMarkup(code) {
863
+ const out = new Out();
864
+ const re = /(<!--[\s\S]*?-->)|(<\/?)([A-Za-z][\w:.-]*)((?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)(\s*\/?>)|([^<]+)/g;
865
+ let m;
866
+ let consumed = 0;
867
+ while ((m = re.exec(code)) !== null) {
868
+ if (m.index > consumed) out.text(code.slice(consumed, m.index));
869
+ consumed = m.index + m[0].length;
870
+ if (m[1]) {
871
+ out.span("comment", m[1]);
872
+ } else if (m[2]) {
873
+ out.span("punct", m[2]);
874
+ out.span("tag", m[3] ?? "");
875
+ const attrs = m[4] ?? "";
876
+ const attrRe = /([^\s=]+)(\s*=\s*)("[^"]*"|'[^']*'|[^\s>]+)/g;
877
+ let a;
878
+ let ac = 0;
879
+ while ((a = attrRe.exec(attrs)) !== null) {
880
+ if (a.index > ac) out.text(attrs.slice(ac, a.index));
881
+ ac = a.index + a[0].length;
882
+ out.span("attr", a[1] ?? "");
883
+ out.span("punct", a[2] ?? "");
884
+ out.span("string", a[3] ?? "");
885
+ }
886
+ if (ac < attrs.length) out.text(attrs.slice(ac));
887
+ out.span("punct", m[5] ?? "");
888
+ } else if (m[6]) {
889
+ out.text(m[6]);
890
+ }
891
+ }
892
+ if (consumed < code.length) out.text(code.slice(consumed));
893
+ return out.toString();
894
+ }
895
+ function highlightJson(code) {
896
+ const out = new Out();
897
+ const re = /("(?:[^"\\]|\\.)*")(\s*:)?|(-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|\b(true|false|null)\b|([{}[\],:])|(\s+)|([^\s{}[\],:"]+)/g;
898
+ let m;
899
+ let consumed = 0;
900
+ while ((m = re.exec(code)) !== null) {
901
+ if (m.index > consumed) out.text(code.slice(consumed, m.index));
902
+ consumed = m.index + m[0].length;
903
+ if (m[1]) {
904
+ if (m[2]) {
905
+ out.span("key", m[1]);
906
+ out.span("punct", m[2]);
907
+ } else {
908
+ out.span("string", m[1]);
909
+ }
910
+ } else if (m[3]) out.span("number", m[3]);
911
+ else if (m[4]) out.span("keyword", m[4]);
912
+ else if (m[5]) out.span("punct", m[5]);
913
+ else if (m[6]) out.text(m[6]);
914
+ else if (m[7]) out.span("comment", m[7]);
915
+ }
916
+ if (consumed < code.length) out.text(code.slice(consumed));
917
+ return out.toString();
918
+ }
919
+ function highlightKeyValue(code) {
920
+ const out = new Out();
921
+ for (const line of code.split("\n")) {
922
+ const hash = /^(\s*#.*)$/.exec(line);
923
+ const kv = /^(\s*)([\w.$-]+)(\s*[:=]\s*)(.*)$/.exec(line);
924
+ const dash = /^(\s*-\s)(.*)$/.exec(line);
925
+ if (hash) {
926
+ out.span("comment", hash[1] ?? "");
927
+ } else if (dash && !line.includes(":")) {
928
+ out.span("punct", dash[1] ?? "");
929
+ out.text(dash[2] ?? "");
930
+ } else if (kv) {
931
+ out.text(kv[1] ?? "");
932
+ out.span("key", kv[2] ?? "");
933
+ out.span("punct", kv[3] ?? "");
934
+ const value = kv[4] ?? "";
935
+ if (/^["'].*["']$/.test(value)) out.span("string", value);
936
+ else if (/^-?\d+(\.\d+)?$/.test(value)) out.span("number", value);
937
+ else if (/^(true|false|null|yes|no)$/i.test(value)) out.span("keyword", value);
938
+ else out.text(value);
939
+ } else {
940
+ out.text(line);
941
+ }
942
+ out.push("\n");
943
+ }
944
+ const html = out.toString();
945
+ return html.endsWith("\n") ? html.slice(0, -1) : html;
946
+ }
947
+ function highlightGeneric(code, family, langKey) {
948
+ const keywords = new Set(KEYWORDS[family] ?? []);
949
+ const out = new Out();
950
+ const hasString = STRING_LANGS.has(family);
951
+ const lineComment = family === "py" || family === "sh" || family === "r" || family === "ruby" ? "#" : family === "sql" || family === "lua" ? "--" : "//";
952
+ const blockComment = family === "sql" || family === "lua" ? null : ["/*", "*/"];
953
+ const hashCommentOnly = family === "py" || family === "r" || family === "sh" || family === "ruby";
954
+ let i = 0;
955
+ while (i < code.length) {
956
+ const ch = code[i] ?? "";
957
+ const rest = code.slice(i, i + 2);
958
+ if (rest.startsWith(lineComment) && !(hashCommentOnly && ch === "#" && i > 0 && /[\w$]/.test(code[i - 1] ?? ""))) {
959
+ const nl = code.indexOf("\n", i);
960
+ const end = nl === -1 ? code.length : nl;
961
+ out.span("comment", code.slice(i, end));
962
+ i = end;
963
+ continue;
964
+ }
965
+ if (blockComment && rest.startsWith(blockComment[0])) {
966
+ const close = code.indexOf(blockComment[1], i + 2);
967
+ const end = close === -1 ? code.length : close + 2;
968
+ out.span("comment", code.slice(i, end));
969
+ i = end;
970
+ continue;
971
+ }
972
+ if (hasString && (ch === '"' || ch === "'" || ch === "`" && (family === "js" || family === "ts"))) {
973
+ let j = i + 1;
974
+ while (j < code.length) {
975
+ const c = code[j];
976
+ if (c === "\\") {
977
+ j += 2;
978
+ continue;
979
+ }
980
+ if (c === ch) {
981
+ j++;
982
+ break;
983
+ }
984
+ if (c === "\n" && ch !== "`") break;
985
+ j++;
986
+ }
987
+ out.span("string", code.slice(i, j));
988
+ i = j;
989
+ continue;
990
+ }
991
+ if (family === "py" && rest === '"""') {
992
+ const close = code.indexOf('"""', i + 3);
993
+ const end = close === -1 ? code.length : close + 3;
994
+ out.span("string", code.slice(i, end));
995
+ i = end;
996
+ continue;
997
+ }
998
+ if (ch === "#" && (family === "rust" || family === "c" || family === "cpp" || family === "ts" || family === "css")) {
999
+ const m = /^#[A-Za-z_][\w-]*/.exec(code.slice(i));
1000
+ if (m) {
1001
+ out.span("meta", m[0]);
1002
+ i += m[0].length;
1003
+ continue;
1004
+ }
1005
+ }
1006
+ if (/[0-9]/.test(ch) && !/[\w$]/.test(code[i - 1] ?? "")) {
1007
+ const m = /^(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)n?/.exec(code.slice(i));
1008
+ if (m) {
1009
+ out.span("number", m[0]);
1010
+ i += m[0].length;
1011
+ continue;
1012
+ }
1013
+ }
1014
+ if (/[A-Za-z_$\u00a0-\uffff]/.test(ch)) {
1015
+ const m = /^[A-Za-z0-9_$\u00a0-\uffff]+/.exec(code.slice(i));
1016
+ if (m) {
1017
+ const word = m[0];
1018
+ const after = code.slice(i + word.length).match(/^\s*\(/)?.[0];
1019
+ if (keywords.has(word)) out.span("keyword", word);
1020
+ else if (family === "css" && word.startsWith("@")) out.span("meta", word);
1021
+ else if (family === "sh" && (word === "echo" || word === "cd" || word === "export")) out.span("keyword", word);
1022
+ else if (after && !["if", "for", "while"].includes(word)) out.span("fn", word);
1023
+ else out.text(word);
1024
+ i += word.length;
1025
+ continue;
1026
+ }
1027
+ }
1028
+ out.text(ch);
1029
+ i++;
1030
+ }
1031
+ return out.toString();
1032
+ }
1033
+
1034
+ // src/host/md.ts
1035
+ function esc(text) {
1036
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1037
+ }
1038
+ function safeHref(raw) {
1039
+ const trimmed = raw.trim();
1040
+ if (!trimmed) return null;
1041
+ if (/^#[A-Za-z0-9_-]+$/.test(trimmed)) return trimmed;
1042
+ if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) return null;
1043
+ const scheme = trimmed.slice(0, trimmed.indexOf(":")).toLowerCase();
1044
+ if (scheme === "http" || scheme === "https" || scheme === "mailto") return trimmed;
1045
+ return null;
1046
+ }
1047
+ function renderMarkdown(source, options = {}) {
1048
+ const opts = {
1049
+ tables: options.tables ?? true,
1050
+ markExternalLinks: options.markExternalLinks ?? true
1051
+ };
1052
+ const lines = source.replace(/\r\n?/g, "\n").split("\n");
1053
+ const out = [];
1054
+ let i = 0;
1055
+ while (i < lines.length) {
1056
+ const line = lines[i] ?? "";
1057
+ if (!line.trim()) {
1058
+ i++;
1059
+ continue;
1060
+ }
1061
+ const fence = /^(\s*)(`{3,}|~{3,})\s*([^\s`]*)\s*$/.exec(line);
1062
+ if (fence) {
1063
+ const indent = fence[1] ?? "";
1064
+ const marker = fence[2] ?? "```";
1065
+ const lang = (fence[3] ?? "").toLowerCase();
1066
+ const body = [];
1067
+ i++;
1068
+ const closeRe = new RegExp(`^\\s*${marker[0] === "`" ? "`" : "~"}{${marker.length},}\\s*$`);
1069
+ while (i < lines.length && !closeRe.test(lines[i] ?? "")) {
1070
+ const raw = lines[i] ?? "";
1071
+ body.push(indent ? raw.slice(Math.min(indent.length, raw.length - raw.trimStart().length)) : raw);
1072
+ i++;
1073
+ }
1074
+ i++;
1075
+ out.push(renderCodeBlock(body.join("\n"), lang));
1076
+ continue;
1077
+ }
1078
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line);
1079
+ if (heading) {
1080
+ const level = (heading[1] ?? "#").length;
1081
+ out.push(`<h${level}>${inline(heading[2] ?? "", opts)}</h${level}>`);
1082
+ i++;
1083
+ continue;
1084
+ }
1085
+ if (/^\s{0,3}(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$/.test(line)) {
1086
+ out.push("<hr>");
1087
+ i++;
1088
+ continue;
1089
+ }
1090
+ if (/^\s{0,3}>/.test(line)) {
1091
+ const quote = [];
1092
+ while (i < lines.length && /^\s{0,3}>/.test(lines[i] ?? "")) {
1093
+ quote.push((lines[i] ?? "").replace(/^\s{0,3}>\s?/, ""));
1094
+ i++;
1095
+ }
1096
+ out.push(`<blockquote>${renderMarkdown(quote.join("\n"), opts)}</blockquote>`);
1097
+ continue;
1098
+ }
1099
+ if (opts.tables) {
1100
+ const table = tryTable(lines, i, opts);
1101
+ if (table) {
1102
+ out.push(table.html);
1103
+ i = table.next;
1104
+ continue;
1105
+ }
1106
+ }
1107
+ const listMatch = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/.exec(line);
1108
+ if (listMatch) {
1109
+ const list = parseList(lines, i, opts);
1110
+ out.push(list.html);
1111
+ i = list.next;
1112
+ continue;
1113
+ }
1114
+ const para = [];
1115
+ while (i < lines.length) {
1116
+ const cur = lines[i] ?? "";
1117
+ if (!cur.trim()) break;
1118
+ if (/^(\s*)(`{3,}|~{3,})/.test(cur)) break;
1119
+ if (/^(#{1,6})\s+/.test(cur)) break;
1120
+ if (/^\s{0,3}>/.test(cur)) break;
1121
+ if (/^(\s*)([-*+]|\d{1,9}[.)])\s+/.test(cur)) break;
1122
+ if (/^\s{0,3}(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$/.test(cur)) break;
1123
+ if (opts.tables && i + 1 < lines.length && isTableHeaderRow(cur, lines[i + 1] ?? "")) break;
1124
+ para.push(cur);
1125
+ i++;
1126
+ }
1127
+ if (para.length) {
1128
+ out.push(`<p>${para.map((l) => inline(l, opts)).join("<br>")}</p>`);
1129
+ }
1130
+ }
1131
+ return out.join("\n");
1132
+ }
1133
+ function renderCodeBlock(code, lang) {
1134
+ const label = LANG_LABEL[lang] ?? (lang ? lang.toUpperCase() : "TEXT");
1135
+ const body = lang ? highlightCode(code, lang) : esc(code);
1136
+ const cls = lang ? ` class="language-${esc(lang)}"` : "";
1137
+ return `<div class="code-block"><div class="code-banner"><span class="code-lang">${esc(label)}</span></div><pre${cls}><code${cls}>${body}</code></pre></div>`;
1138
+ }
1139
+ function readListMark(line) {
1140
+ const m = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/.exec(line);
1141
+ if (!m) return null;
1142
+ const indent = (m[1] ?? "").replace(/\t/g, " ").length;
1143
+ const token = m[2] ?? "-";
1144
+ const ordered = /^\d/.test(token);
1145
+ return {
1146
+ indent,
1147
+ ordered,
1148
+ start: ordered ? Number.parseInt(token, 10) : 1,
1149
+ text: m[3] ?? ""
1150
+ };
1151
+ }
1152
+ function parseList(lines, start, opts) {
1153
+ const first = readListMark(lines[start] ?? "");
1154
+ if (!first) return { html: "", next: start + 1 };
1155
+ const baseIndent = first.indent;
1156
+ const ordered = first.ordered;
1157
+ const items = [];
1158
+ let i = start;
1159
+ let current = [];
1160
+ const flush = () => {
1161
+ if (current.length) items.push(current.join("\n"));
1162
+ current = [];
1163
+ };
1164
+ while (i < lines.length) {
1165
+ const line = lines[i] ?? "";
1166
+ const mark = readListMark(line);
1167
+ if (mark && mark.indent <= baseIndent && mark.ordered === ordered && mark.indent === baseIndent) {
1168
+ flush();
1169
+ current.push(mark.text);
1170
+ i++;
1171
+ continue;
1172
+ }
1173
+ if (!line.trim()) {
1174
+ const ahead = peekNextMeaningful(lines, i + 1);
1175
+ if (ahead === null) {
1176
+ i++;
1177
+ break;
1178
+ }
1179
+ const nextMark = readListMark(lines[ahead] ?? "");
1180
+ if (nextMark && nextMark.indent >= baseIndent) {
1181
+ current.push("");
1182
+ i++;
1183
+ continue;
1184
+ }
1185
+ break;
1186
+ }
1187
+ if (/^\s+/.test(line) || mark && mark.indent > baseIndent) {
1188
+ current.push(line);
1189
+ i++;
1190
+ continue;
1191
+ }
1192
+ if (current.length) {
1193
+ current.push(line);
1194
+ i++;
1195
+ continue;
1196
+ }
1197
+ break;
1198
+ }
1199
+ flush();
1200
+ const rendered = items.map((raw) => {
1201
+ const [head, ...rest] = raw.split("\n");
1202
+ let text = head ?? "";
1203
+ let task = "";
1204
+ const taskMatch = /^\[([ xX])\]\s+(.*)$/.exec(text);
1205
+ if (taskMatch) {
1206
+ task = `<span class="task-box${taskMatch[1] === " " ? "" : " task-done"}" aria-hidden="true"></span>`;
1207
+ text = taskMatch[2] ?? "";
1208
+ }
1209
+ const tail = rest.length ? renderMarkdown(rest.join("\n"), opts) : "";
1210
+ return `<li>${task}${inline(text, opts)}${tail}</li>`;
1211
+ });
1212
+ const tag = ordered ? "ol" : "ul";
1213
+ const startAttr = ordered && first.start !== 1 ? ` start="${first.start}"` : "";
1214
+ return { html: `<${tag}${startAttr}>${rendered.join("")}</${tag}>`, next: i };
1215
+ }
1216
+ function peekNextMeaningful(lines, from) {
1217
+ for (let k = from; k < lines.length; k++) {
1218
+ if ((lines[k] ?? "").trim()) return k;
1219
+ }
1220
+ return null;
1221
+ }
1222
+ function splitRow(line) {
1223
+ const cells = [];
1224
+ let buf = "";
1225
+ let inCode = false;
1226
+ for (let i = 0; i < line.length; i++) {
1227
+ const ch = line[i] ?? "";
1228
+ if (ch === "\\" && line[i + 1] === "|") {
1229
+ buf += "|";
1230
+ i++;
1231
+ continue;
1232
+ }
1233
+ if (ch === "`") inCode = !inCode;
1234
+ if (ch === "|" && !inCode) {
1235
+ cells.push(buf);
1236
+ buf = "";
1237
+ continue;
1238
+ }
1239
+ buf += ch;
1240
+ }
1241
+ cells.push(buf);
1242
+ const trimmed = line.trim();
1243
+ if (trimmed.startsWith("|")) cells.shift();
1244
+ if (trimmed.endsWith("|") && cells.length) cells.pop();
1245
+ return cells.map((c) => c.trim());
1246
+ }
1247
+ function isTableHeaderRow(headerLine, sepLine) {
1248
+ if (!headerLine.includes("|")) return false;
1249
+ const sep = sepLine.trim();
1250
+ if (!/^\|?\s*:?-{1,}:?\s*(?:\|\s*:?-{1,}:?\s*)*\|?$/.test(sep)) return false;
1251
+ const cols = splitRow(headerLine).length;
1252
+ return cols > 0 && splitRow(sepLine.replace(/^\|/, "").replace(/\|$/, "")).length === cols;
1253
+ }
1254
+ function parseAlign(sepLine) {
1255
+ return splitRow(sepLine).map((cell) => {
1256
+ const left = cell.startsWith(":");
1257
+ const right = cell.endsWith(":");
1258
+ if (left && right) return "center";
1259
+ if (right) return "right";
1260
+ if (left) return "left";
1261
+ return null;
1262
+ });
1263
+ }
1264
+ function tryTable(lines, start, opts) {
1265
+ const headerLine = lines[start] ?? "";
1266
+ const sepLine = lines[start + 1] ?? "";
1267
+ if (!isTableHeaderRow(headerLine, sepLine)) return null;
1268
+ const headers = splitRow(headerLine);
1269
+ const aligns = parseAlign(sepLine);
1270
+ const rows = [];
1271
+ let i = start + 2;
1272
+ while (i < lines.length) {
1273
+ const line = lines[i] ?? "";
1274
+ if (!line.trim() || !line.includes("|")) break;
1275
+ rows.push(splitRow(line));
1276
+ i++;
1277
+ }
1278
+ const alignAttr = (idx) => {
1279
+ const a = aligns[idx];
1280
+ return a ? ` style="text-align:${a}"` : "";
1281
+ };
1282
+ const head = `<tr>${headers.map((h, idx) => `<th${alignAttr(idx)}>${inline(h, opts)}</th>`).join("")}</tr>`;
1283
+ const body = rows.map((row) => {
1284
+ const cells = headers.map((_, idx) => `<td${alignAttr(idx)}>${inline(row[idx] ?? "", opts)}</td>`);
1285
+ return `<tr>${cells.join("")}</tr>`;
1286
+ }).join("");
1287
+ return {
1288
+ html: `<div class="table-wrap"><table><thead>${head}</thead><tbody>${body}</tbody></table></div>`,
1289
+ next: i
1290
+ };
1291
+ }
1292
+ function inline(text, opts) {
1293
+ const codes = [];
1294
+ const PLACEHOLDER = "\0C";
1295
+ let work = text.replace(/(`+)([\s\S]*?)\1/g, (_m, _ticks, body) => {
1296
+ const idx = codes.length;
1297
+ codes.push(`<code>${esc(body.replace(/^ | $/g, ""))}</code>`);
1298
+ return `${PLACEHOLDER}${idx}\0`;
1299
+ });
1300
+ work = esc(work);
1301
+ work = work.replace(
1302
+ /\[([^\]]*)\]\((?:&lt;)?([^)\s]+?)(?:&gt;)?(?:\s+&quot;([^&]*)&quot;)?\)/g,
1303
+ (_m, label, href, title) => {
1304
+ const decodedHref = href.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
1305
+ const safe = safeHref(decodedHref);
1306
+ if (!safe) return label;
1307
+ const isExternal = /^https?:/i.test(safe);
1308
+ const cls = isExternal && opts.markExternalLinks ? ' class="ext"' : "";
1309
+ const titleAttr = title ? ` title="${title}"` : "";
1310
+ const rel = isExternal ? ' rel="noopener noreferrer"' : "";
1311
+ const target = isExternal ? ' target="_blank"' : "";
1312
+ return `<a href="${esc(safe)}"${cls}${titleAttr}${rel}${target}>${label}</a>`;
1313
+ }
1314
+ );
1315
+ work = work.replace(/&lt;(https?:\/\/[^\s&]+)&gt;/g, (_m, url) => {
1316
+ const safe = safeHref(url);
1317
+ if (!safe) return `&lt;${url}&gt;`;
1318
+ return `<a href="${esc(safe)}" class="ext" rel="noopener noreferrer" target="_blank">${url}</a>`;
1319
+ });
1320
+ work = work.replace(/\*\*\*([^*]+)\*\*\*/g, "<strong><em>$1</em></strong>");
1321
+ work = work.replace(/(^|[^\w*])\*\*([^*]+)\*\*/g, "$1<strong>$2</strong>");
1322
+ work = work.replace(/(^|[^\w*])__([^_]+)__/g, "$1<strong>$2</strong>");
1323
+ work = work.replace(/(^|[^\w*])\*([^*\n]+)\*/g, "$1<em>$2</em>");
1324
+ work = work.replace(/(^|[^\w_])_([^_\n]+)_(?![\w])/g, "$1<em>$2</em>");
1325
+ work = work.replace(/~~([^~]+)~~/g, "<del>$1</del>");
1326
+ work = work.replace(new RegExp(`${PLACEHOLDER}(\\d+)\\u0000`, "g"), (_m, idx) => codes[Number(idx)] ?? "");
1327
+ return work;
1328
+ }
1329
+
1330
+ // src/host/tokens.generated.ts
1331
+ var TOKENS = {
1332
+ "bg-base": { light: "#fff", dark: "#151517" },
1333
+ "bg-layer-1": { light: "#fff", dark: "#232324" },
1334
+ "bg-layer-2": { light: "#fff", dark: "#2c2c2e" },
1335
+ "bg-layer-3": { light: "#fff", dark: "#353638" },
1336
+ "bg-overlay": { light: "#e9ecf2", dark: "#61666b" },
1337
+ "border-l1": { light: "#0000000a", dark: "#ffffff0f" },
1338
+ "border-l2": { light: "#0000001a", dark: "#ffffff1f" },
1339
+ "border-l3": { light: "#0000001f", dark: "#ffffff29" },
1340
+ "border-l4": { light: "#00000029", dark: "#fff3" },
1341
+ "label-primary": { light: "#0f1115", dark: "#f9fafb" },
1342
+ "label-secondary": { light: "#61666b", dark: "#cfd3d6" },
1343
+ "label-tertiary": { light: "#81858c", dark: "#adb2b8" },
1344
+ "label-caption": { light: "#adb2b8", dark: "#81858c" },
1345
+ "label-on-color": { light: "#fff", dark: "#fff" },
1346
+ "brand-text": { light: "#0f1115", dark: "#f9fafb" },
1347
+ "link": { light: "#4176e6", dark: "#7aaaff" },
1348
+ "markdown-code-block": { light: "#f9fafb", dark: "#1b1b1c" },
1349
+ "markdown-code-block-banner": { light: "#f9fafb", dark: "#2c2c2e" },
1350
+ "markdown-inline-code": { light: "#fafafa", dark: "#292929" },
1351
+ "markdown-tag": { light: "#f1f3f5", dark: "#2c2c2e" },
1352
+ "markdown-citation": { light: "#ebeef2", dark: "#353638" },
1353
+ "state-success-primary": { light: "#22c55e", dark: "#22c55e" },
1354
+ "state-error-primary": { light: "#ec1313", dark: "#f25a5a" },
1355
+ "state-warn-primary": { light: "#f59e0b", dark: "#f59e0b" },
1356
+ "state-done-primary": { light: "#7c3aed", dark: "#a78bfa" },
1357
+ "interactive-bg-hover": { light: "#2631480f", dark: "#ffffff14" },
1358
+ "button-primary-fill": { light: "#0f1115", dark: "#f9fafb" },
1359
+ "button-primary-hover": { light: "#43454a", dark: "#ebeef2" },
1360
+ "bg-mask-2": { light: "#0000001f", dark: "#0003" },
1361
+ "bg-skeleton": { light: "#0000000a", dark: "#ffffff14" },
1362
+ "tooltip-bg": { light: "#2c2c2e", dark: "#43454a" },
1363
+ "tooltip-label": { light: "#fff", dark: "#fff" },
1364
+ "toast-bg": { light: "#353638", dark: "#43454a" },
1365
+ "toast-label": { light: "#fff", dark: "#fff" },
1366
+ "bubble": { light: "#edf3fe", dark: "#2c2c2e" },
1367
+ "bubble_highlight": { light: "#d3e2ff", dark: "#43454a" },
1368
+ "input_major": { light: "#fff", dark: "#2c2c2e" },
1369
+ "tip": { light: "#f5f6f7", dark: "#353638" }
1370
+ };
1371
+ var SCALARS = {
1372
+ "radius-xs": "4px",
1373
+ "radius-sm": "8px",
1374
+ "radius-md": "12px",
1375
+ "radius-lg": "16px",
1376
+ "radius-xl": "20px",
1377
+ "radius-panel": "28px",
1378
+ "ease-in-out": "cubic-bezier(.4, 0, .2, 1)",
1379
+ "duration": ".2s",
1380
+ "duration-fast": ".1s",
1381
+ "font-text": '-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif',
1382
+ "font-code": '"SF Mono", "JetBrains Mono", "Fira Code", Consolas, "Liberation Mono", Menlo, Courier, "PingFang SC", "Microsoft YaHei"'
1383
+ };
1384
+ var THEME_VERSION = "0.2.2-rc.5";
1385
+ var SYNTAX = {
1386
+ string: { light: "#2f4c8f", dark: "#7aaaff" },
1387
+ number: { light: "#7c3aed", dark: "#a78bfa" },
1388
+ keyword: { light: "#2563eb", dark: "#7aaaff" },
1389
+ comment: { light: "#61666b", dark: "#979da6" },
1390
+ fn: { light: "#0f1115", dark: "#f9fafb" },
1391
+ punct: { light: "#61666b", dark: "#adb2b8" },
1392
+ meta: { light: "#0e3074", dark: "#93c5fd" },
1393
+ tag: { light: "#2563eb", dark: "#7aaaff" },
1394
+ attr: { light: "#7c3aed", dark: "#a78bfa" },
1395
+ add: { light: "#233c2c", dark: "#4ed17e" },
1396
+ del: { light: "#570c0c", dark: "#f25a5a" },
1397
+ hunk: { light: "#2563eb", dark: "#7aaaff" }
1398
+ };
1399
+
1400
+ // src/host/theme.ts
1401
+ function varsFor(mode) {
1402
+ const lines = [];
1403
+ for (const key of Object.keys(TOKENS)) {
1404
+ const literal = TOKENS[key]?.[mode];
1405
+ if (!literal) continue;
1406
+ lines.push(` --dsh-${key.replace(/_/g, "-")}: ${literal};`);
1407
+ }
1408
+ for (const key of Object.keys(SYNTAX)) {
1409
+ const literal = SYNTAX[key]?.[mode];
1410
+ if (!literal) continue;
1411
+ lines.push(` --dsh-code-${key}: ${literal};`);
1412
+ }
1413
+ if (mode === "light") {
1414
+ for (const key of Object.keys(SCALARS)) {
1415
+ const value = SCALARS[key];
1416
+ if (value === void 0) continue;
1417
+ lines.push(` --dsh-${key}: ${value};`);
1418
+ }
1419
+ }
1420
+ return lines.join("\n");
1421
+ }
1422
+ function tokenCss() {
1423
+ return [
1424
+ ":root {",
1425
+ varsFor("light"),
1426
+ " color-scheme: light dark;",
1427
+ "}",
1428
+ "@media (prefers-color-scheme: dark) {",
1429
+ " :root {",
1430
+ varsFor("dark"),
1431
+ " }",
1432
+ "}",
1433
+ "",
1434
+ "/* \u663E\u5F0F\u4E3B\u9898\u8986\u76D6\uFF1A\u5141\u8BB8\u8BFB\u8005\u624B\u52A8\u5207\u5230\u4EFB\u610F\u4E00\u5957\uFF08\u65E0\u9700\u811A\u672C\uFF0C\u9760 data-theme\uFF09 */",
1435
+ ':root[data-theme="light"] {',
1436
+ varsFor("light"),
1437
+ "}",
1438
+ ':root[data-theme="dark"] {',
1439
+ varsFor("dark"),
1440
+ "}"
1441
+ ].join("\n");
1442
+ }
1443
+ function componentCss() {
1444
+ return `
1445
+ *, *::before, *::after { box-sizing: border-box; }
1446
+
1447
+ html { -webkit-text-size-adjust: 100%; }
1448
+
1449
+ body {
1450
+ margin: 0;
1451
+ background: var(--dsh-bg-base);
1452
+ color: var(--dsh-label-primary);
1453
+ font-family: var(--dsh-font-text);
1454
+ font-size: 14px;
1455
+ line-height: 24px;
1456
+ -webkit-font-smoothing: antialiased;
1457
+ -moz-osx-font-smoothing: grayscale;
1458
+ }
1459
+
1460
+ a { color: var(--dsh-link); text-decoration: none; font-weight: 500; }
1461
+ a:hover { text-decoration: underline dotted var(--dsh-link); text-underline-offset: 3px; }
1462
+ a.ext::after {
1463
+ content: "\u2197";
1464
+ display: inline-block;
1465
+ margin-left: 2px;
1466
+ font-size: .85em;
1467
+ opacity: .7;
1468
+ text-decoration: none;
1469
+ }
1470
+
1471
+ /* ---------- \u6587\u6863\u5916\u58F3 ---------- */
1472
+
1473
+ .doc {
1474
+ max-width: 748px;
1475
+ margin: 0 auto;
1476
+ padding: 40px 24px 96px;
1477
+ }
1478
+
1479
+ .doc-header {
1480
+ border-bottom: .5px solid var(--dsh-border-l2);
1481
+ padding-bottom: 20px;
1482
+ margin-bottom: 32px;
1483
+ }
1484
+
1485
+ .doc-title {
1486
+ margin: 0;
1487
+ font-size: 24px;
1488
+ line-height: 32px;
1489
+ font-weight: 600;
1490
+ color: var(--dsh-brand-text);
1491
+ overflow-wrap: anywhere;
1492
+ }
1493
+
1494
+ .doc-meta {
1495
+ margin-top: 10px;
1496
+ display: flex;
1497
+ flex-wrap: wrap;
1498
+ gap: 6px 14px;
1499
+ color: var(--dsh-label-tertiary);
1500
+ font-size: 12px;
1501
+ line-height: 18px;
1502
+ font-variant-numeric: tabular-nums;
1503
+ }
1504
+
1505
+ .doc-meta .chip {
1506
+ display: inline-flex;
1507
+ align-items: center;
1508
+ gap: 5px;
1509
+ }
1510
+
1511
+ .doc-meta .chip + .chip::before {
1512
+ content: "";
1513
+ width: 2px;
1514
+ height: 2px;
1515
+ border-radius: 1px;
1516
+ background: var(--dsh-label-caption);
1517
+ margin-right: 9px;
1518
+ }
1519
+
1520
+ .doc-meta .chip:first-child::before { content: none; }
1521
+
1522
+ .badge {
1523
+ display: inline-flex;
1524
+ align-items: center;
1525
+ border-radius: var(--dsh-radius-sm);
1526
+ padding: 1px 6px;
1527
+ font-size: 11px;
1528
+ line-height: 18px;
1529
+ background: var(--dsh-markdown-tag);
1530
+ color: var(--dsh-label-secondary);
1531
+ }
1532
+
1533
+ .badge.warn {
1534
+ background: color-mix(in srgb, var(--dsh-state-warn-primary) 14%, transparent);
1535
+ color: var(--dsh-state-warn-primary);
1536
+ }
1537
+
1538
+ /* ---------- \u6D88\u606F ---------- */
1539
+
1540
+ main { display: flex; flex-direction: column; gap: 28px; }
1541
+
1542
+ .msg { display: flex; flex-direction: column; }
1543
+
1544
+ .msg[data-role="user"] {
1545
+ align-items: flex-end;
1546
+ gap: 8px;
1547
+ }
1548
+
1549
+ .msg[data-role="assistant"] {
1550
+ align-items: stretch;
1551
+ gap: 4px;
1552
+ }
1553
+
1554
+ .bubble {
1555
+ max-width: min(calc(748px * .702), 82%);
1556
+ background: var(--dsh-bubble);
1557
+ border-radius: var(--dsh-radius-xl);
1558
+ padding: 10px 16px;
1559
+ font-size: 14px;
1560
+ line-height: 22px;
1561
+ color: var(--dsh-label-primary);
1562
+ white-space: pre-wrap;
1563
+ overflow-wrap: anywhere;
1564
+ word-break: break-word;
1565
+ }
1566
+
1567
+ .msg-model {
1568
+ margin-top: 6px;
1569
+ color: var(--dsh-label-tertiary);
1570
+ font-size: 12px;
1571
+ line-height: 18px;
1572
+ display: flex;
1573
+ gap: 10px;
1574
+ flex-wrap: wrap;
1575
+ font-variant-numeric: tabular-nums;
1576
+ }
1577
+
1578
+ /* ---------- \u6587\u4EF6\u5143\u4FE1\u606F ---------- */
1579
+
1580
+ .files {
1581
+ display: flex;
1582
+ flex-wrap: wrap;
1583
+ gap: 8px;
1584
+ justify-content: flex-end;
1585
+ max-width: 100%;
1586
+ }
1587
+
1588
+ .file-card {
1589
+ display: inline-flex;
1590
+ align-items: center;
1591
+ gap: 10px;
1592
+ width: 240px;
1593
+ max-width: 100%;
1594
+ min-height: 64px;
1595
+ padding: 8px 12px;
1596
+ border: .5px solid var(--dsh-border-l2);
1597
+ border-radius: var(--dsh-radius-lg);
1598
+ background: var(--dsh-input-major);
1599
+ }
1600
+
1601
+ .file-type {
1602
+ flex: none;
1603
+ width: 28px;
1604
+ height: 28px;
1605
+ display: grid;
1606
+ place-items: center;
1607
+ border-radius: var(--dsh-radius-sm);
1608
+ background: var(--dsh-markdown-tag);
1609
+ color: var(--dsh-label-secondary);
1610
+ font-family: var(--dsh-font-code);
1611
+ font-size: 9px;
1612
+ font-weight: 600;
1613
+ letter-spacing: -.02em;
1614
+ }
1615
+
1616
+ .file-body { min-width: 0; display: flex; flex-direction: column; }
1617
+
1618
+ .file-name {
1619
+ color: var(--dsh-label-primary);
1620
+ font-size: 14px;
1621
+ font-weight: 500;
1622
+ line-height: 22px;
1623
+ white-space: nowrap;
1624
+ overflow: hidden;
1625
+ text-overflow: ellipsis;
1626
+ }
1627
+
1628
+ .file-meta { color: var(--dsh-label-tertiary); font-size: 12px; line-height: 15px; }
1629
+
1630
+ /* ---------- \u6298\u53E0\u5757\uFF08\u601D\u8003 / \u5DE5\u5177 / \u68C0\u7D22 / \u6DF1\u7814\uFF09 ---------- */
1631
+
1632
+ details.process {
1633
+ margin: 2px 0;
1634
+ border-radius: var(--dsh-radius-sm);
1635
+ }
1636
+
1637
+ details.process > summary {
1638
+ display: flex;
1639
+ align-items: center;
1640
+ gap: 8px;
1641
+ min-height: 28px;
1642
+ padding: 2px 0;
1643
+ cursor: pointer;
1644
+ color: var(--dsh-label-tertiary);
1645
+ font-size: 13px;
1646
+ line-height: 20px;
1647
+ list-style: none;
1648
+ user-select: none;
1649
+ }
1650
+
1651
+ details.process > summary::-webkit-details-marker { display: none; }
1652
+
1653
+ details.process > summary::after {
1654
+ content: "";
1655
+ flex: none;
1656
+ width: 6px;
1657
+ height: 6px;
1658
+ margin-right: 2px;
1659
+ border-right: 1.5px solid currentColor;
1660
+ border-bottom: 1.5px solid currentColor;
1661
+ transform: rotate(-45deg);
1662
+ transition: transform var(--dsh-duration-fast) var(--dsh-ease-in-out);
1663
+ }
1664
+
1665
+ details.process[open] > summary::after { transform: rotate(45deg); }
1666
+
1667
+ @media (hover: hover) {
1668
+ details.process > summary:hover { color: var(--dsh-label-secondary); }
1669
+ }
1670
+
1671
+ details.process > summary:focus-visible {
1672
+ outline: 1.5px solid var(--dsh-link);
1673
+ outline-offset: 2px;
1674
+ border-radius: var(--dsh-radius-xs);
1675
+ }
1676
+
1677
+ .sum-name {
1678
+ flex: none;
1679
+ color: var(--dsh-label-secondary);
1680
+ font-family: var(--dsh-font-code);
1681
+ font-size: 12px;
1682
+ }
1683
+
1684
+ .sum-text {
1685
+ min-width: 0;
1686
+ overflow: hidden;
1687
+ text-overflow: ellipsis;
1688
+ white-space: nowrap;
1689
+ }
1690
+
1691
+ .sum-dot {
1692
+ flex: none;
1693
+ width: 2px;
1694
+ height: 2px;
1695
+ border-radius: 1px;
1696
+ background: var(--dsh-label-caption);
1697
+ }
1698
+
1699
+ .sum-state {
1700
+ flex: none;
1701
+ font-size: 12px;
1702
+ display: inline-flex;
1703
+ align-items: center;
1704
+ gap: 5px;
1705
+ }
1706
+
1707
+ .sum-state::before {
1708
+ content: "";
1709
+ width: 6px;
1710
+ height: 6px;
1711
+ border-radius: 50%;
1712
+ background: var(--dsh-state-success-primary);
1713
+ }
1714
+
1715
+ .sum-state[data-status="error"] { color: var(--dsh-state-error-primary); }
1716
+ .sum-state[data-status="error"]::before { background: var(--dsh-state-error-primary); }
1717
+ .sum-state[data-status="pending"] { color: var(--dsh-label-tertiary); }
1718
+ .sum-state[data-status="pending"]::before { background: var(--dsh-state-warn-primary); }
1719
+
1720
+ .process-body {
1721
+ margin: 4px 0 8px 22px;
1722
+ color: var(--dsh-label-tertiary);
1723
+ font-size: 13px;
1724
+ line-height: 22px;
1725
+ overflow-wrap: anywhere;
1726
+ }
1727
+
1728
+ .process-body > *:first-child { margin-top: 0; }
1729
+ .process-body > *:last-child { margin-bottom: 0; }
1730
+
1731
+ .kv {
1732
+ display: grid;
1733
+ grid-template-columns: minmax(72px, auto) minmax(0, 1fr);
1734
+ gap: 2px 14px;
1735
+ margin: 0 0 8px;
1736
+ }
1737
+
1738
+ .kv dt {
1739
+ color: var(--dsh-label-caption);
1740
+ font-family: var(--dsh-font-code);
1741
+ font-size: 11px;
1742
+ line-height: 20px;
1743
+ }
1744
+
1745
+ .kv dd {
1746
+ margin: 0;
1747
+ color: var(--dsh-label-secondary);
1748
+ font-family: var(--dsh-font-code);
1749
+ font-size: 11px;
1750
+ line-height: 20px;
1751
+ white-space: pre-wrap;
1752
+ overflow-wrap: anywhere;
1753
+ }
1754
+
1755
+ pre.out {
1756
+ margin: 8px 0 0;
1757
+ padding: 8px 12px;
1758
+ max-height: 260px;
1759
+ overflow: auto;
1760
+ border-radius: var(--dsh-radius-sm);
1761
+ background: var(--dsh-markdown-code-block);
1762
+ border: .5px solid var(--dsh-border-l1);
1763
+ font-family: var(--dsh-font-code);
1764
+ font-size: 11px;
1765
+ line-height: 19px;
1766
+ color: var(--dsh-label-secondary);
1767
+ white-space: pre-wrap;
1768
+ overflow-wrap: anywhere;
1769
+ }
1770
+
1771
+ .trunc-note {
1772
+ margin-top: 6px;
1773
+ display: inline-flex;
1774
+ align-items: center;
1775
+ gap: 5px;
1776
+ font-size: 12px;
1777
+ color: var(--dsh-label-tertiary);
1778
+ }
1779
+
1780
+ /* ---------- \u68C0\u7D22\u7ED3\u679C ---------- */
1781
+
1782
+ .results { margin: 6px 0 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 8px; }
1783
+
1784
+ .result {
1785
+ padding: 8px 12px;
1786
+ border: .5px solid var(--dsh-border-l1);
1787
+ border-radius: var(--dsh-radius-sm);
1788
+ background: var(--dsh-markdown-citation);
1789
+ }
1790
+
1791
+ .result-title { font-size: 13px; line-height: 20px; color: var(--dsh-label-primary); font-weight: 500; }
1792
+ .result-title a { font-weight: 500; }
1793
+ .result-site { font-size: 11px; line-height: 16px; color: var(--dsh-label-tertiary); margin-top: 2px; }
1794
+ .result-snippet { font-size: 12px; line-height: 20px; color: var(--dsh-label-secondary); margin-top: 4px; }
1795
+
1796
+ /* ---------- Markdown \u6B63\u6587 ---------- */
1797
+
1798
+ .md {
1799
+ min-width: 0;
1800
+ overflow-wrap: anywhere;
1801
+ font-size: 14px;
1802
+ line-height: 24px;
1803
+ color: var(--dsh-label-primary);
1804
+ }
1805
+
1806
+ .md > *:first-child { margin-top: 0 !important; }
1807
+ .md > *:last-child { margin-bottom: 0 !important; }
1808
+
1809
+ .md h1 { font-size: 21px; line-height: 30px; font-weight: 700; margin: 32px 0 16px; }
1810
+ .md h2 { font-size: 19px; line-height: 28px; font-weight: 700; margin: 32px 0 16px; }
1811
+ .md h3 { font-size: 18px; line-height: 26px; font-weight: 700; margin: 32px 0 16px; }
1812
+ .md h4 { font-size: 14px; line-height: 24px; font-weight: 600; margin: 16px 0; }
1813
+ .md h5, .md h6 { font-size: 14px; line-height: 24px; font-weight: 600; margin: 16px 0; color: var(--dsh-label-secondary); }
1814
+ .md h1 strong, .md h2 strong, .md h3 strong, .md h4 strong { font-weight: inherit; }
1815
+ .md h1 code, .md h2 code, .md h3 code, .md h4 code { font: inherit; font-family: var(--dsh-font-code); }
1816
+
1817
+ .md p { margin: 16px 0; }
1818
+ .md strong { font-weight: 600; }
1819
+
1820
+ .md ul, .md ol { margin: 16px 0; padding-left: 18px; }
1821
+ .md li:not(:first-child) { margin-top: 6px; }
1822
+ .md li > ul, .md li > ol { margin-top: 4px; }
1823
+ .md li::marker { color: var(--dsh-label-secondary); line-height: 24px; }
1824
+ .md li > p { margin: 8px 0; }
1825
+ .md li > *:first-child { margin-top: 0; }
1826
+ .md li > *:last-child { margin-bottom: 0; }
1827
+
1828
+ .md blockquote {
1829
+ margin: 16px 0;
1830
+ padding-left: 14px;
1831
+ border-left: 2px solid var(--dsh-label-caption);
1832
+ color: var(--dsh-label-secondary);
1833
+ }
1834
+
1835
+ .md hr {
1836
+ display: block;
1837
+ border: none;
1838
+ height: .5px;
1839
+ margin: 32px 0;
1840
+ background: var(--dsh-border-l2);
1841
+ }
1842
+
1843
+ .md :not(pre) > code {
1844
+ font-family: var(--dsh-font-code);
1845
+ font-size: .875em;
1846
+ padding: 1px 5px;
1847
+ border-radius: var(--dsh-radius-xs);
1848
+ background: var(--dsh-markdown-inline-code);
1849
+ border: .5px solid var(--dsh-border-l1);
1850
+ overflow-wrap: break-word;
1851
+ }
1852
+
1853
+ .task-box {
1854
+ display: inline-block;
1855
+ width: 12px;
1856
+ height: 12px;
1857
+ margin-right: 7px;
1858
+ vertical-align: -1px;
1859
+ border: 1.5px solid var(--dsh-label-caption);
1860
+ border-radius: 3px;
1861
+ }
1862
+
1863
+ .task-box.task-done {
1864
+ background: var(--dsh-label-secondary);
1865
+ border-color: var(--dsh-label-secondary);
1866
+ }
1867
+
1868
+ /* \u4EE3\u7801\u5757\uFF1A\u4E0E DSH \u4E00\u81F4\u2014\u2014radius-lg\uFF0C\u9876\u90E8 banner \u6761\uFF0C11px/19px */
1869
+ .code-block {
1870
+ margin: 16px 0;
1871
+ border-radius: var(--dsh-radius-lg);
1872
+ background: var(--dsh-markdown-code-block);
1873
+ color: var(--dsh-label-primary);
1874
+ overflow: hidden;
1875
+ }
1876
+
1877
+ .code-banner {
1878
+ padding: 9px 14px;
1879
+ background: var(--dsh-markdown-code-block-banner);
1880
+ border-bottom: .5px solid var(--dsh-border-l1);
1881
+ font-size: 11px;
1882
+ line-height: 18px;
1883
+ color: var(--dsh-label-tertiary);
1884
+ }
1885
+
1886
+ .code-lang { font-family: var(--dsh-font-text); letter-spacing: .02em; }
1887
+
1888
+ .code-block pre {
1889
+ margin: 0;
1890
+ padding: 16px;
1891
+ overflow-x: auto;
1892
+ font-family: var(--dsh-font-code);
1893
+ font-size: 11px;
1894
+ line-height: 19px;
1895
+ tab-size: 2;
1896
+ }
1897
+
1898
+ .code-block pre code {
1899
+ font: inherit;
1900
+ background: none;
1901
+ padding: 0;
1902
+ border: 0;
1903
+ white-space: pre;
1904
+ }
1905
+
1906
+ /* \u8868\u683C\uFF1A\u4E0E DSH \u4E00\u81F4\u2014\u2014\u65E0\u5916\u6846\uFF0C\u4EC5\u884C\u5E95\u7EC6\u7EBF */
1907
+ .table-wrap { max-width: 100%; overflow-x: auto; margin: 16px 0; }
1908
+ .table-wrap table { border-collapse: collapse; width: 100%; min-width: max-content; }
1909
+ .table-wrap th {
1910
+ text-align: start;
1911
+ padding: 10px 16px;
1912
+ font-size: 13px;
1913
+ line-height: 22px;
1914
+ font-weight: 500;
1915
+ color: var(--dsh-label-primary);
1916
+ border-bottom: .5px solid var(--dsh-border-l3);
1917
+ min-width: 100px;
1918
+ max-width: min(30vw, 320px);
1919
+ }
1920
+ .table-wrap td {
1921
+ padding: 10px 16px;
1922
+ font-size: 13px;
1923
+ line-height: 22px;
1924
+ color: var(--dsh-label-secondary);
1925
+ border-bottom: .5px solid var(--dsh-border-l2);
1926
+ min-width: 100px;
1927
+ max-width: min(30vw, 320px);
1928
+ }
1929
+ .table-wrap th:first-child, .table-wrap td:first-child { padding-left: 0; }
1930
+ .table-wrap td:last-child { padding-right: 0; }
1931
+ .table-wrap table code { font-size: 11px; }
1932
+
1933
+ /* ---------- \u8BED\u6CD5\u9AD8\u4EAE ----------
1934
+ * \u53D6\u503C\u6765\u81EA tokens.generated.ts \u7684 SYNTAX \u8868\uFF1ADSH \u540C\u65CF\u8272\u9636\u91CC\u5C0F\u5B57\u5BF9\u6BD4\u5EA6\u8FBE\u6807\u7684\u503C\u3002
1935
+ * \u4E0D\u590D\u7528 state-* \u8BED\u4E49\u8272\u2014\u2014\u90A3\u7EC4\u5728\u6D45\u8272\u4E0B\u505A\u4EE3\u7801\u7740\u8272\u5BF9\u6BD4\u5EA6\u4E0D\u8DB3\uFF08\u89C1\u8BE5\u8868\u6CE8\u91CA\uFF09\u3002 */
1936
+ .tok-comment { color: var(--dsh-code-comment); font-style: italic; }
1937
+ .tok-string { color: var(--dsh-code-string); }
1938
+ .tok-number { color: var(--dsh-code-number); }
1939
+ .tok-keyword { color: var(--dsh-code-keyword); font-weight: 500; }
1940
+ .tok-key { color: var(--dsh-code-string); }
1941
+ .tok-fn { color: var(--dsh-code-fn); }
1942
+ .tok-tag { color: var(--dsh-code-tag); }
1943
+ .tok-attr { color: var(--dsh-code-attr); }
1944
+ .tok-punct { color: var(--dsh-code-punct); }
1945
+ .tok-meta { color: var(--dsh-code-meta); }
1946
+ .tok-diff-add { color: var(--dsh-code-add); }
1947
+ .tok-diff-del { color: var(--dsh-code-del); }
1948
+ .tok-diff-hunk { color: var(--dsh-code-hunk); }
1949
+ .tok-diff-meta { color: var(--dsh-code-punct); }
1950
+
1951
+ /* ---------- \u9875\u811A ---------- */
1952
+
1953
+ .doc-footer {
1954
+ margin-top: 56px;
1955
+ padding-top: 20px;
1956
+ border-top: .5px solid var(--dsh-border-l2);
1957
+ color: var(--dsh-label-tertiary);
1958
+ font-size: 12px;
1959
+ line-height: 20px;
1960
+ display: flex;
1961
+ flex-direction: column;
1962
+ gap: 6px;
1963
+ }
1964
+
1965
+ .doc-footer p { margin: 0; }
1966
+ .doc-footer ul { margin: 0; padding-left: 18px; }
1967
+ .doc-footer code { font-family: var(--dsh-font-code); font-size: 11px; }
1968
+
1969
+ /* ---------- \u6253\u5370 ---------- */
1970
+ @media print {
1971
+ .doc { max-width: none; padding: 0; }
1972
+ details.process { break-inside: avoid; }
1973
+ details.process > summary { cursor: default; }
1974
+ .code-block pre { overflow: visible; white-space: pre-wrap; }
1975
+ }
1976
+
1977
+ /* ---------- \u7A84\u5C4F ---------- */
1978
+ @media (max-width: 640px) {
1979
+ .doc { padding: 24px 16px 64px; }
1980
+ .bubble { max-width: 92%; }
1981
+ .md h1 { font-size: 19px; line-height: 28px; margin: 24px 0 12px; }
1982
+ .md h2 { font-size: 18px; line-height: 26px; margin: 24px 0 12px; }
1983
+ .md h3 { font-size: 16px; line-height: 24px; margin: 24px 0 12px; }
1984
+ .table-wrap th, .table-wrap td { max-width: 60vw; }
1985
+ }
1986
+ `.trim();
1987
+ }
1988
+ function themeCss() {
1989
+ return `/* DSH \u8BBE\u8BA1\u4EE4\u724C\u5FEB\u7167 ${THEME_VERSION} \u2014\u2014 \u5B57\u9762\u503C\u5185\u8054\uFF0C\u5BFC\u51FA\u540E\u72EC\u7ACB\u53EF\u7528 */
1990
+ ${tokenCss()}
1991
+
1992
+ ${componentCss()}
1993
+ `;
1994
+ }
1995
+
1996
+ // src/host/html.ts
1997
+ var GENERATOR = "dsh-share-html";
1998
+ function renderHtml(model, meta = {}) {
1999
+ const started = performanceNow();
2000
+ const warnings = [...meta.warnings ?? []];
2001
+ const version = meta.version ?? "0.1.0";
2002
+ const lang = meta.lang ?? "zh-CN";
2003
+ const stats = { turns: model.turns.length, messages: 0, toolCalls: 0, elapsedMs: 0 };
2004
+ const body = [];
2005
+ for (const turn of model.turns) {
2006
+ if (turn.user) {
2007
+ stats.messages += 1;
2008
+ body.push(renderUserMessage(turn.user));
2009
+ }
2010
+ const assistantBlocks = [];
2011
+ for (const msg of turn.assistants) {
2012
+ stats.messages += 1;
2013
+ stats.toolCalls += msg.blocks.filter((b) => b.kind === "tool").length;
2014
+ assistantBlocks.push(renderAssistantMessage(msg));
2015
+ }
2016
+ if (assistantBlocks.length) {
2017
+ body.push(`<article class="msg" data-role="assistant">
2018
+ ${assistantBlocks.join("\n")}
2019
+ </article>`);
2020
+ }
2021
+ }
2022
+ if (!body.length) {
2023
+ body.push('<p class="empty-note">\u8FD9\u4E2A\u4F1A\u8BDD\u5728\u6240\u9009\u7C92\u5EA6\u4E0B\u6CA1\u6709\u53EF\u5BFC\u51FA\u7684\u5185\u5BB9\u3002</p>');
2024
+ }
2025
+ if (meta.redacted === false) warnings.push("unredacted");
2026
+ if (model.dropped.systemMessages > 0) {
2027
+ warnings.push(`dropped ${model.dropped.systemMessages} system/developer message(s)`);
2028
+ }
2029
+ if (model.dropped.injectedUserContext > 0) {
2030
+ warnings.push(`dropped ${model.dropped.injectedUserContext} injected context message(s)`);
2031
+ }
2032
+ const html = buildDocument({ model, body: body.join("\n"), meta, version, lang, stats, warnings: dedupe(warnings) });
2033
+ stats.elapsedMs = Math.round(performanceNow() - started);
2034
+ return { html, stats, warnings: dedupe(warnings) };
2035
+ }
2036
+ function buildDocument(input) {
2037
+ const { model, body, meta, version, lang, stats, warnings } = input;
2038
+ const title = model.title || "Untitled session";
2039
+ const exportedAt = meta.exportedAt ?? model.exportedAt;
2040
+ const metaWarnings = warnings.length ? warnings.join("; ") : "none";
2041
+ const chips = [];
2042
+ chips.push(`<span class="chip">${esc(String(stats.turns))} \u8F6E</span>`);
2043
+ chips.push(`<span class="chip">${esc(String(stats.messages))} \u6761\u6D88\u606F</span>`);
2044
+ if (stats.toolCalls) chips.push(`<span class="chip">${esc(String(stats.toolCalls))} \u6B21\u5DE5\u5177\u8C03\u7528</span>`);
2045
+ if (exportedAt !== void 0) {
2046
+ chips.push(`<span class="chip">\u5BFC\u51FA\u4E8E ${esc(formatTime(exportedAt, meta.timeZone))}</span>`);
2047
+ }
2048
+ if (meta.preset) chips.push(`<span class="chip">\u7C92\u5EA6\uFF1A${esc(presetLabel(meta.preset))}</span>`);
2049
+ if (meta.redacted === false) {
2050
+ chips.push('<span class="chip"><span class="badge warn">\u672A\u8131\u654F</span></span>');
2051
+ } else if (meta.redactions && meta.redactions > 0) {
2052
+ chips.push(`<span class="chip"><span class="badge">\u5DF2\u8131\u654F ${esc(String(meta.redactions))} \u5904</span></span>`);
2053
+ }
2054
+ const footer = buildFooter({ meta, warnings, version, stats });
2055
+ return `<!DOCTYPE html>
2056
+ <html lang="${esc(lang)}">
2057
+ <head>
2058
+ <meta charset="utf-8">
2059
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2060
+ <meta name="generator" content="${esc(GENERATOR)} ${esc(version)}">
2061
+ <meta name="dsh-share-theme" content="${esc(THEME_VERSION)}">
2062
+ <meta name="dsh-share-warnings" content="${esc(metaWarnings)}">
2063
+ <meta name="dsh-share-preset" content="${esc(meta.preset ?? "unknown")}">
2064
+ <meta name="dsh-share-redacted" content="${meta.redacted === false ? "false" : "true"}">
2065
+ <meta name="referrer" content="no-referrer">
2066
+ <meta name="robots" content="noindex, nofollow">
2067
+ <title>${esc(title)}</title>
2068
+ <style>
2069
+ ${themeCss()}</style>
2070
+ </head>
2071
+ <body>
2072
+ <div class="doc">
2073
+ <header class="doc-header">
2074
+ <h1 class="doc-title">${esc(title)}</h1>
2075
+ <div class="doc-meta">
2076
+ ${chips.join("\n")}
2077
+ </div>
2078
+ </header>
2079
+ <main>
2080
+ ${body}
2081
+ </main>
2082
+ <footer class="doc-footer">
2083
+ ${footer}
2084
+ </footer>
2085
+ </div>
2086
+ </body>
2087
+ </html>
2088
+ `;
2089
+ }
2090
+ function buildFooter(input) {
2091
+ const { meta, warnings, version, stats } = input;
2092
+ const lines = [];
2093
+ lines.push(`<p>\u7531 <code>${esc(GENERATOR)}</code> v${esc(version)} \u4ECE DSH \u4F1A\u8BDD\u5BFC\u51FA\uFF08\u5355\u4E00\u81EA\u5305\u542B\u6587\u4EF6\uFF0C\u79BB\u7EBF\u53EF\u7528\uFF0C\u4E0D\u542B\u811A\u672C\u3001\u4E0D\u52A0\u8F7D\u4EFB\u4F55\u5916\u90E8\u8D44\u6E90\uFF09\u3002</p>`);
2094
+ if (meta.redacted === false) {
2095
+ lines.push("<p><strong>\u672C\u6587\u4EF6\u672A\u7ECF\u8131\u654F</strong>\uFF1A\u5305\u542B\u539F\u59CB\u6587\u672C\uFF0C\u5206\u4EAB\u524D\u8BF7\u81EA\u884C\u68C0\u67E5\u662F\u5426\u542B\u5BC6\u94A5\u3001\u5185\u7F51\u5730\u5740\u7B49\u654F\u611F\u4FE1\u606F\u3002</p>");
2096
+ } else {
2097
+ lines.push("<p>\u5DF2\u6309 best-effort \u89C4\u5219\u8131\u654F\uFF08API Key\u3001\u4EE4\u724C\u3001\u79C1\u94A5\u3001\u90AE\u7BB1\u3001\u5185\u7F51 IP\u3001\u7EDD\u5BF9\u8DEF\u5F84\uFF09\u3002\u81EA\u52A8\u8131\u654F\u53EF\u80FD\u6F0F\u5224\uFF0C\u5206\u4EAB\u524D\u4ECD\u5EFA\u8BAE\u901A\u8BFB\u3002</p>");
2098
+ }
2099
+ const notable = warnings.filter((w) => w !== "unredacted");
2100
+ if (notable.length) {
2101
+ lines.push("<ul>");
2102
+ for (const w of notable) lines.push(`<li>${esc(w)}</li>`);
2103
+ lines.push("</ul>");
2104
+ }
2105
+ lines.push(`<p>\u7EDF\u8BA1\uFF1A${esc(String(stats.turns))} \u8F6E / ${esc(String(stats.messages))} \u6761\u6D88\u606F / ${esc(String(stats.toolCalls))} \u6B21\u5DE5\u5177\u8C03\u7528\u3002</p>`);
2106
+ return lines.join("\n");
2107
+ }
2108
+ function renderUserMessage(msg) {
2109
+ const parts = [];
2110
+ const fileBlocks = msg.blocks.filter((b) => b.kind === "files");
2111
+ const textBlocks = msg.blocks.filter((b) => b.kind === "text");
2112
+ for (const block of fileBlocks) {
2113
+ if (block.kind === "files") parts.push(renderFiles(block.files));
2114
+ }
2115
+ for (const block of textBlocks) {
2116
+ if (block.kind === "text") {
2117
+ parts.push(`<div class="bubble">${esc(block.md)}</div>`);
2118
+ }
2119
+ }
2120
+ return `<article class="msg" data-role="user">
2121
+ ${parts.join("\n")}
2122
+ </article>`;
2123
+ }
2124
+ function renderAssistantMessage(msg) {
2125
+ const parts = [];
2126
+ for (const block of msg.blocks) {
2127
+ parts.push(renderBlock(block));
2128
+ }
2129
+ if (msg.model) {
2130
+ parts.push(`<div class="msg-model"><span>${esc(msg.model)}</span></div>`);
2131
+ }
2132
+ return parts.filter(Boolean).join("\n");
2133
+ }
2134
+ function renderBlock(block) {
2135
+ switch (block.kind) {
2136
+ case "text":
2137
+ return `<div class="md">${renderMarkdown(block.md)}</div>`;
2138
+ case "reasoning":
2139
+ return renderDetails({
2140
+ kind: "reasoning",
2141
+ summary: "\u601D\u8003\u8FC7\u7A0B",
2142
+ body: `<div class="md">${renderMarkdown(block.text)}</div>`
2143
+ });
2144
+ case "tool":
2145
+ return renderTool(block);
2146
+ case "retrieval":
2147
+ return renderRetrieval(block);
2148
+ case "research":
2149
+ return renderDetails({
2150
+ kind: "research",
2151
+ summary: "\u6DF1\u5EA6\u7814\u7A76\u8FC7\u7A0B",
2152
+ name: block.title,
2153
+ status: block.status,
2154
+ body: `<div class="md">${renderMarkdown(block.text)}</div>`
2155
+ });
2156
+ case "files":
2157
+ return renderFiles(block.files);
2158
+ }
2159
+ }
2160
+ function renderDetails(input) {
2161
+ const statusAttr = input.status ? ` data-status="${esc(input.status)}"` : "";
2162
+ const nameHtml = input.name ? `<span class="sum-name">${esc(input.name)}</span>` : "";
2163
+ return `<details class="process" data-kind="${esc(input.kind)}">
2164
+ <summary><span class="sum-text">${esc(input.summary)}</span>${nameHtml}${statusDot(input.status)}</summary>
2165
+ <div class="process-body">
2166
+ ${input.body}
2167
+ </div>
2168
+ </details>`;
2169
+ }
2170
+ function statusDot(status) {
2171
+ if (!status || status === "ok") return "";
2172
+ if (status === "error") return '<span class="sum-state" data-status="error">\u5931\u8D25</span>';
2173
+ if (status === "pending") return '<span class="sum-state" data-status="pending">\u672A\u5B8C\u6210</span>';
2174
+ return "";
2175
+ }
2176
+ function renderTool(block) {
2177
+ const summaryText = toolSummary(block);
2178
+ const body = [];
2179
+ if (block.argsFields?.length) {
2180
+ const rows = block.argsFields.map((f) => `<dt>${esc(f.key)}</dt><dd>${esc(f.value)}</dd>`).join("");
2181
+ body.push(`<dl class="kv">${rows}</dl>`);
2182
+ } else if (block.args) {
2183
+ body.push(`<pre class="out">${esc(block.args)}</pre>`);
2184
+ }
2185
+ if (block.result !== void 0) {
2186
+ if (block.result.trim()) {
2187
+ body.push(`<pre class="out">${esc(block.result)}</pre>`);
2188
+ } else {
2189
+ body.push('<div class="trunc-note">\uFF08\u65E0\u8F93\u51FA\uFF09</div>');
2190
+ }
2191
+ if (block.truncated) {
2192
+ body.push('<div class="trunc-note">\u5185\u5BB9\u5DF2\u6309\u6240\u9009\u7C92\u5EA6\u622A\u65AD</div>');
2193
+ }
2194
+ } else if (block.status === "pending") {
2195
+ body.push('<div class="trunc-note">\u4F1A\u8BDD\u5BFC\u51FA\u65F6\u8BE5\u8C03\u7528\u5C1A\u672A\u8FD4\u56DE</div>');
2196
+ }
2197
+ const stateText = block.status === "error" ? "\u5931\u8D25" : block.status === "pending" ? "\u672A\u5B8C\u6210" : "";
2198
+ return `<details class="process" data-kind="tool" data-tool="${esc(block.name)}">
2199
+ <summary><span class="sum-name">${esc(block.name)}</span><span class="sum-dot"></span><span class="sum-text">${esc(summaryText)}</span>${stateText ? `<span class="sum-state" data-status="${esc(block.status)}">${esc(stateText)}</span>` : ""}</summary>
2200
+ <div class="process-body">
2201
+ ${body.join("\n")}
2202
+ </div>
2203
+ </details>`;
2204
+ }
2205
+ function toolSummary(block) {
2206
+ const fields = block.argsFields ?? [];
2207
+ const preferred = ["description", "command", "file_path", "path", "pattern", "query", "url", "name", "prompt", "code"];
2208
+ for (const key of preferred) {
2209
+ const hit = fields.find((f) => f.key === key);
2210
+ if (hit && hit.value.trim()) return firstLine(hit.value, 110);
2211
+ }
2212
+ if (fields.length) {
2213
+ const first = fields[0];
2214
+ if (first && first.value.trim()) return firstLine(first.value, 110);
2215
+ }
2216
+ if (block.args) return firstLine(block.args, 110);
2217
+ return "";
2218
+ }
2219
+ function firstLine(text, max) {
2220
+ const line = text.split("\n").find((l) => l.trim())?.trim() ?? "";
2221
+ return line.length > max ? `${line.slice(0, max)}\u2026` : line;
2222
+ }
2223
+ function renderRetrieval(block) {
2224
+ const items = block.items.map((item) => {
2225
+ const href = item.url ? safeHref(item.url) : null;
2226
+ const titleHtml = href ? `<a href="${esc(href)}" class="ext" rel="noopener noreferrer" target="_blank">${esc(item.title)}</a>` : esc(item.title);
2227
+ const siteHtml = item.site ? `<div class="result-site">${esc(item.site)}</div>` : "";
2228
+ const snippetHtml = item.snippet ? `<div class="result-snippet">${esc(item.snippet)}</div>` : "";
2229
+ return `<li class="result"><div class="result-title">${titleHtml}</div>${siteHtml}${snippetHtml}</li>`;
2230
+ }).join("\n");
2231
+ const body = items ? `<ul class="results">${items}</ul>` : `<div class="md">${renderMarkdown(block.raw ?? "\uFF08\u65E0\u7ED3\u679C\uFF09")}</div>`;
2232
+ return renderDetails({
2233
+ kind: "retrieval",
2234
+ summary: block.query ? `\u68C0\u7D22\uFF1A${block.query}` : `\u68C0\u7D22\u7ED3\u679C\uFF08${block.items.length} \u6761\uFF09`,
2235
+ name: `${block.items.length} \u6761`,
2236
+ body
2237
+ });
2238
+ }
2239
+ function renderFiles(files) {
2240
+ const cards = files.map((f) => {
2241
+ const size = f.bytes !== void 0 ? formatBytes(f.bytes) : "";
2242
+ const meta = [f.type, size].filter(Boolean).join(" ");
2243
+ return `<div class="file-card"><span class="file-type">${esc(f.type.slice(0, 4))}</span><span class="file-body"><span class="file-name">${esc(basename(f.name))}</span><span class="file-meta">${esc(meta)}</span></span></div>`;
2244
+ }).join("");
2245
+ return `<div class="files">${cards}</div>`;
2246
+ }
2247
+ function basename(name) {
2248
+ const parts = name.split(/[\\/]/).filter(Boolean);
2249
+ return parts.length ? parts[parts.length - 1] ?? name : name;
2250
+ }
2251
+ function formatBytes(bytes) {
2252
+ if (!Number.isFinite(bytes) || bytes < 0) return "";
2253
+ if (bytes < 1024) return `${bytes} B`;
2254
+ const units = ["KB", "MB", "GB"];
2255
+ let value = bytes / 1024;
2256
+ let unit = 0;
2257
+ while (value >= 1024 && unit < units.length - 1) {
2258
+ value /= 1024;
2259
+ unit += 1;
2260
+ }
2261
+ return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
2262
+ }
2263
+ function presetLabel(preset) {
2264
+ switch (preset) {
2265
+ case "conversation":
2266
+ return "\u5BF9\u8BDD";
2267
+ case "process":
2268
+ return "\u8FC7\u7A0B";
2269
+ case "full":
2270
+ return "\u5B8C\u6574";
2271
+ default:
2272
+ return preset;
2273
+ }
2274
+ }
2275
+ function formatTime(epochMs, timeZone) {
2276
+ try {
2277
+ const parts = new Intl.DateTimeFormat("sv-SE", {
2278
+ year: "numeric",
2279
+ month: "2-digit",
2280
+ day: "2-digit",
2281
+ hour: "2-digit",
2282
+ minute: "2-digit",
2283
+ hour12: false,
2284
+ ...timeZone ? { timeZone } : {}
2285
+ }).formatToParts(new Date(epochMs));
2286
+ const get = (type) => parts.find((p) => p.type === type)?.value ?? "";
2287
+ const date = `${get("year")}-${get("month")}-${get("day")}`;
2288
+ const time = `${get("hour")}:${get("minute")}`;
2289
+ const zone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC";
2290
+ return `${date} ${time} (${zone})`;
2291
+ } catch {
2292
+ return new Date(epochMs).toISOString().replace("T", " ").slice(0, 16) + " (UTC)";
2293
+ }
2294
+ }
2295
+ function performanceNow() {
2296
+ const perf = globalThis.performance;
2297
+ return perf && typeof perf.now === "function" ? perf.now() : Date.now();
2298
+ }
2299
+ function dedupe(items) {
2300
+ const seen = /* @__PURE__ */ new Set();
2301
+ const out = [];
2302
+ for (const item of items) {
2303
+ if (!item || seen.has(item)) continue;
2304
+ seen.add(item);
2305
+ out.push(item);
2306
+ }
2307
+ return out;
2308
+ }
2309
+ function shareFilename(model, at, timeZone) {
2310
+ const slug = slugify(model.title).slice(0, 40) || "session";
2311
+ const id8 = (model.id || "unknown").replace(/^session-/, "").slice(0, 8) || "unknown";
2312
+ const stamp = filenameStamp(at, timeZone);
2313
+ return `share-${slug}-${id8}-${stamp}.html`;
2314
+ }
2315
+ function slugify(title) {
2316
+ return title.normalize("NFKC").replace(/[\\/:*?"<>|\s]+/g, "-").replace(/[^\p{L}\p{N}-]+/gu, "").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
2317
+ }
2318
+ function filenameStamp(epochMs, timeZone) {
2319
+ const parts = new Intl.DateTimeFormat("sv-SE", {
2320
+ year: "numeric",
2321
+ month: "2-digit",
2322
+ day: "2-digit",
2323
+ hour: "2-digit",
2324
+ minute: "2-digit",
2325
+ hour12: false,
2326
+ ...timeZone ? { timeZone } : {}
2327
+ }).formatToParts(new Date(epochMs));
2328
+ const get = (type) => parts.find((p) => p.type === type)?.value ?? "00";
2329
+ return `${get("year")}${get("month")}${get("day")}-${get("hour")}${get("minute")}`;
2330
+ }
2331
+
2332
+ // src/host/index.ts
2333
+ var VERSION = "0.1.0";
2334
+ function exportSession(input) {
2335
+ const preset = input.preset ?? "conversation";
2336
+ const opts = shareOptions(preset, input.options ?? {});
2337
+ const exportedAt = input.exportedAt;
2338
+ const model = project(input.events, {
2339
+ ...input.projectOptions ?? {},
2340
+ exportedAt,
2341
+ ...input.projectOptions?.title ? { title: input.projectOptions.title } : {}
2342
+ });
2343
+ const { model: pruned, stats: policy } = applySharePolicy(model, opts);
2344
+ const redacted = opts.redact ? redact(pruned, input.redactOptions ?? {}) : { model: pruned, stats: { hits: {}, total: 0, mode: input.redactOptions?.mode ?? "mask" } };
2345
+ const warnings = [];
2346
+ if (policy.truncated > 0) warnings.push(`${policy.truncated} block(s) truncated by share policy`);
2347
+ if (!opts.redact) warnings.push("unredacted");
2348
+ const render = renderHtml(redacted.model, {
2349
+ ...input.meta ?? {},
2350
+ version: VERSION,
2351
+ preset,
2352
+ redactions: redacted.stats.total,
2353
+ redacted: opts.redact,
2354
+ exportedAt,
2355
+ warnings
2356
+ });
2357
+ return {
2358
+ html: render.html,
2359
+ filename: shareFilename(redacted.model, exportedAt, input.meta?.timeZone),
2360
+ model,
2361
+ policy,
2362
+ redaction: redacted.stats,
2363
+ render: render.stats,
2364
+ warnings: render.warnings
2365
+ };
2366
+ }
2367
+
2368
+ // src/host/contract.ts
2369
+ var PRESETS = ["conversation", "process", "full"];
2370
+ var ContractError = class extends Error {
2371
+ code;
2372
+ constructor(code, message) {
2373
+ super(message);
2374
+ this.name = "ContractError";
2375
+ this.code = code;
2376
+ }
2377
+ };
2378
+ function isRecord(value) {
2379
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2380
+ }
2381
+ function rejectUnknown(prefix, input, allowed) {
2382
+ for (const key of Object.keys(input)) {
2383
+ if (!allowed.includes(key)) {
2384
+ throw new ContractError("unknown-field", `${prefix} \u4E0D\u63A5\u53D7\u5B57\u6BB5 "${key}"\uFF08\u5141\u8BB8\uFF1A${allowed.join(", ")}\uFF09`);
2385
+ }
2386
+ }
2387
+ }
2388
+ function optionalBoolean(prefix, input, key) {
2389
+ const value = input[key];
2390
+ if (value === void 0) return void 0;
2391
+ if (typeof value !== "boolean") throw new ContractError("bad-type", `${prefix}.${key} \u5FC5\u987B\u662F\u5E03\u5C14\u503C`);
2392
+ return value;
2393
+ }
2394
+ function optionalCount(prefix, input, key, max) {
2395
+ const value = input[key];
2396
+ if (value === void 0) return void 0;
2397
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > max) {
2398
+ throw new ContractError("bad-range", `${prefix}.${key} \u5FC5\u987B\u662F 0..${max} \u4E4B\u95F4\u7684\u6574\u6570`);
2399
+ }
2400
+ return value;
2401
+ }
2402
+ var INCLUDE_KEYS = [
2403
+ "reasoning",
2404
+ "retrieval",
2405
+ "toolCalls",
2406
+ "toolResults",
2407
+ "toolArgumentChars",
2408
+ "toolResultChars",
2409
+ "files",
2410
+ "deepResearch",
2411
+ "modelMeta"
2412
+ ];
2413
+ var REQUEST_KEYS = [
2414
+ "sessionId",
2415
+ "preset",
2416
+ "turns",
2417
+ "include",
2418
+ "redact",
2419
+ "redactMode",
2420
+ "redactEmail",
2421
+ "redactInternalIp"
2422
+ ];
2423
+ var MAX_TURNS = 1e4;
2424
+ var MAX_ARG_CHARS = 1e5;
2425
+ function parseRenderRequest(raw) {
2426
+ if (!isRecord(raw)) throw new ContractError("bad-shape", "\u8BF7\u6C42\u5FC5\u987B\u662F\u4E00\u4E2A\u5BF9\u8C61");
2427
+ rejectUnknown("\u8BF7\u6C42", raw, REQUEST_KEYS);
2428
+ const sessionId = raw.sessionId;
2429
+ if (typeof sessionId !== "string" || !sessionId.trim()) {
2430
+ throw new ContractError("bad-session", "sessionId \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");
2431
+ }
2432
+ if (!/^(?:session-)?[A-Za-z0-9_-]{8,128}$/.test(sessionId)) {
2433
+ throw new ContractError("bad-session", "sessionId \u5F62\u6001\u975E\u6CD5");
2434
+ }
2435
+ const preset = raw.preset;
2436
+ if (typeof preset !== "string" || !PRESETS.includes(preset)) {
2437
+ throw new ContractError("bad-preset", `preset \u5FC5\u987B\u662F ${PRESETS.join(" / ")} \u4E4B\u4E00`);
2438
+ }
2439
+ let turns;
2440
+ if (raw.turns !== void 0) {
2441
+ if (raw.turns === null) {
2442
+ turns = null;
2443
+ } else if (Array.isArray(raw.turns)) {
2444
+ if (raw.turns.length > MAX_TURNS) throw new ContractError("bad-turns", `turns \u6700\u591A ${MAX_TURNS} \u9879`);
2445
+ for (const t of raw.turns) {
2446
+ if (typeof t !== "number" || !Number.isInteger(t) || t < 1) {
2447
+ throw new ContractError("bad-turns", "turns \u53EA\u80FD\u5305\u542B >= 1 \u7684\u6574\u6570");
2448
+ }
2449
+ }
2450
+ turns = [...new Set(raw.turns)].sort((a, b) => a - b);
2451
+ } else {
2452
+ throw new ContractError("bad-turns", "turns \u5FC5\u987B\u662F\u6574\u6570\u6570\u7EC4\u6216 null");
2453
+ }
2454
+ }
2455
+ let include;
2456
+ if (raw.include !== void 0) {
2457
+ if (!isRecord(raw.include)) throw new ContractError("bad-include", "include \u5FC5\u987B\u662F\u5BF9\u8C61");
2458
+ rejectUnknown("include", raw.include, INCLUDE_KEYS);
2459
+ include = {};
2460
+ for (const key of ["reasoning", "retrieval", "toolCalls", "toolResults", "files", "deepResearch", "modelMeta"]) {
2461
+ const value = optionalBoolean("include", raw.include, key);
2462
+ if (value !== void 0) include[key] = value;
2463
+ }
2464
+ const argChars = optionalCount("include", raw.include, "toolArgumentChars", MAX_ARG_CHARS);
2465
+ if (argChars !== void 0) include.toolArgumentChars = argChars;
2466
+ const resChars = optionalCount("include", raw.include, "toolResultChars", MAX_ARG_CHARS);
2467
+ if (resChars !== void 0) include.toolResultChars = resChars;
2468
+ }
2469
+ const redact2 = optionalBoolean("\u8BF7\u6C42", raw, "redact");
2470
+ const redactEmail = optionalBoolean("\u8BF7\u6C42", raw, "redactEmail");
2471
+ const redactInternalIp = optionalBoolean("\u8BF7\u6C42", raw, "redactInternalIp");
2472
+ let redactMode;
2473
+ if (raw.redactMode !== void 0) {
2474
+ if (raw.redactMode !== "mask" && raw.redactMode !== "mask-hash") {
2475
+ throw new ContractError("bad-redact-mode", "redactMode \u5FC5\u987B\u662F mask \u6216 mask-hash");
2476
+ }
2477
+ redactMode = raw.redactMode;
2478
+ }
2479
+ const request = { sessionId, preset };
2480
+ if (turns !== void 0) request.turns = turns;
2481
+ if (include !== void 0 && Object.keys(include).length) request.include = include;
2482
+ if (redact2 !== void 0) request.redact = redact2;
2483
+ if (redactMode !== void 0) request.redactMode = redactMode;
2484
+ if (redactEmail !== void 0) request.redactEmail = redactEmail;
2485
+ if (redactInternalIp !== void 0) request.redactInternalIp = redactInternalIp;
2486
+ return request;
2487
+ }
2488
+ function parseCapabilitiesRequest(raw) {
2489
+ if (raw === void 0 || raw === null) return {};
2490
+ if (!isRecord(raw)) throw new ContractError("bad-shape", "capabilities \u4E0D\u63A5\u53D7\u53C2\u6570");
2491
+ const keys = Object.keys(raw);
2492
+ if (keys.length > 0) {
2493
+ throw new ContractError("bad-shape", `capabilities \u4E0D\u63A5\u53D7\u53C2\u6570\uFF08\u6536\u5230\uFF1A${keys.join(", ")}\uFF09`);
2494
+ }
2495
+ return {};
2496
+ }
2497
+ function errorResponse(error) {
2498
+ if (error instanceof ContractError) {
2499
+ return { __error: true, code: error.code, message: error.message };
2500
+ }
2501
+ const message = error instanceof Error ? error.message : String(error);
2502
+ return { __error: true, code: "internal", message };
2503
+ }
2504
+
2505
+ // src/host/session.ts
2506
+ var MAX_HTML_BYTES = 8 * 1024 * 1024;
2507
+ var MAX_EVENTS = 2e5;
2508
+ async function renderForRequest(ctx, rawRequest, options = {}) {
2509
+ try {
2510
+ const request = parseRenderRequest(rawRequest);
2511
+ const now = options.now ?? Date.now;
2512
+ const timeZone = options.timeZone ?? defaultTimeZone();
2513
+ const snapshot = await ctx.sessionQuery.readSession(request.sessionId);
2514
+ const events = toRawEvents(snapshot);
2515
+ let title;
2516
+ try {
2517
+ const snapshotTitle = await ctx.sessionQuery.readTitle?.(request.sessionId);
2518
+ const value = snapshotTitle?.title;
2519
+ if (value && typeof value === "string" && value.trim()) title = value.trim();
2520
+ } catch {
2521
+ }
2522
+ const truncatedEvents = events.length > MAX_EVENTS ? events.slice(0, MAX_EVENTS) : events;
2523
+ const warnings = [];
2524
+ if (truncatedEvents.length < events.length) {
2525
+ warnings.push(`\u4F1A\u8BDD\u4E8B\u4EF6\u8FC7\u591A\uFF0C\u4EC5\u5BFC\u51FA\u524D ${MAX_EVENTS} \u6761\uFF08\u5171 ${events.length} \u6761\uFF09`);
2526
+ }
2527
+ const shareOptions2 = {};
2528
+ if (request.turns !== void 0) shareOptions2.turns = request.turns;
2529
+ if (request.include) shareOptions2.include = { ...presetInclude(request.preset), ...request.include };
2530
+ if (request.redact !== void 0) shareOptions2.redact = request.redact;
2531
+ const out = exportSession({
2532
+ events: truncatedEvents,
2533
+ preset: request.preset,
2534
+ options: shareOptions2,
2535
+ redactOptions: {
2536
+ mode: request.redactMode ?? "mask",
2537
+ email: request.redactEmail ?? true,
2538
+ internalIp: request.redactInternalIp ?? true
2539
+ },
2540
+ projectOptions: {
2541
+ sessionId: request.sessionId,
2542
+ ...title ? { title } : {}
2543
+ },
2544
+ meta: { timeZone },
2545
+ exportedAt: now()
2546
+ });
2547
+ const bytes = Buffer.byteLength(out.html, "utf8");
2548
+ if (bytes > MAX_HTML_BYTES) {
2549
+ throw new Error(`\u4EA7\u7269 ${(bytes / 1024 / 1024).toFixed(1)}MB \u8D85\u8FC7 ${MAX_HTML_BYTES / 1024 / 1024}MB \u4E0A\u9650\uFF0C\u8BF7\u6539\u7528\u66F4\u5C0F\u7684\u7C92\u5EA6\u6216\u51CF\u5C11\u8F6E\u6B21`);
2550
+ }
2551
+ return {
2552
+ filename: out.filename,
2553
+ html: out.html,
2554
+ stats: {
2555
+ turns: out.render.turns,
2556
+ messages: out.render.messages,
2557
+ toolCalls: out.render.toolCalls,
2558
+ bytes,
2559
+ elapsedMs: out.render.elapsedMs
2560
+ },
2561
+ warnings: [...warnings, ...out.warnings],
2562
+ redaction: {
2563
+ total: out.redaction.total,
2564
+ mode: out.redaction.mode,
2565
+ hits: out.redaction.hits
2566
+ }
2567
+ };
2568
+ } catch (error) {
2569
+ return errorResponse(error);
2570
+ }
2571
+ }
2572
+ function capabilitiesForRequest(rawRequest) {
2573
+ try {
2574
+ parseCapabilitiesRequest(rawRequest);
2575
+ } catch (error) {
2576
+ return errorResponse(error);
2577
+ }
2578
+ const include = presetInclude("full");
2579
+ return {
2580
+ version: VERSION,
2581
+ presets: ["conversation", "process", "full"],
2582
+ includeKeys: Object.keys(include).filter((key) => key !== "fileBytes"),
2583
+ limits: { maxTurns: 1e4, maxArgChars: MAX_ARG_CHARS },
2584
+ fileBytes: false
2585
+ };
2586
+ }
2587
+ function toRawEvents(snapshot) {
2588
+ const events = Array.isArray(snapshot.events) ? snapshot.events : [];
2589
+ const out = [];
2590
+ for (const event of events) {
2591
+ if (!event || typeof event.type !== "string") continue;
2592
+ const raw = { type: event.type };
2593
+ if (typeof event.seq === "number") raw.seq = event.seq;
2594
+ if (typeof event.time === "number") raw.time = event.time;
2595
+ if (event.data !== void 0 && event.data !== null && typeof event.data === "object") {
2596
+ raw.data = event.data;
2597
+ }
2598
+ out.push(raw);
2599
+ }
2600
+ return out;
2601
+ }
2602
+ function defaultTimeZone() {
2603
+ try {
2604
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
2605
+ } catch {
2606
+ return void 0;
2607
+ }
2608
+ }
2609
+ function createHandlers(ctx, options = {}) {
2610
+ return {
2611
+ "share-html/capabilities": (args) => capabilitiesForRequest(args),
2612
+ "share-html/render": (args) => renderForRequest(ctx, args, options),
2613
+ "share-html/inspect": async (args) => {
2614
+ const result = await renderForRequest(ctx, args, options);
2615
+ if ("__error" in result) return result;
2616
+ return {
2617
+ filename: result.filename,
2618
+ stats: result.stats,
2619
+ warnings: result.warnings,
2620
+ redaction: { total: result.redaction.total, mode: result.redaction.mode }
2621
+ };
2622
+ }
2623
+ };
2624
+ }
2625
+ export {
2626
+ MAX_EVENTS,
2627
+ MAX_HTML_BYTES,
2628
+ capabilitiesForRequest,
2629
+ createHandlers,
2630
+ renderForRequest,
2631
+ toRawEvents
2632
+ };