forked from doctly/switchboard
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcomposer-state.js
More file actions
368 lines (318 loc) · 11.6 KB
/
Copy pathcomposer-state.js
File metadata and controls
368 lines (318 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// composer-state.js — a model of what the user has typed and not submitted.
// see docs/automation.md ("Politeness") for what each rule protects and where
// the model is blind.
'use strict';
const MAX_PARTIAL = 32;
const PASTE_START = '\x1b[200~';
const PASTE_END = '\x1b[201~';
// Stands in for input whose text cannot be known: a Ctrl+V image paste, a
// history recall, an escape sequence too long to parse.
const OPAQUE = '';
function createComposerState() {
return { pending: 0, lastInputAt: 0, inPaste: false, partial: '', text: '', cursor: 0 };
}
function isComposerEmpty(state) {
return !state || state.pending === 0;
}
// ── The composer model ────────────────────────────────────────────────────────
// `text` is what we believe sits in the box, `cursor` a UTF-16 index into it.
// `pending` is derived: the number of code points, so an astral character
// weighs one, exactly as one backspace removes it.
function isHighSurrogate(code) { return code >= 0xd800 && code <= 0xdbff; }
function isLowSurrogate(code) { return code >= 0xdc00 && code <= 0xdfff; }
function prevBoundary(text, i) {
if (i <= 0) return 0;
if (i >= 2 && isLowSurrogate(text.charCodeAt(i - 1)) && isHighSurrogate(text.charCodeAt(i - 2))) {
return i - 2;
}
return i - 1;
}
function nextBoundary(text, i) {
if (i >= text.length) return text.length;
if (i + 1 < text.length && isHighSurrogate(text.charCodeAt(i)) && isLowSurrogate(text.charCodeAt(i + 1))) {
return i + 2;
}
return i + 1;
}
function countCodePoints(text) {
let n = 0;
for (let i = 0; i < text.length; i++) {
n++;
if (isHighSurrogate(text.charCodeAt(i)) && i + 1 < text.length
&& isLowSurrogate(text.charCodeAt(i + 1))) {
i++;
}
}
return n;
}
const WHITESPACE = /\s/;
function wordStart(text, i) {
let j = i;
while (j > 0 && WHITESPACE.test(text[j - 1])) j--;
while (j > 0 && !WHITESPACE.test(text[j - 1])) j--;
return j;
}
function wordEnd(text, i) {
let j = i;
while (j < text.length && WHITESPACE.test(text[j])) j++;
while (j < text.length && !WHITESPACE.test(text[j])) j++;
return j;
}
function insertText(state, s) {
if (!s) return;
state.text = state.text.slice(0, state.cursor) + s + state.text.slice(state.cursor);
state.cursor += s.length;
}
function deleteRange(state, from, to) {
if (from >= to) return;
state.text = state.text.slice(0, from) + state.text.slice(to);
state.cursor = from;
}
function backspace(state) { deleteRange(state, prevBoundary(state.text, state.cursor), state.cursor); }
function deleteForward(state) { deleteRange(state, state.cursor, nextBoundary(state.text, state.cursor)); }
function killWordBack(state) { deleteRange(state, wordStart(state.text, state.cursor), state.cursor); }
function killToEnd(state) { state.text = state.text.slice(0, state.cursor); }
function clearAll(state) { state.text = ''; state.cursor = 0; }
function moveLeft(state) { state.cursor = prevBoundary(state.text, state.cursor); }
function moveRight(state) { state.cursor = nextBoundary(state.text, state.cursor); }
function moveWordLeft(state) { state.cursor = wordStart(state.text, state.cursor); }
function moveWordRight(state) { state.cursor = wordEnd(state.text, state.cursor); }
function moveHome(state) { state.cursor = 0; }
function moveEnd(state) { state.cursor = state.text.length; }
function sync(state) {
state.pending = countCodePoints(state.text);
return state;
}
// ── The parser ────────────────────────────────────────────────────────────────
/** True when `buf` from `i` is a strict prefix of `seq` and runs to the end. */
function isTruncatedPrefixOf(buf, i, seq) {
const rest = buf.length - i;
return rest < seq.length && seq.startsWith(buf.slice(i));
}
/**
* Match one escape sequence starting at `i`.
* Returns { len, kind, params, final } or null when the sequence is not yet
* complete. kind: 'csi' | 'ss3' | 'osc' | 'esc'
*/
function matchEscape(buf, i) {
const next = buf[i + 1];
if (next === undefined) return null;
if (next === '[') {
let j = i + 2;
while (j < buf.length && buf[j] >= '\x30' && buf[j] <= '\x3f') j++;
const paramsEnd = j;
while (j < buf.length && buf[j] >= '\x20' && buf[j] <= '\x2f') j++;
if (j >= buf.length) return null;
const final = buf[j];
if (final < '\x40' || final > '\x7e') return { len: j - i + 1, kind: 'csi', params: '', final };
return { len: j - i + 1, kind: 'csi', params: buf.slice(i + 2, paramsEnd), final };
}
if (next === 'O') {
if (i + 2 >= buf.length) return null;
return { len: 3, kind: 'ss3', final: buf[i + 2] };
}
if (next === ']') {
for (let j = i + 2; j < buf.length; j++) {
if (buf[j] === '\x07') return { len: j - i + 1, kind: 'osc' };
if (buf[j] === '\x1b' && buf[j + 1] === '\\') return { len: j - i + 2, kind: 'osc' };
if (buf[j] === '\x1b' && j + 1 >= buf.length) return null;
}
return null;
}
// ESC followed by ESC is not Alt+ESC: consume only the first, so the second
// is re-examined and can still open a bracketed paste.
if (next === '\x1b') return { len: 1, kind: 'esc', final: '\x1b' };
return { len: 2, kind: 'esc', final: next };
}
// ── Terminal reports ─────────────────────────────────────────────────────────
// Mouse, focus and cursor-position reports ride the same channel as
// keystrokes but are not user input: neither text nor activity. Recognition
// is deliberately strict — see .ai/contexts/trigger-watcher.md.
const SGR_MOUSE_PARAMS_RE = /^<\d{1,10};\d{1,10};\d{1,10}$/;
// DECXCPR only, `?` mandatory: `CSI ? row ; col [; page] R` — see .ai/contexts/trigger-watcher.md.
const CPR_PARAMS_RE = /^\?\d{1,4};\d{1,4}(?:;\d{1,4})?$/;
/**
* How many bytes of terminal report start at the sequence `seq` just matched.
* 0 when the sequence is not a report.
*/
function reportLength(seq) {
if (seq.kind !== 'csi') return 0;
const { final, params } = seq;
// SGR (CSI ?1006h): `CSI < b ; x ; y M` press, `… m` release.
if ((final === 'M' || final === 'm') && SGR_MOUSE_PARAMS_RE.test(params)) return seq.len;
// Focus in / focus out (CSI ?1004h).
if ((final === 'I' || final === 'O') && params === '') return seq.len;
// Cursor position report.
if (final === 'R' && CPR_PARAMS_RE.test(params)) return seq.len;
return 0;
}
// A kitty Enter is a line break only when it carries a modifier parameter;
// bare `ESC [ 13 u` is a submission.
const KITTY_ENTER_RE = /^13;[0-9:;]+$/;
/** Numeric prefix of a CSI parameter string: '3;5' → '3'. */
function firstParam(params) {
const semi = params.indexOf(';');
return semi === -1 ? params : params.slice(0, semi);
}
function isModified(params) {
return params.indexOf(';') !== -1;
}
function applyCsi(state, seq) {
const { final, params } = seq;
switch (final) {
case 'A':
// Bare Up recalls history and fills the box; modified Up does nothing on
// Claude Code v2.1.258.
if (params === '') insertText(state, OPAQUE);
return;
case 'C':
if (isModified(params)) moveWordRight(state); else moveRight(state);
return;
case 'D':
if (isModified(params)) moveWordLeft(state); else moveLeft(state);
return;
case 'H': moveHome(state); return;
case 'F': moveEnd(state); return;
case 'u':
if (KITTY_ENTER_RE.test(params)) insertText(state, '\n');
return;
case '~': {
const p = firstParam(params);
if (p === '3') deleteForward(state);
else if (p === '1' || p === '7') moveHome(state);
else if (p === '4' || p === '8') moveEnd(state);
return;
}
default:
}
}
function applySs3(state, seq) {
switch (seq.final) {
case 'A': insertText(state, OPAQUE); return;
case 'C': moveRight(state); return;
case 'D': moveLeft(state); return;
case 'H': moveHome(state); return;
case 'F': moveEnd(state); return;
default:
}
}
function applyEsc(state, seq) {
if (seq.final === '\x7f' || seq.final === '\b') killWordBack(state);
}
/**
* Insert a run of literal characters. A run ending on a lone high surrogate at
* the very end of the buffer is held back so a pair split across two IPC
* chunks is not counted twice.
*/
function insertRun(state, run, atBufferEnd) {
let s = run;
if (atBufferEnd && s.length && isHighSurrogate(s.charCodeAt(s.length - 1))) {
state.partial = s.slice(-1);
s = s.slice(0, -1);
}
insertText(state, s);
}
/**
* Fold one chunk of renderer keystrokes into `state`.
*
* A chunk made only of terminal reports leaves the state untouched, clock
* included; anything else pushes `lastInputAt`.
*
* @param {object} state from createComposerState()
* @param {string|Buffer} data bytes the user just sent to the PTY
* @param {number} now epoch ms
*/
function noteUserInput(state, data, now) {
if (!state) return state;
const chunk = typeof data === 'string' ? data : String(data ?? '');
if (chunk.length === 0) return state;
const buf = state.partial + chunk;
state.partial = '';
let counted = false;
const finish = () => {
if (counted) state.lastInputAt = now;
return sync(state);
};
let i = 0;
while (i < buf.length) {
const c = buf[i];
if (state.inPaste) {
counted = true;
if (buf.startsWith(PASTE_END, i)) {
state.inPaste = false;
i += PASTE_END.length;
continue;
}
if (c === '\x1b' && isTruncatedPrefixOf(buf, i, PASTE_END)) {
state.partial = buf.slice(i);
return finish();
}
let j = i;
while (j < buf.length && buf[j] !== '\x1b') j++;
if (j === i) j = i + 1;
insertRun(state, buf.slice(i, j), j === buf.length);
i = j;
continue;
}
if (c === '\x1b') {
if (buf.startsWith(PASTE_START, i)) {
counted = true;
state.inPaste = true;
i += PASTE_START.length;
continue;
}
if (isTruncatedPrefixOf(buf, i, PASTE_START)) {
counted = true;
state.partial = buf.slice(i);
return finish();
}
const seq = matchEscape(buf, i);
if (!seq) {
counted = true;
const tail = buf.slice(i);
if (tail.length > MAX_PARTIAL) {
insertText(state, OPAQUE);
return finish();
}
state.partial = tail;
return finish();
}
const report = reportLength(seq);
if (report > 0) {
i += report;
continue;
}
counted = true;
if (seq.kind === 'csi') applyCsi(state, seq);
else if (seq.kind === 'ss3') applySs3(state, seq);
else if (seq.kind === 'esc') applyEsc(state, seq);
i += seq.len;
continue;
}
counted = true;
if (c === '\r' || c === '\n' || c === '\x15' || c === '\x03') {
clearAll(state);
} else if (c === '\x7f' || c === '\b') {
backspace(state);
} else if (c === '\x17') {
killWordBack(state);
} else if (c === '\x0b') {
killToEnd(state);
} else if (c === '\x01') {
moveHome(state);
} else if (c === '\x05') {
moveEnd(state);
} else if (c === '\x16') {
insertText(state, OPAQUE);
} else if (c >= '\x20') {
let j = i;
while (j < buf.length && buf[j] >= '\x20' && buf[j] !== '\x7f') j++;
insertRun(state, buf.slice(i, j), j === buf.length);
i = j;
continue;
}
i += 1;
}
return finish();
}
module.exports = { createComposerState, noteUserInput, isComposerEmpty, MAX_PARTIAL };