File size: 35,011 Bytes
85270f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
import webConfig from "@/constants/common-env";

export type ChatRole = "user" | "assistant";

export type ChatAttachment = {
  id: string;
  name: string;
  type: string;
  size: number;
  dataUrl: string;
};

const CHAT_RASTER_IMAGE_MIME_TYPES = new Set([
  "image/png",
  "image/jpeg",
  "image/webp",
  "image/gif",
]);

export function isRasterImageMimeType(value: string) {
  return CHAT_RASTER_IMAGE_MIME_TYPES.has(String(value || "").split(";", 1)[0].trim().toLowerCase());
}

export function isImageAttachment(attachment: ChatAttachment) {
  const dataUrlMime = attachment.dataUrl.match(/^data:([^;,]+)/i)?.[1] || "";
  return isRasterImageMimeType(attachment.type) || isRasterImageMimeType(dataUrlMime);
}

export function resolveChatArtifactUrl(value: string) {
  const url = String(value || "").trim();
  if (!url.startsWith("/files/")) return url;
  const apiBase = webConfig.apiUrl.replace(/\/$/, "");
  return apiBase ? `${apiBase}${url}` : url;
}

export type ChatCitation = {
  title: string;
  url: string;
};

export type ChatToolPart = {
  type: "tool";
  toolId: string;
  invocationId: string;
  status: "pending" | "running" | "success" | "error";
  title: string;
  input?: unknown;
  output?: unknown;
  error?: string;
};

export type ChatGeneratedImage = {
  id: string;
  src: string;
  prompt: string;
  revisedPrompt?: string;
  size?: string;
  model?: string;
  origin?: "generated" | "search";
  sourceUrl?: string;
};

export type ChatPlace = {
  id: string;
  title: string;
  address: string;
};

export type ChatPlacePart = {
  type: "place";
  places: ChatPlace[];
};

export type ChatDilCardRow = {
  title: string;
  badge?: string;
  badgeTone?: "success" | "warning" | "info";
  subtitle?: string;
  description?: string;
};

export type ChatInlineSegment =
  | { type: "text"; content: string }
  | { type: "place"; places: ChatPlace[] }
  | { type: "image_carousel"; queries: string[]; aspectRatio: string }
  | { type: "question_card"; questions: { question: string; options: string[] }[] }
  | { type: "card_list"; rows: ChatDilCardRow[] };

export type ChatRichTextPart = {
  type: "rich_text";
  segments: ChatInlineSegment[];
};

function jsonValueAt(text: string, start: number): { value: unknown; end: number } | null {
  const opening = text[start];
  const closing = opening === "[" ? "]" : opening === "{" ? "}" : "";
  if (!closing) return null;
  let depth = 0;
  let quote = "";
  let escaped = false;
  for (let index = start; index < text.length; index += 1) {
    const character = text[index];
    if (quote) {
      if (escaped) escaped = false;
      else if (character === "\\") escaped = true;
      else if (character === quote) quote = "";
      continue;
    }
    if (character === '"' || character === "'") {
      quote = character;
      continue;
    }
    if (character === opening) depth += 1;
    if (character === closing) {
      depth -= 1;
      if (depth === 0) {
        try {
          return { value: JSON.parse(text.slice(start, index + 1)), end: index + 1 };
        } catch {
          return null;
        }
      }
    }
  }
  return null;
}

/**
 * ChatGPT 网页端新上的 DIL 声明式卡片标记(<box>/<row>/<AsyncImage>/<Entity>/<badge>/
 * <radio-group> + {@body} 状态 + GenUI.issueNewTurn)。这套协议只有官方前端认识,直接渲染
 * 会漏出原始标签。这里做一层降级转换:
 * - {@body} 状态声明、MapWidgetV2/Cite/AsyncImage 等无法本地复刻的组件 → 剥掉;
 * - badge/Entity/text/divider → 等价 markdown;
 * - radio-group 问卷(含前面的 `<text weight="medium">N. 问题</text>` 标题)→ 抽成
 *   question_card,复用站内可点选项卡片。
 */
