@unscientificjszhai/howto 1.0.2 → 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 (51) hide show
  1. package/README.md +88 -29
  2. package/{README.CN.md → README.zh-hans-cn.md} +84 -25
  3. package/THIRD_PARTY_NOTICES.md +1 -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 +8 -0
  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 +10 -3
  23. package/dist/errors.js +4 -0
  24. package/dist/index.js +11 -4
  25. package/dist/init/ChatGptInitializationStep.js +223 -0
  26. package/dist/init/InitializationApp.js +71 -37
  27. package/dist/init/index.js +24 -5
  28. package/dist/init/state.js +14 -3
  29. package/dist/prompt.js +36 -6
  30. package/dist/shell/command-analysis.js +24 -4
  31. package/dist/ui/App.js +99 -10
  32. package/dist/ui/ConfirmView.js +6 -39
  33. package/dist/ui/InteractiveSessionProvider.js +7 -8
  34. package/dist/ui/ResolvePlaceholdersView.js +6 -1
  35. package/dist/ui/UsageApprovalView.js +320 -0
  36. package/dist/ui/interactive-session.js +180 -39
  37. package/dist/ui/keyboard-framing.js +102 -0
  38. package/dist/ui/paste-framing.js +69 -32
  39. package/dist/ui/resize-safe-output.js +2 -2
  40. package/dist/ui/run-interactive-command.js +2 -2
  41. package/dist/ui/text-input.js +4 -1
  42. package/dist/ui/use-keyboard-input.js +6 -1
  43. package/dist/ui/use-paste-aware-input.js +8 -3
  44. package/dist/usage/arguments.js +61 -0
  45. package/dist/usage/generate.js +156 -0
  46. package/dist/usage/output.js +216 -0
  47. package/dist/usage/risk.js +17 -0
  48. package/dist/usage/runner.js +238 -0
  49. package/dist/usage/types.js +1 -0
  50. package/dist/validation/usage-response.js +39 -0
  51. package/package.json +21 -19
