@unscientificjszhai/howto 1.0.1 → 1.1.0

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.
Files changed (60) hide show
  1. package/README.md +127 -31
  2. package/README.zh-hans-cn.md +331 -0
  3. package/THIRD_PARTY_NOTICES.md +2 -0
  4. package/dist/ai/chatgpt-models.js +148 -0
  5. package/dist/ai/chatgpt.js +495 -0
  6. package/dist/ai/command-schema.js +15 -1
  7. package/dist/ai/errors.js +6 -0
  8. package/dist/ai/gemini.js +117 -4
  9. package/dist/ai/index.js +4 -1
  10. package/dist/ai/openai.js +105 -2
  11. package/dist/ai/usage-session.js +144 -0
  12. package/dist/auth/chatgpt/commands.js +90 -0
  13. package/dist/auth/chatgpt/errors.js +85 -0
  14. package/dist/auth/chatgpt/http.js +97 -0
  15. package/dist/auth/chatgpt/index.js +229 -0
  16. package/dist/auth/chatgpt/instructions.js +22 -0
  17. package/dist/auth/chatgpt/oauth.js +320 -0
  18. package/dist/auth/chatgpt/storage.js +366 -0
  19. package/dist/auth/chatgpt/types.js +1 -0
  20. package/dist/cli.js +77 -16
  21. package/dist/config-file.js +2 -0
  22. package/dist/config.js +11 -4
  23. package/dist/errors.js +6 -1
  24. package/dist/execute.js +4 -13
  25. package/dist/index.js +32 -12
  26. package/dist/init/ChatGptInitializationStep.js +223 -0
  27. package/dist/init/InitializationApp.js +74 -38
  28. package/dist/init/index.js +24 -5
  29. package/dist/init/state.js +14 -3
  30. package/dist/prompt.js +56 -10
  31. package/dist/safety/command-risk.js +11 -0
  32. package/dist/safety/dangerous-command.js +209 -0
  33. package/dist/shell/command-analysis.js +25 -5
  34. package/dist/shell/execution-environment.js +25 -0
  35. package/dist/shell/runtime-environment.js +61 -0
  36. package/dist/ui/App.js +104 -15
  37. package/dist/ui/ConfirmView.js +8 -41
  38. package/dist/ui/InteractiveSessionProvider.js +7 -8
  39. package/dist/ui/ResolvePlaceholdersView.js +8 -3
  40. package/dist/ui/SelectCommandView.js +2 -2
  41. package/dist/ui/UsageApprovalView.js +320 -0
  42. package/dist/ui/interactive-session.js +243 -33
  43. package/dist/ui/keyboard-framing.js +102 -0
  44. package/dist/ui/paste-framing.js +69 -32
  45. package/dist/ui/resize-safe-output.js +2 -2
  46. package/dist/ui/run-interactive-command.js +2 -2
  47. package/dist/ui/text-input.js +4 -1
  48. package/dist/ui/use-keyboard-input.js +17 -2
  49. package/dist/ui/use-paste-aware-input.js +12 -3
  50. package/dist/usage/arguments.js +61 -0
  51. package/dist/usage/generate.js +156 -0
  52. package/dist/usage/output.js +216 -0
  53. package/dist/usage/risk.js +17 -0
  54. package/dist/usage/runner.js +238 -0
  55. package/dist/usage/types.js +1 -0
  56. package/dist/validation/ai-response.js +24 -3
  57. package/dist/validation/command-tool.js +7 -6
  58. package/dist/validation/usage-response.js +39 -0
  59. package/package.json +31 -17
  60. package/README.CN.md +0 -235
@@ -1,10 +1,15 @@
1
+ import { closeSync, constants, openSync, readSync } from "node:fs";
1
2
  import { Readable } from "node:stream";
2
3
  import { StringDecoder } from "node:string_decoder";
3
4
  import { ReadStream } from "node:tty";
5
+ import { onExit as signalExit } from "signal-exit";
4
6
  import { normalizePhysicalRows, toResizeSafeOutput } from "./resize-safe-output.js";