function convertDilMarkup(raw: string): {
  text: string;
  questions: { question: string; options: string[] }[];
  cards: ChatDilCardRow[];
} {
  const text = String(raw || "");
  if (!/<{@body|<radio-group|<MapWidgetV2|<AsyncImage|<Cite|<Entity|<box[\s>]/.test(text)) {
    return { text, questions: [], cards: [] };
  }
  const questions: { question: string; options: string[] }[] = [];
  const cards: ChatDilCardRow[] = [];
  const cardMarker = (index: number) => `\u0000DILCARD${index}\u0000`;
  // 0) 抽卡片列表:`<row>`(推荐条目,行间以 divider 分隔)。行内含标题(bold+Entity)、
  //    badge、灰色副标题(text color=secondary)、描述正文。转成结构化 rows,原位置留标记。
  const withRows = text.replace(
    /<row[^>]*>([\s\S]*?)<\/row>/g,
    (rowMatch: string, rowBody: string) => {
      const titleMatch = rowBody.match(/\*\*([\s\S]*?)\*\*/);
      const title = titleMatch
        ? titleMatch[1]
            .replace(/<Entity[^>]*?value="([^"]*)"[^>]*\/>/g, "$1")
            .replace(/<[^>]+>/g, "")
            .trim()
        : "";
      if (!title) return rowMatch;
      const badgeMatch = rowBody.match(/<badge[^>]*color="([^"]*)"[^>]*>([\s\S]*?)<\/badge>/);
      const subtitleMatch = rowBody.match(/<text[^>]*color="secondary"[^>]*>([\s\S]*?)<\/text>/);
      const description = rowBody
        .replace(/\*\*[\s\S]*?\*\*/g, "")
        .replace(/<AsyncImage[^>]*\/>/g, "")
        .replace(/<Cite[^>]*\/>/g, "")
        .replace(/<badge[\s\S]*?<\/badge>/g, "")
        .replace(/<Entity[^>]*?\/>/g, "")
        .replace(/<text[^>]*color="secondary"[^>]*>[\s\S]*?<\/text>/g, "")
        .replace(/<[^>]+>/g, " ")
        .replace(/[ \t]+/g, " ")
        .replace(/\s*\n\s*/g, " ")
        .trim();
      const tone = String(badgeMatch?.[1] || "");
      cards.push({
        title,
        badge: badgeMatch ? badgeMatch[2].trim() : undefined,
        badgeTone: tone === "success" ? "success" : tone === "warning" ? "warning" : tone ? "info" : undefined,
        subtitle: subtitleMatch ? subtitleMatch[1].trim() : undefined,
        description: description || undefined,
      });
      return cardMarker(cards.length - 1);
    },
  );
  // 1) 抽问卷:`<text weight="medium">N. 问题</text>` 紧跟 `<radio-group>…<radio>label</radio>…</radio-group>`。
  const withQuestions = withRows.replace(
    /<text[^>]*weight="medium"[^>]*>\s*([^<]+?)\s*<\/text>\s*<radio-group[^>]*>([\s\S]*?)<\/radio-group>/g,
    (_match, questionText: string, groupBody: string) => {
      const options: string[] = [];
      const radioPattern = /<radio[^>]*>([\s\S]*?)<\/radio>/g;
      let radioMatch: RegExpExecArray | null;
      while ((radioMatch = radioPattern.exec(groupBody))) {
        const label = radioMatch[1].trim();
        if (label) options.push(label);
      }
      const question = String(questionText || "").trim();
      if (question && options.length) questions.push({ question, options });
      return "";
    },
  );
  let working = withQuestions
    // 行间 divider(marker 夹着 divider)不转成 `---`,卡片组件自带分隔线;须在通用 divider 规则之前。
    .replace(/(\u0000DILCARD\d+\u0000)\s*<divider[^>]*\/>/g, "$1")
    .replace(/<divider[^>]*\/>\s*(?=\u0000DILCARD)/g, "")
    .replace(/\{@body[^}]*\}\n?/g, "") // 状态声明
    .replace(/<MapWidgetV2[\s\S]*?\/>/g, "") // 官方地图组件(无本地等价物)
    .replace(/<\/?MapWidgetV2[^>]*>/g, "")
    .replace(/<Cite[^>]*\/>/g, "") // 官方引用角标(ref 只在官方会话里有意义)
    .replace(/<AsyncImage[^>]*\/>/g, "") // 官方图片搜索占位(本站无按 query 拉图管道)
    .replace(/<button[^>]*>[\s\S]*?<\/button>/g, "") // GenUI.issueNewTurn 按钮(交互已由 question_card 承担)
    .replace(/<badge[^>]*>([\s\S]*?)<\/badge>/g, "「$1」")
    .replace(/<Entity[^>]*?value="([^"]*)"[^>]*\/>/g, "$1")
    .replace(/<text[^>]*>([\s\S]*?)<\/text>/g, "$1")
    .replace(/<divider[^>]*\/>/g, "\n---\n")
    .replace(/<\/?(?:box|row|button|radio-group|radio|text|badge|entity|MapWidgetV2)[^>]*>/g, "")
    .replace(/\n{3,}/g, "\n\n")
    .trim();
  if (!working && (questions.length || cards.length)) working = "";
  return { text: working, questions, cards };
}

