Spaces:
Running

File size: 48,648 Bytes
1d919a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
// A continuing chain for one hard task. The MoE gate's think bit (router.js)
// starts it. Each step stays in the same trace, a tool result comes back into
// that trace, and the chain stops on DONE or after STEP_CAP steps. The final
// call answers from the whole trace.

import { features, KIND, SUBJECT_SOURCES, THINK_AT, join, route, searchQuery, sourceFor } from "./router.js";
import { toolCallOf } from "./ext.js";
import { frameEcho } from "./frame.js";

export { THINK_AT };
export const STEP_CAP = 8;
export const STEP_TOKENS = 384;
export const ANSWER_TOKENS = 2048;
// Text of the top search hit's page the write sees. A one-line snippet held the
// answer to that one line; a page gives a long answer something true to say.
// About 1,100 tokens, which leaves room in a 4,096-token window for a long answer.
const PAGE_CHARS = 4500;
const TRACE_CAP = 6000;

export function wantsChain(text, thinkOn) {
  if (thinkOn) return true;
  const f = features(String(text || ""), {});
  return f.think >= THINK_AT;
}

export function isDone(text) {
  const s = String(text || "").trim();
  return /^(?:DONE|ANSWER)\b/i.test(s) || /\bDONE\s*$/i.test(s);
}

function doneBody(text) {
  return String(text || "").replace(/\s*\bDONE\s*$/i, "").replace(/^(?:DONE|ANSWER)\b[:\s-]*/i, "").replace(/\s+/g, " ").trim();
}

export function traceText(trace) {
  const lines = (trace || []).map((item) => {
    if (item.kind === "tool") return item.step + ". [" + item.tool + "] " + String(item.text || "").replace(/\s+/g, " ").trim();
    return item.step + ". " + String(item.text || "").replace(/\s+/g, " ").trim();
  });
  let s = lines.join("\n");
  if (s.length > TRACE_CAP) s = s.slice(s.length - TRACE_CAP);
  return s;
}

export function stepPrompt(question, trace, step) {
  const prior = trace && trace.length ? "\nWork so far:\n" + traceText(trace) : "";
  return "You are working one task through to the end. Continue from the work so far. " +
    "Write the next step in a few sentences, or one tool call and nothing else. " +
    "A tool call is only this JSON: {\"type\":\"tool_call\",\"tool\":\"exec\",\"args\":{\"cmd\":\"...\"}} " +
    "(tool is exec, search, gather, notes, tasks, or canvas). " +
    "exec runs in EncryptidVM, the TunnelTug guest, never on the host. " +
    "When the work is finished, reply with DONE and stop. Do not give the final answer before DONE." +
    prior + "\nQuestion: " + question + "\nStep " + step + ":";
}

export function answerPrompt(question, trace, notes) {
  const note = notes ? "\nNotes:\n" + notes : "";
  const work = traceText(trace);
  return "Explain the answer in plain words. Do not use a tool.\nWork:\n" + work + note + "\nQuestion: " + question;
}

// hooks.chat(prompt, maxTokens) and hooks.answer(prompt, maxTokens) return the
// visible text, or null when the turn cannot start. hooks.run(call) runs a tool.
// hooks.stop() is true when the person pressed Stop. hooks.notes(question)
// returns recalled notes. hooks.onStep(item) shows one step.
export async function runChain(question, hooks) {
  const h = hooks || {};
  const trace = [];
  let steps = 0;
  while (steps < STEP_CAP) {
    if (h.stop && h.stop()) return { trace, answer: "", stopped: true };
    steps++;
    const got = await h.chat(stepPrompt(question, trace, steps), STEP_TOKENS);
    if (got == null) return { trace, answer: "", stopped: true };
    const call = toolCallOf(got);
    if (call && h.run) {
      await beginStep(h, (call.tool || "Working") + "…");
      const ran = await h.run(call);
      const item = { step: steps, kind: "tool", tool: call.tool, text: (ran && ran.output) || "" };
      trace.push(item);
      if (h.onStep) h.onStep(item);
      continue;
    }
    const text = String(got || "").replace(/\s+/g, " ").trim();
    if (!text) continue;
    if (isDone(text)) {
      const rest = doneBody(text);
      if (rest) {
        const item = { step: steps, kind: "think", text: rest };
        trace.push(item);
        if (h.onStep) h.onStep(item);
      }
      break;
    }
    const item = { step: steps, kind: "think", text };
    trace.push(item);
    if (h.onStep) h.onStep(item);
  }
  if (h.stop && h.stop()) return { trace, answer: "", stopped: true };
  const notes = h.notes ? h.notes(question) : "";
  const answer = await h.answer(answerPrompt(question, trace, notes), ANSWER_TOKENS);
  return { trace, answer: answer || "", stopped: false };
}

const OUTLINE_TOKENS = 384;
const SEGMENT_TOKENS = 768;