5
- import { PasteFramingFilter, PasteStartObserver } from "./paste-framing.js";
7
+ import { PasteFramingError, PasteFramingFilter } from "./paste-framing.js";
8
+ import { KeyboardFramingFilter } from "./keyboard-framing.js";
6
9
  export const ENABLE_PASTE = "\u001b[?2004h";
7
10
  export const DISABLE_PASTE = "\u001b[?2004l";
11
+ export const PASTE_IDLE_TIMEOUT_MS = 5_000;
12
+ export const PASTE_DURATION_LIMIT_MS = 30_000;
8
13
  export class InteractiveSessionError extends Error {
9
14
  constructor(message = "交互终端输入不可用。") {
10
15
  super(message);
@@ -37,6 +42,29 @@ function assertAvailableInput(input, output) {
37
42
  class SessionInput extends Readable {
38
43
  isTTY = true;
39
44
  isRaw = true;
45
+ owners = new WeakMap();
46
+ onDelivery;
47
+ constructor(onDelivery) {
48
+ // 每次 read 只交付一批输入,Ink 不能把不同页面收到的批次合并后重新解释。
49
+ super({ objectMode: true });
50
+ this.onDelivery = onDelivery;
51
+ }
52
+ deliver(text, owner) {
53
+ const chunk = Buffer.from(text);
54
+ this.owners.set(chunk, owner);
55
+ this.push(chunk);
56
+ }
57
+ read(size) {
58
+ const chunk = super.read(size);
59
+ // Ink 的独立 Esc 会延后解析;空 read 不能抹掉它原本的输入归属。
60
+ if (chunk !== null)
61
+ this.onDelivery(this.owners.get(chunk));
62
+ return chunk;
63
+ }
64
+ setEncoding() {
65
+ // UTF-8 已由物理会话完整解码;保留 Buffer 身份以及对应的输入边界。
66
+ return this;
67
+ }
40
68
  _read() { }
41
69
  setRawMode(enabled) {
42
70
  this.isRaw = enabled;
@@ -50,14 +78,26 @@ class SessionInput extends Readable {
50
78
  }
51
79
  }
52
80
  export class InteractiveSession {
53
- physicalInput;
54
- physicalOutput;
55
- resources;
56
81
  input;
57
82
  output;
58
- bridge = new SessionInput();
59
- observer = new PasteStartObserver();
60
- filter = new PasteFramingFilter();
83
+ bridge = new SessionInput((owner) => {
84
+ this.deliveryOwner = owner;
85
+ });
86
+ keyboard = new KeyboardFramingFilter();
87
+ filter = new PasteFramingFilter((reason) => {
88
+ this.reportInputNotice(reason === "control"
89
+ ? "粘贴内容包含不支持的控制字符,已整块丢弃;请检查后重新输入。"
90
+ : "粘贴跨越页面、字段或隐藏阶段,已整块丢弃;请在当前字段重新粘贴。");
91
+ }, () => this.clearPasteTimers(), (text, active) => {
92
+ this.keyboard.setActive(active);
93
+ const framed = this.keyboard.push(text);
94
+ this.keyboard.setActive(this.inputActive);
95
+ return framed;
96
+ });
97
+ inputOwner = {};
98
+ deliveryOwner;
99
+ noticeListeners = new Set();
100
+ pendingNotices = new Set();
61
101
  decoder = new StringDecoder("utf8");
62
102
  policyListeners = new Set();
63
103
  failureListeners = new Set();
@@ -77,6 +117,13 @@ export class InteractiveSession {
77
117
  view;
78
118
  viewEnabled = false;
79
119
  prefixTimer;
120
+ pasteIdleTimer;
121
+ pasteDurationTimer;
122
+ unfinishedInputAtClose = false;
123
+ removeExitHook;
124
+ physicalInput;
125
+ physicalOutput;
126
+ resources;
80
127
  constructor(physicalInput, physicalOutput, resources = {}) {
81
128
  this.physicalInput = physicalInput;
82
129
  this.physicalOutput = physicalOutput;
@@ -86,6 +133,16 @@ export class InteractiveSession {
86
133
  this.originalRaw = resources.restoreRaw ?? physicalInput.isRaw === true;
87
134
  try {
88
135
  assertAvailableInput(physicalInput, physicalOutput);
136
+ // Ink 先卸载界面,再由资源持有者同步恢复物理终端。
137
+ const registerExit = resources.registerExit ?? signalExit;
138
+ this.removeExitHook = registerExit(() => {
139
+ try {
140
+ this.dispose();
141
+ }
142
+ catch {
143
+ // 退出时尽力清理,不能让清理异常改变原退出码或终止信号。
144
+ }
145
+ }, { alwaysLast: true });
89
146
  // 校验拒绝时不能读取仍由原消费者持有的缓冲。
90
147
  this.inputAcquired = true;
91
148
  physicalInput.on("readable", this.drain);
@@ -119,6 +176,17 @@ export class InteractiveSession {
119
176
  }
120
177
  }
121
178
  getExecutionPolicy = () => this.policy;
179
+ checkExecutionPolicy = () => {
180
+ this.throwIfFailed();
181
+ if (this.closed)
182
+ throw new InteractiveSessionError();
183
+ // 查询保留终端租约;启动进程前同步检查尚未交付的输入及未闭合粘贴。
184
+ this.drain();
185
+ this.observePendingInput();
186
+ this.throwIfFailed();
187
+ this.assertCompleteInput();
188
+ return this.policy;
189
+ };
122
190
  subscribeExecutionPolicy = (listener) => {
123
191
  this.policyListeners.add(listener);
124
192
  return () => {
@@ -134,6 +202,31 @@ export class InteractiveSession {
134
202
  this.failureListeners.delete(listener);
135
203
  };
136
204
  }
205
+ isInputCurrent = () => this.inputActive && this.deliveryOwner === this.inputOwner;
206
+ reportInputNotice(message) {
207
+ if (this.disposing || this.closed)
208
+ return;
209
+ if (this.noticeListeners.size === 0)
210
+ this.pendingNotices.add(message);
211
+ else
212
+ for (const listener of this.noticeListeners)
213
+ listener(message);
214
+ }
215
+ reportIgnoredPaste = () => {
216
+ this.reportInputNotice("当前页面忽略粘贴,请使用键盘完成选择或确认。");
217
+ };
218
+ reportStalePaste = () => {
219
+ this.reportInputNotice("粘贴属于上一页面或字段,已丢弃;请在当前字段重新粘贴。");
220
+ };
221
+ subscribeInputNotice(listener) {
222
+ this.noticeListeners.add(listener);
223
+ for (const message of this.pendingNotices)
224
+ listener(message);
225
+ this.pendingNotices.clear();
226
+ return () => {
227
+ this.noticeListeners.delete(listener);
228
+ };
229
+ }
137
230
  beginView() {
138
231
  this.throwIfFailed();
139
232
  if (this.closed)
@@ -151,6 +244,7 @@ export class InteractiveSession {
151
244
  };
152
245
  }
153
246
  suspendViewInput() {
247
+ this.inputOwner = {};
154
248
  this.viewEnabled = false;
155
249
  this.setInputActive(false);
156
250
  this.drain();
@@ -163,9 +257,13 @@ export class InteractiveSession {
163
257
  if (this.closed)
164
258
  throw new InteractiveSessionError();
165
259
  this.drain();
260
+ this.observePendingInput();
166
261
  this.throwIfFailed();
262
+ this.assertCompleteInput();
167
263
  this.dispose();
168
264
  this.throwIfFailed();
265
+ if (this.unfinishedInputAtClose)
266
+ throw new InteractiveSessionError("粘贴或输入序列尚未结束,已取消本次交互。");
169
267
  // 本次检查后不经过 await,执行 action 必须同步到达实际 spawn。
170
268
  return this.getExecutionPolicy() === "print" ? actions.print() : actions.execute();
171
269
  }
@@ -173,12 +271,22 @@ export class InteractiveSession {
173
271
  if (this.closed || this.disposing)
174
272
  return;
175
273
  this.disposing = true;
274
+ try {
275
+ this.disposeResources();
276
+ }
277
+ finally {
278
+ const removeExitHook = this.removeExitHook;
279
+ this.removeExitHook = undefined;
280
+ removeExitHook?.();
281
+ }
282
+ }
283
+ disposeResources() {
176
284
  const previousFailure = this.failure;
177
285
  this.checkTerminalState();
178
286
  this.viewEnabled = false;
179
287
  this.setInputActive(false);
180
288
  this.clearPrefixTimer();
181
- this.filter.clear();
289
+ this.clearPasteTimers();
182
290
  let cleanupFailed = false;
183
291
  const cleanup = (action) => {
184
292
  try {
@@ -193,6 +301,7 @@ export class InteractiveSession {
193
301
  cleanup(() => {
194
302
  this.physicalOutput.write(DISABLE_PASTE);
195
303
  });
304
+ cleanup(() => this.observePendingInput());
196
305
  if (this.rawAcquired)
197
306
  cleanup(() => {
198
307
  this.physicalInput.setRawMode(this.originalRaw);
@@ -203,6 +312,14 @@ export class InteractiveSession {
203
312
  });
204
313
  // 恢复终端时仍保留原始观察,最后再同步排空并撤下监听。
205
314
  this.drain();
315
+ try {
316
+ this.assertCompleteInput();
317
+ }
318
+ catch {
319
+ this.unfinishedInputAtClose = true;
320
+ }
321
+ this.filter.clear();
322
+ this.keyboard.clear();
206
323
  this.checkTerminalState();
207
324
  this.physicalInput.off("readable", this.drain);
208
325
  this.physicalInput.off("end", this.handleFailure);
@@ -235,6 +352,8 @@ export class InteractiveSession {
235
352
  this.bridge.destroy();
236
353
  this.policyListeners.clear();
237
354
  this.failureListeners.clear();
355
+ this.noticeListeners.clear();
356
+ this.pendingNotices.clear();
238
357
  if (cleanupFailed && !this.failure) {
239
358
  this.failure = new InteractiveSessionError("无法恢复交互终端状态。");
240
359
  }
@@ -286,11 +405,14 @@ export class InteractiveSession {
286
405
  };
287
406
  setInputActive(active) {
288
407
  if (active !== this.inputActive) {
408
+ if (!active)
409
+ this.inputOwner = {};
289
410
  // 隐藏边界不能把未完成的 UTF-8 字符带入下一个可见输入阶段。
290
411
  this.decoder = new StringDecoder("utf8");
291
412
  }
292
413
  this.inputActive = active;
293
414
  this.filter.setActive(active);
415
+ this.keyboard.setActive(active);
294
416
  }
295
417
  updateVisibility = () => {
296
418
  const active = this.viewEnabled && normalizePhysicalRows(this.physicalOutput.rows) > 1;
@@ -303,6 +425,70 @@ export class InteractiveSession {
303
425
  clearTimeout(this.prefixTimer);
304
426
  this.prefixTimer = undefined;
305
427
  }
428
+ clearPasteTimers() {
429
+ if (this.pasteIdleTimer !== undefined)
430
+ clearTimeout(this.pasteIdleTimer);
431
+ if (this.pasteDurationTimer !== undefined)
432
+ clearTimeout(this.pasteDurationTimer);
433
+ this.pasteIdleTimer = undefined;
434
+ this.pasteDurationTimer = undefined;
435
+ }
436
+ updatePasteTimers() {
437
+ if (this.disposing ||
438
+ (!this.filter.hasUnfinishedPaste() && !this.keyboard.hasUnfinishedSequence())) {
439
+ this.clearPasteTimers();
440
+ return;
441
+ }
442
+ const stop = () => {
443
+ this.fail(new InteractiveSessionError("粘贴或按键序列未在时限内结束,已取消本次交互;请重新运行。"));
444
+ };
445
+ if (this.pasteIdleTimer !== undefined)
446
+ clearTimeout(this.pasteIdleTimer);
447
+ this.pasteIdleTimer = setTimeout(stop, this.resources.pasteIdleTimeoutMs ?? PASTE_IDLE_TIMEOUT_MS);
448
+ this.pasteDurationTimer ??= setTimeout(stop, this.resources.pasteDurationLimitMs ?? PASTE_DURATION_LIMIT_MS);
449
+ }
450
+ processInput(bytes) {
451
+ const owner = this.inputOwner;
452
+ if (normalizePhysicalRows(this.physicalOutput.rows) <= 1)
453
+ this.setInputActive(false);
454
+ const filtered = this.filter.push(this.decoder.write(bytes));
455
+ if (filtered !== "")
456
+ this.bridge.deliver(filtered, owner);
457
+ this.updatePasteTimers();
458
+ }
459
+ assertCompleteInput() {
460
+ this.filter.assertComplete();
461
+ this.keyboard.assertComplete();
462
+ }
463
+ flushPrefix(owner, flush) {
464
+ this.prefixTimer = setTimeout(() => {
465
+ this.prefixTimer = undefined;
466
+ if (this.closed)
467
+ return;
468
+ try {
469
+ const text = flush();
470
+ if (text !== "")
471
+ this.bridge.deliver(text, owner);
472
+ this.updatePasteTimers();
473
+ if (this.keyboard.hasStandaloneEscape()) {
474
+ this.flushPrefix(owner, () => this.keyboard.flushEscape());
475
+ }
476
+ }
477
+ catch (error) {
478
+ this.failInput(error);
479
+ }
480
+ }, 20);
481
+ }
482
+ failInput(error) {
483
+ this.fail(new InteractiveSessionError(error instanceof PasteFramingError ? error.message : undefined));
484
+ }
485
+ observePendingInput() {
486
+ if (!this.inputAcquired || this.failure || !this.resources.readPendingInput)
487
+ return;
488
+ const bytes = this.resources.readPendingInput();
489
+ if (bytes.length > 0)
490
+ this.processInput(bytes);
491
+ }
306
492
  drain = () => {
307
493
  if (this.closed || !this.inputAcquired)
308
494
  return;
@@ -313,32 +499,19 @@ export class InteractiveSession {
313
499
  if (typeof chunk !== "string" && !Buffer.isBuffer(chunk))
314
500
  throw new InteractiveSessionError();
315
501
  const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
316
- if (this.observer.observe(bytes) && this.policy !== "print") {
317
- this.policy = "print";
318
- for (const listener of this.policyListeners)
319
- listener();
320
- }
321
- if (normalizePhysicalRows(this.physicalOutput.rows) <= 1)
322
- this.setInputActive(false);
323
- const text = typeof chunk === "string" ? chunk : this.decoder.write(chunk);
324
- const filtered = this.filter.push(text);
325
- if (filtered !== "")
326
- this.bridge.push(filtered);
502
+ this.processInput(bytes);
327
503
  }
328
504
  if (!this.disposing && this.filter.hasPendingKeyboardPrefix()) {
329
- // 此延迟仅保留独立 Esc 的键盘语义,绝不用于恢复执行权限。
330
- this.prefixTimer = setTimeout(() => {
331
- this.prefixTimer = undefined;
332
- if (this.closed)
333
- return;
334
- const text = this.filter.flushKeyboardPrefix();
335
- if (text !== "")
336
- this.bridge.push(text);
337
- }, 20);
505
+ // 此延迟只保留独立 Esc 的键盘语义;刷新仍属于收到前缀时的输入边界。
506
+ const owner = this.inputOwner;
507
+ this.flushPrefix(owner, () => this.filter.flushKeyboardPrefix());
508
+ }
509
+ else if (!this.disposing && this.keyboard.hasStandaloneEscape()) {
510
+ this.flushPrefix(this.inputOwner, () => this.keyboard.flushEscape());
338
511
  }
339
512
  }
340
- catch {
341
- this.handleFailure();
513
+ catch (error) {
514
+ this.failInput(error);
342
515
  }
343
516
  };
344
517
  wrapOutput() {
@@ -349,10 +522,12 @@ export class InteractiveSession {
349
522
  if (property === "write") {
350
523
  return (chunk, ...args) => {
351
524
  const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;
352
- if (this.failure ||
525
+ // Ink 8 可在 session 清理后才卸载;粘贴租约始终归 session,异常时仍允许恢复光标。
526
+ if ((this.failure && text !== "\u001b[?25h") ||
353
527
  target.destroyed ||
354
528
  target.writableEnded ||
355
- (!this.closed && (text === ENABLE_PASTE || text === DISABLE_PASTE))) {
529
+ text === ENABLE_PASTE ||
530
+ text === DISABLE_PASTE) {
356
531
  const callback = args.find((arg) => typeof arg === "function");
357
532
  callback?.();
358
533
  return true;
@@ -388,17 +563,52 @@ export function createInteractiveSession(options) {
388
563
  }
389
564
  const restoreRaw = options.input.isRaw === true;
390
565
  let reader;
566
+ let pendingFd;
567
+ const readPendingInput = () => {
568
+ if (pendingFd === undefined)
569
+ return Buffer.alloc(0);
570
+ const chunks = [];
571
+ // 独立非阻塞描述符只在同步交接边界读取,不改变 fd 0 的 flags 或读取所有权。
572
+ // 限制单次排空大小,持续输入不能让同步退出无限循环;超限安全失败。
573
+ for (let count = 0; count < 64; count++) {
574
+ const chunk = Buffer.allocUnsafe(4096);
575
+ try {
576
+ const length = readSync(pendingFd, chunk, 0, chunk.length, null);
577
+ if (length === 0)
578
+ throw new InteractiveSessionError();
579
+ chunks.push(chunk.subarray(0, length));
580
+ }
581
+ catch (error) {
582
+ if (error.code === "EAGAIN")
583
+ return Buffer.concat(chunks);
584
+ throw error;
585
+ }
586
+ }
587
+ throw new InteractiveSessionError("交接期间输入过多,已取消执行。");
588
+ };
391
589
  let released = false;
392
590
  const releaseInput = () => {
393
591
  if (released)
394
592
  return;
395
593
  released = true;
396
594
  reader?.destroy();
595
+ if (pendingFd !== undefined) {
596
+ closeSync(pendingFd);
597
+ pendingFd = undefined;
598
+ }
397
599
  };
398
600
  try {
399
601
  // 标准 fd 0 保留给原 stdin 和子进程;该读者的生命周期只属于本会话。
602
+ if (process.platform === "linux") {
603
+ // Linux /proc/self/fd 指向当前实际 stdin;不使用可能属于其他终端的 /dev/tty。
604
+ pendingFd = openSync("/proc/self/fd/0", constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY);
605
+ }
400
606
  reader = new ReadStream(0);
401
- return new InteractiveSession(reader, options.output, { restoreRaw, releaseInput });
607
+ return new InteractiveSession(reader, options.output, {
608
+ restoreRaw,
609
+ releaseInput,
610
+ readPendingInput,
611
+ });
402
612
  }
403
613
  catch {
404
614
  releaseInput();
@@ -0,0 +1,102 @@
1
+ import { PASTE_START, PASTE_END, PasteFramingError } from "./paste-framing.js";
2
+ const ESCAPE = "\u001b";
3
+ // 使用 Ink 已支持的完整按键编码,避免独立 Esc 再次进入 Ink 的前缀缓存。
4
+ const ESCAPE_KEY = "\u001b[27u";
5
+ const MAX_KEY_SEQUENCE_LENGTH = 4096;
6
+ /** 只向 Ink 交付完整按键序列,未完成前缀不能跨页面取得新的输入归属。 */
7
+ export class KeyboardFramingFilter {
8
+ pending = "";
9
+ active = false;
10
+ valid = true;
11
+ setActive(active) {
12
+ this.active = active;
13
+ if (!active)
14
+ this.valid = false;
15
+ }
16
+ push(text) {
17
+ let output = "";
18
+ let index = 0;
19
+ while (index < text.length) {
20
+ // 上一层只交付完整粘贴。数据帧不能与待定 Esc 或 CSI 前缀合成按键。
21
+ if (text.startsWith(PASTE_START, index)) {
22
+ const end = text.indexOf(PASTE_END, index + PASTE_START.length);
23
+ if (end < 0)
24
+ throw new PasteFramingError("粘贴输入序列不完整,已取消本次交互。");
25
+ output += this.flushEscape();
26
+ this.pending = "";
27
+ if (this.active)
28
+ output += text.slice(index, end + PASTE_END.length);
29
+ index = end + PASTE_END.length;
30
+ continue;
31
+ }
32
+ const character = String.fromCodePoint(text.codePointAt(index));
33
+ index += character.length;
34
+ if (this.pending === "") {
35
+ if (character !== ESCAPE) {
36
+ if (this.active)
37
+ output += character;
38
+ continue;
39
+ }
40
+ this.valid = this.active;
41
+ }
42
+ this.pending += character;
43
+ if (this.pending.length > MAX_KEY_SEQUENCE_LENGTH)
44
+ throw new PasteFramingError("按键输入序列过长,已取消本次交互。");
45
+ if (!this.isComplete())
46
+ continue;
47
+ if (this.pending.startsWith(ESCAPE + ESCAPE) && !["[", "O"].includes(this.pending[2])) {
48
+ if (this.valid && this.active)
49
+ output += ESCAPE_KEY.repeat(2);
50
+ // 第三个码点重新分帧,尤其不能把第三个 Esc 原样交给 Ink 缓存。
51
+ this.pending = "";
52
+ index -= character.length;
53
+ continue;
54
+ }
55
+ if (this.valid && this.active)
56
+ output += this.pending;
57
+ this.pending = "";
58
+ }
59
+ return output;
60
+ }
61
+ isComplete() {
62
+ const prefix = this.pending[1] === ESCAPE ? 2 : 1;
63
+ if (this.pending.length <= prefix)
64
+ return false;
65
+ const kind = this.pending[prefix];
66
+ if (kind !== "[" && kind !== "O")
67
+ return true;
68
+ const payload = this.pending.slice(prefix + 1);
69
+ if (payload === "")
70
+ return false;
71
+ for (const [index, character] of [...payload].entries()) {
72
+ const code = character.codePointAt(0);
73
+ if (kind === "[" && ((code >= 0x20 && code <= 0x3f) || (index === 0 && character === "[")))
74
+ continue;
75
+ if (code >= 0x40 && code <= 0x7e)
76
+ return true;
77
+ throw new PasteFramingError("按键输入序列无效,已取消本次交互。");
78
+ }
79
+ return false;
80
+ }
81
+ hasStandaloneEscape() {
82
+ return this.pending === ESCAPE || this.pending === ESCAPE + ESCAPE;
83
+ }
84
+ hasUnfinishedSequence() {
85
+ return this.pending !== "" && !this.hasStandaloneEscape();
86
+ }
87
+ flushEscape() {
88
+ if (!this.hasStandaloneEscape())
89
+ return "";
90
+ const output = this.valid && this.active ? ESCAPE_KEY.repeat(this.pending.length) : "";
91
+ this.pending = "";
92
+ return output;
93
+ }
94
+ assertComplete() {
95
+ if (this.pending !== "")
96
+ throw new PasteFramingError("按键输入序列尚未结束,已取消本次交互。");
97
+ }
98
+ clear() {
99
+ this.pending = "";
100
+ this.active = false;
101
+ }
102
+ }