@@ -0,0 +1,320 @@
1
+ import React, { useRef, useState, useLayoutEffect } from "react";
2
+ import { Box, Text } from "ink";
3
+ import stringWidth from "string-width";
4
+ import { formatLiteralArguments, formatUsageCommand, parseLiteralArguments, validateUsageLookupArguments, } from "../usage/arguments.js";
5
+ import { resolveUsageCommandDanger } from "../usage/risk.js";
6
+ import { renderTerminalSafeText } from "../terminal-text.js";
7
+ import { useInteractiveSession } from "./InteractiveSessionProvider.js";
8
+ import { usePasteAwareInput } from "./use-paste-aware-input.js";
9
+ import { deleteLastGrapheme, isTextInputEvent } from "./text-input.js";
10
+ import { toTailPreview } from "./single-line-preview.js";
11
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
12
+ export const UsageApprovalView = (props) => {
13
+ const session = useInteractiveSession();
14
+ const viewProps = {
15
+ ...props,
16
+ knownCredentials: [
17
+ ...(props.knownCredentials ?? []),
18
+ ...(props.request.knownCredentials ?? []),
19
+ ],
20
+ };
21
+ const [args, setArgs] = useState(props.request.lookup.args);
22
+ const [editing, setEditing] = useState(false);
23
+ const [revision, setRevision] = useState(0);
24
+ // 每个页面取得新的输入边界,上一页同批输入不能批准下一页。
25
+ useLayoutEffect(() => session.beginView(), [session, editing, revision]);
26
+ const danger = revision === 0
27
+ ? props.request.danger
28
+ : resolveUsageCommandDanger(props.request.commandName, props.request.executable, args, props.request.lookup);
29
+ const switchPage = (nextEditing) => {
30
+ session.suspendViewInput();
31
+ setEditing(nextEditing);
32
+ };
33
+ return editing ? (React.createElement(UsageArgumentsEditor, { ...viewProps, args: args, onSave: (nextArgs) => {
34
+ session.suspendViewInput();
35
+ setArgs(nextArgs);
36
+ setRevision((previous) => previous + 1);
37
+ setEditing(false);
38
+ }, onBack: () => switchPage(false) })) : (React.createElement(UsageReview, { ...viewProps, key: revision, request: { ...props.request, danger }, args: args, onEdit: () => switchPage(true) }));
39
+ };
40
+ function UsageReview({ request, args, availableRows, availableColumns, knownCredentials = [], onApprove, onReject, onCancel, onEdit, }) {
41
+ const session = useInteractiveSession();
42
+ const [scroll, setScroll] = useState(0);
43
+ const [confirmation, setConfirmation] = useState("");
44
+ const confirmationRef = useRef("");
45
+ const finished = useRef(false);
46
+ const columns = Math.max(1, availableColumns);
47
+ const bodyRows = Math.max(1, availableRows - (availableRows >= 2 ? 1 : 0));
48
+ const safe = (value) => safeUsageDisplay(value, knownCredentials ?? []);
49
+ const controls = request.danger
50
+ ? "输入 EXECUTE 后 Enter 批准;Tab 编辑;Esc 拒绝;↑↓ 查看;Ctrl+C 取消"
51
+ : "Enter 批准;Tab 编辑;Esc 拒绝;↑↓ 查看;Ctrl+C 取消";
52
+ const lines = [
53
+ "查询审批(↑↓ 查看全部内容)",
54
+ `程序: ${safe(request.commandName)}`,
55
+ `实际路径: ${safe(request.executable)}`,
56
+ `命令: ${safe(formatUsageCommand(request.executable, args))}`,
57
+ `目的: ${safe(request.lookup.purpose)}`,
58
+ `风险: ${request.danger ? safe(request.danger.reason) : "未发现已知风险"}`,
59
+ "批准同时授权将本次查询输出发送给当前 AI provider。",
60
+ controls,
61
+ ...(request.danger ? [`EXECUTE> ${confirmation}`] : []),
62
+ ].flatMap((line) => wrapUsageText(line, columns));
63
+ const maximumScroll = Math.max(0, lines.length - bodyRows);
64
+ const offset = scroll === "end" ? maximumScroll : Math.min(scroll, maximumScroll);
65
+ const inputReady = usePasteAwareInput({
66
+ onInput: (input, key) => {
67
+ if (finished.current || availableRows <= 0)
68
+ return;
69
+ if (key.ctrl && input === "c") {
70
+ finished.current = true;
71
+ onCancel();
72
+ }
73
+ else if (key.escape) {
74
+ finished.current = true;
75
+ onReject();
76
+ }
77
+ else if (key.tab) {
78
+ finished.current = true;
79
+ onEdit();
80
+ }
81
+ else if (key.upArrow || key.pageUp) {
82
+ setScroll((previous) => Math.max(0, (previous === "end" ? maximumScroll : Math.min(previous, maximumScroll)) -
83
+ (key.pageUp ? bodyRows : 1)));
84
+ }
85
+ else if (key.downArrow || key.pageDown) {
86
+ setScroll((previous) => Math.min(maximumScroll, (previous === "end" ? maximumScroll : previous) + (key.pageDown ? bodyRows : 1)));
87
+ }
88
+ else if (key.return) {
89
+ if (!request.danger || confirmationRef.current.toUpperCase() === "EXECUTE") {
90
+ finished.current = true;
91
+ onApprove(args);
92
+ }
93
+ }
94
+ else if (request.danger) {
95
+ if (key.backspace || key.delete) {
96
+ confirmationRef.current = deleteLastGrapheme(confirmationRef.current);
97
+ }
98
+ else if (isTextInputEvent(input, key)) {
99
+ confirmationRef.current += input;
100
+ }
101
+ setConfirmation(confirmationRef.current);
102
+ if (availableRows === 1)
103
+ setScroll("end");
104
+ }
105
+ },
106
+ onPaste: session.reportIgnoredPaste,
107
+ isPasteActive: availableRows > 0,
108
+ });
109
+ if (!inputReady || availableRows <= 0)
110
+ return null;
111
+ return (React.createElement(Box, { flexDirection: "column", height: Math.min(availableRows, lines.length + 1), overflowY: "hidden" },
112
+ lines.slice(offset, offset + bodyRows).map((line, index) => (React.createElement(Text, { key: index, color: request.danger ? "yellow" : undefined }, line))),
113
+ availableRows >= 2 && (React.createElement(Text, { wrap: "truncate-end" }, request.danger
114
+ ? `EXECUTE> ${toTailPreview(confirmation, Math.max(0, columns - 20))} Enter Tab Esc ↑↓`
115
+ : "Enter批准 Tab编辑 Esc拒绝 ↑↓"))));
116
+ }
117
+ function UsageArgumentsEditor({ request, args, availableRows, availableColumns, knownCredentials = [], onSave, onBack, onCancel, }) {
118
+ const session = useInteractiveSession();
119
+ const initial = formatLiteralArguments(args);
120
+ const [value, setValue] = useState(initial);
121
+ const [cursor, setCursor] = useState(initial.length);
122
+ const [error, setError] = useState("");
123
+ const [details, setDetails] = useState(false);
124
+ const detailsRef = useRef(false);
125
+ const [detailScroll, setDetailScroll] = useState(0);
126
+ const valueRef = useRef(value);
127
+ const cursorRef = useRef(cursor);
128
+ const finished = useRef(false);
129
+ useLayoutEffect(() => session.beginView(), [session, details]);
130
+ const columns = Math.max(1, availableColumns);
131
+ const safeProgram = safeUsageDisplay(request.executable, knownCredentials ?? []);
132
+ const detailRows = Math.max(1, availableRows - (availableRows >= 2 ? 1 : 0));
133
+ const detailLines = [
134
+ ...(error ? [error] : []),
135
+ `固定程序: ${safeUsageDisplay(request.commandName, knownCredentials ?? [])}`,
136
+ `实际路径: ${safeProgram}`,
137
+ "仅编辑参数;支持引号、←→、Home/End、字素级删除。",
138
+ "Enter 保存并重新审批;Esc 返回;Tab 查看详情;Ctrl+C 取消。",
139
+ ].flatMap((line) => wrapUsageText(line, columns));
140
+ const maximumDetailScroll = Math.max(0, detailLines.length - detailRows);
141
+ const showDetails = (visible) => {
142
+ if (visible !== detailsRef.current)
143
+ session.suspendViewInput();
144
+ detailsRef.current = visible;
145
+ setDetails(visible);
146
+ setDetailScroll(0);
147
+ };
148
+ const update = (nextValue, nextCursor) => {
149
+ // 插入的基字符可能与右侧已有组合符重新形成字素;光标不能停在新字素内部。
150
+ const containing = graphemes.segment(nextValue).containing(nextCursor);
151
+ if (containing !== undefined && containing.index < nextCursor) {
152
+ nextCursor = containing.index + containing.segment.length;
153
+ }
154
+ valueRef.current = nextValue;
155
+ cursorRef.current = nextCursor;
156
+ setValue(nextValue);
157
+ setCursor(nextCursor);
158
+ setError("");
159
+ showDetails(false);
160
+ };
161
+ const inputReady = usePasteAwareInput({
162
+ onInput: (input, key) => {
163
+ if (finished.current || availableRows <= 0)
164
+ return;
165
+ const current = valueRef.current;
166
+ const position = cursorRef.current;
167
+ if (key.ctrl && input === "c") {
168
+ finished.current = true;
169
+ onCancel();
170
+ }
171
+ else if (key.tab) {
172
+ showDetails(!detailsRef.current);
173
+ }
174
+ else if (detailsRef.current && (key.upArrow || key.pageUp)) {
175
+ setDetailScroll((previous) => Math.max(0, previous - (key.pageUp ? detailRows : 1)));
176
+ }
177
+ else if (detailsRef.current && (key.downArrow || key.pageDown)) {
178
+ setDetailScroll((previous) => Math.min(maximumDetailScroll, previous + (key.pageDown ? detailRows : 1)));
179
+ }
180
+ else if (detailsRef.current && (key.return || key.escape)) {
181
+ showDetails(false);
182
+ }
183
+ else if (detailsRef.current) {
184
+ return;
185
+ }
186
+ else if (key.escape) {
187
+ finished.current = true;
188
+ onBack();
189
+ }
190
+ else if (key.return) {
191
+ try {
192
+ const parsed = validateUsageLookupArguments({
193
+ ...request.lookup,
194
+ args: parseLiteralArguments(current),
195
+ });
196
+ finished.current = true;
197
+ onSave(parsed.args);
198
+ }
199
+ catch {
200
+ setError("参数无效:仅允许字面参数;请检查引号、shell 操作符和展开语法。");
201
+ if (availableRows <= 2)
202
+ showDetails(true);
203
+ }
204
+ }
205
+ else if (key.home || (key.ctrl && input === "a")) {
206
+ update(current, 0);
207
+ }
208
+ else if (key.end || (key.ctrl && input === "e")) {
209
+ update(current, current.length);
210
+ }
211
+ else if (key.ctrl && input === "u") {
212
+ update(current.slice(position), 0);
213
+ }
214
+ else if (key.leftArrow) {
215
+ update(current, previousGraphemeOffset(current, position));
216
+ }
217
+ else if (key.rightArrow) {
218
+ update(current, nextGraphemeOffset(current, position));
219
+ }
220
+ else if (key.backspace) {
221
+ const previous = previousGraphemeOffset(current, position);
222
+ update(current.slice(0, previous) + current.slice(position), previous);
223
+ }
224
+ else if (key.delete) {
225
+ update(current.slice(0, position) + current.slice(nextGraphemeOffset(current, position)), position);
226
+ }
227
+ else if (isTextInputEvent(input, key)) {
228
+ update(current.slice(0, position) + input + current.slice(position), position + input.length);
229
+ }
230
+ },
231
+ onPaste: (input) => {
232
+ if (finished.current || availableRows <= 0)
233
+ return;
234
+ if (detailsRef.current) {
235
+ session.reportIgnoredPaste();
236
+ return;
237
+ }
238
+ const position = cursorRef.current;
239
+ const current = valueRef.current;
240
+ update(current.slice(0, position) + input + current.slice(position), position + input.length);
241
+ },
242
+ isPasteActive: availableRows > 0,
243
+ });
244
+ if (!inputReady || availableRows <= 0)
245
+ return null;
246
+ if (details) {
247
+ const offset = Math.min(detailScroll, maximumDetailScroll);
248
+ return (React.createElement(Box, { flexDirection: "column", maxHeight: availableRows, overflowY: "hidden" },
249
+ detailLines.slice(offset, offset + detailRows).map((line, index) => (React.createElement(Text, { key: index, color: error ? "red" : undefined }, line))),
250
+ availableRows >= 2 && React.createElement(Text, { wrap: "truncate-end" }, "\u2191\u2193\u67E5\u770B Tab\u8FD4\u56DE\u7F16\u8F91")));
251
+ }
252
+ // 等长遮罩保留光标位置;在切片前完成脱敏,避免光标切开凭据后暴露部分内容。
253
+ const safeValue = usageDisplayCredentials(knownCredentials).reduce((text, credential) => text.split(credential).join("*".repeat(credential.length)), value);
254
+ const programPreview = clippedProgram(safeProgram, Math.max(1, Math.floor(columns / 3)));
255
+ const prefix = availableRows === 1 ? `${error ? "!" : ""}${programPreview}:` : "> ";
256
+ const inputColumns = Math.max(1, columns - stringWidth(prefix));
257
+ const before = toTailPreview(safeValue.slice(0, cursor), Math.max(0, inputColumns - 1));
258
+ const after = wrapUsageText(renderTerminalSafeText(safeValue.slice(cursor)), Math.max(1, inputColumns - stringWidth(before)))[0] ?? " ";
259
+ const cursorText = graphemes.segment(after)[Symbol.iterator]().next().value?.segment ?? " ";
260
+ const suffix = after.slice(cursorText.length);
261
+ return (React.createElement(Box, { flexDirection: "column", maxHeight: availableRows, overflowY: "hidden", overflowX: "hidden" },
262
+ availableRows >= 3 && (React.createElement(Text, { wrap: "truncate-end" },
263
+ "\u7F16\u8F91\u67E5\u8BE2\u53C2\u6570\uFF08\u7A0B\u5E8F\u56FA\u5B9A\uFF09: ",
264
+ safeProgram)),
265
+ availableRows === 2 && (React.createElement(Text, { wrap: "truncate-end" },
266
+ error ? "! " : "",
267
+ clippedProgram(safeProgram, Math.max(1, columns - 8)),
268
+ " Tab\u8BE6\u60C5")),
269
+ React.createElement(Box, { height: 1, overflowX: "hidden" },
270
+ React.createElement(Text, null,
271
+ prefix,
272
+ before,
273
+ React.createElement(Text, { inverse: true }, cursorText),
274
+ suffix)),
275
+ availableRows >= 3 && (React.createElement(Text, { color: error ? "red" : undefined, wrap: "truncate-end" }, error || "Enter保存并重新审批 Esc返回 ←→移动 Tab详情 Ctrl+C取消"))));
276
+ }
277
+ export function previousGraphemeOffset(value, offset) {
278
+ return graphemes.segment(value).containing(offset - 1)?.index ?? 0;
279
+ }
280
+ export function nextGraphemeOffset(value, offset) {
281
+ const next = graphemes.segment(value).containing(offset);
282
+ return next === undefined ? value.length : next.index + next.segment.length;
283
+ }
284
+ export function wrapUsageText(value, columns) {
285
+ const lines = [];
286
+ let line = "";
287
+ let width = 0;
288
+ for (const { segment } of graphemes.segment(value)) {
289
+ const size = stringWidth(segment);
290
+ if (line !== "" && width + size > Math.max(1, columns)) {
291
+ lines.push(line);
292
+ line = "";
293
+ width = 0;
294
+ }
295
+ line += segment;
296
+ width += size;
297
+ }
298
+ lines.push(line);
299
+ return lines;
300
+ }
301
+ function clippedProgram(value, columns) {
302
+ return stringWidth(value) <= columns
303
+ ? value
304
+ : `…${toTailPreview(value, Math.max(0, columns - 1))}`;
305
+ }
306
+ export function safeUsageDisplay(value, credentials) {
307
+ const redacted = usageDisplayCredentials(credentials).reduce((text, credential) => text.split(credential).join("[REDACTED]"), value);
308
+ return renderTerminalSafeText(redacted);
309
+ }
310
+ function usageDisplayCredentials(credentials) {
311
+ // shell 引用会展开单引号;同时匹配引用内部文本,覆盖嵌入参数的凭据。
312
+ return [
313
+ ...new Set(credentials
314
+ .filter((credential) => credential !== "")
315
+ .flatMap((credential) => {
316
+ const quoted = formatLiteralArguments([credential]);
317
+ return [credential, quoted.startsWith("'") ? quoted.slice(1, -1) : quoted];
318
+ })),
319
+ ].sort((left, right) => right.length - left.length);
320
+ }
@@ -2,11 +2,14 @@ import { closeSync, constants, openSync, readSync } from "node:fs";
2
2
  import { Readable } from "node:stream";