export function sectionTitles(text) {
  const src = String(text || "").replace(/\r/g, "");
  // A one- or two-digit index. A year such as 1968 is not a subject.
  const re = /(?:^|\n|[ \t])(?:[-*]|\d{1,2}[.)]|#{1,3})[ \t]+/g;
  const hits = [];
  let m;
  while ((m = re.exec(src))) hits.push({ at: m.index, len: m[0].length });
  let raws;
  const marked = hits.length > 0;
  if (marked) {
    raws = hits.map((h, i) => src.slice(h.at + h.len, i + 1 < hits.length ? hits[i + 1].at : src.length).trim());
    if (raws.length > 1 && /[.!?]["']?$/.test(raws[0]) && !/[.!?]["']?$/.test(raws[raws.length - 1])) raws.pop();
  } else {
    raws = src.split(/\n/).map((s) => s.trim()).filter(Boolean);
  }
  const out = [];
  const seen = new Set();
  for (const raw of raws) {
    let s = String(raw || "").replace(/\s+/g, " ").trim();
    const dash = s.split(/\s+[—–-]\s+/)[0];
    if (s.split(" ").length > 24 && dash.split(" ").length <= 24) s = dash;
    s = s.replace(/[:.]\s*$/, "").trim();
    if (s.length < 3 || s.length > 180) continue;
    if (s.split(" ").length > 24) continue;
    if (/^(?:outline|parts|sections|section titles|title)$/i.test(s)) continue;
    const key = s.toLowerCase();
    if (seen.has(key)) continue;
    seen.add(key);
    out.push(s);
    if (out.length >= 8) break;
  }
  if (out.length === 1 && out[0].length > 80) return [];
  return out;
}

export function sourceKept(output) {
  const s = String(output || "").replace(/\s+/g, " ").trim();
  if (s.length < 12) return false;
  if (/^(?:the lookup failed|missing search query|nothing matched|unknown tool|that address is not available)\b/i.test(s)) return false;
  // A refused gather is not a page. Quoting it would publish the refusal as the answer.
  if (/reads only an address the person gave or a search listed/i.test(s)) return false;
  return true;
}

// A JavaScript shell answers with a browser banner and a menu. That text is
// not the article. A real page is returned as it arrived.
const CHROME_RE = /\b(?:outdated browser|upgrade your browser|upgrade your web browser|enable javascript|javascript is (?:required|disabled)|turn on javascript)\b/i;
const NAV_LEAD = /^(?:(?:skip to content|where to eat|overview|recipe|comments|home|menu|search|navigation)\s+){2,}/i;

export function pageProse(text) {
  const raw = String(text || "").replace(/\r/g, "").trim();
  const flat = raw.replace(/\s+/g, " ").trim();
  if (!flat) return "";
  const kept = [];
  let dropped = false;
  for (const part of flat.split(/(?<=[.!?])\s+/)) {
    const s = part.trim();
    if (!s) continue;
    if (CHROME_RE.test(s)) { dropped = true; continue; }
    kept.push(s);
  }
  let body = kept.join(" ").trim();
  if (dropped) body = body.replace(NAV_LEAD, "").trim();
  const words = body ? body.split(/\s+/).length : 0;
  if (dropped && words < 12) return "";
  if (!dropped) return flat.length < 12 ? "" : raw;
  return body;
}

function clip(s, n) {
  const t = String(s || "").replace(/\s+/g, " ").trim();
  return t.length > n ? t.slice(0, n) : t;
}

function clipLines(s, n) {
  const t = String(s || "").replace(/\r/g, "").trim();
  return t.length > n ? t.slice(0, n) : t;
}

function planLines(trace) {
  return (trace || []).map((item) => {
    if (item.kind === "tool") {
      const name = item.label || item.tool;
      return item.kept ? name + ": " + clip(item.text, item.page ? PAGE_CHARS : 500) : name + ": nothing returned";
    }
    return clip(item.text, 500);
  }).join("\n");
}

// The write sees at most 700 characters of this step, so it is held to a few sentences.
const REASON_TOKENS = 160;

function reasonPrompt(question) {
  return "Think through this question step by step in three or four short sentences. Do not write the final answer yet.\nQuestion: " + question;
}

function outlinePrompt(question) {
  return "List the topics of the answer, one short line each. Do not state a fact. Do not answer yet.\nQuestion: " + question;
}

// The lookup is the person's question. An outline sentence is not a query.
export function lookupQuery(question) {
  const ask = String(question || "").replace(/\s+/g, " ").trim()
    .replace(/^(?:please\s+)?(?:research|search(?:\s+for)?|look\s*up|lookup)\s+/i, "")
    .trim();
  return (ask || String(question || "").replace(/\s+/g, " ").trim()).slice(0, 120);
}

function topicOf(subject) {
  const raw = String(subject || "").replace(/\s+/g, " ").trim();
  const head = raw.split(/\s+(?:was|were|is|are|became|saw|had|has|have)\b/i)[0]
    .replace(/\([^)]*\)/g, " ").replace(/\s+/g, " ").replace(/[.:;,]+$/g, "").trim();
  return head || raw;
}

function pageItems(trace) {
  return (trace || []).filter((item) => item.kind === "tool" && item.page && item.kept && item.text);
}

function sourceBlob(trace) {
  const pages = pageItems(trace);
  const items = pages.length ? pages : (trace || []).filter((item) => item.kind === "tool" && item.kept && item.text);
  return items.map((item) => String(item.text)).join("\n");
}

// A grounded sentence may only carry a year or a name the sources already
// contain. Anything else is the model filling a gap, which is where a short
// checkpoint invents a river, a year, or a city.
function sentenceHeld(sentence, src) {
  const source = String(src || "");
  const low = source.toLowerCase();
  const years = String(sentence).match(/\b\d{3,4}\b/g) || [];
  for (const y of years) if (!source.includes(y)) return false;
  const words = String(sentence).match(/\b[A-Za-z][A-Za-z'-]*/g) || [];
  for (let i = 1; i < words.length; i++) {
    const w = words[i];
    if (!/^[A-Z]/.test(w)) continue;
    if (w.length < 2) continue;
    if (!low.includes(w.toLowerCase())) return false;
  }
  return true;
}

function wordsOf(s) {
  return String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
}

// A looked-up sentence has to be the page's own words. A six-word run of the
// sentence must sit in the source, and every longer word must already be on
// the page. A six-word run alone keeps "incorporated" when the page says
// "unincorporated". A fragment such as "In 1797, the U.S." has too few words.
function spanHeld(sentence, src) {
  const words = wordsOf(sentence);
  const source = wordsOf(src);
  if (!words.length || !source.length) return false;
  const content = words.filter((w) => w.length > 2);
  if (content.length < 3) return false;
  const bag = new Set(source);
  if (content.some((w) => !bag.has(w))) return false;
  if (words.length < 6) return true;
  const blob = " " + source.join(" ") + " ";
  for (let i = 0; i + 6 <= words.length; i++) {
    if (blob.includes(" " + words.slice(i, i + 6).join(" ") + " ")) return true;
  }
  return false;
}

function factualTrace(trace) {
  if (pageItems(trace).length) return true;
  return (trace || []).some((item) => item.kind === "tool" && item.kept && parseHits(item.text).length > 0);
}

// The first page's own lead. Later pages stay in the source list so a company
// page is not read as the definition of the dish.
function leadQuotes(text, n) {
  const quotes = quoteSentences(text, 5, n);
  if (quotes.length) return quotes.slice(0, n);
  const out = [];
  for (const chunk of String(text || "").split(/\n{2,}/)) {
    const s = chunk.replace(/\s+/g, " ").trim();
    if (s.split(/\s+/).filter(Boolean).length < 8) continue;
    out.push(s.length > 500 ? s.slice(0, 500).replace(/\s+\S*$/, "").trim() : s);
    if (out.length >= n) break;
  }
  return out;
}

const CITE_STOP = new Set("the a an of and to in on for is was are were what who where when why how me about look up lookup tell please with from that this into its or as at by be it".split(" "));

function queryWords(question) {
  return wordsOf(question).filter((w) => w.length > 2 && !CITE_STOP.has(w));
}

const GENERIC = new Set("news latest today tonight headline headlines breaking current update updates weather forecast right now price prices cost score scores standing standings".split(" "));
const LEAD = new Set("research search lookup look causes effects history impact facts fact give tell describe explain write about please formatted recipe recipes".split(" "));

function subjectWords(question) {
  return queryWords(question).filter((w) => !GENERIC.has(w) && !LEAD.has(w));
}

function nameWords(words) {
  if (words.length <= 2) return words;
  let first = 0;
  let second = 1;
  if (words[1].length > words[0].length) { first = 1; second = 0; }
  for (let i = 2; i < words.length; i++) {
    if (words[i].length > words[first].length) { second = first; first = i; }
    else if (words[i].length > words[second].length) second = i;
  }
  return [words[first], words[second]];
}

function stemMatch(tok, word) {
  if (tok === word) return true;
  if (word.length >= 4 && tok.startsWith(word) && tok.length <= word.length + 2) return true;
  if (tok.length >= 4 && word.startsWith(tok) && word.length <= tok.length + 2) return true;
  return false;
}

// The reply names the subject. A menu page that never says the dish does not.
function carriesName(question, text) {
  const names = nameWords(subjectWords(question));
  if (!names.length) return true;
  const toks = wordsOf(text);
  return names.every((w) => toks.some((tok) => stemMatch(tok, w)));
}

// A short reply that shares no content word with the question.
function offSubject(question, text) {
  const words = queryWords(question);
  if (!words.length) return false;
  const t = String(text || "").trim();
  if (!t || t.split(/\s+/).length > 24) return false;
  return scoreSentence(t, words) === 0;
}

const ROUTE_ONLY = /^(?:fact|recipe|command|talk)[.!:]?$/i;

function modelStands(question, text) {
  const t = String(text || "").trim();
  if (!t || ROUTE_ONLY.test(t)) return false;
  if (offSubject(question, t)) return false;
  return carriesName(question, t);
}

function briefNotes(trace) {
  const pages = pageItems(trace);
  const items = pages.length ? pages : (trace || []);
  const bits = [];
  for (const item of items) {
    if (item.kind !== "tool" || !item.kept || !item.text) continue;
    const t = String(item.text).replace(/\s+/g, " ").trim();
    if (!t) continue;
    bits.push(t);
    if (bits.length >= 3) break;
  }
  return bits.join(" ").slice(0, 700);
}

// The search card is titles, addresses, and cut snippets. It is not the answer.
function hitDump(text) {
  const s = String(text || "");
  return /https?:\/\//i.test(s) || /\s\d{1,2}\.\s+[A-Za-z]/.test(s);
}

function pageLead(text) {
  const quotes = quoteSentences(text, 8, 2);
  if (quotes.length) return quotes.join(" ");
  const paras = String(text || "").split(/\n{2,}/).map((s) => s.replace(/\s+/g, " ").trim());
  return paras.find((s) => s.split(/\s+/).length >= 12) || "";
}

function scoreSentence(sentence, qwords) {
  if (!qwords.length) return 1;
  const bag = new Set(wordsOf(sentence));
  let n = 0;
  for (const w of qwords) if (bag.has(w)) n++;
  return n;
}

// The first page keeps its lead, in order. Another page contributes the
// sentence that shares the most words with the question.
function pickSentences(text, qwords, n, lead) {
  const sentences = leadQuotes(text, n);
  if (!sentences.length) return [];
  if (lead) return sentences.slice(0, n);
  const ranked = sentences.map((s, i) => ({ s, i, score: scoreSentence(s, qwords) }));
  ranked.sort((a, b) => b.score - a.score || a.i - b.i);
  const best = ranked.filter((row) => row.score > 0).slice(0, n);
  if (!best.length) return [];
  return best.sort((a, b) => a.i - b.i).map((row) => row.s);
}

// A page that shares one stray word is not the dish when another page shares the name.
function groundHits(question, trace) {
  const qwords = queryWords(question);
  const pages = pageItems(trace);
  const sources = citedSources(trace);
  if (!pages.length || !qwords.length) return sources;
  const byUrl = new Map(pages.map((page) => [page.url, page]));
  const scored = sources.map((src) => ({
    src,
    score: scoreSentence((byUrl.get(src.url) || {}).text || src.snippet || "", qwords),
  }));
  const best = scored.reduce((m, row) => Math.max(m, row.score), 0);
  if (best < 3) return sources;
  const kept = scored.filter((row) => row.score >= best - 1).map((row) => row.src);
  return kept.length ? kept : sources;
}

function citeLine(sentence, n, url) {
  const title = String(url || "");
  if (!title) return sentence;
  return sentence + " [" + n + "](" + title + ")";
}

const RECIPE_AMOUNT = /(?:about\s+)?(?:as needed|\d+[¼½¾⅓⅔⅛⅜⅝⅞]|\d+\s+\d+\/\d+|\d+\/\d+|[¼½¾⅓⅔⅛⅜⅝⅞]|\d+(?:\.\d+)?)(?:\s*(?:lb|lbs|pounds?|g|kg|oz|ml|cups?|tbsp|tsp|tablespoons?|teaspoons?|inches?|inch))?(?:\s*\([^)]*\))?(?:,\s*divided)?(?:\s+in the pan)?/gi;

function cleanName(s) {
  return String(s || "").replace(/^[\s,;:.\-–—]+|[\s,;:.\-–—]+$/g, "").replace(/\s+,/g, ",").replace(/\s+/g, " ").trim();
}

function rowScore(name, amount) {
  const words = name.split(" ").length;
  const unit = /\b(?:cups?|tbsp|tsp|teaspoons?|tablespoons?|lb|lbs|oz|ml|g|kg)\b/i.test(amount);
  const bare = /^\d+$/.test(amount);
  let score = 0;
  if (unit && words <= 5) score += 2;
  if (unit && words > 6) score -= 3;
  if (bare && /egg/i.test(name)) score += 2;
  if (bare && !/egg/i.test(name)) score -= 2;
  if (!amount && words > 5) score += 1;
  return score;
}

// A flattened recipe is either "name amount" or "amount name". Both are tried.
// The alignment that puts cups and teaspoons on the short names wins, so a
// long chicken line does not take the corn flakes' 5 cups.
function maskNameParens(section) {
  return section.replace(/\(([^)]*)\)/g, (full, inner) => {
    if (/^\s*(?:about\s+)?[\d¼½¾⅓⅔⅛./\s-]+(?:lb|lbs|g|kg|oz|ml|cups?)?\s*$/i.test(inner)) return full;
    return " ".repeat(full.length);
  });
}

function liftParenAmount(name, amount) {
  if (amount) return [name, amount];
  const paren = name.match(/\(([^)]*\d[^)]*)\)/);
  if (!paren || paren[1].length > 40) return [name, amount];
  return [cleanName(name.replace(paren[0], " ")), paren[1].replace(/\s+/g, " ").trim()];
}

