@bash0816/claude-code 2.1.270 → 2.1.272

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/README.md CHANGED
@@ -37,7 +37,7 @@ npm が `claude` bin link を管理する状態になれば、通常の `npm ins
37
37
  Latest audited version / 最新監査済み版:
38
38
 
39
39
  ```sh
40
- npm install -g @bash0816/claude-code@2.1.269
40
+ npm install -g @bash0816/claude-code@2.1.270
41
41
  ```
42
42
 
43
43
  ## Update / 更新
@@ -1885,7 +1885,7 @@
1885
1885
  "entry_format": "esm-chunked",
1886
1886
  "tarball_integrity": "sha512-ByrnDr5s29glkjniJiYgnEVn/Qlc2xzodC+c/Cmg/SiFVPQrKtYGFFD8oO3MPFZVPddS+y15ESD3Jym1lUAv0A==",
1887
1887
  "tarball_sha256": "9c2c52fc53e97cc8e5e20848865c53425193251e6764c2abe975c6642587e9f3",
1888
- "status": "offset_discovered",
1888
+ "status": "termux_verified",
1889
1889
  "num_modules": 1864,
1890
1890
  "byte_count": 135681456,
1891
1891
  "cycle_hoists": [
@@ -1977,6 +1977,113 @@
1977
1977
  "hljsBundle.generated.min.js",
1978
1978
  "mermaid.min.js"
1979
1979
  ]
1980
+ },
1981
+ "2.1.272": {
1982
+ "wrapper_spec": "@anthropic-ai/claude-code@2.1.272",
1983
+ "native_spec": "@anthropic-ai/claude-code-linux-arm64@2.1.272",
1984
+ "entry_format": "esm-chunked",
1985
+ "tarball_integrity": "sha512-tpUGL+bDziPYaBplXrR018NdSE191nNvQGDHv9QluLB7u4h3t4iRSVnZ8e2KVJerAkER7JeS76sdRGoMPRSIfA==",
1986
+ "tarball_sha256": "642b6f19cbf5f3c9c1470faa868ba5dfb7ab3a08963bf7798574d1a123608c3f",
1987
+ "status": "offset_discovered",
1988
+ "num_modules": 1913,
1989
+ "byte_count": 138745069,
1990
+ "cycle_hoists": [
1991
+ {
1992
+ "file": "chunk-0egp6cb4.js",
1993
+ "targetModule": "chunk-kkbvpec7.js",
1994
+ "expectedOccurrences": 1,
1995
+ "assertProperties": []
1996
+ },
1997
+ {
1998
+ "file": "chunk-0egp6cb4.js",
1999
+ "targetModule": "chunk-th77y66m.js",
2000
+ "expectedOccurrences": 2,
2001
+ "assertProperties": []
2002
+ },
2003
+ {
2004
+ "file": "chunk-0egp6cb4.js",
2005
+ "targetModule": "chunk-7emrmste.js",
2006
+ "expectedOccurrences": 1,
2007
+ "assertProperties": []
2008
+ },
2009
+ {
2010
+ "file": "chunk-0egp6cb4.js",
2011
+ "targetModule": "chunk-qms6m20k.js",
2012
+ "expectedOccurrences": 1,
2013
+ "assertProperties": [
2014
+ "MonitorTool"
2015
+ ]
2016
+ },
2017
+ {
2018
+ "file": "chunk-0egp6cb4.js",
2019
+ "targetModule": "chunk-8t4wj1j2.js",
2020
+ "expectedOccurrences": 1,
2021
+ "assertProperties": [
2022
+ "ProposeSkillsTool"
2023
+ ]
2024
+ },
2025
+ {
2026
+ "file": "chunk-0egp6cb4.js",
2027
+ "targetModule": "chunk-b1fqz98g.js",
2028
+ "expectedOccurrences": 1,
2029
+ "assertProperties": [
2030
+ "EndConversationTool"
2031
+ ]
2032
+ },
2033
+ {
2034
+ "file": "chunk-0egp6cb4.js",
2035
+ "targetModule": "chunk-77ef5k50.js",
2036
+ "expectedOccurrences": 1,
2037
+ "assertProperties": [
2038
+ "ArtifactTool"
2039
+ ]
2040
+ },
2041
+ {
2042
+ "file": "chunk-0egp6cb4.js",
2043
+ "targetModule": "chunk-xeqmjw4x.js",
2044
+ "expectedOccurrences": 1,
2045
+ "assertProperties": [
2046
+ "AppifactReplTool"
2047
+ ]
2048
+ },
2049
+ {
2050
+ "file": "chunk-0egp6cb4.js",
2051
+ "targetModule": "chunk-yxynkd0p.js",
2052
+ "expectedOccurrences": 1,
2053
+ "assertProperties": [
2054
+ "WorkflowTool"
2055
+ ]
2056
+ },
2057
+ {
2058
+ "file": "chunk-0egp6cb4.js",
2059
+ "targetModule": "chunk-32beppym.js",
2060
+ "expectedOccurrences": 1,
2061
+ "assertProperties": [
2062
+ "default"
2063
+ ]
2064
+ },
2065
+ {
2066
+ "file": "chunk-0egp6cb4.js",
2067
+ "targetModule": "chunk-42cgs51t.js",
2068
+ "expectedOccurrences": 3,
2069
+ "assertProperties": [
2070
+ "getWorkflowCommands",
2071
+ "invalidateWorkflowCache",
2072
+ "warmWorkflows"
2073
+ ]
2074
+ },
2075
+ {
2076
+ "file": "chunk-pfa5raq4.js",
2077
+ "targetModule": "chunk-s6nvvtmm.js",
2078
+ "expectedOccurrences": 1,
2079
+ "assertProperties": []
2080
+ }
2081
+ ],
2082
+ "cycle_hoists_skipped_assets": [
2083
+ "chart.umd.min.js",
2084
+ "hljsBundle.generated.min.js",
2085
+ "mermaid.min.js"
2086
+ ]
1980
2087
  }
1981
2088
  }
1982
2089
  }
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "manifest_version": 1,
3
3
  "package_name": "@bash0816/claude-code",
4
- "latest_audited_version": "2.1.269",
5
- "latest_candidate_version": "2.1.270",
6
- "previous_stable_version": "2.1.268",
4
+ "latest_audited_version": "2.1.270",
5
+ "latest_candidate_version": "2.1.272",
6
+ "previous_stable_version": "2.1.269",
7
7
  "stable_pinned_version": "2.1.220-2",
8
8
  "manifest_url": "https://raw.githubusercontent.com/bash0816/ClaudeCode-Termux/main/config/claude-termux-release-manifest.json"
9
9
  }
@@ -0,0 +1,569 @@
1
+ module.exports = function createBunCellSegmenterShim({ graphemeWidth }) {
2
+ // Constants and bit masks (from vendor bundle analysis)
3
+ const pn = 3; // width mask (2 bits)
4
+ const Ub = 10; // runIndex shift
5
+ const fC = 255; // width mask (8 bits)
6
+ const dC = 256; // tab flag bit
7
+
8
+ // BiDi control character codepoint ranges (U+061C, U+202A-U+202E, U+2066-U+2069)
9
+ const aXe = [[1564, 1564], [8234, 8238], [8294, 8297]];
10
+
11
+ // Build regex for BiDi control character detection
12
+ const Nc = aXe.map(([n, s]) => `\\u{${n.toString(16)}}` + (s > n ? `-\\u{${s.toString(16)}}` : '')).join('');
13
+ const mSn = new RegExp(`[${Nc}]`, 'gu');
14
+
15
+ // Intl.Segmenter instance for grapheme segmentation (reuse across calls)
16
+ const globalSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
17
+
18
+ // ============================================================
19
+ // sliceAnsi: Split string by display columns using grapheme units
20
+ // ============================================================
21
+ function sliceAnsi(str, start, end) {
22
+ let visibleCol = 0;
23
+ let result = '';
24
+ let i = 0;
25
+
26
+ // Regex for non-SGR CSI sequences: ESC [ ... (@ to ~, excluding m)
27
+ const csiNonSgrRegex = /^\x1b\[[0-?]*[ -/]*[@-~]/;
28
+
29
+ while (i < str.length) {
30
+ // Invariant: must advance i by at least 1 per iteration
31
+ // Four-way dispatch with catch-all fallback (§9-6)
32
+
33
+ // 1. Complete SGR code: \x1b[...m with params (\d, ;, :)
34
+ if (str[i] === '\x1b' && str[i + 1] === '[') {
35
+ let j = i + 2;
36
+ // Find 'm' terminator, accepting digits, ;, and : (colon for kitty underline)
37
+ while (j < str.length && /[\d;:]/.test(str[j])) {
38
+ j++;
39
+ }
40
+ if (j < str.length && str[j] === 'm') {
41
+ // Match complete SGR
42
+ result += str.slice(i, j + 1);
43
+ i = j + 1;
44
+ continue;
45
+ }
46
+ // Otherwise fall through to catch-all
47
+ }
48
+
49
+ // 2. Complete OSC8 sequence: \x1b]8;;...BEL or \x1b]8...ST
50
+ if (str[i] === '\x1b' && str[i + 1] === ']' && str[i + 2] === '8' && str[i + 3] === ';') {
51
+ let j = i + 4;
52
+ let foundEnd = false;
53
+ while (j < str.length) {
54
+ if (str[j] === '\x07') {
55
+ // BEL terminator
56
+ result += str.slice(i, j + 1);
57
+ i = j + 1;
58
+ foundEnd = true;
59
+ break;
60
+ }
61
+ if (str[j] === '\x1b' && j + 1 < str.length && str[j + 1] === '\\') {
62
+ // ST terminator
63
+ result += str.slice(i, j + 2);
64
+ i = j + 2;
65
+ foundEnd = true;
66
+ break;
67
+ }
68
+ j++;
69
+ }
70
+ if (foundEnd) continue;
71
+ // Otherwise fall through to catch-all (incomplete OSC8)
72
+ }
73
+
74
+ // 3. Non-SGR CSI sequence: match and skip (skip without adding to result)
75
+ if (str[i] === '\x1b' && str[i + 1] === '[') {
76
+ const remaining = str.slice(i);
77
+ const csiMatch = remaining.match(csiNonSgrRegex);
78
+ if (csiMatch) {
79
+ // Skip CSI sequence without adding to result (consumed but not output)
80
+ i += csiMatch[0].length;
81
+ continue;
82
+ }
83
+ // Otherwise fall through to catch-all (malformed CSI)
84
+ }
85
+
86
+ // 4. Catch-all: any other character (ESC alone or normal char)
87
+ // Distinguish between lone ESC and normal text
88
+ if (str[i] === '\x1b') {
89
+ // Single ESC character (incomplete sequence) - consume it as-is
90
+ result += str[i];
91
+ i += 1;
92
+ continue;
93
+ }
94
+
95
+ // Normal character: find the next ESC and segment everything up to it
96
+ let chunkEnd = str.length; // Default: rest of string (no more ESCs)
97
+ for (let j = i + 1; j < str.length; j++) {
98
+ if (str[j] === '\x1b') {
99
+ chunkEnd = j;
100
+ break;
101
+ }
102
+ }
103
+
104
+ const chunk = str.slice(i, chunkEnd);
105
+ const graphemes = Array.from(globalSegmenter.segment(chunk)).map(seg => seg.segment);
106
+
107
+ for (const grapheme of graphemes) {
108
+ const charWidth = graphemeWidth(grapheme);
109
+ const nextCol = visibleCol + charWidth;
110
+
111
+ // Include if entirely within [start, end)
112
+ if (nextCol <= end && visibleCol < end) {
113
+ if (visibleCol >= start) {
114
+ result += grapheme;
115
+ }
116
+ visibleCol = nextCol;
117
+ } else if (visibleCol >= end) {
118
+ break;
119
+ } else {
120
+ visibleCol = nextCol;
121
+ }
122
+ }
123
+
124
+ if (visibleCol >= end) {
125
+ break;
126
+ }
127
+
128
+ i = chunkEnd;
129
+ }
130
+
131
+ return result;
132
+ }
133
+
134
+ // ============================================================
135
+ // sleepSync: Sleep using Atomics.wait (blocking)
136
+ // ============================================================
137
+ function sleepSync(ms) {
138
+ const buf = new Int32Array(new SharedArrayBuffer(4));
139
+ Atomics.wait(buf, 0, 0, ms);
140
+ }
141
+
142
+ // ============================================================
143
+ // CellSegmenter: Main text segmentation and painting class
144
+ // ============================================================
145
+ class CellSegmenter {
146
+ constructor(config) {
147
+ this.ambiguousIsNarrow = config.ambiguousIsNarrow ?? true;
148
+ this.substitute = config.substitute || [];
149
+ this.screen = config.screen || {
150
+ widthMask: pn,
151
+ narrow: 0,
152
+ wide: 1,
153
+ spacerTail: 2,
154
+ spacerHead: 3,
155
+ emptyCharIndex: 0,
156
+ spacerCharIndex: 1,
157
+ emptyWord: 0,
158
+ tabWidth: 8,
159
+ };
160
+
161
+ // GraphemeIndex to charPoolIndex mapping (per-instance state)
162
+ this.graphemes = [];
163
+ this.sgrKeys = ['']; // Index 0 = default (no style applied)
164
+ this.sgrCloseKeys = [''];
165
+ this.uris = ['']; // Index 0 = no link (reserved dummy), per §9-2
166
+ }
167
+
168
+ // ============================================================
169
+ // setCell: Write single cell to destination buffer
170
+ // ============================================================
171
+ setCell(destCells, destWidth, x, y, charPoolIndex, packedStyleHyperlinkWidth) {
172
+ // Clamp to screen width
173
+ if (x < 0 || x >= destWidth || y < 0) {
174
+ return 0;
175
+ }
176
+
177
+ // Calculate cell index: must bind the shift result before adding 1
178
+ const idx = (y * destWidth + x) << 1;
179
+ if (idx + 1 >= destCells.length) {
180
+ return 0; // Out of bounds
181
+ }
182
+
183
+ destCells[idx] = charPoolIndex;
184
+ destCells[idx + 1] = packedStyleHyperlinkWidth;
185
+
186
+ // Return damage rect: xStart * 2^20 + endCol * 2^36
187
+ const xStart = x;
188
+ const endCol = x + 1;
189
+ return endCol + xStart * (2 ** 20) + endCol * (2 ** 36);
190
+ }
191
+
192
+ // ============================================================
193
+ // segment: Parse text into grapheme cells, SGR styles, and URIs (BL-1,2,3,4,5,6,7 fixes)
194
+ // ============================================================
195
+ segment(text, cells, runs, reordered) {
196
+ // Apply BiDi character substitution
197
+ const processedText = text.replace(mSn, '�');
198
+
199
+ // Pre-allocate capacity check
200
+ const estimatedGraphemes = processedText.length;
201
+ if (cells.length < estimatedGraphemes * 2) {
202
+ return -(estimatedGraphemes);
203
+ }
204
+ if (runs.length < estimatedGraphemes * 2) {
205
+ return -(estimatedGraphemes);
206
+ }
207
+
208
+ let graphemeIndex = this.graphemes.length;
209
+ let cellCount = 0;
210
+ let localRunIndex = 0;
211
+ let currentUri = 0;
212
+
213
+ // Track current active style attributes by category (§9-4, BL-6)
214
+ let fgColor = null; // Current foreground color code (null = none)
215
+ let bgColor = null; // Current background color code (null = none)
216
+ const booleanAttrs = new Set(); // bold, dim, italic, underline, blink, reverse, hidden, strikethrough
217
+
218
+ // Track run states to fill runs array later
219
+ const runToState = new Map(); // Map of runIdx -> {sgrCodes, uriIdx}
220
+
221
+ // Helper: build SGR code array from current state
222
+ const buildSgrCodes = () => {
223
+ const codes = [];
224
+ if (fgColor !== null) codes.push(fgColor);
225
+ if (bgColor !== null) codes.push(bgColor);
226
+ for (const attr of booleanAttrs) codes.push(attr);
227
+ return codes.sort();
228
+ };
229
+
230
+ // Helper: get close codes corresponding to open codes (§9-5)
231
+ // Returns codes in escape sequence format: \x1b[...m (not raw codes)
232
+ const getCloseCodes = (openCodes) => {
233
+ const closeMap = {
234
+ '1': '22', '2': '22',
235
+ '3': '23', '4': '24', '5': '25', '6': '25',
236
+ '7': '27', '8': '28', '9': '29'
237
+ };
238
+ return openCodes.map(code => {
239
+ let closeCode = '';
240
+ // Check for composite color codes first
241
+ if (/^38/.test(code)) closeCode = '39'; // Foreground color (38;5;n or 38;2;r;g;b)
242
+ else if (/^48/.test(code)) closeCode = '49'; // Background color (48;5;n or 48;2;r;g;b)
243
+ // Check for basic foreground colors (30-37, 90-97)
244
+ else if (/^(30|31|32|33|34|35|36|37|90|91|92|93|94|95|96|97)$/.test(code)) closeCode = '39';
245
+ // Check for basic background colors (40-47, 100-107)
246
+ else if (/^(40|41|42|43|44|45|46|47|100|101|102|103|104|105|106|107)$/.test(code)) closeCode = '49';
247
+ // Check for other attributes
248
+ else if (/^\d+$/.test(code)) closeCode = closeMap[code] || '';
249
+ // Return as escape sequence: \x1b[...m, or empty if no mapping
250
+ return closeCode ? `\x1b[${closeCode}m` : '';
251
+ });
252
+ };
253
+
254
+ // Helper: parse SGR parameter and update state (BL-6)
255
+ const applySgrParam = (param) => {
256
+ if (param === '0' || param === '') {
257
+ fgColor = null;
258
+ bgColor = null;
259
+ booleanAttrs.clear();
260
+ } else if (param === '1' || param === '2') {
261
+ booleanAttrs.add(param);
262
+ } else if (param === '3') {
263
+ booleanAttrs.add(param);
264
+ } else if (param === '4') {
265
+ booleanAttrs.add(param);
266
+ } else if (param === '5' || param === '6') {
267
+ booleanAttrs.add(param);
268
+ } else if (param === '7') {
269
+ booleanAttrs.add(param);
270
+ } else if (param === '8') {
271
+ booleanAttrs.add(param);
272
+ } else if (param === '9') {
273
+ booleanAttrs.add(param);
274
+ } else if (param === '22') {
275
+ booleanAttrs.delete('1');
276
+ booleanAttrs.delete('2');
277
+ } else if (param === '23') {
278
+ booleanAttrs.delete('3');
279
+ } else if (param === '24') {
280
+ booleanAttrs.delete('4');
281
+ } else if (param === '25') {
282
+ booleanAttrs.delete('5');
283
+ booleanAttrs.delete('6');
284
+ } else if (param === '27') {
285
+ booleanAttrs.delete('7');
286
+ } else if (param === '28') {
287
+ booleanAttrs.delete('8');
288
+ } else if (param === '29') {
289
+ booleanAttrs.delete('9');
290
+ } else if (param === '39') {
291
+ fgColor = null;
292
+ } else if (param === '49') {
293
+ bgColor = null;
294
+ } else if (/^(30|31|32|33|34|35|36|37|90|91|92|93|94|95|96|97)$/.test(param)) {
295
+ fgColor = param;
296
+ } else if (/^(40|41|42|43|44|45|46|47|100|101|102|103|104|105|106|107)$/.test(param)) {
297
+ bgColor = param;
298
+ }
299
+ };
300
+
301
+ // Helper: parse full SGR sequence
302
+ const parseSgrSequence = (paramStr) => {
303
+ if (!paramStr) {
304
+ applySgrParam('0');
305
+ return;
306
+ }
307
+ const parts = paramStr.split(';');
308
+ let k = 0;
309
+ while (k < parts.length) {
310
+ const p = parts[k];
311
+ if ((p === '38' || p === '48') && parts[k + 1] === '5' && k + 2 < parts.length) {
312
+ const composite = `${p};5;${parts[k + 2]}`;
313
+ if (p === '38') fgColor = composite;
314
+ else bgColor = composite;
315
+ k += 3;
316
+ continue;
317
+ } else if ((p === '38' || p === '48') && parts[k + 1] === '2' && k + 4 < parts.length) {
318
+ const composite = `${p};2;${parts[k + 2]};${parts[k + 3]};${parts[k + 4]}`;
319
+ if (p === '38') fgColor = composite;
320
+ else bgColor = composite;
321
+ k += 5;
322
+ continue;
323
+ }
324
+ applySgrParam(p);
325
+ k++;
326
+ }
327
+ };
328
+
329
+ // Regex for non-SGR CSI sequences (with ^ anchor to match at current position)
330
+ const csiNonSgrRegex = /^\x1b\[[0-?]*[ -/]*[@-~]/;
331
+
332
+ let i = 0;
333
+ let prevState = null; // Previous SGR+URI state for BL-3 (monotonic run allocation)
334
+
335
+ while (i < processedText.length) {
336
+ // Invariant: must advance i by at least 1 per iteration (§9-6)
337
+ // Four-way dispatch with catch-all fallback
338
+
339
+ // 1. Complete SGR code: \x1b[...m
340
+ if (processedText[i] === '\x1b' && processedText[i + 1] === '[') {
341
+ let j = i + 2;
342
+ while (j < processedText.length && /[\d;:]/.test(processedText[j])) {
343
+ j++;
344
+ }
345
+ if (j < processedText.length && processedText[j] === 'm') {
346
+ const params = processedText.slice(i + 2, j);
347
+ parseSgrSequence(params);
348
+ i = j + 1;
349
+ continue;
350
+ }
351
+ }
352
+
353
+ // 2. Complete OSC8 sequence: \x1b]8;;...
354
+ if (processedText[i] === '\x1b' && processedText[i + 1] === ']' && processedText[i + 2] === '8' && processedText[i + 3] === ';') {
355
+ let j = i + 4;
356
+ let foundEnd = false;
357
+ while (j < processedText.length) {
358
+ if (processedText[j] === '\x07') {
359
+ const oscSeq = processedText.slice(i + 4, j);
360
+ const semicolonPos = oscSeq.indexOf(';');
361
+ if (semicolonPos >= 0) {
362
+ const url = oscSeq.slice(semicolonPos + 1);
363
+ if (url) {
364
+ let uriIdx = this.uris.indexOf(url);
365
+ if (uriIdx === -1) {
366
+ uriIdx = this.uris.length;
367
+ this.uris.push(url);
368
+ }
369
+ currentUri = uriIdx;
370
+ } else {
371
+ currentUri = 0;
372
+ }
373
+ }
374
+ i = j + 1;
375
+ foundEnd = true;
376
+ break;
377
+ }
378
+ if (processedText[j] === '\x1b' && j + 1 < processedText.length && processedText[j + 1] === '\\') {
379
+ const oscSeq = processedText.slice(i + 4, j);
380
+ const semicolonPos = oscSeq.indexOf(';');
381
+ if (semicolonPos >= 0) {
382
+ const url = oscSeq.slice(semicolonPos + 1);
383
+ if (url) {
384
+ let uriIdx = this.uris.indexOf(url);
385
+ if (uriIdx === -1) {
386
+ uriIdx = this.uris.length;
387
+ this.uris.push(url);
388
+ }
389
+ currentUri = uriIdx;
390
+ } else {
391
+ currentUri = 0;
392
+ }
393
+ }
394
+ i = j + 2;
395
+ foundEnd = true;
396
+ break;
397
+ }
398
+ j++;
399
+ }
400
+ if (foundEnd) continue;
401
+ }
402
+
403
+ // 3. Non-SGR CSI sequence: match and skip
404
+ if (processedText[i] === '\x1b' && processedText[i + 1] === '[') {
405
+ const remaining = processedText.slice(i);
406
+ const csiMatch = remaining.match(csiNonSgrRegex);
407
+ if (csiMatch) {
408
+ i += csiMatch[0].length;
409
+ continue;
410
+ }
411
+ }
412
+
413
+ // 4. Catch-all: lone ESC or normal character
414
+ // Distinguish between lone ESC and normal text
415
+ if (processedText[i] === '\x1b') {
416
+ // Single ESC character (incomplete sequence) - consume it as-is, don't segment
417
+ i += 1;
418
+ continue;
419
+ }
420
+
421
+ // Normal character: find the next ESC and segment everything up to it
422
+ let chunkEnd = processedText.length; // Default: rest of string (no more ESCs)
423
+ for (let j = i + 1; j < processedText.length; j++) {
424
+ if (processedText[j] === '\x1b') {
425
+ chunkEnd = j;
426
+ break;
427
+ }
428
+ }
429
+
430
+ const chunk = processedText.slice(i, chunkEnd);
431
+ const graphemeArray = Array.from(globalSegmenter.segment(chunk)).map(seg => seg.segment);
432
+
433
+ for (const grapheme of graphemeArray) {
434
+ // Determine run index: compare current state with previous (BL-3)
435
+ const currentSgrCodes = buildSgrCodes();
436
+ const currentState = JSON.stringify({ sgr: currentSgrCodes, uri: currentUri });
437
+
438
+ let runIdx;
439
+ if (prevState !== currentState) {
440
+ runIdx = localRunIndex++;
441
+ prevState = currentState;
442
+
443
+ // Register in sgrKeys/sgrCloseKeys pool if needed
444
+ if (currentSgrCodes.length > 0) {
445
+ const poolEntry = currentSgrCodes.map(code => `\x1b[${code}m`).join('\x00');
446
+ let poolIdx = this.sgrKeys.indexOf(poolEntry);
447
+ if (poolIdx === -1) {
448
+ poolIdx = this.sgrKeys.length;
449
+ this.sgrKeys.push(poolEntry);
450
+ const closeCodes = getCloseCodes(currentSgrCodes);
451
+ this.sgrCloseKeys.push(closeCodes.join('\x00'));
452
+ }
453
+ }
454
+
455
+ // Store state for this run
456
+ runToState.set(runIdx, { sgrCodes: currentSgrCodes, uriIdx: currentUri });
457
+ } else {
458
+ // Reuse previous run
459
+ runIdx = localRunIndex - 1;
460
+ }
461
+
462
+ // Add grapheme to pool
463
+ this.graphemes.push(grapheme);
464
+ const width = graphemeWidth(grapheme);
465
+
466
+ cells[cellCount * 2] = graphemeIndex;
467
+ cells[cellCount * 2 + 1] = (runIdx << Ub) | (width & fC);
468
+
469
+ if (grapheme === '\t') {
470
+ cells[cellCount * 2 + 1] |= dC;
471
+ }
472
+
473
+ graphemeIndex++;
474
+ cellCount++;
475
+ }
476
+
477
+ i = chunkEnd;
478
+ }
479
+
480
+ // Build runs array from tracked run states
481
+ for (let runIdx = 0; runIdx < localRunIndex; runIdx++) {
482
+ const state = runToState.get(runIdx) || { sgrCodes: [], uriIdx: 0 };
483
+ let poolIdx = 0;
484
+ if (state.sgrCodes.length > 0) {
485
+ const poolEntry = state.sgrCodes.map(code => `\x1b[${code}m`).join('\x00');
486
+ poolIdx = this.sgrKeys.indexOf(poolEntry);
487
+ if (poolIdx === -1) poolIdx = 0;
488
+ }
489
+ runs[runIdx * 2] = poolIdx;
490
+ runs[runIdx * 2 + 1] = state.uriIdx;
491
+ }
492
+
493
+ return cellCount;
494
+ }
495
+
496
+ // ============================================================
497
+ // paint: Render segmented cells to destination screen buffer
498
+ // ============================================================
499
+ paint(destCells, destWidth, x, y, srcCells, srcCount, unused, charIndices, runWords) {
500
+ let col = x;
501
+ let maxX = x;
502
+
503
+ for (let i = 0; i < srcCount; i++) {
504
+ if (col < 0) {
505
+ col++;
506
+ continue;
507
+ }
508
+
509
+ if (col >= destWidth) {
510
+ break;
511
+ }
512
+
513
+ const graphemeIndex = srcCells[i * 2];
514
+ const width = srcCells[i * 2 + 1] & fC;
515
+ const tab = (srcCells[i * 2 + 1] & dC) !== 0;
516
+ const runIndex = srcCells[i * 2 + 1] >>> Ub;
517
+ const word = runWords[runIndex] || 0;
518
+
519
+ // Skip wide characters that would overshoot screen width
520
+ if (width === 2 && col + 1 >= destWidth) {
521
+ break;
522
+ }
523
+
524
+ // Calculate cell index: bind result to variable before adding 1
525
+ const idx = (y * destWidth + col) << 1;
526
+
527
+ if (tab) {
528
+ // Fill tab stops with spaces (use this.screen.emptyCharIndex for space)
529
+ const tabWidth = this.screen.tabWidth || 8;
530
+ const nextTabStop = Math.min(((Math.floor(col / tabWidth) + 1) * tabWidth), destWidth);
531
+ while (col < nextTabStop && col < destWidth) {
532
+ const cellIdx = (y * destWidth + col) << 1;
533
+ destCells[cellIdx] = this.screen.emptyCharIndex;
534
+ destCells[cellIdx + 1] = word | 0; // width code 0 for space
535
+ col++;
536
+ }
537
+ maxX = col;
538
+ } else {
539
+ destCells[idx] = charIndices[graphemeIndex] || 0;
540
+ destCells[idx + 1] = word | (width === 2 ? 1 : 0);
541
+
542
+ if (width === 2) {
543
+ // Wide character: write spacer tail to next cell
544
+ const spacerIdx = idx + 2;
545
+ if (col + 1 < destWidth && spacerIdx + 1 < destCells.length) {
546
+ destCells[spacerIdx] = this.screen.spacerCharIndex;
547
+ destCells[spacerIdx + 1] = word | 2; // width code 2 (spacerTail)
548
+ }
549
+ col += 2;
550
+ maxX = col;
551
+ } else {
552
+ col++;
553
+ maxX = col;
554
+ }
555
+ }
556
+ }
557
+
558
+ // Return damage rect: must use * and + only, not <<
559
+ const endCol = Math.min(col, destWidth);
560
+ const xStart = x;
561
+ return endCol + xStart * (2 ** 20) + endCol * (2 ** 36);
562
+ }
563
+ }
564
+
565
+ // ============================================================
566
+ // Return factory exports
567
+ // ============================================================
568
+ return { sliceAnsi, sleepSync, CellSegmenter };
569
+ };
@@ -673,6 +673,7 @@ async function esmChunkedMain() {
673
673
  const libDir = path.join(process.env.CLAUDE_TERMUX_PACKAGE_DIR, 'lib');
674
674
 
675
675
  globalThis.__claudeYaml = createYamlShim();
676
+ const { sliceAnsi, sleepSync, CellSegmenter } = require(path.join(process.env.CLAUDE_TERMUX_PACKAGE_DIR, 'lib', 'bun-cellsegmenter-shim.js'))({ stringWidth, graphemeWidth });
676
677
  globalThis.Bun = {
677
678
  version: '1.1.8',
678
679
  stringWidth,
@@ -692,6 +693,9 @@ async function esmChunkedMain() {
692
693
  unsafe: {
693
694
  setJITPolicy: () => undefined,
694
695
  },
696
+ sliceAnsi,
697
+ sleepSync,
698
+ ant: { CellSegmenter },
695
699
  };
696
700
  Object.defineProperty(process.versions, 'bun', { value: '1.1.8', configurable: true });
697
701
  globalThis.__claudeBunShim = globalThis.Bun;
@@ -930,6 +934,7 @@ async function legacyCjsMain() {
930
934
  process.once('uncaughtException', onAsyncError);
931
935
  process.once('unhandledRejection', onAsyncError);
932
936
  Object.defineProperty(process.versions, 'bun', { value: '1.1.8', configurable: true });
937
+ const { sliceAnsi, sleepSync, CellSegmenter } = require(path.join(process.env.CLAUDE_TERMUX_PACKAGE_DIR, 'lib', 'bun-cellsegmenter-shim.js'))({ stringWidth, graphemeWidth });
933
938
  const _realChild = require('child_process');
934
939
  globalThis.Bun = {
935
940
  version: '1.1.8',
@@ -1016,6 +1021,9 @@ async function legacyCjsMain() {
1016
1021
  unsafe: {
1017
1022
  setJITPolicy: () => undefined,
1018
1023
  },
1024
+ sliceAnsi,
1025
+ sleepSync,
1026
+ ant: { CellSegmenter },
1019
1027
  };
1020
1028
  Object.assign(globalThis.__claudeBunShim, globalThis.Bun);
1021
1029
  if (typeof globalThis.__claudeBunShim.gc !== 'function') {
@@ -1709,6 +1717,7 @@ async function esmChunkedMain() {
1709
1717
  const libDir = path.join(process.env.CLAUDE_TERMUX_PACKAGE_DIR, 'lib');
1710
1718
 
1711
1719
  globalThis.__claudeYaml = createYamlShim();
1720
+ const { sliceAnsi, sleepSync, CellSegmenter } = require(path.join(process.env.CLAUDE_TERMUX_PACKAGE_DIR, 'lib', 'bun-cellsegmenter-shim.js'))({ stringWidth, graphemeWidth });
1712
1721
  globalThis.Bun = {
1713
1722
  version: '1.1.8',
1714
1723
  stringWidth,
@@ -1728,6 +1737,9 @@ async function esmChunkedMain() {
1728
1737
  unsafe: {
1729
1738
  setJITPolicy: () => undefined,
1730
1739
  },
1740
+ sliceAnsi,
1741
+ sleepSync,
1742
+ ant: { CellSegmenter },
1731
1743
  };
1732
1744
  Object.defineProperty(process.versions, 'bun', { value: '1.1.8', configurable: true });
1733
1745
  globalThis.__claudeBunShim = globalThis.Bun;
@@ -1968,6 +1980,7 @@ async function legacyCjsMain() {
1968
1980
  process.once('uncaughtException', onAsyncError);
1969
1981
  process.once('unhandledRejection', onAsyncError);
1970
1982
  Object.defineProperty(process.versions, 'bun', { value: '1.1.8', configurable: true });
1983
+ const { sliceAnsi, sleepSync, CellSegmenter } = require(path.join(process.env.CLAUDE_TERMUX_PACKAGE_DIR, 'lib', 'bun-cellsegmenter-shim.js'))({ stringWidth, graphemeWidth });
1971
1984
  const _realChild = require('child_process');
1972
1985
  globalThis.Bun = {
1973
1986
  version: '1.1.8',
@@ -2054,6 +2067,9 @@ async function legacyCjsMain() {
2054
2067
  unsafe: {
2055
2068
  setJITPolicy: () => undefined,
2056
2069
  },
2070
+ sliceAnsi,
2071
+ sleepSync,
2072
+ ant: { CellSegmenter },
2057
2073
  };
2058
2074
  Object.assign(globalThis.__claudeBunShim, globalThis.Bun);
2059
2075
  if (typeof globalThis.__claudeBunShim.gc !== 'function') {
@@ -1567,6 +1567,9 @@ function loadBunShim(source) {
1567
1567
  wrapAnsi: value => value,
1568
1568
  stripANSI: value => value,
1569
1569
  stableHash: () => 0,
1570
+ sliceAnsi: (s) => s,
1571
+ sleepSync: () => {},
1572
+ CellSegmenter: class {},
1570
1573
  __claudeYaml: {},
1571
1574
  Buffer,
1572
1575
  require,
@@ -1595,6 +1598,9 @@ function loadEsmBunShim(source) {
1595
1598
  wrapAnsi: value => value,
1596
1599
  stripANSI: value => value,
1597
1600
  stableHash: () => 0,
1601
+ sliceAnsi: (s) => s,
1602
+ sleepSync: () => {},
1603
+ CellSegmenter: class {},
1598
1604
  process: { versions: {} },
1599
1605
  Buffer,
1600
1606
  require,
@@ -1856,3 +1862,304 @@ test('termux-run-claude-native.sh maintains compatibility with new zstd fields',
1856
1862
  const blocks = (script.match(/globalThis\.Bun\s*=\s*{/g) || []);
1857
1863
  assert.ok(blocks.length >= 2, 'should have at least 2 Bun initializations for helper and bootstrap');
1858
1864
  });
1865
+
1866
+ test('ESM and legacy Bun shims include new CellSegmenter exports', () => {
1867
+ for (const blockMarker of ['cat <<\'NODE\' > "$_helper"', 'cat <<\'NODE\' > "$_bootstrap"']) {
1868
+ const block = extractBlock(blockMarker, '\n export ENABLE_CLAUDEAI_MCP_SERVERS=');
1869
+ const BunEsm = loadEsmBunShim(extractEsmShimSource(block));
1870
+ const BunLegacy = loadBunShim(extractShimSource(block));
1871
+
1872
+ // Verify sliceAnsi is present
1873
+ assert.equal(typeof BunEsm.sliceAnsi, 'function', `${blockMarker}: ESM sliceAnsi should be a function`);
1874
+ assert.equal(typeof BunLegacy.sliceAnsi, 'function', `${blockMarker}: legacy sliceAnsi should be a function`);
1875
+
1876
+ // Verify sleepSync is present
1877
+ assert.equal(typeof BunEsm.sleepSync, 'function', `${blockMarker}: ESM sleepSync should be a function`);
1878
+ assert.equal(typeof BunLegacy.sleepSync, 'function', `${blockMarker}: legacy sleepSync should be a function`);
1879
+
1880
+
1881
+ // Verify CellSegmenter is present
1882
+ assert.equal(typeof BunEsm.ant.CellSegmenter, 'function', `${blockMarker}: ESM ant.CellSegmenter should be a function`);
1883
+ assert.equal(typeof BunLegacy.ant.CellSegmenter, 'function', `${blockMarker}: legacy ant.CellSegmenter should be a function`);
1884
+ }
1885
+ });
1886
+
1887
+ // ============================================================
1888
+ // CellSegmenter integration tests with vendor harness (G3 v2 revision)
1889
+ // ============================================================
1890
+
1891
+ test('CellSegmenter: run monotonicity and style non-contamination (BL-3)', () => {
1892
+ const createHarness = require('./test-support/vendor-cellsegmenter-harness.js');
1893
+ const h = createHarness((s) => s.replace(/\x1b\[[0-9;]*m/g, '').length, (s) => 1);
1894
+ const { D, Pool } = h;
1895
+
1896
+ const stylePool = new Pool();
1897
+ const charPool = new Pool([' ', 'S']);
1898
+ const hyperPool = new Pool(['']);
1899
+
1900
+ // Test case: style repeats after gap (BL-3 regression)
1901
+ const d1 = new D(stylePool, charPool);
1902
+ d1.segment('aa\x1b[34mBLUE\x1b[39m', false);
1903
+ d1.paint(h.mkScreen(40, 1).cells, 40, 0, 0, hyperPool);
1904
+
1905
+ const d2 = new D(stylePool, charPool);
1906
+ const n = d2.segment('ok \x1b[1mERR\x1b[22m done', false);
1907
+
1908
+ // Verify run indices are monotonic
1909
+ const runIndices = [];
1910
+ for (let i = 0; i < n; i++) {
1911
+ runIndices.push(d2.cells[2*i+1] >>> 10);
1912
+ }
1913
+ for (let i = 1; i < runIndices.length; i++) {
1914
+ assert.ok(runIndices[i] >= runIndices[i-1], `run ${i} should be >= run ${i-1}`);
1915
+ }
1916
+
1917
+ // Paint and verify style isolation (find the bold run, not run 0)
1918
+ d2.paint(h.mkScreen(40, 1).cells, 40, 0, 0, hyperPool);
1919
+ const boldRunIdx = runIndices.find(r => r > 0) || 0; // Skip run 0 (unstyled)
1920
+ const boldStyleId = d2.styleId(d2.runs[2*boldRunIdx]);
1921
+ const blueStyleId = stylePool.arr.findIndex(s => s.includes('34'));
1922
+ assert.ok(boldStyleId !== blueStyleId || blueStyleId === -1, 'style should not contaminate between segments');
1923
+ });
1924
+
1925
+ test('CellSegmenter: foreground color exclusivity (BL-6)', () => {
1926
+ const createHarness = require('./test-support/vendor-cellsegmenter-harness.js');
1927
+ const h = createHarness((s) => s.replace(/\x1b\[[0-9;]*m/g, '').length, (s) => 1);
1928
+ const { D, Pool } = h;
1929
+
1930
+ const stylePool = new Pool();
1931
+ const charPool = new Pool([' ', 'S']);
1932
+ const d = new D(stylePool, charPool);
1933
+
1934
+ const text = '\x1b[31mRED\x1b[32mGREEN\x1b[0m';
1935
+ d.segment(text, false);
1936
+
1937
+ // Extract runIndices for RED and GREEN
1938
+ const reds = [];
1939
+ const greens = [];
1940
+ for (let i = 0; i < d.count; i++) {
1941
+ const runIdx = d.cells[2*i+1] >>> 10;
1942
+ if (d.graphemes[d.cells[2*i]] === 'R') reds.push(runIdx);
1943
+ if (d.graphemes[d.cells[2*i]] === 'G') greens.push(runIdx);
1944
+ }
1945
+
1946
+ const redStyleId = reds.length > 0 ? d.styleId(d.runs[2*reds[0]]) : -1;
1947
+ const greenStyleId = greens.length > 0 ? d.styleId(d.runs[2*greens[0]]) : -1;
1948
+ assert.notEqual(redStyleId, greenStyleId, 'RED and GREEN should have distinct styleIds');
1949
+
1950
+ // Direct validation: GREEN run should NOT contain red (31) code - verifying exclusivity
1951
+ if (greens.length > 0) {
1952
+ const greenRunIdx = greens[0];
1953
+ const greenSgrIdx = d.runs[2*greenRunIdx];
1954
+ const greenCodes = d.ansiCodes(greenSgrIdx);
1955
+ const hasBothColors = greenCodes.some(c => c.code.includes('31')) && greenCodes.some(c => c.code.includes('32'));
1956
+ assert.ok(!hasBothColors, 'GREEN run should not contain red (31) code - colors must be exclusive');
1957
+ }
1958
+ });
1959
+
1960
+ test('CellSegmenter: sgrCloseKeys derivation (§9-5)', () => {
1961
+ const createHarness = require('./test-support/vendor-cellsegmenter-harness.js');
1962
+ const h = createHarness((s) => s.replace(/\x1b\[[0-9;]*m/g, '').length, (s) => 1);
1963
+ const { D, Pool, mC } = h;
1964
+
1965
+ const stylePool = new Pool();
1966
+ const charPool = new Pool([' ', 'S']);
1967
+ const d = new D(stylePool, charPool);
1968
+
1969
+ const text = '\x1b[1;31mX';
1970
+ d.segment(text, false);
1971
+
1972
+ // Check that sgrKeys[1] contains open codes and sgrCloseKeys[1] contains matching close codes
1973
+ const keys = d.sgrKeys[1];
1974
+ const closeKeys = d.sgrCloseKeys[1];
1975
+ const keyList = keys.split('\x00').filter(k => k);
1976
+ const closeList = closeKeys.split('\x00').filter(k => k);
1977
+
1978
+ assert.equal(keyList.length, closeList.length, 'open and close codes should have same count');
1979
+ assert.ok(keyList.some(k => k.includes('1')), 'should have bold (1)');
1980
+ assert.ok(keyList.some(k => k.includes('31')), 'should have fg-red (31)');
1981
+ assert.ok(closeList.some(c => c.includes('22')), 'should have bold-close (22)');
1982
+ assert.ok(closeList.some(c => c.includes('39')), 'should have fg-close (39)');
1983
+ });
1984
+
1985
+ test('CellSegmenter: URI indexing and OSC8 handling (BL-4, BL-5)', () => {
1986
+ const createHarness = require('./test-support/vendor-cellsegmenter-harness.js');
1987
+ const h = createHarness((s) => s.replace(/\x1b\[[0-9;]*m/g, '').length, (s) => 1);
1988
+ const { D, Pool, mkScreen, readCell } = h;
1989
+
1990
+ const stylePool = new Pool();
1991
+ const charPool = new Pool([' ', 'S']);
1992
+ const hyperPool = new Pool(['']);
1993
+ const d = new D(stylePool, charPool);
1994
+
1995
+ // Test OSC8 with BEL terminator
1996
+ const text1 = 'A\x1b]8;;http://x\x07B\x1b]8;;\x07C';
1997
+ d.segment(text1, false);
1998
+ const screen1 = mkScreen(40, 1);
1999
+ d.paint(screen1.cells, 40, 0, 0, hyperPool);
2000
+
2001
+ const cellA = readCell(screen1, charPool, hyperPool, 0, 0);
2002
+ const cellB = readCell(screen1, charPool, hyperPool, 1, 0);
2003
+ const cellC = readCell(screen1, charPool, hyperPool, 2, 0);
2004
+
2005
+ assert.equal(cellA.hyperlink, undefined, 'A should have no hyperlink');
2006
+ assert.equal(cellB.hyperlink, 'http://x', 'B should link to http://x');
2007
+ assert.equal(cellC.hyperlink, undefined, 'C should have no hyperlink');
2008
+
2009
+ // Test OSC8 with ST terminator (ESC backslash)
2010
+ stylePool.arr = [];
2011
+ stylePool.map.clear();
2012
+ const d2 = new D(stylePool, charPool);
2013
+ const text2 = '\x1b]8;;http://st\x1b\\ST\x1b]8;;\x1b\\';
2014
+ d2.segment(text2, false);
2015
+
2016
+ // Verify no ESC byte mixed into text
2017
+ const textReconstructed = d2.graphemes.slice(0, d2.count).join('');
2018
+ assert.equal(textReconstructed, 'ST', 'ST terminator should not include ESC bytes');
2019
+
2020
+ // BL-5: Verify uris array has clean URLs without ESC bytes
2021
+ const uriWithoutEsc = d2.uris[1]; // Index 1 because 0 is reserved
2022
+ assert.ok(uriWithoutEsc, 'should have URI at index 1');
2023
+ assert.equal(uriWithoutEsc, 'http://st', 'URI should be clean without ESC bytes');
2024
+ });
2025
+
2026
+ test('CellSegmenter: no infinite loops on malformed escapes (BL-1, BL-2)', function() {
2027
+ const createShim = require('./bun-cellsegmenter-shim.js');
2028
+ const { CellSegmenter, sliceAnsi } = createShim({
2029
+ stringWidth: (s) => s.replace(/\x1b\[[0-9;]*m/g, '').length,
2030
+ graphemeWidth: (s) => 1
2031
+ });
2032
+
2033
+ const cases = {
2034
+ 'osc-title': '\x1b]0;my title\x07hello',
2035
+ 'osc9': '\x1b]9;notify\x07hi',
2036
+ 'osc8-badprefix': '\x1b]8x;;http://a\x07hi',
2037
+ 'esc-alone': 'abc\x1b',
2038
+ 'esc-paren': 'abc\x1bcdef',
2039
+ 'esc-dcs': '\x1bPsomething\x1b\\text',
2040
+ 'esc-st': 'a\x1b\\b',
2041
+ 'esc-charset': '\x1b(Bhello',
2042
+ 'esc-esc': 'a\x1b\x1bb',
2043
+ 'sgr-unterm': 'abc\x1b[31',
2044
+ 'osc8-unterm': 'abc\x1b]8;;http://x',
2045
+ 'csi-K': '\x1b[Khello, my friend',
2046
+ 'csi-cursor': '\x1b[2J\x1b[Hmenu item',
2047
+ };
2048
+
2049
+ const seg = new CellSegmenter({
2050
+ ambiguousIsNarrow: true,
2051
+ substitute: [],
2052
+ screen: { widthMask: 3, narrow: 0, wide: 1, spacerTail: 2, spacerHead: 3, emptyCharIndex: 0, spacerCharIndex: 1, emptyWord: 0, tabWidth: 8 }
2053
+ });
2054
+
2055
+ for (const [label, text] of Object.entries(cases)) {
2056
+ // Test segment() with timeout
2057
+ const startSeg = Date.now();
2058
+ const n = seg.segment(text, new Int32Array(1024), new Int32Array(1024), false);
2059
+ const segTime = Date.now() - startSeg;
2060
+ assert.ok(segTime < 500, `segment(${label}) took ${segTime}ms (>500ms suggests hang)`);
2061
+ assert.ok(n >= 0 || n === -1, `segment(${label}) returned invalid result ${n}`);
2062
+
2063
+ // Test sliceAnsi() with timeout
2064
+ const startSlice = Date.now();
2065
+ const result = sliceAnsi(text, 0, 100);
2066
+ const sliceTime = Date.now() - startSlice;
2067
+ assert.ok(sliceTime < 500, `sliceAnsi(${label}) took ${sliceTime}ms (>500ms suggests hang)`);
2068
+
2069
+ // Verify CSI sequences are consumed (not in output text)
2070
+ if (label === 'csi-K') {
2071
+ assert.equal(result, 'hello, my friend', 'CSI-K should consume and not appear in output');
2072
+ }
2073
+ if (label === 'csi-cursor') {
2074
+ assert.equal(result, 'menu item', 'CSI-2J and CSI-H should not appear in output');
2075
+ }
2076
+ }
2077
+ });
2078
+
2079
+ test('CellSegmenter: grapheme boundary correctness (BL-8 regression prevention)', () => {
2080
+ const createHarness = require('./test-support/vendor-cellsegmenter-harness.js');
2081
+ const h = createHarness((s) => s.replace(/\x1b\[[0-9;]*m/g, '').length, (s) => {
2082
+ // Proper grapheme width calculation
2083
+ const symbols = Array.from(String(s || ''));
2084
+ const codePoints = symbols.map(sym => sym.codePointAt(0)).filter(cp => Number.isFinite(cp));
2085
+ if (codePoints.length === 0) return 0;
2086
+ if (codePoints.length > 1 && codePoints.every(cp => cp >= 0x1f1e6 && cp <= 0x1f1ff)) return 2; // Flag pairs
2087
+ if (codePoints.includes(0x200d) || codePoints.includes(0x20e3) || codePoints.includes(0xfe0f)) return 2; // ZWJ, VS16
2088
+ if (codePoints.some(cp => (cp >= 0x1f300 && cp <= 0x1f6ff) || (cp >= 0x1f900 && cp <= 0x1f9ff))) return 2; // Emoji
2089
+ return 1;
2090
+ });
2091
+ const { D, Pool } = h;
2092
+
2093
+ const stylePool = new Pool();
2094
+ const charPool = new Pool([' ', 'S']);
2095
+
2096
+ // Test 1: ZWJ family emoji (👨‍👩‍👧) should be 1 grapheme, not split
2097
+ const d1 = new D(stylePool, charPool);
2098
+ const family = '👨‍👩‍👧';
2099
+ const n1 = d1.segment(family, false);
2100
+ assert.equal(n1, 1, `Family emoji ${JSON.stringify(family)} should be 1 grapheme cluster`);
2101
+
2102
+ // Test 2: Flag emoji (🇯🇵) should be 1 grapheme (surrogate pair combined)
2103
+ const d2 = new D(stylePool, charPool);
2104
+ const jpFlag = '🇯🇵';
2105
+ const n2 = d2.segment(jpFlag, false);
2106
+ assert.equal(n2, 1, `Flag emoji ${JSON.stringify(jpFlag)} should be 1 grapheme cluster`);
2107
+
2108
+ // Test 3: sliceAnsi() should not produce isolated surrogates
2109
+ const { sliceAnsi } = h;
2110
+ const sliceResult = sliceAnsi('a👍b', 0, 2);
2111
+ // Check for isolated surrogates (UTF-16 range 0xD800-0xDFFF)
2112
+ const isSurrogatePair = /[\ud800-\udfff]/.test(sliceResult);
2113
+ assert.ok(!isSurrogatePair, `sliceAnsi('a👍b', 0, 2) should not have orphaned surrogates: ${JSON.stringify(sliceResult)}`);
2114
+
2115
+ // Test 4: Warning symbol with VS16 (⚠️) should have correct width
2116
+ const d4 = new D(stylePool, charPool);
2117
+ const warning = '⚠️ warn';
2118
+ const n4 = d4.segment(warning, false);
2119
+ // Intl.Segmenter splits as: '⚠️' (1 grapheme) + ' ' (1) + 'w' (1) + 'a' (1) + 'r' (1) + 'n' (1) = 6 graphemes
2120
+ assert.equal(n4, 6, `Warning symbol with VS16 should produce 6 graphemes: got ${n4}`);
2121
+ });
2122
+
2123
+ test('CellSegmenter: fresh instance pool initialization (NB-2)', () => {
2124
+ const createHarness = require('./test-support/vendor-cellsegmenter-harness.js');
2125
+ const h = createHarness((s) => s.replace(/\x1b\[[0-9;]*m/g, '').length, (s) => {
2126
+ // Simple width calculator
2127
+ const codePoints = Array.from(String(s || '')).map(sym => sym.codePointAt(0)).filter(cp => Number.isFinite(cp));
2128
+ if (codePoints.length === 0) return 0;
2129
+ if (codePoints.length > 1 && codePoints.every(cp => cp >= 0x1f1e6 && cp <= 0x1f1ff)) return 2; // Flag pairs
2130
+ if (codePoints.includes(0x200d) || codePoints.includes(0x20e3) || codePoints.includes(0xfe0f)) return 2; // ZWJ, VS16
2131
+ return 1;
2132
+ });
2133
+ const { D, Pool } = h;
2134
+
2135
+ // Test 1: New instance pool initialization
2136
+ const stylePool = new Pool();
2137
+ const charPool = new Pool([' ', 'a', 'b', 'c']);
2138
+ const d = new D(stylePool, charPool);
2139
+
2140
+ // Verify initial pool state: sgrKeys should have [''] (index 0 only)
2141
+ assert.equal(d.sgrKeys.length, 1, 'sgrKeys should start with length 1 (index 0 only)');
2142
+ assert.equal(d.sgrKeys[0], '', 'sgrKeys[0] should be empty string');
2143
+
2144
+ // Verify initial pool state: uris should have [''] (index 0 only)
2145
+ assert.equal(d.uris.length, 1, 'uris should start with length 1 (index 0 only)');
2146
+ assert.equal(d.uris[0], '', 'uris[0] should be empty string');
2147
+
2148
+ // Test 2: Multiple segments work correctly without reset
2149
+ d.segment('hello world', false);
2150
+ d.segment('test string', false);
2151
+ assert.ok(d.sgrKeys.length >= 1, 'sgrKeys should grow or stay at 1 (unstyled input)');
2152
+ assert.ok(d.graphemes.length >= 20, 'graphemes should accumulate');
2153
+
2154
+ // Test 3: Fresh instance has clean pools
2155
+ const d2 = new D(stylePool, charPool);
2156
+ assert.equal(d2.sgrKeys.length, 1, 'new instance sgrKeys should be at length 1');
2157
+ assert.equal(d2.sgrKeys[0], '', 'new instance sgrKeys[0] should be empty string');
2158
+ assert.equal(d2.uris.length, 1, 'new instance uris should be at length 1');
2159
+ assert.equal(d2.uris[0], '', 'new instance uris[0] should be empty string');
2160
+
2161
+ // Test 4: Fresh instance can segment immediately
2162
+ const count2 = d2.segment('fresh test', false);
2163
+ assert.ok(count2 > 0, 'should successfully segment after reset');
2164
+ assert.equal(d2.graphemes.length, count2, 'grapheme count should match segment result');
2165
+ });
@@ -0,0 +1,142 @@
1
+ // Faithful re-implementation of the vendor-side consumer (class _d) from
2
+ // cellsegmenter-extracted-functions.js, so we can exercise the shim exactly
3
+ // the way claude-code 2.1.272 does.
4
+ const createShim = require('../bun-cellsegmenter-shim.js');
5
+
6
+ // Create shim factory that accepts stringWidth and graphemeWidth
7
+ function createHarness(stringWidth, graphemeWidth) {
8
+ const { CellSegmenter, sliceAnsi, sleepSync } = createShim({
9
+ stringWidth,
10
+ graphemeWidth,
11
+ });
12
+
13
+ const fl = 17, Fo = 2, kr = 32767, pn = 3, Ub = 10, fC = 255, dC = 256, Eut = 8;
14
+ const aXe = [[1564, 1564], [8234, 8238], [8294, 8297]];
15
+ function qn(n, s, u) { return n << fl | s << Fo | u; }
16
+ function Ys(n, s, u) {
17
+ if (n.length >= s) return n;
18
+ let f = new Int32Array(Math.max(s, 2 * n.length));
19
+ if (u > 0) f.set(n.subarray(0, Math.min(u, n.length)));
20
+ return f;
21
+ }
22
+ class Pool {
23
+ constructor(seed) { this.arr = seed ? seed.slice() : []; this.map = new Map(); this.arr.forEach((v, i) => this.map.set(v, i)); }
24
+ intern(v) { if (this.map.has(v)) return this.map.get(v); const i = this.arr.length; this.arr.push(v); this.map.set(v, i); return i; }
25
+ get(i) { return this.arr[i]; }
26
+ }
27
+ function As() {
28
+ return new CellSegmenter({
29
+ ambiguousIsNarrow: true,
30
+ substitute: aXe,
31
+ screen: { widthMask: pn, narrow: 0, wide: 1, spacerTail: 2, spacerHead: 3, emptyCharIndex: 0, spacerCharIndex: 1, emptyWord: qn(0, 0, 0), tabWidth: Eut },
32
+ });
33
+ }
34
+ // class _d
35
+ class D {
36
+ constructor(stylePool, charPool) {
37
+ this.stylePool = stylePool; this.charPool = charPool;
38
+ this.native = As();
39
+ this.cells = new Int32Array(512); this.runs = new Int32Array(512);
40
+ this.count = 0; this.reordered = false;
41
+ this.graphemes = this.native.graphemes;
42
+ this.sgrKeys = this.native.sgrKeys;
43
+ this.sgrCloseKeys = this.native.sgrCloseKeys;
44
+ this.uris = this.native.uris;
45
+ this.charMap = new Int32Array(256); this.charMapLength = 0;
46
+ this.styleIds = new Int32Array(64);
47
+ this.linkIds = new Int32Array(16);
48
+ this.words = new Int32Array(64);
49
+ this.retries = 0;
50
+ }
51
+ segment(n, s) {
52
+ let u = this.native.segment(n, this.cells, this.runs, s);
53
+ if (u < 0) {
54
+ this.retries++;
55
+ let f = Math.max(-u, this.cells.length);
56
+ this.cells = new Int32Array(2 * f); this.runs = new Int32Array(2 * f);
57
+ u = this.native.segment(n, this.cells, this.runs, s);
58
+ }
59
+ this.count = u; this.reordered = s; return u;
60
+ }
61
+ width(n, s, u) {
62
+ let f = this.segment(n, u), p = s;
63
+ for (let y = 0; y < f; y++) {
64
+ let S = this.cells[2 * y + 1];
65
+ p += (S & dC) !== 0 ? Eut - p % Eut : S & fC;
66
+ }
67
+ return p - s;
68
+ }
69
+ charIndices() {
70
+ let n = this.graphemes;
71
+ if (this.charMapLength < n.length) {
72
+ this.charMap = Ys(this.charMap, n.length, this.charMapLength);
73
+ for (let s = this.charMapLength; s < n.length; s++) this.charMap[s] = this.charPool.intern(n[s]);
74
+ this.charMapLength = n.length;
75
+ }
76
+ return this.charMap;
77
+ }
78
+ // verbatim from vendor bundle
79
+ runWords(n) {
80
+ let s = this.count;
81
+ if (s === 0) return this.words;
82
+ if (this.hyperlinkPool !== n) { this.hyperlinkPool = n; this.linkIds.fill(0); }
83
+ let u = this.cells[2 * s - 1] >>> Ub;
84
+ if (this.reordered) for (let p = 0; p < s; p++) u = Math.max(u, this.cells[2 * p + 1] >>> Ub);
85
+ let f = u + 1;
86
+ this.words = Ys(this.words, f, 0);
87
+ this.runCount = f;
88
+ for (let p = 0; p < f; p++) {
89
+ let y = this.runs[2 * p + 1], S = 0;
90
+ if (y !== 0) {
91
+ if (this.linkIds = Ys(this.linkIds, y + 1, this.linkIds.length), S = this.linkIds[y], S === 0)
92
+ S = n.intern(this.uris[y]) + 1, this.linkIds[y] = S;
93
+ S -= 1;
94
+ }
95
+ this.words[p] = qn(this.styleId(this.runs[2 * p]), S, 0);
96
+ }
97
+ return this.words;
98
+ }
99
+ paint(n, s, u, f, p) {
100
+ return this.native.paint(n, s, u, f, this.cells, this.count, void 0, this.charIndices(), this.runWords(p));
101
+ }
102
+ // ansiCodes / styleId per vendor bundle
103
+ ansiCodes(n) {
104
+ if (n === 0) return [];
105
+ let s = this.sgrKeys[n].split('\x00'), u = this.sgrCloseKeys[n].split('\x00'), f = [];
106
+ for (let p = 0; p < s.length; p++) {
107
+ let y = s[p];
108
+ if (mC.test(y)) f.push({ type: 'ansi', code: y, endCode: u[p] });
109
+ }
110
+ return f;
111
+ }
112
+ styleId(n) {
113
+ this.styleIds = Ys(this.styleIds, n + 1, this.styleIds.length);
114
+ let s = this.styleIds[n];
115
+ if (s === 0) { s = this.stylePool.intern(JSON.stringify(this.ansiCodes(n))) + 1; this.styleIds[n] = s; }
116
+ return s - 1;
117
+ }
118
+ }
119
+ const mC = /^\x1b\[(?:\d{1,3})(?:;5;\d{1,3}|;2;\d{1,3};\d{1,3};\d{1,3})?m$/;
120
+
121
+ // Y0 damage decode
122
+ function Y0(u) {
123
+ let f = Math.floor(u / 1048576) % 65536;
124
+ let p = Math.floor(u / 68719476736);
125
+ if (f >= p) return null;
126
+ return { x: f, width: p - f };
127
+ }
128
+
129
+ function mkScreen(width, height) {
130
+ return { width, height, cells: new Int32Array(width * height * 2) };
131
+ }
132
+ function readCell(screen, charPool, hyperPool, x, y) {
133
+ const i = (y * screen.width + x) << 1;
134
+ const p = screen.cells[i + 1];
135
+ const h = p >>> Fo & kr;
136
+ return { char: charPool.get(screen.cells[i]), styleId: p >>> fl, width: p & pn, hyperlink: h === 0 ? undefined : hyperPool.get(h) };
137
+ }
138
+
139
+ return { CellSegmenter, sliceAnsi, sleepSync, D, Pool, As, qn, Y0, mkScreen, readCell, mC, fl, Fo, kr, pn, Ub, fC, dC };
140
+ }
141
+
142
+ module.exports = createHarness;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bash0816/claude-code",
3
- "version": "2.1.270",
3
+ "version": "2.1.272",
4
4
  "description": "Unofficial Termux-native Claude Code wrapper with audited native replay",
5
5
  "license": "GPL-3.0-only",
6
6
  "bin": {