3
3
  import { StringDecoder } from "node:string_decoder";
4
4
  import { ReadStream } from "node:tty";
5
- import signalExit from "signal-exit";
5
+ import { onExit as signalExit } from "signal-exit";
6
6
  import { normalizePhysicalRows, toResizeSafeOutput } from "./resize-safe-output.js";
7
- import { PasteFramingFilter, PasteStartObserver } from "./paste-framing.js";
7
+ import { PasteFramingError, PasteFramingFilter } from "./paste-framing.js";
8
+ import { KeyboardFramingFilter } from "./keyboard-framing.js";
8
9
  export const ENABLE_PASTE = "\u001b[?2004h";
9
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;
10
13
  export class InteractiveSessionError extends Error {
11
14
  constructor(message = "交互终端输入不可用。") {
12
15
  super(message);
@@ -39,6 +42,29 @@ function assertAvailableInput(input, output) {
39
42
  class SessionInput extends Readable {
40
43
  isTTY = true;
41
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
+ }
42
68
  _read() { }
43
69
  setRawMode(enabled) {
44
70
  this.isRaw = enabled;
@@ -52,14 +78,26 @@ class SessionInput extends Readable {
52
78
  }
53
79
  }
54
80
  export class InteractiveSession {
55
- physicalInput;
56
- physicalOutput;
57
- resources;
58
81
  input;
59
82
  output;
60
- bridge = new SessionInput();
61
- observer = new PasteStartObserver();
62
- 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();
63
101
  decoder = new StringDecoder("utf8");
64
102
  policyListeners = new Set();
65
103
  failureListeners = new Set();
@@ -79,7 +117,13 @@ export class InteractiveSession {
79
117
  view;
80
118
  viewEnabled = false;
81
119
  prefixTimer;
120
+ pasteIdleTimer;
121
+ pasteDurationTimer;
122
+ unfinishedInputAtClose = false;
82
123
  removeExitHook;
124
+ physicalInput;
125
+ physicalOutput;
126
+ resources;
83
127
  constructor(physicalInput, physicalOutput, resources = {}) {
84
128
  this.physicalInput = physicalInput;
85
129
  this.physicalOutput = physicalOutput;
@@ -90,7 +134,8 @@ export class InteractiveSession {
90
134
  try {
91
135
  assertAvailableInput(physicalInput, physicalOutput);
92
136
  // Ink 先卸载界面,再由资源持有者同步恢复物理终端。
93
- this.removeExitHook = (resources.registerExit ?? signalExit)(() => {
137
+ const registerExit = resources.registerExit ?? signalExit;
138
+ this.removeExitHook = registerExit(() => {
94
139
  try {
95
140
  this.dispose();
96
141
  }
@@ -131,6 +176,17 @@ export class InteractiveSession {
131
176
  }
132
177
  }
133
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
+ };
134
190
  subscribeExecutionPolicy = (listener) => {
135
191
  this.policyListeners.add(listener);
136
192
  return () => {
@@ -146,6 +202,31 @@ export class InteractiveSession {
146
202
  this.failureListeners.delete(listener);
147
203
  };
148
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
+ }
149
230
  beginView() {
150
231
  this.throwIfFailed();
151
232
  if (this.closed)
@@ -163,6 +244,7 @@ export class InteractiveSession {
163
244
  };
164
245
  }
165
246
  suspendViewInput() {
247
+ this.inputOwner = {};
166
248
  this.viewEnabled = false;
167
249
  this.setInputActive(false);
168
250
  this.drain();
@@ -177,8 +259,11 @@ export class InteractiveSession {
177
259
  this.drain();
178
260
  this.observePendingInput();
179
261
  this.throwIfFailed();
262
+ this.assertCompleteInput();
180
263
  this.dispose();
181
264
  this.throwIfFailed();
265
+ if (this.unfinishedInputAtClose)
266
+ throw new InteractiveSessionError("粘贴或输入序列尚未结束,已取消本次交互。");
182
267
  // 本次检查后不经过 await,执行 action 必须同步到达实际 spawn。
183
268
  return this.getExecutionPolicy() === "print" ? actions.print() : actions.execute();
184
269
  }
@@ -201,7 +286,7 @@ export class InteractiveSession {
201
286
  this.viewEnabled = false;
202
287
  this.setInputActive(false);
203
288
  this.clearPrefixTimer();
204
- this.filter.clear();
289
+ this.clearPasteTimers();
205
290
  let cleanupFailed = false;
206
291
  const cleanup = (action) => {
207
292
  try {
@@ -227,6 +312,14 @@ export class InteractiveSession {
227
312
  });
228
313
  // 恢复终端时仍保留原始观察,最后再同步排空并撤下监听。
229
314
  this.drain();
315
+ try {
316
+ this.assertCompleteInput();
317
+ }
318
+ catch {
319
+ this.unfinishedInputAtClose = true;
320
+ }
321
+ this.filter.clear();
322
+ this.keyboard.clear();
230
323
  this.checkTerminalState();
231
324
  this.physicalInput.off("readable", this.drain);
232
325
  this.physicalInput.off("end", this.handleFailure);
@@ -259,6 +352,8 @@ export class InteractiveSession {
259
352
  this.bridge.destroy();
260
353
  this.policyListeners.clear();
261
354
  this.failureListeners.clear();
355
+ this.noticeListeners.clear();
356
+ this.pendingNotices.clear();
262
357
  if (cleanupFailed && !this.failure) {
263
358
  this.failure = new InteractiveSessionError("无法恢复交互终端状态。");
264
359
  }
@@ -310,11 +405,14 @@ export class InteractiveSession {
310
405
  };
311
406
  setInputActive(active) {
312
407
  if (active !== this.inputActive) {
408
+ if (!active)
409
+ this.inputOwner = {};
313
410
  // 隐藏边界不能把未完成的 UTF-8 字符带入下一个可见输入阶段。
314
411
  this.decoder = new StringDecoder("utf8");
315
412
  }
316
413
  this.inputActive = active;
317
414
  this.filter.setActive(active);
415
+ this.keyboard.setActive(active);
318
416
  }
319
417
  updateVisibility = () => {
320
418
  const active = this.viewEnabled && normalizePhysicalRows(this.physicalOutput.rows) > 1;
@@ -327,15 +425,69 @@ export class InteractiveSession {
327
425
  clearTimeout(this.prefixTimer);
328
426
  this.prefixTimer = undefined;
329
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
+ }
330
485
  observePendingInput() {
331
486
  if (!this.inputAcquired || this.failure || !this.resources.readPendingInput)
332
487
  return;
333
488
  const bytes = this.resources.readPendingInput();
334
- if (this.observer.observe(bytes) && this.policy !== "print") {
335
- this.policy = "print";
336
- for (const listener of this.policyListeners)
337
- listener();
338
- }
489
+ if (bytes.length > 0)
490
+ this.processInput(bytes);
339
491
  }
340
492
  drain = () => {
341
493
  if (this.closed || !this.inputAcquired)
@@ -347,32 +499,19 @@ export class InteractiveSession {
347
499
  if (typeof chunk !== "string" && !Buffer.isBuffer(chunk))
348
500
  throw new InteractiveSessionError();
349
501
  const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
350
- if (this.observer.observe(bytes) && this.policy !== "print") {
351
- this.policy = "print";
352
- for (const listener of this.policyListeners)
353
- listener();
354
- }
355
- if (normalizePhysicalRows(this.physicalOutput.rows) <= 1)
356
- this.setInputActive(false);
357
- const text = typeof chunk === "string" ? chunk : this.decoder.write(chunk);
358
- const filtered = this.filter.push(text);
359
- if (filtered !== "")
360
- this.bridge.push(filtered);
502
+ this.processInput(bytes);
361
503
  }
362
504
  if (!this.disposing && this.filter.hasPendingKeyboardPrefix()) {
363
- // 此延迟仅保留独立 Esc 的键盘语义,绝不用于恢复执行权限。
364
- this.prefixTimer = setTimeout(() => {
365
- this.prefixTimer = undefined;
366
- if (this.closed)
367
- return;
368
- const text = this.filter.flushKeyboardPrefix();
369
- if (text !== "")
370
- this.bridge.push(text);
371
- }, 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());
372
511
  }
373
512
  }
374
- catch {
375
- this.handleFailure();
513
+ catch (error) {
514
+ this.failInput(error);
376
515
  }
377
516
  };
378
517
  wrapOutput() {
@@ -383,10 +522,12 @@ export class InteractiveSession {
383
522
  if (property === "write") {
384
523
  return (chunk, ...args) => {
385
524
  const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;
386
- if (this.failure ||
525
+ // Ink 8 可在 session 清理后才卸载;粘贴租约始终归 session,异常时仍允许恢复光标。
526
+ if ((this.failure && text !== "\u001b[?25h") ||
387
527
  target.destroyed ||
388
528
  target.writableEnded ||
389
- (!this.closed && (text === ENABLE_PASTE || text === DISABLE_PASTE))) {
529
+ text === ENABLE_PASTE ||
530
+ text === DISABLE_PASTE) {
390
531
  const callback = args.find((arg) => typeof arg === "function");
391
532
  callback?.();
392
533
  return true;