function recipeRows(section) {
  const masked = maskNameParens(section);
  const matches = [...masked.matchAll(new RegExp(RECIPE_AMOUNT.source, "gi"))];
  if (!matches.length) return [];
  const amountOf = (m) => m[0].replace(/\s+/g, " ").trim();
  const gaps = [];
  let start = 0;
  for (const m of matches) {
    gaps.push(cleanName(section.slice(start, m.index)));
    start = m.index + m[0].length;
  }
  gaps.push(cleanName(section.slice(start)));
  const before = [];
  matches.forEach((m, i) => { if (gaps[i]) before.push([gaps[i], amountOf(m)]); });
  const after = [];
  if (gaps[0] && gaps[0].split(" ").length > 5) after.push([gaps[0], ""]);
  matches.forEach((m, i) => { if (gaps[i + 1]) after.push([gaps[i + 1], amountOf(m)]); });
  const score = (rows) => rows.reduce((n, [name, amount]) => n + rowScore(name, amount), 0);
  const picked = score(after) > score(before) ? after : before;
  return picked.map(([name, amount]) => liftParenAmount(name, amount));
}

function recipeMeta(head) {
  const re = /\b(Makes|Serves|Servings|Prep|Cook(?:\s+time)?|Total|Yield)\s*:\s*/gi;
  const marks = [];
  let m;
  while ((m = re.exec(head))) marks.push({ label: m[1], at: m.index, len: m[0].length });
  if (!marks.length) return { title: head.trim(), lines: [] };
  const title = head.slice(0, marks[0].at).replace(/[.?!]+$/g, "").trim();
  const lines = marks.map((mark, i) => {
    const end = i + 1 < marks.length ? marks[i + 1].at : head.length;
    const value = head.slice(mark.at + mark.len, end).replace(/\s+/g, " ").replace(/[\s·•|]+$/g, "").trim();
    const label = mark.label.replace(/\s+time$/i, "");
    return value ? label + ": " + value : "";
  }).filter(Boolean);
  return { title, lines };
}

