@hncode/hncode 0.7.3 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/agent.js +10 -5
- package/src/banner.js +222 -0
- package/src/colors.js +50 -1
- package/src/config.js +46 -2
- package/src/highlight.js +432 -0
- package/src/i18n.js +5 -5
- package/src/registry-browser.js +1 -1
- package/src/settings-schema.js +4 -0
- package/src/team-panel.js +1 -1
- package/src/term.js +971 -764
- package/src/tools/edit.js +63 -12
- package/src/tools/memory.js +92 -80
- package/src/tui.js +22214 -21521
- package/src/wordlist.js +6 -0
package/src/term.js
CHANGED
|
@@ -1,764 +1,971 @@
|
|
|
1
|
-
// Small TTY / terminal utilities.
|
|
2
|
-
// Test file for Write size display - this comment should be long enough to measure
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
return { cols: 80, rows: 24 };
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
stream.
|
|
31
|
-
stream.
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
cleanup
|
|
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
|
-
if (
|
|
70
|
-
const
|
|
71
|
-
if (
|
|
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
|
-
|| (c >=
|
|
133
|
-
|| (c >=
|
|
134
|
-
|| (c >=
|
|
135
|
-
|| (c >=
|
|
136
|
-
|| (c >=
|
|
137
|
-
|| (c >=
|
|
138
|
-
|| (c >=
|
|
139
|
-
|| (c >=
|
|
140
|
-
|| (c >=
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|| (c >=
|
|
154
|
-
|| (c >=
|
|
155
|
-
|| (c >=
|
|
156
|
-
||
|
|
157
|
-
|| c
|
|
158
|
-
|| c
|
|
159
|
-
|| c ===
|
|
160
|
-
|| c ===
|
|
161
|
-
||
|
|
162
|
-
|| c ===
|
|
163
|
-
|| (c >=
|
|
164
|
-
|| c ===
|
|
165
|
-
|| c
|
|
166
|
-
|| (c >=
|
|
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
|
-
if (c ===
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
//
|
|
298
|
-
//
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
if (
|
|
302
|
-
if (
|
|
303
|
-
return
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
//
|
|
309
|
-
//
|
|
310
|
-
//
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
//
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
if (
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
//
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
// Width of one grapheme cluster. Allocation-free on the common path: a
|
|
338
|
-
|
|
339
|
-
//
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
if (cps.includes(
|
|
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
|
-
const
|
|
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
|
-
let
|
|
434
|
-
let
|
|
435
|
-
let
|
|
436
|
-
let
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
if (cp
|
|
444
|
-
if (
|
|
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
|
-
// The
|
|
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
|
-
return
|
|
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
|
-
export function
|
|
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
|
-
|
|
1
|
+
// Small TTY / terminal utilities.
|
|
2
|
+
// Test file for Write size display - this comment should be long enough to measure
|
|
3
|
+
|
|
4
|
+
import { COMMON_WORDS } from './wordlist.js';
|
|
5
|
+
|
|
6
|
+
export function isTTY() {
|
|
7
|
+
return !!process.stdout.isTTY;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function size() {
|
|
11
|
+
try {
|
|
12
|
+
const [cols, rows] = process.stdout.getWindowSize();
|
|
13
|
+
return { cols: cols || 80, rows: rows || 24 };
|
|
14
|
+
} catch {
|
|
15
|
+
return { cols: 80, rows: 24 };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function writeRaw(str) {
|
|
20
|
+
if (!process.stdout.write(str)) return false;
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Enable raw mode around a callback, restoring on exit/error.
|
|
25
|
+
export function withRawMode(cb) {
|
|
26
|
+
const stream = process.stdin;
|
|
27
|
+
if (!stream.isTTY) {
|
|
28
|
+
throw new Error('hncode: interactive mode requires a TTY (stdin is not a terminal).');
|
|
29
|
+
}
|
|
30
|
+
const wasRaw = stream.isRaw;
|
|
31
|
+
stream.setRawMode(true);
|
|
32
|
+
stream.resume();
|
|
33
|
+
stream.setEncoding('utf8');
|
|
34
|
+
const cleanup = () => {
|
|
35
|
+
try { stream.setRawMode(wasRaw || false); } catch {}
|
|
36
|
+
stream.pause();
|
|
37
|
+
};
|
|
38
|
+
try {
|
|
39
|
+
return cb(cleanup);
|
|
40
|
+
} finally {
|
|
41
|
+
cleanup();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Visible width ignoring ANSI escapes (approx; no CJK width handling).
|
|
46
|
+
// NOTE: kept for back-compat; prefer visualWidth() for display-accurate width.
|
|
47
|
+
export function strWidth(s) {
|
|
48
|
+
return (s || '').replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').length;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// True visual column-width of a plain string (no ANSI), assuming a terminal that
|
|
52
|
+
// renders East Asian / wide / some symbol glyphs as 2 columns. Must be used for any
|
|
53
|
+
// cursor positioning and line wrapping so an I-shaped (insert) caret lines up.
|
|
54
|
+
// Source of truth: Unicode wide ranges + a small set of CJK-fused symbol glyphs.
|
|
55
|
+
//
|
|
56
|
+
// PERFORMANCE (this is the hottest function in the whole TUI — a profile of a
|
|
57
|
+
// 500-message transcript streaming markdown put ~48% of samples in this plus
|
|
58
|
+
// clusterWidth/clusterGlyphWidth/isWideByDefault):
|
|
59
|
+
// * a printable-ASCII fast path returns the length immediately. Agent output
|
|
60
|
+
// is overwhelmingly ASCII, and measuring it cost ~30 range comparisons per
|
|
61
|
+
// character for nothing. 1MB of ASCII went from 219ms to ~0.
|
|
62
|
+
// * everything else is memoised (see WIDTH_CACHE_MAX). Rows are re-measured
|
|
63
|
+
// every frame while a reply streams, and the same substrings come back
|
|
64
|
+
// again and again.
|
|
65
|
+
export function visualWidth(s) {
|
|
66
|
+
if (!s) return 0;
|
|
67
|
+
const str = typeof s === 'string' ? s : String(s);
|
|
68
|
+
// Fast path: printable ASCII measures exactly its length.
|
|
69
|
+
if (isPrintableAscii(str)) return str.length;
|
|
70
|
+
const hit = widthCache.get(str);
|
|
71
|
+
if (hit !== undefined) return hit;
|
|
72
|
+
const w = clusterWidth(str);
|
|
73
|
+
if (widthCache.size >= WIDTH_CACHE_MAX) {
|
|
74
|
+
// Cheap eviction: drop the oldest insertion (Map preserves order).
|
|
75
|
+
const oldest = widthCache.keys().next().value;
|
|
76
|
+
if (oldest !== undefined) widthCache.delete(oldest);
|
|
77
|
+
}
|
|
78
|
+
widthCache.set(str, w);
|
|
79
|
+
return w;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// All code units printable ASCII? `\t`/newline/escape all fail, which is what we
|
|
83
|
+
// want: those have their own width rules (tab = 4, ESC starts an ANSI sequence).
|
|
84
|
+
function isPrintableAscii(str) {
|
|
85
|
+
for (let i = 0; i < str.length; i++) {
|
|
86
|
+
const c = str.charCodeAt(i);
|
|
87
|
+
if (c < 0x20 || c > 0x7e) return false;
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const WIDTH_CACHE_MAX = 4096;
|
|
93
|
+
const widthCache = new Map();
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
// ---- East Asian Width tables (Unicode 15) --------------------------------
|
|
97
|
+
// Wide/Fullwidth ranges -> 2 columns. Everything else is 1 unless it is a
|
|
98
|
+
// zero-width character (see ZERO_WIDTH) or emoji presentation (see below).
|
|
99
|
+
const WIDE = [
|
|
100
|
+
[0x1100, 0x115F], [0x231A, 0x231B], [0x2329, 0x232A], [0x23E9, 0x23EC],
|
|
101
|
+
[0x23F0, 0x23F0], [0x23F3, 0x23F3], [0x25FD, 0x25FE], [0x2614, 0x2615],
|
|
102
|
+
[0x2648, 0x2653], [0x267F, 0x267F], [0x2693, 0x2693], [0x26A1, 0x26A1],
|
|
103
|
+
[0x26AA, 0x26AB], [0x26BD, 0x26BE], [0x26C4, 0x26C5], [0x26CE, 0x26CE],
|
|
104
|
+
[0x26D4, 0x26D4], [0x26EA, 0x26EA], [0x26F2, 0x26F3], [0x26F5, 0x26F5],
|
|
105
|
+
[0x26FA, 0x26FA], [0x26FD, 0x26FD], [0x2705, 0x2705], [0x270A, 0x270B],
|
|
106
|
+
[0x2728, 0x2728], [0x274C, 0x274C], [0x274E, 0x274E], [0x2753, 0x2755],
|
|
107
|
+
[0x2757, 0x2757], [0x2795, 0x2797], [0x27B0, 0x27B0], [0x27BF, 0x27BF],
|
|
108
|
+
[0x2B1B, 0x2B1C], [0x2B50, 0x2B50], [0x2B55, 0x2B55],
|
|
109
|
+
[0x2E80, 0x303E], [0x3041, 0x33FF], [0x3400, 0x4DBF], [0x4E00, 0x9FFF],
|
|
110
|
+
[0xA000, 0xA4CF], [0xA960, 0xA97F], [0xAC00, 0xD7A3], [0xF900, 0xFAFF],
|
|
111
|
+
[0xFE10, 0xFE19], [0xFE30, 0xFE6F], [0xFF00, 0xFF60], [0xFFE0, 0xFFE6],
|
|
112
|
+
[0x16FE0, 0x16FE4], [0x17000, 0x187F7], [0x18800, 0x18CD5],
|
|
113
|
+
[0x1B000, 0x1B152], [0x1B164, 0x1B167], [0x1B170, 0x1B2FB],
|
|
114
|
+
[0x1F004, 0x1F004], [0x1F0CF, 0x1F0CF], [0x1F18E, 0x1F18E],
|
|
115
|
+
[0x1F191, 0x1F19A], [0x1F200, 0x1F320], [0x1F32D, 0x1F335],
|
|
116
|
+
[0x1F337, 0x1F37C], [0x1F37E, 0x1F393], [0x1F3A0, 0x1F3CA],
|
|
117
|
+
[0x1F3CF, 0x1F3D3], [0x1F3E0, 0x1F3F0], [0x1F3F4, 0x1F3F4],
|
|
118
|
+
[0x1F3F8, 0x1F43E], [0x1F440, 0x1F440], [0x1F442, 0x1F4FC],
|
|
119
|
+
[0x1F4FF, 0x1F53D], [0x1F54B, 0x1F54E], [0x1F550, 0x1F567],
|
|
120
|
+
[0x1F57A, 0x1F57A], [0x1F595, 0x1F596], [0x1F5A4, 0x1F5A4],
|
|
121
|
+
[0x1F5FB, 0x1F64F], [0x1F680, 0x1F6C5], [0x1F6CC, 0x1F6CC],
|
|
122
|
+
[0x1F6D0, 0x1F6D2], [0x1F6D5, 0x1F6D7], [0x1F6DC, 0x1F6DF],
|
|
123
|
+
[0x1F6EB, 0x1F6EC], [0x1F6F4, 0x1F6FC], [0x1F7E0, 0x1F7EB],
|
|
124
|
+
[0x1F7F0, 0x1F7F0], [0x1F90C, 0x1F93A], [0x1F93C, 0x1F945],
|
|
125
|
+
[0x1F947, 0x1F9FF], [0x1FA70, 0x1FAFF],
|
|
126
|
+
[0x20000, 0x2FFFD], [0x30000, 0x3FFFD],
|
|
127
|
+
];
|
|
128
|
+
|
|
129
|
+
// Combining / formatting characters that occupy no cell.
|
|
130
|
+
function isZeroWidth(c) {
|
|
131
|
+
return (c >= 0x200B && c <= 0x200F) // ZWSP..RLM (incl. ZWJ U+200D)
|
|
132
|
+
|| (c >= 0x0300 && c <= 0x036F)
|
|
133
|
+
|| (c >= 0x0483 && c <= 0x0489)
|
|
134
|
+
|| (c >= 0x0591 && c <= 0x05BD) || c === 0x05BF || (c >= 0x05C1 && c <= 0x05C2)
|
|
135
|
+
|| (c >= 0x0610 && c <= 0x061A)
|
|
136
|
+
|| (c >= 0x064B && c <= 0x065F) || c === 0x0670
|
|
137
|
+
|| (c >= 0x06D6 && c <= 0x06DC)
|
|
138
|
+
|| (c >= 0x0E31 && c <= 0x0E3A) || (c >= 0x0E47 && c <= 0x0E4E)
|
|
139
|
+
|| (c >= 0x1AB0 && c <= 0x1AFF) || (c >= 0x1DC0 && c <= 0x1DFF)
|
|
140
|
+
|| (c >= 0x20D0 && c <= 0x20FF) || (c >= 0xFE00 && c <= 0xFE0F)
|
|
141
|
+
|| (c >= 0xFE20 && c <= 0xFE2F) || (c >= 0xE0100 && c <= 0xE01EF)
|
|
142
|
+
|| (c >= 0x1160 && c <= 0x11FF); // Hangul Jamo medial/final
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Regional Indicator (flags) — two of them form one glyph.
|
|
146
|
+
const isRegional = (c) => c >= 0x1F1E6 && c <= 0x1F1FF;
|
|
147
|
+
|
|
148
|
+
// Emoji that occupy TWO cells by default (Emoji_Presentation=Yes), even
|
|
149
|
+
// without U+FE0F. Text-default symbols (U+276F >, U+2603 ☃, U+00B7 ·, …) are
|
|
150
|
+
// NOT in here: they are 1 cell unless followed by U+FE0F.
|
|
151
|
+
function isWideByDefault(c) {
|
|
152
|
+
return (c >= 0x1F300 && c <= 0x1F5FF)
|
|
153
|
+
|| (c >= 0x1F600 && c <= 0x1F64F)
|
|
154
|
+
|| (c >= 0x1F680 && c <= 0x1F6FF)
|
|
155
|
+
|| (c >= 0x1F900 && c <= 0x1F9FF)
|
|
156
|
+
|| (c >= 0x1FA70 && c <= 0x1FAFF)
|
|
157
|
+
|| (c >= 0x1F000 && c <= 0x1F0FF)
|
|
158
|
+
|| isRegional(c)
|
|
159
|
+
|| c === 0x231A || c === 0x231B || c === 0x23E9 || c === 0x23EC
|
|
160
|
+
|| c === 0x23F0 || c === 0x23F3 || c === 0x25FD || c === 0x25FE
|
|
161
|
+
|| c === 0x2614 || c === 0x2615 || (c >= 0x2648 && c <= 0x2653)
|
|
162
|
+
|| c === 0x267F || c === 0x2693 || c === 0x26A1 || (c >= 0x26AA && c <= 0x26AB)
|
|
163
|
+
|| (c >= 0x26BD && c <= 0x26BE) || (c >= 0x26C4 && c <= 0x26C5)
|
|
164
|
+
|| c === 0x26CE || c === 0x26D4 || c === 0x26EA
|
|
165
|
+
|| (c >= 0x26F2 && c <= 0x26F3) || c === 0x26F5 || c === 0x26FA || c === 0x26FD
|
|
166
|
+
|| c === 0x2705 || (c >= 0x270A && c <= 0x270B) || c === 0x2728
|
|
167
|
+
|| c === 0x274C || c === 0x274E || (c >= 0x2753 && c <= 0x2755) || c === 0x2757
|
|
168
|
+
|| (c >= 0x2795 && c <= 0x2797) || c === 0x27B0 || c === 0x27BF
|
|
169
|
+
|| (c >= 0x2B1B && c <= 0x2B1C) || c === 0x2B50 || c === 0x2B55;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ---------------------------------------------------------------------------
|
|
173
|
+
// East Asian AMBIGUOUS width
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// Unicode gives every character an East Asian Width class. `A` (Ambiguous) means
|
|
176
|
+
// ONE column on a Western terminal and TWO on a CJK one — the terminal decides, the
|
|
177
|
+
// character does not say. hncode's chrome leans on these heavily, which is why they
|
|
178
|
+
// had to be handled rather than avoided:
|
|
179
|
+
//
|
|
180
|
+
// box rules ─ │ ╭ ╮ ╰ ╯ ┌ ┐ └ ┘ ├ ┤ ┬ ┴ ┼
|
|
181
|
+
// separators · … — –
|
|
182
|
+
// markers ↑ ↓ ← → > ● ○ ✓ ✗
|
|
183
|
+
// math ± × ÷ ≠ ≤ ≥ ∞
|
|
184
|
+
//
|
|
185
|
+
// Measuring them as 1 column on a CJK terminal made every row containing one N columns
|
|
186
|
+
// short, so the row's right edge landed N columns past the panel it belonged to —
|
|
187
|
+
// "the text pushes the wall right". The panel's own background could not hide it
|
|
188
|
+
// either: the overflow is REAL cells on screen, not a measurement disagreement inside
|
|
189
|
+
// one row.
|
|
190
|
+
//
|
|
191
|
+
// Default: follow the LOCALE. A CJK locale is the standard reason a terminal treats
|
|
192
|
+
// EAW=A as wide, and it is the only signal available before anything is drawn — the
|
|
193
|
+
// code page does not say (a UTF-8 Windows console still renders them wide), and no
|
|
194
|
+
// terminal query reports it.
|
|
195
|
+
let ambiguousWide = null; // lazily resolved so a test can set the env first
|
|
196
|
+
|
|
197
|
+
/** EAW=A ranges (Unicode 15), ascending — `inRanges` binary-searches this. */
|
|
198
|
+
const AMBIGUOUS = [
|
|
199
|
+
[0x00A1, 0x00A1], [0x00A4, 0x00A4], [0x00A7, 0x00A8], [0x00AA, 0x00AA],
|
|
200
|
+
[0x00AD, 0x00AE], [0x00B0, 0x00B4], [0x00B6, 0x00BA], [0x00BC, 0x00BF],
|
|
201
|
+
[0x00C6, 0x00C6], [0x00D0, 0x00D0], [0x00D7, 0x00D8], [0x00DE, 0x00E1],
|
|
202
|
+
[0x00E6, 0x00E6], [0x00E8, 0x00EA], [0x00EC, 0x00ED], [0x00F0, 0x00F0],
|
|
203
|
+
[0x00F2, 0x00F3], [0x00F7, 0x00FA], [0x00FC, 0x00FC], [0x00FE, 0x00FE],
|
|
204
|
+
[0x0101, 0x0101], [0x0111, 0x0111], [0x0113, 0x0113], [0x011B, 0x011B],
|
|
205
|
+
[0x0126, 0x0127], [0x012B, 0x012B], [0x0131, 0x0133], [0x0138, 0x0138],
|
|
206
|
+
[0x013F, 0x0142], [0x0144, 0x0144], [0x0148, 0x014B], [0x014D, 0x014D],
|
|
207
|
+
[0x0152, 0x0153], [0x0166, 0x0167], [0x016B, 0x016B], [0x01CE, 0x01CE],
|
|
208
|
+
[0x01D0, 0x01D0], [0x01D2, 0x01D2], [0x01D4, 0x01D4], [0x01D6, 0x01D6],
|
|
209
|
+
[0x01D8, 0x01D8], [0x01DA, 0x01DA], [0x01DC, 0x01DC], [0x0251, 0x0251],
|
|
210
|
+
[0x0261, 0x0261], [0x02C4, 0x02C4], [0x02C7, 0x02C7], [0x02C9, 0x02CB],
|
|
211
|
+
[0x02CD, 0x02CD], [0x02D0, 0x02D0], [0x02D8, 0x02DB], [0x02DD, 0x02DD],
|
|
212
|
+
[0x02DF, 0x02DF], [0x0300, 0x036F], [0x0391, 0x03A1], [0x03A3, 0x03A9],
|
|
213
|
+
[0x03B1, 0x03C1], [0x03C3, 0x03C9], [0x0401, 0x0401], [0x0410, 0x044F],
|
|
214
|
+
[0x0451, 0x0451], [0x2010, 0x2010], [0x2013, 0x2016], [0x2018, 0x2019],
|
|
215
|
+
[0x201C, 0x201D], [0x2020, 0x2022], [0x2024, 0x2027], [0x2030, 0x2030],
|
|
216
|
+
[0x2032, 0x2033], [0x2035, 0x2035], [0x203B, 0x203B], [0x203E, 0x203E],
|
|
217
|
+
[0x2074, 0x2074], [0x207F, 0x207F], [0x2081, 0x2084], [0x20AC, 0x20AC],
|
|
218
|
+
[0x2103, 0x2103], [0x2105, 0x2105], [0x2109, 0x2109], [0x2113, 0x2113],
|
|
219
|
+
[0x2116, 0x2116], [0x2121, 0x2122], [0x2126, 0x2126], [0x212B, 0x212B],
|
|
220
|
+
[0x2153, 0x2154], [0x215B, 0x215E], [0x2160, 0x216B], [0x2170, 0x2179],
|
|
221
|
+
[0x2189, 0x2189], [0x2190, 0x2199], [0x21B8, 0x21B9], [0x21D2, 0x21D2],
|
|
222
|
+
[0x21D4, 0x21D4], [0x21E7, 0x21E7], [0x2200, 0x2200], [0x2202, 0x2203],
|
|
223
|
+
[0x2207, 0x2208], [0x220B, 0x220B], [0x220F, 0x220F], [0x2211, 0x2211],
|
|
224
|
+
[0x2215, 0x2215], [0x221A, 0x221A], [0x221D, 0x2220], [0x2223, 0x2223],
|
|
225
|
+
[0x2225, 0x2225], [0x2227, 0x222C], [0x222E, 0x222E], [0x2234, 0x2237],
|
|
226
|
+
[0x223C, 0x223D], [0x2248, 0x2248], [0x224C, 0x224C], [0x2252, 0x2252],
|
|
227
|
+
[0x2260, 0x2261], [0x2264, 0x2267], [0x226A, 0x226B], [0x226E, 0x226F],
|
|
228
|
+
[0x2282, 0x2283], [0x2286, 0x2287], [0x2295, 0x2295], [0x2299, 0x2299],
|
|
229
|
+
[0x22A5, 0x22A5], [0x22BF, 0x22BF], [0x2312, 0x2312], [0x2460, 0x24E9],
|
|
230
|
+
[0x24EB, 0x254B], [0x2550, 0x2573], [0x2580, 0x258F], [0x2592, 0x2595],
|
|
231
|
+
[0x25A0, 0x25A1], [0x25A3, 0x25A9], [0x25B2, 0x25B3], [0x25B6, 0x25B7],
|
|
232
|
+
[0x25BC, 0x25BD], [0x25C0, 0x25C1], [0x25C6, 0x25C8], [0x25CB, 0x25CB],
|
|
233
|
+
[0x25CE, 0x25D1], [0x25E2, 0x25E5], [0x25EF, 0x25EF], [0x2605, 0x2606],
|
|
234
|
+
[0x2609, 0x2609], [0x260E, 0x260F], [0x261C, 0x261C], [0x261E, 0x261E],
|
|
235
|
+
[0x2640, 0x2640], [0x2642, 0x2642], [0x2660, 0x2661], [0x2663, 0x2665],
|
|
236
|
+
[0x2667, 0x266A], [0x266C, 0x266D], [0x266F, 0x266F], [0x269E, 0x269F],
|
|
237
|
+
[0x26C6, 0x26CD], [0x26CF, 0x26D3], [0x26D5, 0x26E1], [0x26E3, 0x26E3],
|
|
238
|
+
[0x26E8, 0x26E9], [0x26EB, 0x26F1], [0x26F4, 0x26F4], [0x26F6, 0x26F9],
|
|
239
|
+
[0x26FB, 0x26FC], [0x26FE, 0x26FF], [0x273D, 0x273D], [0x2761, 0x2761],
|
|
240
|
+
[0x2776, 0x277F], [0x2B56, 0x2B59], [0x3248, 0x324F], [0xE000, 0xF8FF],
|
|
241
|
+
[0xFE00, 0xFE0F], [0xFFFD, 0xFFFD], [0x1F100, 0x1F10A],
|
|
242
|
+
[0x1F110, 0x1F12D], [0x1F130, 0x1F169], [0x1F170, 0x1F19A],
|
|
243
|
+
];
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Should EAW=Ambiguous characters measure 2 columns?
|
|
247
|
+
*
|
|
248
|
+
* Resolved once, from (in order):
|
|
249
|
+
* 1. `HNCODE_AMBIGUOUS_WIDTH` — an explicit override, for a terminal whose setting
|
|
250
|
+
* does not match its locale;
|
|
251
|
+
* 2. the locale — `zh`/`ja`/`ko` mean a CJK terminal, which is the standard reason a
|
|
252
|
+
* terminal renders these wide.
|
|
253
|
+
*/
|
|
254
|
+
export function detectAmbiguousWide(env = process.env) {
|
|
255
|
+
const raw = env.HNCODE_AMBIGUOUS_WIDTH;
|
|
256
|
+
if (raw !== undefined && raw !== '') return /^(1|true|yes|on)$/i.test(raw);
|
|
257
|
+
let loc = '';
|
|
258
|
+
try { loc = (Intl.DateTimeFormat().resolvedOptions().locale) || ''; } catch { /* no Intl */ }
|
|
259
|
+
const tag = loc || env.LC_ALL || env.LC_CTYPE || env.LANG || '';
|
|
260
|
+
return /^(zh|ja|ko)\b/i.test(tag) || /^(zh|ja|ko)[-_]/i.test(tag);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function isAmbiguousWide() {
|
|
264
|
+
if (ambiguousWide === null) ambiguousWide = detectAmbiguousWide();
|
|
265
|
+
return ambiguousWide;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Turn the ambiguous-as-wide rule on or off. Clears the width cache, which is keyed by
|
|
270
|
+
* string alone and would otherwise hand back widths measured under the other rule.
|
|
271
|
+
*/
|
|
272
|
+
export function setAmbiguousWide(on) {
|
|
273
|
+
const next = !!on;
|
|
274
|
+
if (next === ambiguousWide) return;
|
|
275
|
+
ambiguousWide = next;
|
|
276
|
+
widthCache.clear();
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const inRanges = (c, ranges) => {
|
|
280
|
+
let lo = 0, hi = ranges.length - 1;
|
|
281
|
+
while (lo <= hi) {
|
|
282
|
+
const mid = (lo + hi) >> 1;
|
|
283
|
+
const [s, e] = ranges[mid];
|
|
284
|
+
if (c < s) hi = mid - 1;
|
|
285
|
+
else if (c > e) lo = mid + 1;
|
|
286
|
+
else return true;
|
|
287
|
+
}
|
|
288
|
+
return false;
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
export function charWidth(ch) {
|
|
292
|
+
const c = String(ch).codePointAt(0);
|
|
293
|
+
if (c === undefined) return 0;
|
|
294
|
+
// Tab renders as 4 spaces in most terminals.
|
|
295
|
+
if (c === 0x09) return 4;
|
|
296
|
+
if (c < 0x20 || c === 0x7F) return 0;
|
|
297
|
+
// FAST PATH: plain printable ASCII is exactly one cell wide. Without this each
|
|
298
|
+
// ASCII character paid for isZeroWidth + isWideByDefault (≈30 range tests) + a
|
|
299
|
+
// binary search, which is most of what made width measurement the hottest
|
|
300
|
+
// function in the TUI.
|
|
301
|
+
if (c >= 0x20 && c <= 0x7e) return 1;
|
|
302
|
+
if (isZeroWidth(c)) return 0;
|
|
303
|
+
if (isWideByDefault(c)) return 2;
|
|
304
|
+
if (inRanges(c, WIDE)) return 2;
|
|
305
|
+
return 1;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Shared native segmenter. `Intl.Segmenter` implements the full Unicode
|
|
309
|
+
// grapheme-break algorithm in native code, so it is both more correct than the
|
|
310
|
+
// hand-rolled scanner it replaces (ZWJ families, flags, combining marks) and
|
|
311
|
+
// much cheaper — that scanner allocated a `{text, next}` object per character,
|
|
312
|
+
// which showed up as GC pressure in profiles.
|
|
313
|
+
const graphemeSegmenter = typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
|
|
314
|
+
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
|
|
315
|
+
: null;
|
|
316
|
+
|
|
317
|
+
// Width of a whole string measured by GRAPHEME CLUSTER: a ZWJ sequence or a
|
|
318
|
+
// flag counts 2 columns total, not the sum of its codepoints (which used to
|
|
319
|
+
// make 👨👩👧 measure 8 columns and break every row it appeared on).
|
|
320
|
+
export function clusterWidth(s) {
|
|
321
|
+
const str = String(s || '');
|
|
322
|
+
if (!str) return 0;
|
|
323
|
+
let w = 0;
|
|
324
|
+
if (graphemeSegmenter) {
|
|
325
|
+
// NOTE: an "ASCII runs are free" split was tried here and made things WORSE
|
|
326
|
+
// (a 500KB markdown string went 97ms -> 544ms): slicing the string into a
|
|
327
|
+
// run per CJK character costs far more than handing the whole thing to the
|
|
328
|
+
// native segmenter. The real win is the printable-ASCII fast path in
|
|
329
|
+
// visualWidth() plus the memo cache, not micro-splitting here.
|
|
330
|
+
for (const { segment } of graphemeSegmenter.segment(str)) w += clusterGlyphWidth(segment);
|
|
331
|
+
return w;
|
|
332
|
+
}
|
|
333
|
+
// Fallback for a runtime without Intl.Segmenter: per code point.
|
|
334
|
+
for (const ch of str) w += clusterGlyphWidth(ch);
|
|
335
|
+
return w;
|
|
336
|
+
}
|
|
337
|
+
// Width of one grapheme cluster. Allocation-free on the common path: a
|
|
338
|
+
|
|
339
|
+
// Width of one grapheme cluster. Allocation-free on the common path: a
|
|
340
|
+
// single-code-point cluster (every ASCII character, most CJK) returns
|
|
341
|
+
// charWidth directly instead of first building an array of code points.
|
|
342
|
+
function clusterGlyphWidth(cluster) {
|
|
343
|
+
const first = cluster.codePointAt(0);
|
|
344
|
+
if (first === undefined) return 0;
|
|
345
|
+
if (cluster.length <= (first > 0xFFFF ? 2 : 1)) return charWidth(cluster);
|
|
346
|
+
|
|
347
|
+
const cps = [];
|
|
348
|
+
for (let i = 0; i < cluster.length;) {
|
|
349
|
+
const cp = cluster.codePointAt(i);
|
|
350
|
+
cps.push(cp);
|
|
351
|
+
i += cp > 0xFFFF ? 2 : 1;
|
|
352
|
+
}
|
|
353
|
+
// ZWJ sequence / flag pair / VS16-presented symbol => 2 columns.
|
|
354
|
+
if (cps.includes(0x200D)) return 2;
|
|
355
|
+
if (cps.some(isRegional)) return 2;
|
|
356
|
+
if (cps.includes(0xFE0F)) return 2; // explicit emoji presentation
|
|
357
|
+
let width = charWidth(String.fromCodePoint(cps[0]));
|
|
358
|
+
for (let k = 1; k < cps.length; k++) width += charWidth(String.fromCodePoint(cps[k]));
|
|
359
|
+
return width;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Estimate the LLM token count of a plain string, matching kimi-code's
|
|
363
|
+
// algorithm in `llm-adapter/contract/tokens.ts`:
|
|
364
|
+
// tokens = ceil(ASCII chars / 4) + non-ASCII chars
|
|
365
|
+
// ASCII characters average ~4 per token; CJK and other non-ASCII are ~1 token
|
|
366
|
+
// each. This is far more accurate than a uniform chars/4 ratio.
|
|
367
|
+
// Token estimate. The character walk is O(len), and the context gauge re-prices
|
|
368
|
+
// whole message bodies (a Read result can be hundreds of KB) every turn.
|
|
369
|
+
//
|
|
370
|
+
// A value cache only helps COMPLETED messages: they are immutable, so the same
|
|
371
|
+
// string is measured again and again. It actively HURTS streaming text, where the
|
|
372
|
+
// string grows every frame — every call is a miss, so the cache pays hashing and an
|
|
373
|
+
// insert each time and (once full) an O(n) eviction sweep, measuring 1ms/call vs
|
|
374
|
+
// ~0.001ms for a plain walk (30k growing-text calls: 31s cached vs 30ms uncached).
|
|
375
|
+
//
|
|
376
|
+
// So the cache is limited to SHORT strings: completed metadata and role names hit
|
|
377
|
+
// it, while a long or growing body is just walked directly. At most 4 KB was chosen
|
|
378
|
+
// because a token estimate is only ever re-asked for values that are cheap to hold
|
|
379
|
+
// and genuinely stable; anything larger is better re-walked than hashed + stored.
|
|
380
|
+
const tokCache = new Map();
|
|
381
|
+
const TOK_CACHE_MAX = 20000;
|
|
382
|
+
const TOK_CACHE_MAX_LEN = 4096; // only memoise strings this short
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* The same estimate, UNROUNDED — for summing many small chunks.
|
|
386
|
+
*
|
|
387
|
+
* `estimateTokens` rounds up, which is right for measuring one finished body: a 5-character
|
|
388
|
+
* message should not read as 1.25 tokens.
|
|
389
|
+
*
|
|
390
|
+
* It is wrong for a STREAM. Deltas arrive a few characters at a time, and each one took
|
|
391
|
+
* `ceil(ascii / 4)` — `ceil(3/4)` is 1, so three characters were billed as a whole token. Over
|
|
392
|
+
* hundreds of chunks that inflated the running figure badly: measured at +33% on ordinary
|
|
393
|
+
* English, and the visible symptom was the output counter DROPPING (3000 -> 2300) the moment the
|
|
394
|
+
* provider's exact `usage` arrived and replaced the estimate. Nothing was lost; the estimate had
|
|
395
|
+
* been lying.
|
|
396
|
+
*
|
|
397
|
+
* So the running counter accumulates this unrounded value, and rounds once when it displays.
|
|
398
|
+
* Callers that measure a complete string keep using `estimateTokens`.
|
|
399
|
+
*/
|
|
400
|
+
export function estimateTokensFloat(text) {
|
|
401
|
+
// THE STREAMING COUNTER MEASURES FRAGMENTS, and this is the estimator for fragments.
|
|
402
|
+
//
|
|
403
|
+
// The segment rules cannot be applied to a fragment: `the quick brown` measured whole is four tokens, and the
|
|
404
|
+
// same text as three-character fragments came out at 1.86x, because each fragment is priced as if it were a
|
|
405
|
+
// whole word. The character-class rule does not care where a fragment starts, so it is the one used here.
|
|
406
|
+
//
|
|
407
|
+
// The class rule is the one this file used for everything before segment pricing was added; it is kept because
|
|
408
|
+
// it is the only rule that survives being cut in half.
|
|
409
|
+
return estimateTokensByClass(String(text ?? ''));
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* The character-class estimator: characters per token, BY CLASS, with no regard for where the text starts.
|
|
414
|
+
*
|
|
415
|
+
* It is the rule this file used for everything before segment pricing was added, and it is kept for the STREAMING
|
|
416
|
+
* COUNTER, which is fed fragments: a delta starts and ends mid-word, and a rule that depends on the shape of the
|
|
417
|
+
* whole cannot be applied to one. Being state-free, it charges a fragment and the whole string the same per
|
|
418
|
+
* character — which is the property that makes a chunked sum agree with a one-shot measurement.
|
|
419
|
+
*
|
|
420
|
+
* The measured rates against `o200k_base`:
|
|
421
|
+
*
|
|
422
|
+
* letters and spaces 4.2 the "four characters per token" folklore, and the only place it holds
|
|
423
|
+
* digits 3.0 punctuation-free but rarely repeated
|
|
424
|
+
* punctuation 2.7 brackets, quotes, colons, operators — merge poorly
|
|
425
|
+
* whitespace (indent) 1.0 a run of spaces still costs a token per couple of columns
|
|
426
|
+
* CJK and other 1.0 one token per character, occasionally two
|
|
427
|
+
*
|
|
428
|
+
* Counted in ONE pass, because this runs on every streamed chunk.
|
|
429
|
+
*/
|
|
430
|
+
export function estimateTokensByClass(s) {
|
|
431
|
+
if (!s) return 0;
|
|
432
|
+
let letters = 0;
|
|
433
|
+
let digits = 0;
|
|
434
|
+
let punct = 0;
|
|
435
|
+
let space = 0;
|
|
436
|
+
let wide = 0;
|
|
437
|
+
|
|
438
|
+
for (const ch of s) {
|
|
439
|
+
const cp = ch.codePointAt(0);
|
|
440
|
+
// A NON-ASCII CHARACTER is not a whole token: `o200k` charges 1.45 characters per token for Chinese, so
|
|
441
|
+
// charging one token each put a Chinese paragraph at 1.57x. The segment rule cannot be used here because a
|
|
442
|
+
// FRAGMENT is not a segment, so the ratio is carried here.
|
|
443
|
+
if (cp > 127) { wide += 1 / 1.45; continue; }
|
|
444
|
+
if (cp === 32 || cp === 9) { space++; continue; }
|
|
445
|
+
if (cp >= 48 && cp <= 57) { digits++; continue; }
|
|
446
|
+
if ((cp >= 65 && cp <= 90) || (cp >= 97 && cp <= 122)) { letters++; continue; }
|
|
447
|
+
punct++;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// Newlines land in `punct` (they are not 32 or 9), which is the right rate for them.
|
|
451
|
+
//
|
|
452
|
+
// The SPACE rate is the delicate one: a run of indentation costs about a token per two columns, but a
|
|
453
|
+
// single space between English words merges into the following word almost for free. Charging every
|
|
454
|
+
// space at the indentation rate made prose read 34% high — a worse error than the undercount it fixed,
|
|
455
|
+
// because prose is what the model WRITES back.
|
|
456
|
+
//
|
|
457
|
+
// So spaces are priced at a third of a token each: cheap enough for prose, and still enough that a
|
|
458
|
+
// deeply indented code block is not free.
|
|
459
|
+
return letters / 4.2 + digits / 3.0 + punct / 2.7 + space / 3.0 + wide;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* A token estimate calibrated against OpenAI's `o200k_base`, by SEGMENT rather than by character class.
|
|
464
|
+
*
|
|
465
|
+
* WHY SEGMENTS
|
|
466
|
+
* ------------
|
|
467
|
+
* The previous rule counted characters per class over the whole string: letters at 4.2 per token, digits at 3.0,
|
|
468
|
+
* punctuation at 2.7. That is a rate for an AVERAGE string, and the interesting cases are not average — a short
|
|
469
|
+
* lowercase word is ONE token however long it is, a digit run is one token per three digits, and a CJK paragraph
|
|
470
|
+
* has no spaces to merge on at all. Averaging those together produces a number that is wrong for every one of them.
|
|
471
|
+
*
|
|
472
|
+
* The rules below are tokenx's, calibrated against `o200k_base` (https://github.com/johannschopplich/tokenx):
|
|
473
|
+
*
|
|
474
|
+
* whitespace 0, except indentation and blank lines, which cost 1
|
|
475
|
+
* a short word 1 — `o200k` merges common lowercase words of up to 8 characters into one token
|
|
476
|
+
* a digit run 1 per 3 digits — `o200k` chunks digits in threes
|
|
477
|
+
* punctuation 1 per 6 characters
|
|
478
|
+
* CJK 1.2 per hanzi, 1.35 per kana, 1.65 per hangul
|
|
479
|
+
* everything else 1 per 7 characters
|
|
480
|
+
*
|
|
481
|
+
* The result is within a few percent of the real tokenizer on prose, code and CJK, where the class-average rule was
|
|
482
|
+
* 20-35% out on code and JSON.
|
|
483
|
+
*/
|
|
484
|
+
function estimateBpe(s) {
|
|
485
|
+
if (!s) return 0;
|
|
486
|
+
let total = 0;
|
|
487
|
+
let previous = '';
|
|
488
|
+
// Split on whitespace runs and punctuation runs: those are the boundaries at which `o200k` starts a new token.
|
|
489
|
+
//
|
|
490
|
+
// The PATH SEPARATORS stay INSIDE the segment: a path is priced as a whole, and splitting it into separators and
|
|
491
|
+
// words made each separator cost a token of its own — a path came out at 1.19x where the real figure is 0.96x.
|
|
492
|
+
// The colon and the comma DO split: `{"a":1,"b":2}` is a run of two-character pairs, and leaving them inside one
|
|
493
|
+
// segment put a minified payload at 0.73x.
|
|
494
|
+
//
|
|
495
|
+
// The QUOTES DO NOT split either: `o200k` keeps `"type"` as one token, quotes included, and splitting them off
|
|
496
|
+
// charged a token for each quote.
|
|
497
|
+
const parts = s.split(/(\s+|[.,!?;(){}<>|@#$%^&*+=`~:]+)/);
|
|
498
|
+
for (let i = 0; i < parts.length; i++) {
|
|
499
|
+
const seg = parts[i];
|
|
500
|
+
if (!seg) continue;
|
|
501
|
+
if (/^\s+$/.test(seg)) {
|
|
502
|
+
// Indentation and blank lines cost a token; a space between words merges into the next word for free.
|
|
503
|
+
// WHITESPACE, priced by what SURROUNDS it. A space merges into the word that follows it and is free;
|
|
504
|
+
// only a space with nothing after it stands on its own. Measured against the real tokenizer:
|
|
505
|
+
//
|
|
506
|
+
// 'the quick brown' 3 tokens — the spaces between the words are free
|
|
507
|
+
// 'function ' 2 tokens — the trailing space is a token of its own
|
|
508
|
+
// ' abc' 1 token — the leading space is free
|
|
509
|
+
// '\n const' 3 tokens — the newline, the indent and the word are three
|
|
510
|
+
const next = parts[i + 1];
|
|
511
|
+
// A space merges into the word after it — and only a WORD. `out = []` has a space before an operator, and that
|
|
512
|
+
// space stands on its own; treating every non-space as a word put a TypeScript sample at 1.35x.
|
|
513
|
+
// WHITESPACE merges into the token BEFORE it, and it is only free when there is nothing before it.
|
|
514
|
+
// Measured against the real tokenizer:
|
|
515
|
+
//
|
|
516
|
+
// 'the quick brown' 3 tokens — the spaces between the words cost nothing
|
|
517
|
+
// 'function ' 2 tokens — the trailing space is a token of its own
|
|
518
|
+
// ' abc' 1 token — the leading space is free
|
|
519
|
+
// '\n const' 3 tokens — the newline, the indent and the word are three
|
|
520
|
+
// 'out = []' the space before an operator is free
|
|
521
|
+
//
|
|
522
|
+
// Looking FORWARD at what follows the space was wrong in both directions: `out = []` has a space before an
|
|
523
|
+
// operator and that space is free, while `function ` has a space at the end of the text and it is not.
|
|
524
|
+
const hadContent = previous.length > 0 && !/^\s+$/.test(previous);
|
|
525
|
+
if (/\n/.test(seg)) {
|
|
526
|
+
// A NEWLINE is a token of its own, and the indentation after it costs ONE token in total:
|
|
527
|
+
// `'\n const'` is three — the newline, the indent and the word — and the indent is a single token however
|
|
528
|
+
// wide it is.
|
|
529
|
+
const spaces = (seg.match(/ /g) || []).length;
|
|
530
|
+
total += 1 + (spaces > 0 ? 1 : 0);
|
|
531
|
+
previous = seg;
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
// A space at the START of the measured text is free: it belongs to the word that follows it, and
|
|
535
|
+
// `o200k` charges one token for `' abc'`.
|
|
536
|
+
//
|
|
537
|
+
// This used to depend on whether anything had been seen YET, which is what a chunked measurement looks
|
|
538
|
+
// like: every chunk starts with the space that ended the previous one, and a turn worth of deltas came out
|
|
539
|
+
// at 2.2x the whole-string measurement. The rule is now unconditional — a leading space is always free.
|
|
540
|
+
previous = seg;
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
// CJK: no spaces, so a whole clause is one segment and the ratio depends on the script mix.
|
|
544
|
+
if (CJK_RE.test(seg)) { total += cjkTokens(seg); previous = seg; continue; }
|
|
545
|
+
// Accented scripts break BPE badly; each has its own measured rate.
|
|
546
|
+
const lang = langCharsPerToken(seg);
|
|
547
|
+
if (lang !== null) { total += Math.ceil(charCount(seg) / lang); previous = seg; continue; }
|
|
548
|
+
// A DIGIT RUN. `o200k` splits a long run into groups of three, but the groups MERGE where they can: ten digits
|
|
549
|
+
// cost four tokens (2.5 characters each) and three digits cost one (3 each). A flat rate has to split the
|
|
550
|
+
// difference, so a short run is charged one token and a long one one per two and a half.
|
|
551
|
+
if (/^\d+$/.test(seg)) { total += seg.length <= 3 ? 1 : Math.ceil(seg.length / 2.5); previous = seg; continue; }
|
|
552
|
+
// Three characters or fewer are always one token.
|
|
553
|
+
if (seg.length <= 3) { total += 1; previous = seg; continue; }
|
|
554
|
+
// A PATH. `o200k` treats `D:\hncode\src\team-panel.js` as one run of characters, and measured it runs at 3.9
|
|
555
|
+
// characters per token — the separators drag it below the 6.3 an identifier gets. Pricing its parts separately
|
|
556
|
+
// charged every separator a token of its own and put a path at 1.19x.
|
|
557
|
+
if (/[/\\]/.test(seg)) { total += Math.ceil(seg.length / 3.9); previous = seg; continue; }
|
|
558
|
+
// A COMMON lowercase word is ONE token, and "common" is the operative word: `o200k` merges `include` (seven
|
|
559
|
+
// letters, one token) and splits `hncode` (six letters, two). No LENGTH threshold separates them — a cutoff of
|
|
560
|
+
// five and a cutoff of eight each get one of the two wrong — so the words that merge are listed instead.
|
|
561
|
+
//
|
|
562
|
+
// The list is the vocabulary of English prose, of code and of the identifiers a session's own transcript is
|
|
563
|
+
// full of, and it is inline because the project has no dependencies and a word list is not worth one.
|
|
564
|
+
if (/^[a-z]+$/.test(seg) && COMMON_WORDS.has(seg)) { total += 1; previous = seg; continue; }
|
|
565
|
+
// A QUOTED WORD is one token in `o200k` — `"type"` is a single token with the quotes attached — and the word
|
|
566
|
+
// inside it is looked up in the same list. Without this a JSON key was priced as a plain word of letters,
|
|
567
|
+
// quotes and all, and every key in a tool schema cost more than it does.
|
|
568
|
+
const quoted = /^"([A-Za-z][A-Za-z0-9_]*)"$/.exec(seg);
|
|
569
|
+
if (quoted && COMMON_WORDS.has(quoted[1].toLowerCase())) { total += 1; previous = seg; continue; }
|
|
570
|
+
// Punctuation merges POORLY, but not one token per character: the pair `{"` and the pair `":` are single
|
|
571
|
+
// tokens in JSON, so a run of them costs about four characters per token. Swept against the real tokenizer
|
|
572
|
+
// over prose, code, JSON, CJK and shell, four is the value that keeps every kind closest.
|
|
573
|
+
if (/^[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]+$/.test(seg)) {
|
|
574
|
+
// A SINGLE separator merges with the word beside it — `\h`, `e-p`, `n=` are each part of one token — so it
|
|
575
|
+
// costs one token. A RUN of them does not merge as well: `{"` and `":` are pairs that do, at about four
|
|
576
|
+
// characters per token.
|
|
577
|
+
total += seg.length === 1 ? 1 : Math.ceil(seg.length / 4); previous = seg; continue;
|
|
578
|
+
}
|
|
579
|
+
// A SEGMENT WITH A DIGIT IN IT is a hex literal, a version or an identifier with a number in it. Measured
|
|
580
|
+
// against the real tokenizer: `abc123` runs at 3 characters per token and `renderFrame` at 5.5, but `v2` and
|
|
581
|
+
// `0x1f` are one token per character — a leading digit breaks every merge.
|
|
582
|
+
if (/\d/.test(seg)) {
|
|
583
|
+
const rate = /^\d/.test(seg) ? 1 : 3;
|
|
584
|
+
total += Math.ceil(seg.length / rate); previous = seg; continue;
|
|
585
|
+
}
|
|
586
|
+
// EVERYTHING ELSE — long identifiers, camelCase, paths, mixed words. Measured: a camelCase identifier runs at
|
|
587
|
+
// 6.3 characters per token, a path at 3.9 (the separators pull it down), plain prose at 4.9 (but prose is caught
|
|
588
|
+
// by the short-word rule above). Six is the compromise that keeps the common case close.
|
|
589
|
+
total += Math.ceil(seg.length / 6);
|
|
590
|
+
previous = seg;
|
|
591
|
+
}
|
|
592
|
+
return total;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// The CJK ranges that carry one or more characters per token. Written as escapes so the file stays ASCII, and
|
|
596
|
+
// listed once each: an earlier version had `豈-` twice and the per-script split below had to look at the
|
|
597
|
+
// code point rather than at the range.
|
|
598
|
+
const CJK_RE = /[⺀-鿿㐀-䶿 -〿豈-︰-﹏--ㄯ㈀-㋿㐀-䷿ꀀ-가-]/;
|
|
599
|
+
// Per-script rates, MEASURED against `o200k_base` rather than taken from tokenx.
|
|
600
|
+
//
|
|
601
|
+
// tokenx's figures are 1.2 per hanzi, 1.35 per kana and 1.65 per hangul, but counting the real tokenizer's own
|
|
602
|
+
// output gives 1.45, 1.54 and 1.38 — tokenx is optimistic on hanzi and hangul, and pessimistic on kana. The numbers
|
|
603
|
+
// below are the measured ones, because the point of the estimator is to agree with what the provider bills.
|
|
604
|
+
const HANZI_PER_TOKEN = 1.45;
|
|
605
|
+
const KANA_PER_TOKEN = 1.54;
|
|
606
|
+
const HANGUL_PER_TOKEN = 1.38;
|
|
607
|
+
// Fullwidth punctuation is its own token class: 1.25 characters per token, measured.
|
|
608
|
+
const FULLWIDTH_PUNCT_PER_TOKEN = 1.25;
|
|
609
|
+
|
|
610
|
+
/** One rounding for the whole segment: rounding each script on its own charges a token per script boundary. */
|
|
611
|
+
function cjkTokens(seg) {
|
|
612
|
+
let kana = 0;
|
|
613
|
+
let hangul = 0;
|
|
614
|
+
let hanzi = 0;
|
|
615
|
+
let punct = 0;
|
|
616
|
+
for (const ch of seg) {
|
|
617
|
+
const cp = ch.codePointAt(0);
|
|
618
|
+
if (cp >= 0x3040 && cp <= 0x30ff) kana++;
|
|
619
|
+
else if ((cp >= 0xac00 && cp <= 0xd7af) || (cp >= 0x1100 && cp <= 0x11ff)
|
|
620
|
+
|| (cp >= 0x3130 && cp <= 0x318f) || (cp >= 0xa960 && cp <= 0xa97f)
|
|
621
|
+
|| (cp >= 0xd7b0 && cp <= 0xd7ff)) hangul++;
|
|
622
|
+
else if ((cp >= 0x3001 && cp <= 0x3003) || (cp >= 0x3008 && cp <= 0x3011)
|
|
623
|
+
|| (cp >= 0x3014 && cp <= 0x301f) || cp === 0x3030 || cp === 0x30fb
|
|
624
|
+
|| (cp >= 0xff01 && cp <= 0xff0f) || (cp >= 0xff1a && cp <= 0xff20)
|
|
625
|
+
|| (cp >= 0xff3b && cp <= 0xff40) || (cp >= 0xff5b && cp <= 0xff65)) punct++;
|
|
626
|
+
else hanzi++;
|
|
627
|
+
}
|
|
628
|
+
return Math.ceil(hanzi / HANZI_PER_TOKEN + kana / KANA_PER_TOKEN + hangul / HANGUL_PER_TOKEN
|
|
629
|
+
+ punct / FULLWIDTH_PUNCT_PER_TOKEN);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* The measured characters-per-token for a segment, or null when no rule applies.
|
|
634
|
+
*
|
|
635
|
+
* An accent rule prices a whole language through the minority of its words that carry the accent, so each rate is
|
|
636
|
+
* fitted against running text in that language rather than against the segments the pattern matches. Every rule
|
|
637
|
+
* needs a non-ASCII character, so ASCII-only segments skip them.
|
|
638
|
+
*/
|
|
639
|
+
function langCharsPerToken(seg) {
|
|
640
|
+
if (!NON_ASCII_RE.test(seg)) return null;
|
|
641
|
+
if (/[äöüßẞ]/i.test(seg)) return 3;
|
|
642
|
+
if (/[éèêëàâîïôûùüÿçœæáíóúñ]/i.test(seg)) return 4.5;
|
|
643
|
+
// Below what the accented segments alone would fit: unaccented Slavic words fall through to the default ratio,
|
|
644
|
+
// and this compensates the shortfall.
|
|
645
|
+
if (/[ąćęłńóśźżěščřžýůúďťň]/i.test(seg)) return 2.5;
|
|
646
|
+
if (/[Ѐ-яё]/i.test(seg)) return 6;
|
|
647
|
+
if (/[Ό-ώ]/i.test(seg)) return 3;
|
|
648
|
+
if (/^\p{Extended_Pictographic}[\p{Extended_Pictographic}\p{Emoji_Component}]*$/u.test(seg)) return 0.9;
|
|
649
|
+
return null;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
const NON_ASCII_RE = /[-]/;
|
|
653
|
+
|
|
654
|
+
/** Code points, not UTF-16 units: an emoji is one character, not two. */
|
|
655
|
+
function charCount(s) {
|
|
656
|
+
let n = 0;
|
|
657
|
+
for (const _ of s) n++;
|
|
658
|
+
return n;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
export function estimateTokens(text) {
|
|
662
|
+
const s = String(text ?? '');
|
|
663
|
+
if (s.length <= TOK_CACHE_MAX_LEN) {
|
|
664
|
+
const hit = tokCache.get(s);
|
|
665
|
+
if (hit !== undefined) return hit;
|
|
666
|
+
// Rounded UP from the same BPE-aware estimate the streaming counter uses. Both must agree: a body
|
|
667
|
+
// measured one way and a stream measured another is how a session ends up reporting two numbers.
|
|
668
|
+
const out = Math.ceil(estimateBpe(s));
|
|
669
|
+
if (tokCache.size >= TOK_CACHE_MAX) {
|
|
670
|
+
// Drop the oldest half in one go: cheaper than one-at-a-time and keeps the
|
|
671
|
+
// recently measured entries that a per-entry eviction would churn.
|
|
672
|
+
let i = 0;
|
|
673
|
+
for (const k of tokCache.keys()) { tokCache.delete(k); if (++i >= TOK_CACHE_MAX / 2) break; }
|
|
674
|
+
}
|
|
675
|
+
tokCache.set(s, out);
|
|
676
|
+
return out;
|
|
677
|
+
}
|
|
678
|
+
// Long body: measured directly, with the SAME estimator as the cached path. The two used to differ, so
|
|
679
|
+
// a long message and a short one were priced by different formulas.
|
|
680
|
+
return Math.ceil(estimateBpe(s));
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// Estimate tokens for the MESSAGES only. The system prompt and tool definitions are
|
|
684
|
+
// NOT included: `messages` usually already starts with the system prompt (the TUI
|
|
685
|
+
// builds `[{ role: 'system', content: sysText }, ...]`), so adding `cfg.systemPrompt`
|
|
686
|
+
// on top counted it twice — and the value in `cfg` is the RAW prompt, not the
|
|
687
|
+
// assembled `sysText` (calm/plan/swarm/AGENTS.md appended), so it was also the wrong
|
|
688
|
+
// number. Callers that want the whole request add it themselves via
|
|
689
|
+
// estimateRequestOverhead().
|
|
690
|
+
export function estimateMessagesTokens(messages, cfg) {
|
|
691
|
+
// THROUGH `messageTokens`, NOT `estimateMessageTokens`. Same arithmetic — the memoised path calls the same
|
|
692
|
+
// estimator — but the raw one re-measures EVERY message on EVERY call, and its callers are the hot ones: the
|
|
693
|
+
// context gauge at each step, and the estimate a request is priced against. On a long session that is a full
|
|
694
|
+
// walk of the history, Read results included, which is what made sending a message pause. `messageTokens` keeps
|
|
695
|
+
// a per-message WeakMap keyed on the object, so an append-only history costs one measurement for what is new.
|
|
696
|
+
let total = 0;
|
|
697
|
+
for (const m of messages || []) total += messageTokens(m, cfg);
|
|
698
|
+
return total;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* Tokens for ONE message. Split out so callers that walk the history (e.g.
|
|
703
|
+
* planCompaction) can price each message ONCE instead of re-summing the whole
|
|
704
|
+
* array per message — that was O(n²) over the transcript.
|
|
705
|
+
*/
|
|
706
|
+
export function estimateMessageTokens(m, cfg) {
|
|
707
|
+
if (!m) return 0;
|
|
708
|
+
let total = estimateTokens(m.role || '');
|
|
709
|
+
const c = m.content;
|
|
710
|
+
if (typeof c === 'string') {
|
|
711
|
+
total += estimateTokens(c);
|
|
712
|
+
} else if (c && typeof c === 'object' && Array.isArray(c.media)) {
|
|
713
|
+
total += estimateMediaContentTokens(c);
|
|
714
|
+
} else {
|
|
715
|
+
total += estimateTokens(JSON.stringify(c || ''));
|
|
716
|
+
}
|
|
717
|
+
if (m.toolCalls) for (const tc of m.toolCalls) {
|
|
718
|
+
total += estimateTokens(tc.name || '') + estimateTokens(JSON.stringify(tc.args || ''));
|
|
719
|
+
}
|
|
720
|
+
return total;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* Tokens for a content block that carries media (an image read from disk, a screenshot).
|
|
725
|
+
*
|
|
726
|
+
* AN IMAGE IS NOT PRICED BY ITS BASE64 LENGTH. `JSON.stringify` on the same object counts every base64
|
|
727
|
+
* character as ordinary text — a 1 MB PNG is ~1.3M characters, which this estimator would price at
|
|
728
|
+
* roughly 400k tokens — while a provider charges by the image's PIXEL dimensions, usually one to two
|
|
729
|
+
* thousand. That is the direction that matters: the gauge would read hundreds of thousands too high, and
|
|
730
|
+
* auto-compaction would fire on a history that was never close to full.
|
|
731
|
+
*
|
|
732
|
+
* The text beside the image is priced normally; each image gets a flat estimate derived from the common
|
|
733
|
+
* tiling rule (a 512x512 tile ≈ 765 tokens, a 1568px max edge ≈ 1100 tokens). Exactness is impossible
|
|
734
|
+
* without decoding the image, and it does not matter here: images are rare, and being within a few
|
|
735
|
+
* hundred tokens beats being wrong by a hundred thousand.
|
|
736
|
+
*/
|
|
737
|
+
function estimateMediaContentTokens(c) {
|
|
738
|
+
let total = estimateTokens(String(c.text == null ? '' : c.text));
|
|
739
|
+
for (const m of c.media || []) {
|
|
740
|
+
if (!m || m.type !== 'image') continue;
|
|
741
|
+
// A thumbnail-sized image costs a tile; a full screenshot costs four. Read the dimensions from the
|
|
742
|
+
// metadata when the reader recorded them, and fall back to the large case otherwise — overestimating
|
|
743
|
+
// an image is far safer than under, because it makes compaction fire EARLY rather than late.
|
|
744
|
+
const w = Number(m.width) || 0;
|
|
745
|
+
const h = Number(m.height) || 0;
|
|
746
|
+
if (w > 0 && h > 0) {
|
|
747
|
+
const tiles = Math.max(1, Math.ceil(w / 512) * Math.ceil(h / 512));
|
|
748
|
+
total += Math.min(4, tiles) * 765;
|
|
749
|
+
} else {
|
|
750
|
+
total += 1100;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
return total;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// ---- per-message token memo -----------------------------------------------
|
|
757
|
+
//
|
|
758
|
+
// Message objects -> { sig, tok }. WeakMap, so a message dropped from the history
|
|
759
|
+
// takes its estimate with it: no unbounded growth, and no manual eviction policy.
|
|
760
|
+
const msgTokMemo = new WeakMap();
|
|
761
|
+
//
|
|
762
|
+
// `estimateMessageTokens` above re-measures an immutable message every time it is
|
|
763
|
+
// asked, and the askers are frequent: the context gauge runs at every step, and
|
|
764
|
+
// compaction walks the whole history to find its cut point. A Read result can be
|
|
765
|
+
// hundreds of KB, so re-walking one costs milliseconds (measured: a 300 KB body is
|
|
766
|
+
// ~5.3 ms to price). Completed messages never change, so their estimate never has
|
|
767
|
+
// to be recomputed.
|
|
768
|
+
//
|
|
769
|
+
// The memo is a WeakMap keyed on the MESSAGE OBJECT, which gives two properties for
|
|
770
|
+
// free: it cannot leak (a dropped message takes its entry with it) and it cannot
|
|
771
|
+
// collide (two equal messages are still two objects).
|
|
772
|
+
//
|
|
773
|
+
// Correctness — the one place a stored message changes underneath us —
|
|
774
|
+
// --------------------------------------------------------------------
|
|
775
|
+
// `trimToolResults` rewrites `m.content` IN PLACE, replacing a large body with a
|
|
776
|
+
// short pointer. A memo that trusted object identity alone would keep serving the
|
|
777
|
+
// pre-trim count, and the gauge would claim the context was still full right after
|
|
778
|
+
// the very operation meant to shrink it — the trim would appear to do nothing and
|
|
779
|
+
// the next request would compact again for no reason.
|
|
780
|
+
//
|
|
781
|
+
// So every entry stores a cheap SIGNATURE of the content alongside the number, and
|
|
782
|
+
// a mismatch recomputes. `.length` on a string is O(1), which is what makes this
|
|
783
|
+
// affordable: streaming text (which grows every frame) misses on the signature and
|
|
784
|
+
// is re-walked, exactly as `estimateTokens`' own short-string cache already
|
|
785
|
+
// established. Content that is neither a string nor an array gets a weaker
|
|
786
|
+
// signature and is simply re-measured each time rather than risk a stale answer.
|
|
787
|
+
function msgSignature(m) {
|
|
788
|
+
const c = m.content;
|
|
789
|
+
let s;
|
|
790
|
+
if (typeof c === 'string') s = 's' + c.length;
|
|
791
|
+
else if (c == null) s = 'n';
|
|
792
|
+
else if (Array.isArray(c)) s = 'a' + c.length;
|
|
793
|
+
else if (typeof c === 'object' && Array.isArray(c.media)) {
|
|
794
|
+
// A media block: its signature is the text plus one marker per image. The base64 payload itself is
|
|
795
|
+
// NOT hashed — it is the expensive part, and it never changes once the message exists.
|
|
796
|
+
s = 'm' + String(c.text == null ? '' : c.text).length + 'x' + c.media.length;
|
|
797
|
+
} else s = ''; // unknown shape: never trust a memo
|
|
798
|
+
if (m.toolCalls) s += 't' + m.toolCalls.length;
|
|
799
|
+
return s;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** Drop any memoised estimate for a message whose content was rewritten in place. */
|
|
803
|
+
export function forgetMessageTokens(m) {
|
|
804
|
+
if (m && typeof m === 'object') msgTokMemo.delete(m);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* `estimateMessageTokens`, memoised per message object.
|
|
809
|
+
*
|
|
810
|
+
* Safe to call on STREAMING messages too: the signature check misses on every
|
|
811
|
+
* frame, so a growing body is simply re-measured and never served stale.
|
|
812
|
+
*/
|
|
813
|
+
export function messageTokens(m, cfg) {
|
|
814
|
+
if (!m || typeof m !== 'object') return estimateMessageTokens(m, cfg);
|
|
815
|
+
const sig = msgSignature(m);
|
|
816
|
+
if (sig !== '') {
|
|
817
|
+
const hit = msgTokMemo.get(m);
|
|
818
|
+
if (hit !== undefined && hit.sig === sig) return hit.tok;
|
|
819
|
+
}
|
|
820
|
+
const tok = estimateMessageTokens(m, cfg);
|
|
821
|
+
if (sig !== '') msgTokMemo.set(m, { sig, tok });
|
|
822
|
+
return tok;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* A rolling total over a message list that grows by appending.
|
|
827
|
+
*
|
|
828
|
+
* This is the idea borrowed from jcode's `ActiveCharEstimate`
|
|
829
|
+
* (`crates/jcode-base/src/compaction.rs`): keep a running count of the messages
|
|
830
|
+
* already priced, so the common append-only case never rescans history. jcode also
|
|
831
|
+
* notes why the cached value and its staleness flag are bundled into one type
|
|
832
|
+
* rather than two independent fields — a path that updated one without the other
|
|
833
|
+
* silently corrupted token accounting. Here the two are a single number,
|
|
834
|
+
* `_counted`: it is meaningless on its own and is only ever read together with the
|
|
835
|
+
* length it was computed against.
|
|
836
|
+
*
|
|
837
|
+
* `sync()` is O(new messages) when the list was only appended to, and O(n) after a
|
|
838
|
+
* compaction (which REPLACES the array, so the old count describes messages that no
|
|
839
|
+
* longer exist). Correctness does not depend on detecting appends perfectly: the
|
|
840
|
+
* boundary identities are spot-checked and any doubt falls back to a full recount,
|
|
841
|
+
* which is still cheap because the per-message memo makes each step a WeakMap hit.
|
|
842
|
+
*/
|
|
843
|
+
export class TokenLedger {
|
|
844
|
+
constructor() {
|
|
845
|
+
this.tokens = 0;
|
|
846
|
+
this._counted = 0;
|
|
847
|
+
this._first = null;
|
|
848
|
+
this._last = null;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/** Total tokens for `messages`, reusing the previous count where it is still valid. */
|
|
852
|
+
sync(messages, cfg) {
|
|
853
|
+
const msgs = Array.isArray(messages) ? messages : [];
|
|
854
|
+
const n = msgs.length;
|
|
855
|
+
const canExtend = this._counted > 0 && this._counted <= n
|
|
856
|
+
&& this._first === msgs[0]
|
|
857
|
+
&& this._last === msgs[this._counted - 1];
|
|
858
|
+
if (canExtend) {
|
|
859
|
+
for (let i = this._counted; i < n; i++) this.tokens += messageTokens(msgs[i], cfg);
|
|
860
|
+
} else {
|
|
861
|
+
// Full recount. Still O(n) WEAK-MAP LOOKUPS rather than O(n) string walks,
|
|
862
|
+
// which is the difference between milliseconds and microseconds.
|
|
863
|
+
let total = 0;
|
|
864
|
+
for (let i = 0; i < n; i++) total += messageTokens(msgs[i], cfg);
|
|
865
|
+
this.tokens = total;
|
|
866
|
+
}
|
|
867
|
+
this._counted = n;
|
|
868
|
+
this._first = n ? msgs[0] : null;
|
|
869
|
+
this._last = n ? msgs[n - 1] : null;
|
|
870
|
+
return this.tokens;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/** Forget everything — call after an in-place edit of an already-counted message. */
|
|
874
|
+
reset() {
|
|
875
|
+
this.tokens = 0;
|
|
876
|
+
this._counted = 0;
|
|
877
|
+
this._first = null;
|
|
878
|
+
this._last = null;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/**
|
|
883
|
+
* The overhead a request carries BEYOND its messages: the system prompt plus the tool definitions.
|
|
884
|
+
* Passed the assembled system text so the number matches what is actually sent.
|
|
885
|
+
*
|
|
886
|
+
* `cfg.toolDefTokens` is the REAL cost of the tool definitions, measured once by whoever built them.
|
|
887
|
+
* This used to charge a flat `n * 8` per tool, which is short by an order of magnitude: a tool's
|
|
888
|
+
* schema is its name, a paragraph of description and a nested parameters object, and measured here the
|
|
889
|
+
* 68 registered tools come to about 15 900 tokens — 29 times what 8 apiece reported.
|
|
890
|
+
*
|
|
891
|
+
* The discrepancy matters because this number is part of the context gauge. A gauge that omits ~15k of
|
|
892
|
+
* every request understates usage by that much per turn, and the user sees the provider's real figure
|
|
893
|
+
* disagree with the app's by a wide margin.
|
|
894
|
+
*
|
|
895
|
+
* The `n * 8` remains only as a FALLBACK for a caller that has not measured its definitions; it is
|
|
896
|
+
* better than nothing and is the old behaviour, exactly.
|
|
897
|
+
*/
|
|
898
|
+
export function estimateRequestOverhead(systemText, cfg) {
|
|
899
|
+
let total = estimateTokens(systemText || '');
|
|
900
|
+
const measured = cfg && Number.isFinite(cfg.toolDefTokens) ? cfg.toolDefTokens : null;
|
|
901
|
+
if (measured != null) return total + measured;
|
|
902
|
+
const n = (cfg && Array.isArray(cfg.toolFilter)) ? cfg.toolFilter.length : 0;
|
|
903
|
+
if (n) total += n * 8; // rough per-tool-definition overhead, when nothing measured it
|
|
904
|
+
return total;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* The token cost of a set of tool definitions, measured the way they are actually sent.
|
|
909
|
+
*
|
|
910
|
+
* Serialised as `{ name, description, parameters }` — the three fields the provider receives — and
|
|
911
|
+
* priced with the same estimator the gauge uses, so the number is comparable with everything else.
|
|
912
|
+
*/
|
|
913
|
+
export function measureToolDefTokens(tools) {
|
|
914
|
+
let total = 0;
|
|
915
|
+
for (const t of tools || []) {
|
|
916
|
+
if (!t || !t.name) continue;
|
|
917
|
+
total += estimateTokens(JSON.stringify({ name: t.name, description: t.description, parameters: t.parameters }));
|
|
918
|
+
}
|
|
919
|
+
return total;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
// Expand TAB characters to spaces at 8-column tab stops. A terminal advances a
|
|
924
|
+
// tab to the NEXT tab stop, but our width math (visualWidth) counts '\t' as 0,
|
|
925
|
+
// so a row containing a tab is padded short and the terminal wraps it onto the
|
|
926
|
+
// next line — the "text bleeding onto another row" corruption. Tool output
|
|
927
|
+
// (e.g. `dir`, `ls -l`, git) contains tabs, so expand before measuring.
|
|
928
|
+
export function expandTabs(s, tabSize = 8) {
|
|
929
|
+
const str = String(s ?? '');
|
|
930
|
+
if (str.indexOf('\t') === -1) return str;
|
|
931
|
+
let out = '';
|
|
932
|
+
let col = 0;
|
|
933
|
+
for (const ch of str) {
|
|
934
|
+
if (ch === '\n') { out += ch; col = 0; continue; }
|
|
935
|
+
if (ch === '\t') {
|
|
936
|
+
const next = tabSize - (col % tabSize);
|
|
937
|
+
out += ' '.repeat(next);
|
|
938
|
+
col += next;
|
|
939
|
+
continue;
|
|
940
|
+
}
|
|
941
|
+
out += ch;
|
|
942
|
+
// Per CHARACTER, `charWidth` is the right measure and is far cheaper than
|
|
943
|
+
// clusterWidth here: the loop already iterates code points (so a surrogate
|
|
944
|
+
// pair arrives as a single `ch`), and clusterWidth would spin up the
|
|
945
|
+
// segmenter for every single character.
|
|
946
|
+
col += charWidth(ch);
|
|
947
|
+
}
|
|
948
|
+
return out;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
// Truncate a string to `width` visible columns, stripping escapes for measurement
|
|
952
|
+
// and padding if shorter. Used for status/header lines. Honors 2-col glyphs.
|
|
953
|
+
export function fit(s, width) {
|
|
954
|
+
const plain = s.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
|
|
955
|
+
const plainW = visualWidth(plain);
|
|
956
|
+
if (plainW <= width) return s + ' '.repeat(width - plainW);
|
|
957
|
+
let kept = '';
|
|
958
|
+
let w = 0;
|
|
959
|
+
for (const ch of s) {
|
|
960
|
+
if (ch === '\x1b') { kept += ch; continue; }
|
|
961
|
+
const cw = charWidth(ch);
|
|
962
|
+
if (w + cw > width) break;
|
|
963
|
+
w += cw;
|
|
964
|
+
kept += ch;
|
|
965
|
+
}
|
|
966
|
+
return kept;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
export function emit(str) {
|
|
970
|
+
process.stdout.write(str);
|
|
971
|
+
}
|