/** Convert ChatGPT web-client place/card directives into portable UI data. */
export function parseInlineRichContent(value: string): { content: string; places: ChatPlace[]; segments: ChatInlineSegment[]; hasWidgets: boolean } {
  const dil = convertDilMarkup(value);
  const text = dil.text;
  const places: ChatPlace[] = [];
  const seen = new Set<string>();
  const segments: ChatInlineSegment[] = [];
  const cardMarkerPattern = /\u0000DILCARD(\d+)\u0000/g;
  const addText = (content: string) => {
    if (!content) return;
    // DIL 卡片列表在文本里的占位标记 → 拆开成 text/card_list 段(保留在原文中的位置)。
    cardMarkerPattern.lastIndex = 0;
    let last = 0;
    let markerMatch: RegExpExecArray | null;
    while ((markerMatch = cardMarkerPattern.exec(content))) {
      if (markerMatch.index > last) segments.push({ type: "text", content: content.slice(last, markerMatch.index) });
      const rows = dil.cards[Number(markerMatch[1])];
      if (rows) segments.push({ type: "card_list", rows: [rows] });
      last = markerMatch.index + markerMatch[0].length;
    }
    if (last < content.length) segments.push({ type: "text", content: content.slice(last) });
  };
  let cursor = 0;
  while (cursor < text.length) {
    const match = /[\[{]/.exec(text.slice(cursor));
    if (!match) {
      addText(text.slice(cursor));
      break;
    }
    const start = cursor + match.index;
    addText(text.slice(cursor, start));
    const parsed = jsonValueAt(text, start);
    if (!parsed) {
      addText(text[start]);
      cursor = start + 1;
      continue;
    }
    const { value: item, end } = parsed;
    const isPlace = Array.isArray(item) && String(item[0] || "").toLowerCase() === "point_of_interest";
    const isCarousel = !Array.isArray(item)
      && Boolean(item)
      && typeof item === "object"
      && Array.isArray((item as { query?: unknown }).query);
    if (isPlace) {
      const title = String(item[1] || "").trim();
      const address = String(item[2] || "").trim();
      const key = `${title}\u0000${address}`;
      if (title && !seen.has(key)) {
        seen.add(key);
        const place = { id: `inline-place-${places.length + 1}`, title, address };
        places.push(place);
        segments.push({ type: "place", places: [place] });
      }
      cursor = end;
      continue;
    }
    if (isCarousel) {
      const metadata = item as { query?: unknown; aspect_ratio?: unknown };
      const queries = (metadata.query as unknown[]).map((query) => String(query || "").trim()).filter(Boolean);
      if (queries.length) {
        segments.push({ type: "image_carousel", queries, aspectRatio: String(metadata.aspect_ratio || "16:9").trim() || "16:9" });
      }
      cursor = end;
      continue;
    }
    // 上游模型偶尔会按 ChatGPT 官方客户端的「小程序块」习惯输出 {"app_block":{title,variant,icon,content}}
    // (content 是一段可交互 HTML,通常带 <canvas>/<script>)。本站没有这个协议,直接渲染会漏出
    // 一坨转义 JSON;这里把它转成 ```html 围栏,交给 AssistantMarkdown 的 CodeBlock —— 那边已有
    // sandbox="allow-scripts" 的交互式 iframe 预览(CSP 允许内联脚本),游戏/小工具可以直接玩。
    const isAppBlock = !Array.isArray(item) && Boolean(item) && typeof item === "object"
      && "app_block" in (item as Record<string, unknown>);
    if (isAppBlock) {
      const block = ((item as { app_block?: unknown }).app_block || {}) as { title?: unknown; content?: unknown };
      const html = String(block.content || "").trim();
      if (html) {
        const title = String(block.title || "").trim();
        addText(`\n\n${title ? `**${title}**\n\n` : ""}\`\`\`html\n${html}\n\`\`\`\n\n`);
        cursor = end;
        continue;
      }
    }
    // 本站自有的「澄清选择题」协议(仿官网 canvas 流程的问卷卡片):模型对含糊的应用/游戏请求
    // 先输出 {"question_card":{"questions":[{"question":"...","options":["..."]}]}},
    // 前端渲染成可点击的选项卡片,点选项即以该文本作为用户消息发送。
    const isQuestionCard = !Array.isArray(item) && Boolean(item) && typeof item === "object"
      && "question_card" in (item as Record<string, unknown>);
    if (isQuestionCard) {
      const card = ((item as { question_card?: unknown }).question_card || {}) as {
        questions?: unknown; question?: unknown; options?: unknown;
      };
      const rawQuestions: unknown[] = Array.isArray(card.questions) && card.questions.length
        ? card.questions
        : (card.question ? [card] : []);
      const questions = rawQuestions
        .map((entry) => {
          const q = (entry || {}) as { question?: unknown; options?: unknown };
          return {
            question: String(q.question || "").trim(),
            options: (Array.isArray(q.options) ? q.options : [])
              .map((option) => String(option || "").trim())
              .filter(Boolean)
              .slice(0, 6),
          };
        })
        .filter((q) => q.question && q.options.length)
        .slice(0, 3);
      if (questions.length) {
        segments.push({ type: "question_card", questions });
        cursor = end;
        continue;
      }
    }
    addText(text.slice(start, end));
    cursor = end;
  }
  if (dil.questions.length && !segments.some((segment) => segment.type === "question_card")) {
    segments.push({ type: "question_card", questions: dil.questions });
  }
  // 相邻的 DIL 卡片行合并成一个 card_list(官方是一个 box 里 divider 分行);中间的纯空白文本段丢弃。
  const mergedSegments: ChatInlineSegment[] = [];
  for (const segment of segments) {
    const last = mergedSegments[mergedSegments.length - 1];
    if (segment.type === "text" && !segment.content.trim() && last?.type === "card_list") continue;
    if (segment.type === "card_list" && last?.type === "card_list") {
      last.rows.push(...segment.rows);
      continue;
    }
    mergedSegments.push(segment);
  }
  const content = mergedSegments
    .filter((segment): segment is Extract<ChatInlineSegment, { type: "text" }> => segment.type === "text")
    .map((segment) => segment.content)
    .join("")
    .replace(/\n{3,}/g, "\n\n")
    .trim();
  return { content, places, segments: mergedSegments, hasWidgets: mergedSegments.some((segment) => segment.type !== "text") };
}

export function extractInlinePlaceCards(value: string): { content: string; places: ChatPlace[] } {
  const parsed = parseInlineRichContent(value);
  return { content: parsed.content, places: parsed.places };
}

export type ChatImagePart = {
  type: "image";
  images: ChatGeneratedImage[];
};

export type ChatTextPart = {
  type: "text";
  text: string;
};

export type ChatReasoningPart = {
  type: "reasoning";
  title: string;
  summary: string;
  status: "running" | "complete" | "error";
};

export type ChatSkillRunStage = "preparing" | "awaiting_input" | "reading" | "executing" | "postprocessing" | "complete" | "error";

export type ChatSkillRunPart = {
  type: "skill_run";
  runId: string;
  skillId: string;
  skillName: string;
  stage: ChatSkillRunStage;
  status: "running" | "complete" | "error";
  summary: string;
  completed?: number;
  total?: number;
  failed?: number;
  startedAt: string;
  updatedAt: string;
  tools?: ChatToolPart[];
  error?: string;
};

/** 「生成式 UI」消息片段:模型输出 OpenUI Lang 1.0,由渲染器解析成交互式界面。 */
export type ChatGenerativeUiPart = {
  type: "generative_ui";
  /** OpenUI Lang 1.0 源码。 */
  source: string;
};

export type ChatMessagePart = ChatTextPart | ChatToolPart | ChatImagePart | ChatPlacePart | ChatRichTextPart | ChatReasoningPart | ChatSkillRunPart | ChatGenerativeUiPart;

export type ChatMessage = {
  id: string;
  role: ChatRole;
  content: string;
  attachments: ChatAttachment[];
  parts: ChatMessagePart[];
  citations: ChatCitation[];
  createdAt: string;
  status?: "sending" | "complete" | "error";
  error?: string;
  requestMode?: ChatCapabilityMode;
};

export type ChatReasoningEffort = "" | "low" | "medium" | "high" | "xhigh";
export type ChatCapabilityMode = "auto" | "chat" | "web_search" | "image_generation";

export type ChatConversation = {
  id: string;
  title: string;
  model: string;
  reasoningEffort: ChatReasoningEffort;
  createdAt: string;
  updatedAt: string;
  messages: ChatMessage[];
};

export type ChatCompletionResponse = {
  choices?: Array<{
    message?: {
      role?: string;
      content?: unknown;
      attachments?: Array<{
        id?: string;
        name?: string;
        type?: string;
        size?: number;
        url?: string;
        preview_url?: string;
        download_url?: string;
        data_url?: string;
      }>;
      images?: Array<{
        id?: string;
        title?: string;
        content_url?: string;
        thumbnail_url?: string;
        source_url?: string;
        query?: string;
        width?: number;
        height?: number;
      }>;
      places?: Array<{
        id?: string;
        title?: string;
        address?: string;
      }>;
      annotations?: Array<{
        type?: string;
        url_citation?: {
          title?: string;
          url?: string;
        };
      }>;
    };
  }>;
};

export type ChatCapability = {
  id: string;
  kind: "builtin" | "skill";
  title: string;
  description: string;
  enabled: boolean;
  command?: string;
};

/**
 * The chat surface consumes capabilities through this stable contract. Search,
 * installed skills and other tools can be registered later without coupling
 * their transport or result UI to the page component.
 */
export const CHAT_CAPABILITIES: readonly ChatCapability[] = [
  {
    id: "web_search",
    kind: "builtin",
    title: "联网搜索",
    description: "搜索互联网并在回复中附带来源",
    enabled: true,
    command: "$搜索",
  },
  {
    id: "image_generation",
    kind: "builtin",
    title: "图片生成 / 编辑",
    description: "生成图片;上传参考图后自动改用图片编辑",
    enabled: true,
    command: "$生图",
  },
];

function textFromUnknownContent(value: unknown): string {
  if (typeof value === "string") return value;
  if (!Array.isArray(value)) return "";
  return value
    .map((part) => {
      if (typeof part === "string") return part;
      if (!part || typeof part !== "object") return "";
      const item = part as { type?: unknown; text?: unknown; content?: unknown };
      if (["text", "output_text"].includes(String(item.type || ""))) {
        return String(item.text || item.content || "");
      }
      return "";
    })
    .join("");
}

export function normalizeAssistantContent(value: unknown): string {
  const text = textFromUnknownContent(value).replace(/^\uFEFF/, "").trim();
  if (!text) return "";
  // Some compatible providers expose hidden reasoning in their text payload.
  // Keep the user-facing answer while avoiding a raw <think> block in Markdown.
  return text.replace(/<think>[\s\S]*?<\/think>/gi, "").trim();
}

function utf8DataUrl(type: string, source: string) {
  return `data:${type};charset=utf-8,${encodeURIComponent(source)}`;
}

function safeArtifactStem(value: string, fallback: string) {
  const stem = value
    .replace(/[<>:"/\\|?*\u0000-\u001f]/g, " ")
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, 64);
  return stem || fallback;
}

/**
 * Compatible providers do not always expose generated files through the
 * message.attachments protocol. Preserve the real source in that case by
 * materialising complete inline SVG/HTML documents as browser attachments.
 */
function materializeInlineArtifacts(content: string): { content: string; attachments: ChatAttachment[] } {
  let display = content;
  const attachments: ChatAttachment[] = [];
  const candidates: Array<{ kind: "svg" | "html"; source: string; fullMatch: string }> = [];
  const fencedPattern = /```(?:svg|xml|html)\s*\n([\s\S]*?)```/gi;
  for (const match of content.matchAll(fencedPattern)) {
    const source = String(match[1] || "").trim();
    const kind = /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(source) ? "html" : "svg";
    if ((kind === "svg" && /<svg[\s>][\s\S]*<\/svg>/i.test(source))
      || (kind === "html" && /<html[\s>][\s\S]*<\/html>/i.test(source))) {
      candidates.push({ kind, source, fullMatch: match[0] });
    }
  }
  if (!candidates.length) {
    const svg = content.match(/<svg[\s>][\s\S]*?<\/svg>/i);
    if (svg?.[0] && svg[0].length >= 120) candidates.push({ kind: "svg", source: svg[0], fullMatch: svg[0] });
    const html = content.match(/(?:<!doctype\s+html[^>]*>\s*)?<html[\s>][\s\S]*?<\/html>/i);
    if (html?.[0] && html[0].length >= 160) candidates.push({ kind: "html", source: html[0], fullMatch: html[0] });
  }
  for (const [index, candidate] of candidates.entries()) {
    const label = candidate.kind === "svg"
      ? candidate.source.match(/aria-label=["']([^"']+)["']/i)?.[1]
      : candidate.source.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1];
    const extension = candidate.kind === "svg" ? "svg" : "html";
    const type = candidate.kind === "svg" ? "image/svg+xml" : "text/html";
    attachments.push({
      id: createChatId(`inline-${extension}`),
      name: `${safeArtifactStem(label || "", `generated-${extension}-${index + 1}`)}.${extension}`,
      type,
      size: new TextEncoder().encode(candidate.source).byteLength,
      dataUrl: utf8DataUrl(type, candidate.source),
    });
    display = display.replace(candidate.fullMatch, `\n\n[已提取完整 ${extension.toUpperCase()} 成品,可在下方预览或下载。]\n\n`);
  }
  return { content: display.replace(/\n{3,}/g, "\n\n").trim(), attachments };
}

export function parseChatCompletionResponse(response: ChatCompletionResponse) {
  const message = response.choices?.[0]?.message;
  let content = normalizeAssistantContent(message?.content);
  const inlineRichContent = parseInlineRichContent(content);
  content = inlineRichContent.content;
  const citationMap = new Map<string, ChatCitation>();
  for (const annotation of message?.annotations || []) {
    if (annotation?.type !== "url_citation") continue;
    const url = String(annotation.url_citation?.url || "").trim();
    if (!/^https?:\/\//i.test(url) || citationMap.has(url)) continue;
    citationMap.set(url, {
      url,
      title: String(annotation.url_citation?.title || url).trim() || url,
    });
  }
  const attachments = (message?.attachments || []).flatMap((item, index) => {
    const dataUrl = resolveChatArtifactUrl(String(item.data_url || item.preview_url || item.download_url || item.url || "").trim());
    if (!dataUrl || !(/^(?:data:|https?:\/\/|\/)/i.test(dataUrl))) return [];
    const name = String(item.name || `artifact-${index + 1}`).trim() || `artifact-${index + 1}`;
    return [{
      id: String(item.id || createChatId("artifact")),
      name,
      type: String(item.type || "application/octet-stream"),
      size: Number(item.size) || 0,
      dataUrl,
    } satisfies ChatAttachment];
  });
  if (!attachments.some((attachment) => /\.(?:svg|html?)$/i.test(attachment.name))) {
    const inline = materializeInlineArtifacts(content);
    content = inline.content;
    attachments.push(...inline.attachments);
  }
  const images = (message?.images || []).flatMap((item, index) => {
    const src = String(item.content_url || item.thumbnail_url || "").trim();
    if (!/^https?:\/\//i.test(src)) return [];
    return [{
      id: String(item.id || createChatId("search-image")),
      src,
      prompt: String(item.query || item.title || `搜索图片 ${index + 1}`).trim(),
      revisedPrompt: String(item.title || item.query || "搜索图片").trim(),
      origin: "search" as const,
      sourceUrl: String(item.source_url || "").trim() || undefined,
    } satisfies ChatGeneratedImage];
  });
  const places = (message?.places || []).flatMap((item, index) => {
    const title = String(item.title || "").trim();
    if (!title) return [];
    return [{
      id: String(item.id || `place-${index + 1}`),
      title,
      address: String(item.address || "").trim(),
    } satisfies ChatPlace];
  });
  for (const place of inlineRichContent.places) {
    if (!places.some((item) => item.title === place.title && item.address === place.address)) places.push(place);
  }
  if (!images.length) {
    const fallbackUrls = new Set<string>();
    const addImageUrl = (rawUrl: string) => {
      const url = rawUrl.trim().replace(/[`'"),.;]+$/g, "");
      if (/^https?:\/\/[^\s]+\.(?:png|jpe?g|webp|gif)(?:\?[^\s]*)?$/i.test(url)) fallbackUrls.add(url);
    };
    for (const citation of citationMap.values()) addImageUrl(citation.url);
    for (const match of content.matchAll(/https?:\/\/[^\s<>"']+/gi)) addImageUrl(match[0]);
    let index = 0;
    for (const url of fallbackUrls) {
      index += 1;
      const matchingCitation = Array.from(citationMap.values()).find((citation) => citation.url.replace(/[`'"),.;]+$/g, "") === url);
      images.push({
        id: createChatId("search-image"),
        src: url,
        prompt: matchingCitation?.title || `搜索图片 ${index}`,
        revisedPrompt: matchingCitation?.title || `搜索图片 ${index}`,
        origin: "search",
        sourceUrl: matchingCitation?.url || url,
      });
    }
  }
  return { content, citations: Array.from(citationMap.values()), attachments, images, places, inlineSegments: inlineRichContent.segments, hasInlineWidgets: inlineRichContent.hasWidgets };
}

const CHAT_SURFACE_SYSTEM_PROMPT = `This is a full chat workspace with managed artifact previews and downloads.
When the user asks you to create or modify a file, create the real file in /mnt/data and include its sandbox:/mnt/data/... link in the final answer. Never claim a file exists without returning that link.
When the user requests complete source or content that is too long for one reply, put the complete content in the generated file; do not refuse because of message length. Briefly explain that the full content is available through the artifact's preview/source view.
Attachments identified by <conversation_artifact_context> were generated by you earlier in this same conversation. Inspect their actual contents and treat short follow-ups such as "continue", "optimize it", or "modify this" as referring to the most recent matching artifact.
Structured data inside <search_result_context> comes from an earlier web search in this same local conversation. Preserve its displayed order and use its exact titles, source URLs, and direct image URLs when the user refers to prior search results or asks for an artifact built from them.
Satisfy every requested modification before returning the artifact.
When you want to include an interactive app, game, or widget in the reply, return it as one complete \`\`\`html code block (the UI renders it as a sandboxed interactive preview). Do not wrap it in {"app_block": ...} or any other custom JSON envelope.
For an app, game, or widget request that leaves key choices open (such as game type, visual style, controls, or where it should run), do NOT guess and build immediately. First reply with one short lead-in sentence followed by exactly one JSON object on its own line: {"question_card":{"questions":[{"question":"...","options":["...","..."]}]}} — at most 2 questions, 3-4 short options each (the UI renders them as clickable choice cards). Do not wrap it in any other envelope and do not emit extra JSON objects. The user may answer with one numbered line per question. Skip the questions entirely when the request is already specific. Once the user answers, build the complete \`\`\`html code block in one go.`;

function toolExecutionContext(message: ChatMessage) {
  const tools = message.parts
    .filter((part): part is ChatToolPart => part.type === "tool")
    .map((part) => ({
      tool_id: part.toolId,
      status: part.status,
      input: part.input,
      output: part.output,
      error: part.error,
    }));
  if (!tools.length) return "";
  const serialized = JSON.stringify(tools);
  return `<tool_execution_context>\n${serialized.slice(0, 16000)}\n</tool_execution_context>`;
}

const MAX_SEARCH_CONTEXT_CHARS = 16_000;
const MAX_TOTAL_SEARCH_CONTEXT_CHARS = 24_000;
const MAX_SEARCH_CONTEXT_CITATIONS = 12;
const MAX_SEARCH_CONTEXT_IMAGES = 8;

function boundedSearchText(value: unknown, maxLength: number) {
  return String(value || "").trim().slice(0, maxLength);
}

function searchResultContext(message: ChatMessage) {
  const citations = message.citations
    .slice(0, MAX_SEARCH_CONTEXT_CITATIONS)
    .map((citation, index) => ({
      position: index + 1,
      title: boundedSearchText(citation.title, 300),
      url: boundedSearchText(citation.url, 1_200),
    }));
  const images = message.parts
    .filter((part): part is ChatImagePart => part.type === "image")
    .flatMap((part) => part.images)
    .filter((image) => image.origin === "search")
    .slice(0, MAX_SEARCH_CONTEXT_IMAGES)
    .map((image, index) => ({
      position: index + 1,
      title: boundedSearchText(image.revisedPrompt || image.prompt, 300),
      query: boundedSearchText(image.prompt, 500),
      image_url: boundedSearchText(image.src, 1_500),
      source_url: boundedSearchText(image.sourceUrl, 1_200),
    }));
  if (!citations.length && !images.length) return "";

  const payload = {
    description: "Structured results from an earlier web search in this local conversation. Use these exact titles and URLs for follow-up questions and requested artifacts. Positions are one-based and preserve the displayed order.",
    citations,
    images,
  };
  let serialized = JSON.stringify(payload);
  while (serialized.length > MAX_SEARCH_CONTEXT_CHARS && (citations.length > 1 || images.length > 1)) {
    if (citations.length > images.length && citations.length > 1) citations.pop();
    else if (images.length > 1) images.pop();
    else citations.pop();
    serialized = JSON.stringify(payload);
  }
  return `<search_result_context>\n${serialized.slice(0, MAX_SEARCH_CONTEXT_CHARS)}\n</search_result_context>`;
}

function recentSearchResultContexts(messages: ChatMessage[]) {
  const contexts = new Map<string, string>();
  let remainingChars = MAX_TOTAL_SEARCH_CONTEXT_CHARS;
  for (const message of [...messages].reverse()) {
    if (message.role !== "assistant") continue;
    const context = searchResultContext(message);
    if (!context) continue;
    if (context.length > remainingChars) break;
    contexts.set(message.id, context);
    remainingChars -= context.length;
  }
  return contexts;
}

export function buildChatCompletionMessages(
  messages: ChatMessage[],
  options: { includePriorImages?: boolean } = {},
) {
  const lastUserIndex = messages.findLastIndex((message) => message.role === "user" && message.status !== "error");
  const latestGeneratedImages = options.includePriorImages ? messages
    .slice(0, Math.max(0, lastUserIndex))
    .reverse()
    .flatMap((message) => [...message.parts].reverse())
    .find((part): part is ChatImagePart => part.type === "image" && part.images.some((image) => image.origin !== "search"))
    ?.images.filter((image) => image.origin !== "search") || [] : [];
  const latestUploadedImages = options.includePriorImages
    ? [...messages.slice(0, Math.max(0, lastUserIndex))]
        .reverse()
        .find((message) => message.role === "user" && message.attachments.some(isImageAttachment))
        ?.attachments.filter(isImageAttachment) || []
    : [];
  const searchContexts = recentSearchResultContexts(messages);

  const conversationMessages = messages
    .filter((message) => message.status !== "error")
    .map((message) => {
      const messageIndex = messages.indexOf(message);
      const isLatestUser = message.role === "user" && messageIndex === lastUserIndex;
      const contextImages = isLatestUser ? latestGeneratedImages.slice(0, 4) : [];
      const contextUploads = isLatestUser ? latestUploadedImages.slice(0, Math.max(0, 4 - contextImages.length)) : [];
      if (isLatestUser && (message.attachments.length > 0 || contextImages.length > 0 || contextUploads.length > 0)) {
        const imageAttachments = message.attachments.filter(isImageAttachment);
        const fileAttachments = message.attachments.filter((attachment) => !isImageAttachment(attachment));
        return {
          role: message.role,
          content: [
            ...(message.content.trim()
              ? [{ type: "text" as const, text: message.content }]
              : []),
            ...(contextImages.length
              ? [{ type: "text" as const, text: "以下是本对话中助手最近生成的图片,请在回答和后续修改时继续参考这些图片。" }]
              : []),
            ...imageAttachments.map((attachment) => ({
              type: "image_url" as const,
              image_url: { url: attachment.dataUrl },
            })),
            ...fileAttachments.map((attachment) => ({
              type: "file" as const,
              file: {
                filename: attachment.name,
                file_data: attachment.dataUrl,
              },
            })),
            ...contextImages.map((image) => ({
              type: "image_url" as const,
              image_url: { url: image.src },
            })),
            ...contextUploads.map((attachment) => ({
              type: "image_url" as const,
              image_url: { url: attachment.dataUrl },
            })),
          ],
        };
      }
      if (message.role === "user" && message.attachments.length > 0) {
        const attachmentNames = message.attachments.map((attachment) => attachment.name).filter(Boolean);
        return {
          role: message.role,
          content: [
            message.content,
            attachmentNames.length ? `[Earlier attachments: ${attachmentNames.join(", ")}]` : "",
          ].filter(Boolean).join("\n\n"),
        };
      }
      const assistantContexts = message.role === "assistant"
        ? [toolExecutionContext(message), searchContexts.get(message.id)].filter(Boolean)
        : [];
      return {
        role: message.role,
        content: [message.content, ...assistantContexts].filter(Boolean).join("\n\n"),
      };
    });
  return [
    { role: "system" as const, content: CHAT_SURFACE_SYSTEM_PROMPT },
    ...conversationMessages,
  ];
}

export function createChatId(prefix: string) {
  const id = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
    ? crypto.randomUUID()
    : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
  return `${prefix}-${id}`;
}

export function createConversationTitle(text: string, hasImages = false) {
  const normalized = text.replace(/\s+/g, " ").trim();
  if (!normalized) return hasImages ? "图片对话" : "新对话";
  return normalized.length > 26 ? `${normalized.slice(0, 26)}…` : normalized;
}