// A flattened recipe is one sentence. The page already renders headings, lists, and tables.
export function formatRecipe(text) {
  const flat = String(text || "").replace(/\s+/g, " ").trim();
  const ingAt = flat.search(/\bIngredients?\b(?:\s+Amount)?/i);
  if (ingAt < 0) return "";
  const rel = flat.slice(ingAt).search(/\b(?:Method|Directions|Instructions|Steps|Preparation|Marinate)\b/i);
  if (rel < 0) return "";
  const methodAt = ingAt + rel;
  const head = flat.slice(0, ingAt).trim();
  const ing = flat.slice(ingAt, methodAt).replace(/^\s*Ingredients?\s*(?:Amount\s*)?/i, "").trim();
  const method = flat.slice(methodAt).replace(/^\s*(?:Method|Directions|Instructions|Steps|Preparation|Marinate)\s*:?\s*/i, "").trim();
  const rows = recipeRows(ing);
  if (rows.length < 2) return "";
  if (head.length > 140) return "";
  if (rows.some(([n]) => n.length > 80 || n.split(" ").length > 14)) return "";
  const meta = recipeMeta(head);
  const steps = method.split(/(?<=[.!?])\s+/).map((s) => s.trim()).filter((s) => s && !/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(s));
  const cell = (s) => s.replace(/\|/g, "/");
  const lines = [];
  if (meta.title) lines.push("## " + meta.title);
  if (meta.lines.length) lines.push(meta.lines.map((l) => "- " + l).join("\n"));
  lines.push("| Ingredient | Amount |\n| --- | --- |\n" + rows.map(([n, a]) => "| " + cell(n) + " | " + cell(a || "—") + " |").join("\n"));
  if (steps.length) lines.push("### Method\n" + steps.map((s, i) => (i + 1) + ". " + s).join("\n"));
  return lines.join("\n\n");
}

const RECIPE_Q = /\b(?:recipes?)\b|\bhow to (?:make|cook|bake|fry|roast|prepare)\b/i;
const COMPARE_Q = /\b(?:compare|comparison|difference between|versus)\b|\bvs\.?\b/i;
const STEPS_Q = /\b(?:how to|how do i|how can i|steps|instructions)\b/i;
const LIST_Q = /\b(?:list|name the|what are the|which are|examples of)\b/i;
const DEFINE_Q = /\b(?:who|what|when|where)\b|\b(?:tell me about|describe)\b/i;

// The question picks the shape. The sentences stay the sources' own words.
export function answerTemplate(question) {
  const t = String(question || "");
  if (RECIPE_Q.test(t)) return "recipe";
  if (COMPARE_Q.test(t)) return "compare";
  if (STEPS_Q.test(t)) return "steps";
  if (LIST_Q.test(t)) return "list";
  if (DEFINE_Q.test(t)) return "define";
  return "prose";
}

function subjectLine(question) {
  const s = searchQuery(question).replace(/^(?:causes?|effects?|reasons?)\s+/i, "").trim();
  if (!s) return "";
  return s.charAt(0).toUpperCase() + s.slice(1);
}

function headed(question, body) {
  const title = subjectLine(question);
  return title ? "## " + title + "\n\n" + body : body;
}

function sideWords(side) {
  return wordsOf(side).filter((w) => w.length > 2 && !CITE_STOP.has(w));
}

function mentionsSide(sentence, side) {
  const words = sideWords(side);
  if (!words.length) return false;
  const bag = new Set(wordsOf(sentence));
  const n = words.filter((w) => bag.has(w)).length;
  return n >= Math.min(2, words.length);
}

function compareSides(question) {
  const t = String(question || "").replace(/\s+/g, " ").replace(/[?.!]+$/g, "").trim();
  const patterns = [
    /\bdifference between\s+(.+?)\s+and\s+(.+)$/i,
    /\bcompare\s+(.+?)\s+(?:and|with|to|versus|vs\.?)\s+(.+)$/i,
    /\b([A-Za-z][^?]{0,48}?)\s+(?:versus|vs\.?)\s+([^?]+)$/i,
  ];
  for (const re of patterns) {
    const m = re.exec(t);
    if (!m) continue;
    const a = m[1].replace(/^(?:the|a|an)\s+/i, "").trim();
    const b = m[2].replace(/^(?:the|a|an)\s+/i, "").trim();
    if (a && b && a.length < 80 && b.length < 80) return [a, b];
  }
  return null;
}

function compareTable(question, blocks) {
  const sides = compareSides(question);
  if (!sides) return "";
  const left = [];
  const right = [];
  const rest = [];
  const cell = (s) => String(s || "").replace(/\|/g, "/").replace(/\s+/g, " ").trim();
  for (const b of blocks) {
    if (b.shaped) { rest.push(b.line); continue; }
    const onLeft = mentionsSide(b.s, sides[0]);
    const onRight = mentionsSide(b.s, sides[1]);
    if (onLeft && !onRight) left.push(b.line);
    else if (onRight && !onLeft) right.push(b.line);
    else rest.push(b.line);
  }
  if (!left.length || !right.length) return "";
  const rows = [];
  for (let i = 0; i < Math.max(left.length, right.length); i++) {
    rows.push("| " + cell(left[i] || "") + " | " + cell(right[i] || "") + " |");
  }
  const table = "| " + cell(sides[0]) + " | " + cell(sides[1]) + " |\n| --- | --- |\n" + rows.join("\n");
  const tail = rest.length ? "\n\n" + rest.join("\n\n") : "";
  return headed(question, table) + tail;
}

function numbered(blocks) {
  let i = 0;
  return blocks.map((b) => {
    if (b.shaped) return b.line;
    i += 1;
    return i + ". " + b.line;
  }).join("\n");
}

function bullets(blocks) {
  return blocks.map((b) => (b.shaped ? b.line : "- " + b.line)).join("\n");
}

// Steps and lists are often one short sentence each. The page quote rule
// drops anything under five words, which deletes "Disconnect the supply lines."
function templateQuotes(question, text, n) {
  const kind = answerTemplate(question);
  if (kind === "steps" || kind === "list" || kind === "compare") {
    const parts = String(text || "").replace(/\s+/g, " ").trim().split(/(?<=[.!?])\s+/).map((s) => s.trim()).filter((s) => wordsOf(s).length >= 3);
    if (parts.length) return parts.slice(0, n);
  }
  return leadQuotes(text, n);
}

function applyTemplate(question, picks) {
  const blocks = (picks || []).map((p) => ({
    s: p.s,
    line: citeLine(p.s, p.n, p.url),
    shaped: /^\s*##\s/m.test(p.s) || /\| Ingredient \|/.test(p.s),
  }));
  if (!blocks.length) return "";
  const kind = answerTemplate(question);
  if (kind === "recipe") {
    const shaped = blocks.filter((b) => b.shaped);
    if (shaped.length) return shaped.map((b) => b.line).join("\n\n");
    return headed(question, numbered(blocks));
  }
  if (kind === "compare") {
    const table = compareTable(question, blocks);
    if (table) return table;
  }
  if (kind === "steps") return headed(question, numbered(blocks));
  if (kind === "list") return headed(question, bullets(blocks));
  if (kind === "define") return headed(question, blocks.map((b) => b.line).join("\n\n"));
  return blocks.map((b) => b.line).join("\n\n");
}

// A web answer is the pages' own sentences, each tied to the source it came
// from. The model is not asked to blend them.
function pageAnswer(question, trace) {
  const qwords = queryWords(question);
  const sources = groundHits(question, trace);
  const pages = pageItems(trace);
  const picks = [];
  // duck.ai and Gemini answer the question. Their text is the other model's reply.
  for (const item of trace || []) {
    if (picks.length >= 6) break;
    if (item.kind !== "tool" || item.tool !== "search" || !item.kept || !item.text) continue;
    if (!/duck\.ai|gemini/i.test(String(item.label || ""))) continue;
    if (parseHits(item.text).length) continue;
    if (scoreSentence(item.text, qwords) < 2) continue;
    const shaped = formatRecipe(item.text);
    if (shaped) {
      picks.push({ s: shaped, n: 0, url: "" });
      continue;
    }
    for (const s of templateQuotes(question, item.text, 6)) {
      if (picks.length >= 6 || picks.some((p) => p.s === s)) continue;
      picks.push({ s, n: 0, url: "" });
    }
  }
  if (pages.length && sources.length) {
    const byUrl = new Map(pages.map((page) => [page.url, page]));
    // The page that shares the question's words is quoted. A page that only
    // shares a stray word is left out of the answer.
    const ordered = sources.slice().sort((a, b) => {
      const as = scoreSentence((byUrl.get(a.url) || {}).text || "", qwords);
      const bs = scoreSentence((byUrl.get(b.url) || {}).text || "", qwords);
      return bs - as;
    });
    ordered.forEach((src, i) => {
      const page = byUrl.get(src.url);
      if (!page || picks.length >= 12) return;
      const shaped = formatRecipe(page.text);
      if (shaped) {
        picks.push({ s: shaped, n: sources.indexOf(src) + 1, url: src.url });
        return;
      }
      for (const s of pickSentences(page.text, qwords, i === 0 ? 8 : 2, i === 0)) {
        if (picks.length >= 12 || picks.some((p) => p.s === s)) continue;
        picks.push({ s, n: sources.indexOf(src) + 1, url: src.url });
      }
    });
  }
  if (!picks.length && sources.length) {
    sources.forEach((src, i) => {
      const s = pickSentences(src.snippet || "", qwords, 1, true)[0];
      if (!s || picks.length >= 4 || picks.some((p) => p.s === s)) return;
      picks.push({ s, n: i + 1, url: src.url });
    });
  }
  if (picks.length) return applyTemplate(question, picks);
  const quotes = [];
  for (const item of trace || []) {
    if (item.kind !== "tool" || !item.kept || !item.text) continue;
    for (const s of leadQuotes(item.text, 2)) {
      if (!quotes.includes(s)) quotes.push(s);
    }
    if (quotes.length) break;
  }
  return applyTemplate(question, quotes.map((s) => ({ s, n: 0, url: "" })));
}

export function keepGrounded(answer, trace) {
  const src = sourceBlob(trace);
  const raw = String(answer || "").trim().split(/\s+(?:Question|Answer)\s*:/i)[0].trim();
  if (!src.trim()) {
    const looked = (trace || []).some((item) => item.kind === "tool" && (item.tool === "search" || item.tool === "gather" || item.page));
    return looked ? "The sources do not cover that." : raw;
  }
  const hold = factualTrace(trace) ? spanHeld : sentenceHeld;
  const kept = [];
  for (const part of raw.split(/(?<=[.!?])\s+/)) {
    const s = part.trim();
    if (!s || !hold(s, src)) continue;
    kept.push(s);
  }
  if (kept.length) return kept.join(" ");
  const quotes = quoteSentences(src);
  if (quotes.length) return quotes.slice(0, 2).join(" ");
  return "The sources do not cover that.";
}

// The source list is the lookup's own titles and addresses. The model was
// starting "Sources: 1." and the loop cut was treating that "1." as the end
// of the answer, so the address never landed.
function citedSources(trace) {
  const out = [];
  const seen = new Set();
  for (const item of pageItems(trace)) {
    if (!item.url || seen.has(item.url)) continue;
    seen.add(item.url);
    out.push({ title: item.label || item.url, url: item.url });
    if (out.length >= 5) return out;
  }
  if (out.length) return out;
  for (const item of trace || []) {
    if (item.kind !== "tool" || !item.kept || !item.text) continue;
    for (const hit of parseHits(item.text)) {
      if (!hit.url || seen.has(hit.url)) continue;
      seen.add(hit.url);
      out.push(hit);
      if (out.length >= 5) return out;
    }
  }
  return out;
}

export function withSources(answer, trace, question) {
  const hits = question ? groundHits(question, trace) : citedSources(trace);
  let body = String(answer || "").trim().replace(/\n*Sources:[\s\S]*$/i, "").trim();
  if (!hits.length) return body;
  const lines = hits.map((hit, i) => {
    const title = String(hit.title || hit.url).replace(/[\[\]]/g, "");
    return (i + 1) + ". [" + title + "](" + hit.url + ")";
  });
  return body + "\n\nSources:\n" + lines.join("\n");
}

function groundWork(trace) {
  const pages = pageItems(trace);
  if (pages.length) {
    return pages.map((item) => (item.label || "Page") + ":\n" + item.text).join("\n\n");
  }
  return planLines(trace);
}

function writePrompt(question, trace) {
  const grounded = (trace || []).some((item) => item.kind === "tool");
  const work = grounded ? groundWork(trace) : planLines(trace);
  if (!work) return question;
  if (grounded) {
    const any = (trace || []).some((item) => item.kind === "tool" && item.kept && String(item.text || "").trim());
    if (!any) return "The lookup returned nothing on this. Say that in one sentence.\nQuestion: " + question;
    return "The lookup is already done. Answer the question the person asked, in plain words. " +
      "Use the notes. Give the answer that question asks for. Do not answer with a label, do not use a heading, and do not use JSON.\nNotes:\n" +
      work + "\nQuestion: " + question;
  }
  return "Answer the person's question from the notes below.\nNotes:\n" + work + "\nQuestion: " + question;
}

// Reads kept search hits, up to five, taking turns across engines so a
// Wikipedia list does not crowd out the other results. A miss is recorded
// so the step does not stay spinning.
async function readSources(trace, h, limit) {
  if (!h.run || trace.some((x) => x.page)) return;
  const cap = limit > 0 ? limit : 1;
  const groups = [];
  for (const item of trace) {
    if (item.kind !== "tool" || item.tool !== "search" || !item.kept) continue;
    const group = parseHits(item.text).filter((hit) => hit.url);
    if (group.length) groups.push(group);
  }
  const hits = [];
  const seen = new Set();
  let more = true;
  while (hits.length < cap && more) {
    more = false;
    for (const group of groups) {
      while (group.length && seen.has(group[0].url)) group.shift();
      if (!group.length) continue;
      more = true;
      const hit = group.shift();
      seen.add(hit.url);
      hits.push(hit);
      if (hits.length >= cap) break;
    }
  }
  for (const hit of hits) {
    if (h.stop && h.stop()) return;
    const label = hit.title || "Page";
    await beginStep(h, "Reading " + label + "…");
    let ran = { output: "" };
    try { ran = (await h.run({ tool: "gather", args: { url: hit.url } })) || ran; } catch { ran = { output: "" }; }
    const prose = sourceKept(ran.output) ? pageProse(ran.output) : "";
    const item = {
      step: trace.length + 1, kind: "tool", tool: "gather", label, page: true, url: hit.url,
      text: prose ? clipLines(prose, PAGE_CHARS) : "", kept: !!prose, empty: !prose,
    };
    trace.push(item);
    if (h.onStep) h.onStep(item);
  }
}

function beatPrompt(question, subject, prior, lookup) {
  const topic = topicOf(subject);
  const tail = prior ? "\nAlready on the page:\n" + String(prior).slice(-600) : "";
  if (lookup) {
    return "Topic: " + topic + ".\n" +
      "Write this topic in paragraphs from the lookup only. If the lookup does not say it, leave it out. " +
      "Do not repeat what is already on the page. Do not ask a question. " +
      "Name a source only when the lookup contains it.\n" +
      "Lookup:\n" + lookup + tail + "\nQuestion: " + question;
  }
  return "Topic: " + topic + ".\n" +
    "Stage this subject. One search tool call and nothing else is allowed, in this form: " +
    "{\"type\":\"tool_call\",\"tool\":\"search\",\"args\":{\"q\":\"...\"}}. " +
    "Otherwise write the subject in paragraphs. Do not list the other subjects." +
    tail + "\nQuestion: " + question;
}

// A search hit is a title, an address, and a snippet. The canvas quotes the page.
function parseHits(text) {
  const src = String(text || "").replace(/\r/g, "").trim();
  if (!src) return [];
  const chunks = src.split(/\n{2,}/);
  if (!chunks.every((c) => /^\d{1,2}[.)]\s+/.test(c.trim()))) return [];
  return chunks.map((chunk) => {
    const lines = chunk.split("\n").map((s) => s.trim()).filter(Boolean);
    const title = lines[0].replace(/^\d{1,2}[.)]\s+/, "");
    const url = lines.find((l) => /^https?:\/\//.test(l)) || "";
    const snippet = lines.filter((l) => l !== lines[0] && l !== url).join(" ");
    return { title, url, snippet };
  }).filter((h) => h.title);
}

// Sentences copied from a page. A fragment cut mid-word is not a quote.
function quoteSentences(text, minWords, maxSentences) {
  const min = minWords || 8;
  const flat = String(text || "").replace(/\s+/g, " ").trim();
  const out = [];
  for (const part of flat.split(/(?<=[.!?])\s+/)) {
    const s = part.trim();
    const n = s.split(/\s+/).length;
    if (n < min || n > 120) continue;
    if (!/[.!?]"?$/.test(s)) continue;
    if (/^(?:home|menu|search|cookie|sign in|subscribe|share|advertisement|i will|i have generated|let me know if|please note)\b/i.test(s)) continue;
    out.push(s);
    if (out.length >= (maxSentences || 16)) break;
  }
  return out;
}

function researchDocument(title, subjects, pages) {
  const parts = ["# " + title];
  if (subjects.length) parts.push(subjects.map((s) => "- " + topicOf(s)).join("\n"));
  let any = false;
  for (const page of pages) {
    const quotes = quoteSentences(page.text);
    if (!quotes.length) continue;
    any = true;
    parts.push("## " + (page.title || "Source"));
    if (page.url) parts.push("[" + (page.title || page.url) + "](" + page.url + ")");
    parts.push(quotes.join("\n\n"));
  }
  return any ? parts.join("\n\n") : "";
}

function canvasTitle(question) {
  return lookupQuery(question).replace(/[.?!]+$/g, "").trim().slice(0, 80) || "Canvas";
}

async function publishCanvas(question, trace, h) {
  const outlined = [...trace].reverse().find((x) => x.role === "outline");
  const subjects = outlined ? sectionTitles(outlined.text) : [];
  const pages = [];
  const seen = new Set();
  for (const item of trace) {
    if (pages.length >= 5) break;
    if (item.kind !== "tool" || item.tool === "canvas" || item.tool === "gather" || !item.kept || !item.text) continue;
    const hits = parseHits(item.text);
    const list = hits.length ? hits.slice(0, 3) : [{ title: "Source", url: "", snippet: item.text }];
    for (const hit of list) {
      if (pages.length >= 5) break;
      const key = hit.url || hit.snippet || "";
      if (!key || seen.has(key)) continue;
      seen.add(key);
      if (h.stop && h.stop()) return { trace, answer: "", stopped: true };
      let text = hit.snippet || "";
      if (hit.url && h.run) {
        await beginStep(h, "Reading " + (hit.title || "page") + "…");
        let ran = { output: "" };
        try { ran = (await h.run({ tool: "gather", args: { url: hit.url } })) || ran; }
        catch { ran = { output: "" }; }
        const got = sourceKept(ran.output) ? clipLines(pageProse(ran.output), 6000) : "";
        const step = {
          step: trace.length + 1, kind: "tool", tool: "gather", label: hit.title || "Page",
          text: got, kept: !!got, empty: !got,
        };
        trace.push(step);
        if (h.onStep) h.onStep(step);
        if (got) text = got;
      }
      pages.push({ title: hit.title, url: hit.url, text });
    }
  }
  const title = (subjects[0] && topicOf(subjects[0]).slice(0, 80)) || canvasTitle(question);
  const text = researchDocument(title, subjects, pages);
  let ran = { output: "", exit_code: 1 };
  if (text && h.run) {
    try { ran = (await h.run({ tool: "canvas", args: { op: "write", title, text } })) || ran; }
    catch { ran = { output: "", exit_code: 1 }; }
  }
  const item = {
    step: trace.length + 1, kind: "tool", tool: "canvas", label: "Canvas",
    text: title, kept: !!text, empty: !text,
  };
  trace.push(item);
  if (h.onStep) h.onStep(item);
  if (h.card && text) {
    h.card({
      tool: "canvas",
      args: { op: "write", title },
      output: text,
      exit_code: ran.exit_code || 0,
      data: (ran.data && Array.isArray(ran.data.blocks) && ran.data.blocks.length)
        ? ran.data
        : { title, text },
    });
  }
  // The canvas card is the document. The chat does not repeat it.
  return { trace, answer: text, stopped: false };
}

async function beginStep(h, label) {
  if (h.onBegin) await h.onBegin({ label });
}

function lookupLines(items) {
  return items.map((item) => {
    const name = String(item.label || item.tool || "source").split(" · ").pop();
    return item.kept && item.text ? name + ": " + item.text : name + ": nothing returned";
  }).join("\n");
}

// One lookup for the question. A later subject reuses that result.
async function loadSubject(subject, question, trace, h) {
  const sub = String(subject || "").replace(/\s+/g, " ").trim();
  const q = lookupQuery(question);
  const prior = trace.filter((x) => x.kind === "tool" && x.tool === "search");
  if (prior.length) return lookupLines(prior);
  const src = sourceFor(question);
  if (h.stop && h.stop()) return null;
  let ran = { output: "" };
  const ask = SUBJECT_SOURCES.has(src.source) ? searchQuery(question) : q;
  await beginStep(h, src.label + "…");
  try { ran = (await h.run({ tool: "search", args: { q: ask, source: src.source } })) || ran; } catch { ran = { output: "" }; }
  const echo = frameEcho(ran.output, question) || frameEcho(ran.output, q);
  const usable = !echo && sourceKept(ran.output);
  const text = usable ? clipLines(ran.output, 1800) : "";
  const item = {
    step: trace.length + 1, kind: "tool", tool: "search", part: sub, query: q,
    label: sub ? sub + " · " + src.label : src.label, text, kept: usable, empty: !text,
  };
  trace.push(item);
  if (h.onStep) h.onStep(item);
  return usable ? src.label + ": " + text : src.label + ": nothing returned";
}

// Each outline line is a chat beat. route stages it. join emits it onto the
// page. A search tool call on that beat is loaded, then the subject is staged
// again. This is the same for every message that listed more than one line.
async function emitSubjects(question, trace, subjects, h, search) {
  let paper = "";
  for (const subject of subjects) {
    if (h.stop && h.stop()) return { trace, answer: paper, stopped: true };
    if (h.room) await h.room();
    let lookup = "";
    if (search) {
      lookup = await loadSubject(subject, question, trace, h);
      if (lookup == null) return { trace, answer: paper, stopped: true };
    }
    if (route(!!(h.full && h.full()), KIND.chat) !== "stage") continue;
    const partials = h.partials ? !!h.partials() : true;
    const placed = h.placed ? !!h.placed() : true;
    if (join(true, partials, placed) !== "emit") continue;
    let got = await h.answer(beatPrompt(question, subject, paper, lookup), SEGMENT_TOKENS);
    if (got == null) return { trace, answer: paper, stopped: true };
    const call = toolCallOf(got);
    if (call && call.tool === "search" && h.run && !lookup) {
      let ran = { output: "" };
      try { ran = (await h.run(call)) || ran; } catch { ran = { output: "" }; }
      const lookup = sourceKept(ran.output) ? clip(ran.output, 700) : "";
      const item = {
        step: trace.length + 1, kind: "tool", tool: "search", part: subject,
        label: subject, text: lookup, kept: !!lookup, empty: !lookup,
      };
      trace.push(item);
      if (h.onStep) h.onStep(item);
      if (h.stop && h.stop()) return { trace, answer: paper, stopped: true };
      got = await h.answer(beatPrompt(question, subject, paper, lookup || "nothing returned"), SEGMENT_TOKENS);
      if (got == null) return { trace, answer: paper, stopped: true };
    }
    const rawBody = String(got || "").trim();
    if (!rawBody || toolCallOf(rawBody)) continue;
    let body = rawBody;
    if (search && !modelStands(question, rawBody)) {
      const notes = briefNotes(trace);
      body = carriesName(question, notes) ? notes : "";
    }
    if (!body) continue;
    paper = paper ? paper.replace(/\s+$/, "") + "\n\n" + body : body;
    if (h.commit) h.commit(body);
  }
  return { trace, answer: paper, stopped: false };
}

// Fills a plan from planOf. Tool steps run together. A reason or outline step
// is one model call. The last step is the write, and it sees only the tool
// text the quality check kept.
export async function runPlan(question, plan, hooks) {
  const h = hooks || {};
  const trace = [];
  const steps = (plan && plan.steps) || [];
  let n = 0;
  let i = 0;
  while (i < steps.length) {
    if (h.stop && h.stop()) return { trace, answer: "", stopped: true };
    if (steps[i].kind === "tool") {
      let j = i;
      while (j < steps.length && steps[j].kind === "tool") j++;
      const batch = steps.slice(i, j);
      let halted = false;
      for (let k = 0; k < batch.length; k++) {
        if (h.stop && h.stop()) { halted = true; break; }
        await beginStep(h, (batch[k].label || batch[k].tool || "Working") + "…");
        let ran = { output: "" };
        try { ran = (await h.run({ tool: batch[k].tool, args: batch[k].args || {} })) || ran; }
        catch { ran = { output: "", exit_code: 1 }; }
        n++;
        const step = batch[k];
        const output = ran.output || "";
        const echo = frameEcho(output, question);
        const usable = !echo && sourceKept(output);
        // clipLines keeps the blank lines between hits, so readTop can parse them.
        const text = usable ? clipLines(output, 1800) : "";
        const looked = step.tool === "search" || step.tool === "gather";
        const kept = usable && (looked || (h.keep ? !!h.keep(output) : true));
        const name = step.label || step.source || step.tool;
        const item = {
          step: n, kind: "tool", tool: step.tool, part: step.part || "",
          query: (step.args && step.args.q) || "",
          label: step.part ? step.part + " · " + name : name,
          text, kept, empty: !text,
        };
        trace.push(item);
        if (h.onStep) h.onStep(item);
      }
      if (halted) return { trace, answer: "", stopped: true };
      i = j;
      continue;
    }
    const step = steps[i];
    i++;
    n++;
    if (step.role === "write") {
      const outlined = [...trace].reverse().find((x) => x.role === "outline");
      const subjects = outlined ? sectionTitles(outlined.text) : [];
      const search = !!(plan && plan.search);
      if (search && !trace.some((x) => x.kind === "tool")) {
        const lookup = await loadSubject(subjects[0] || "", question, trace, h);
        if (lookup == null) return { trace, answer: "", stopped: true };
      }
      if (search && !trace.some((x) => x.page)) await readSources(trace, h, 1);
      if (subjects.length >= 2) return await emitSubjects(question, trace, subjects, h, search);
      if (h.stop && h.stop()) return { trace, answer: "", stopped: true };
      // The page's opening is the answer. The checkpoint rewrites "unincorporated"
      // into "incorporated" and copies the search card's cut snippets.
      const page = search ? pageItems(trace)[0] : null;
      const lead = page ? pageLead(page.text) : "";
      if (lead && carriesName(question, lead)) {
        const body = withSources(lead, trace, question);
        if (body && h.commit) h.commit(body);
        return { trace, answer: body, stopped: false };
      }
      const answer = await h.answer(writePrompt(question, trace), ANSWER_TOKENS);
      if (answer == null) return { trace, answer: "", stopped: true };
      const rawBody = String(answer).trim();
      if (toolCallOf(rawBody)) return { trace, answer: rawBody, stopped: false };
      let spoken = rawBody;
      if (search) {
        // A sentence the page does not hold is the checkpoint filling a gap
        // with a year or a name. The search card is titles and cut snippets.
        // When the write copies that card, the page's opening stays.
        const page = pageItems(trace)[0];
        const grounded = keepGrounded(rawBody, trace);
        const stands = modelStands(question, grounded) && !/sources do not cover/i.test(grounded) && !hitDump(grounded);
        if (stands) spoken = grounded;
        else if (page) spoken = pageLead(page.text);
        else spoken = "";
      }
      const body = withSources(spoken, trace, question);
      if (body && h.commit) h.commit(body);
      return { trace, answer: body, stopped: false };
    }
    const prompt = step.role === "reason" ? reasonPrompt(question) : outlinePrompt(question);
    const max = step.role === "reason" ? REASON_TOKENS : OUTLINE_TOKENS;
    const got = await h.chat(prompt, max);
    if (got == null) return { trace, answer: "", stopped: true };
    const call = toolCallOf(got);
    if (call && call.tool && call.tool !== "search" && h.run) {
      let ran = { output: "" };
      try { ran = (await h.run(call)) || ran; } catch { ran = { output: "" }; }
      const item = {
        step: n, kind: "tool", tool: call.tool, label: call.tool,
        text: sourceKept(ran.output) ? clip(ran.output, 700) : "",
        kept: sourceKept(ran.output), empty: !sourceKept(ran.output),
      };
      trace.push(item);
      if (h.onStep) h.onStep(item);
      continue;
    }
    const text = step.role === "outline" ? clipLines(got, 700) : clip(got, 700);
    if (!text) continue;
    const item = { step: n, kind: "model", role: step.role, text };
    trace.push(item);
    if (h.onStep) h.onStep(item);
  }
  return { trace, answer: "", stopped: false };
}