@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.
- package/README.md +88 -29
- package/{README.CN.md → README.zh-hans-cn.md} +84 -25
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/dist/ai/chatgpt-models.js +148 -0
- package/dist/ai/chatgpt.js +495 -0
- package/dist/ai/command-schema.js +8 -0
- package/dist/ai/errors.js +6 -0
- package/dist/ai/gemini.js +117 -4
- package/dist/ai/index.js +4 -1
- package/dist/ai/openai.js +105 -2
- package/dist/ai/usage-session.js +144 -0
- package/dist/auth/chatgpt/commands.js +90 -0
- package/dist/auth/chatgpt/errors.js +85 -0
- package/dist/auth/chatgpt/http.js +97 -0
- package/dist/auth/chatgpt/index.js +229 -0
- package/dist/auth/chatgpt/instructions.js +22 -0
- package/dist/auth/chatgpt/oauth.js +320 -0
- package/dist/auth/chatgpt/storage.js +366 -0
- package/dist/auth/chatgpt/types.js +1 -0
- package/dist/cli.js +77 -16
- package/dist/config-file.js +2 -0
- package/dist/config.js +10 -3
- package/dist/errors.js +4 -0
- package/dist/index.js +11 -4
- package/dist/init/ChatGptInitializationStep.js +223 -0
- package/dist/init/InitializationApp.js +71 -37
- package/dist/init/index.js +24 -5
- package/dist/init/state.js +14 -3
- package/dist/prompt.js +36 -6
- package/dist/shell/command-analysis.js +24 -4
- package/dist/ui/App.js +99 -10
- package/dist/ui/ConfirmView.js +6 -39
- package/dist/ui/InteractiveSessionProvider.js +7 -8
- package/dist/ui/ResolvePlaceholdersView.js +6 -1
- package/dist/ui/UsageApprovalView.js +320 -0
- package/dist/ui/interactive-session.js +180 -39
- package/dist/ui/keyboard-framing.js +102 -0
- package/dist/ui/paste-framing.js +69 -32
- package/dist/ui/resize-safe-output.js +2 -2
- package/dist/ui/run-interactive-command.js +2 -2
- package/dist/ui/text-input.js +4 -1
- package/dist/ui/use-keyboard-input.js +6 -1
- package/dist/ui/use-paste-aware-input.js +8 -3
- package/dist/usage/arguments.js +61 -0
- package/dist/usage/generate.js +156 -0
- package/dist/usage/output.js +216 -0
- package/dist/usage/risk.js +17 -0
- package/dist/usage/runner.js +238 -0
- package/dist/usage/types.js +1 -0
- package/dist/validation/usage-response.js +39 -0
- package/package.json +21 -19
|
@@ -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
|
+
}
|
package/dist/ui/paste-framing.js
CHANGED
|
@@ -1,85 +1,108 @@
|
|
|
1
1
|
import { hasUnsafeTerminalControlCharacters } from "../terminal-text.js";
|
|
2
2
|
export const PASTE_START = "\u001b[200~";
|
|
3
3
|
export const PASTE_END = "\u001b[201~";
|
|
4
|
-
/**
|
|
5
|
-
export
|
|
6
|
-
|
|
7
|
-
observe(chunk) {
|
|
8
|
-
const combined = Buffer.concat([this.suffix, chunk]);
|
|
9
|
-
const found = combined.includes(Buffer.from(PASTE_START));
|
|
10
|
-
this.suffix = Buffer.from(combined.subarray(Math.max(0, combined.length - 5)));
|
|
11
|
-
return found;
|
|
12
|
-
}
|
|
4
|
+
/** 包括被丢弃的内容在内都受此上限约束,避免未闭合粘贴无限积累。 */
|
|
5
|
+
export const MAX_PASTE_BYTES = 256 * 1024;
|
|
6
|
+
export class PasteFramingError extends Error {
|
|
13
7
|
}
|
|
14
8
|
/** 只交付完整的可见粘贴;按解码后的字符检查 C1,避免误拒绝 UTF-8 延续字节。 */
|
|
15
9
|
export class PasteFramingFilter {
|
|
16
10
|
active = false;
|
|
17
11
|
pending = "";
|
|
18
12
|
flushedPrefix = 0;
|
|
19
|
-
|
|
13
|
+
// 失效前缀仍参与标记匹配,并带失效状态交给下层闭合按键序列。
|
|
14
|
+
invalidPrefixLength = 0;
|
|
20
15
|
collecting = false;
|
|
21
16
|
discardPaste = false;
|
|
22
17
|
paste = "";
|
|
18
|
+
pasteBytes = 0;
|
|
19
|
+
onDiscard;
|
|
20
|
+
onBoundary;
|
|
21
|
+
frameInput;
|
|
22
|
+
constructor(onDiscard = () => { }, onBoundary = () => { }, frameInput = (text, active) => (active ? text : "")) {
|
|
23
|
+
this.onDiscard = onDiscard;
|
|
24
|
+
this.onBoundary = onBoundary;
|
|
25
|
+
this.frameInput = frameInput;
|
|
26
|
+
}
|
|
27
|
+
discard(reason) {
|
|
28
|
+
if (!this.discardPaste)
|
|
29
|
+
this.onDiscard(reason);
|
|
30
|
+
this.discardPaste = true;
|
|
31
|
+
this.paste = "";
|
|
32
|
+
}
|
|
23
33
|
setActive(active) {
|
|
24
34
|
this.active = active;
|
|
25
35
|
if (!active) {
|
|
26
|
-
this.
|
|
36
|
+
this.invalidPrefixLength = this.pending.length;
|
|
27
37
|
if (this.collecting) {
|
|
28
|
-
this.
|
|
29
|
-
this.paste = "";
|
|
38
|
+
this.discard("boundary");
|
|
30
39
|
}
|
|
31
40
|
}
|
|
32
41
|
}
|
|
33
42
|
push(text) {
|
|
34
43
|
let output = "";
|
|
35
44
|
for (const character of text) {
|
|
36
|
-
if (this.pending === "" && !this.collecting)
|
|
37
|
-
this.invalidPrefix = !this.active;
|
|
38
45
|
this.pending += character;
|
|
39
46
|
if (!this.active)
|
|
40
|
-
this.
|
|
47
|
+
this.invalidPrefixLength = this.pending.length;
|
|
41
48
|
if (this.collecting) {
|
|
42
49
|
while (this.pending !== "" && !PASTE_END.startsWith(this.pending)) {
|
|
50
|
+
const character = String.fromCodePoint(this.pending.codePointAt(0));
|
|
51
|
+
this.pasteBytes += Buffer.byteLength(character);
|
|
52
|
+
if (this.pasteBytes > MAX_PASTE_BYTES) {
|
|
53
|
+
throw new PasteFramingError("粘贴内容超过 256 KiB,已取消本次交互。");
|
|
54
|
+
}
|
|
55
|
+
if (hasUnsafeTerminalControlCharacters(character))
|
|
56
|
+
this.discard("control");
|
|
43
57
|
if (!this.discardPaste)
|
|
44
|
-
this.paste +=
|
|
45
|
-
this.pending = this.pending.slice(
|
|
58
|
+
this.paste += character;
|
|
59
|
+
this.pending = this.pending.slice(character.length);
|
|
46
60
|
}
|
|
47
61
|
if (this.pending === PASTE_END) {
|
|
62
|
+
this.onBoundary();
|
|
48
63
|
if (this.active &&
|
|
49
64
|
!this.discardPaste &&
|
|
50
65
|
!hasUnsafeTerminalControlCharacters(this.paste)) {
|
|
51
|
-
output += PASTE_START + this.paste + PASTE_END;
|
|
66
|
+
output += this.frameInput(PASTE_START + this.paste + PASTE_END, true);
|
|
52
67
|
}
|
|
53
68
|
this.collecting = false;
|
|
54
69
|
this.paste = "";
|
|
70
|
+
this.pasteBytes = 0;
|
|
55
71
|
this.pending = "";
|
|
56
|
-
this.
|
|
72
|
+
this.invalidPrefixLength = 0;
|
|
57
73
|
}
|
|
58
74
|
continue;
|
|
59
75
|
}
|
|
60
76
|
while (this.pending !== "" &&
|
|
61
77
|
!PASTE_START.startsWith(this.pending) &&
|
|
62
78
|
!PASTE_END.startsWith(this.pending)) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
79
|
+
const character = String.fromCodePoint(this.pending.codePointAt(0));
|
|
80
|
+
if (this.flushedPrefix > 0) {
|
|
81
|
+
this.flushedPrefix = Math.max(0, this.flushedPrefix - character.length);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
output += this.frameInput(character, this.active && this.invalidPrefixLength === 0);
|
|
85
|
+
}
|
|
86
|
+
this.invalidPrefixLength = Math.max(0, this.invalidPrefixLength - character.length);
|
|
87
|
+
this.pending = this.pending.slice(character.length);
|
|
70
88
|
}
|
|
71
89
|
if (this.pending === PASTE_START) {
|
|
90
|
+
this.onBoundary();
|
|
72
91
|
this.collecting = true;
|
|
73
|
-
this.discardPaste =
|
|
92
|
+
this.discardPaste = false;
|
|
93
|
+
if (!this.active || this.invalidPrefixLength > 0 || this.flushedPrefix > 0)
|
|
94
|
+
this.discard("boundary");
|
|
74
95
|
this.pending = "";
|
|
75
96
|
this.flushedPrefix = 0;
|
|
97
|
+
this.invalidPrefixLength = 0;
|
|
76
98
|
this.paste = "";
|
|
99
|
+
this.pasteBytes = 0;
|
|
77
100
|
}
|
|
78
101
|
else if (this.pending === PASTE_END) {
|
|
79
102
|
// 孤立的协议结束标记不作为表单文字交付。
|
|
80
103
|
this.pending = "";
|
|
81
104
|
this.flushedPrefix = 0;
|
|
82
|
-
this.
|
|
105
|
+
this.invalidPrefixLength = 0;
|
|
83
106
|
}
|
|
84
107
|
}
|
|
85
108
|
return output;
|
|
@@ -87,18 +110,32 @@ export class PasteFramingFilter {
|
|
|
87
110
|
hasPendingKeyboardPrefix() {
|
|
88
111
|
return !this.collecting && this.pending.length > this.flushedPrefix;
|
|
89
112
|
}
|
|
113
|
+
hasUnfinishedPaste() {
|
|
114
|
+
return (this.collecting ||
|
|
115
|
+
(this.pending.length > 1 &&
|
|
116
|
+
(PASTE_START.startsWith(this.pending) || PASTE_END.startsWith(this.pending))));
|
|
117
|
+
}
|
|
118
|
+
assertComplete() {
|
|
119
|
+
if (this.hasUnfinishedPaste() ||
|
|
120
|
+
(this.pending.length > this.flushedPrefix && PASTE_START.startsWith(this.pending))) {
|
|
121
|
+
throw new PasteFramingError("粘贴或输入序列尚未结束,已取消本次交互。");
|
|
122
|
+
}
|
|
123
|
+
}
|
|
90
124
|
flushKeyboardPrefix() {
|
|
91
|
-
|
|
125
|
+
// CSI 前缀继续由会话保管,不能提前交给 Ink 后在新页面拼成按键。
|
|
126
|
+
if (this.collecting || this.pending.length > 1)
|
|
92
127
|
return "";
|
|
93
|
-
const result = this.
|
|
94
|
-
//
|
|
128
|
+
const result = this.frameInput(this.pending.slice(this.flushedPrefix), this.active && this.invalidPrefixLength === 0);
|
|
129
|
+
// 刷新只影响键盘体验,仍保留完整标记匹配状态及跨边界丢弃语义。
|
|
95
130
|
this.flushedPrefix = this.pending.length;
|
|
96
131
|
return result;
|
|
97
132
|
}
|
|
98
133
|
clear() {
|
|
99
134
|
this.pending = "";
|
|
100
135
|
this.paste = "";
|
|
136
|
+
this.pasteBytes = 0;
|
|
101
137
|
this.flushedPrefix = 0;
|
|
138
|
+
this.invalidPrefixLength = 0;
|
|
102
139
|
this.collecting = false;
|
|
103
140
|
this.active = false;
|
|
104
141
|
}
|
|
@@ -68,6 +68,6 @@ export function normalizePhysicalRows(value) {
|
|
|
68
68
|
}
|
|
69
69
|
return Math.max(0, Math.floor(value));
|
|
70
70
|
}
|
|
71
|
-
function readPhysicalRows(output) {
|
|
72
|
-
return normalizePhysicalRows(output.rows);
|
|
71
|
+
export function readPhysicalRows(output) {
|
|
72
|
+
return normalizePhysicalRows("rows" in output ? output.rows : undefined);
|
|
73
73
|
}
|
|
@@ -4,14 +4,14 @@ import { executeCommand } from "../execute.js";
|
|
|
4
4
|
import { App } from "./App.js";
|
|
5
5
|
import { InteractiveSessionProvider } from "./InteractiveSessionProvider.js";
|
|
6
6
|
export const MANUAL_EXECUTION_NOTICE = "本次会话包含粘贴,howto 不会自动执行命令。请检查输出内容后手动运行。";
|
|
7
|
-
export async function runInteractiveCommand({ session, provider, request, execute = executeCommand, print = (command) => {
|
|
7
|
+
export async function runInteractiveCommand({ session, provider, request, knownCredentials, execute = executeCommand, print = (command) => {
|
|
8
8
|
console.error(MANUAL_EXECUTION_NOTICE);
|
|
9
9
|
console.log(command);
|
|
10
10
|
}, }) {
|
|
11
11
|
let finalCommand;
|
|
12
12
|
let appError;
|
|
13
13
|
const instance = render(React.createElement(InteractiveSessionProvider, { session: session },
|
|
14
|
-
React.createElement(App, { provider: provider, request: request, onSuccess: (command) => {
|
|
14
|
+
React.createElement(App, { provider: provider, request: request, knownCredentials: knownCredentials, onSuccess: (command) => {
|
|
15
15
|
finalCommand = command;
|
|
16
16
|
session.suspendViewInput();
|
|
17
17
|
instance.clear();
|
package/dist/ui/text-input.js
CHANGED
|
@@ -2,12 +2,15 @@
|
|
|
2
2
|
import { hasUnsafeTerminalControlCharacters } from "../terminal-text.js";
|
|
3
3
|
const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
4
4
|
// eslint-disable-next-line no-control-regex -- 显式识别传统终端协议的按键控制字节。
|
|
5
|
-
const LEGACY_CONTROL_PATTERN = /([\r\n\t\u0003\u0008\u001b\u007f])/;
|
|
5
|
+
const LEGACY_CONTROL_PATTERN = /([\r\n\t\u0001\u0003\u0005\u0008\u0015\u001b\u007f])/;
|
|
6
6
|
const LEGACY_CONTROL_KEYS = new Map([
|
|
7
7
|
["\r", { input: "", key: { return: true } }],
|
|
8
8
|
["\n", { input: "", key: { return: true } }],
|
|
9
9
|
["\t", { input: "", key: { tab: true } }],
|
|
10
10
|
["\u0003", { input: "c", key: { ctrl: true } }],
|
|
11
|
+
["\u0001", { input: "a", key: { ctrl: true } }],
|
|
12
|
+
["\u0005", { input: "e", key: { ctrl: true } }],
|
|
13
|
+
["\u0015", { input: "u", key: { ctrl: true } }],
|
|
11
14
|
["\u0008", { input: "", key: { backspace: true } }],
|
|
12
15
|
["\u007f", { input: "", key: { backspace: true } }],
|
|
13
16
|
["\u001b", { input: "", key: { escape: true } }],
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { useEffect, useState } from "react";
|
|
2
2
|
import { useInput, useStdin } from "ink";
|
|
3
3
|
import { splitKeyboardInput } from "./text-input.js";
|
|
4
|
+
import { useOptionalInteractiveSession } from "./InteractiveSessionProvider.js";
|
|
4
5
|
export function useKeyboardInput(onInput, options) {
|
|
5
6
|
const { isRawModeSupported } = useStdin();
|
|
7
|
+
const session = useOptionalInteractiveSession();
|
|
6
8
|
// renderToString 没有真实输入订阅,应保留同步静态渲染。
|
|
7
9
|
const [ready, setReady] = useState(!isRawModeSupported);
|
|
8
10
|
useInput((input, key) => {
|
|
@@ -12,8 +14,11 @@ export function useKeyboardInput(onInput, options) {
|
|
|
12
14
|
if (key.eventType === "release")
|
|
13
15
|
return;
|
|
14
16
|
// 同步交付给本次视图的回调,不能把剩余按键排队到下一页。
|
|
15
|
-
for (const event of splitKeyboardInput(input, key))
|
|
17
|
+
for (const event of splitKeyboardInput(input, key)) {
|
|
18
|
+
if (session && !session.isInputCurrent())
|
|
19
|
+
break;
|
|
16
20
|
onInput(event.input, event.key);
|
|
21
|
+
}
|
|
17
22
|
}, options);
|
|
18
23
|
// Ink 在被动 effect 中注册输入。先完成订阅,再允许调用方显示可交互帧;
|
|
19
24
|
// 否则立即写出的新页面可能先于它自己的按键监听器接受用户输入。
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import { usePaste } from "ink";
|
|
2
2
|
import { useKeyboardInput } from "./use-keyboard-input.js";
|
|
3
|
+
import { useOptionalInteractiveSession } from "./InteractiveSessionProvider.js";
|
|
3
4
|
export function usePasteAwareInput({ onInput, onPaste, isInputActive = true, isPasteActive = true, }) {
|
|
4
|
-
|
|
5
|
+
const session = useOptionalInteractiveSession();
|
|
6
|
+
// 粘贴只交给接收时的逻辑页面或字段,不因 React 切页重新绑定接收者。
|
|
5
7
|
const ready = useKeyboardInput(onInput, { isActive: isInputActive });
|
|
6
8
|
usePaste((input) => {
|
|
7
|
-
if (ready)
|
|
8
|
-
|
|
9
|
+
if (!ready || (session && !session.isInputCurrent())) {
|
|
10
|
+
session?.reportStalePaste();
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
onPaste(input);
|
|
9
14
|
}, { isActive: isPasteActive });
|
|
10
15
|
return ready;
|
|
11
16
|
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { parseLiteralArguments as parseShellLiteralArguments } from "../shell/command-analysis.js";
|
|
2
|
+
import { hasUnsafeTerminalControlCharacters } from "../terminal-text.js";
|
|
3
|
+
const INVALID_ARGUMENTS_MESSAGE = "Invalid usage lookup arguments";
|
|
4
|
+
const ARGUMENT_KEYS = new Set(["args", "purpose", "dangerous", "dangerReason"]);
|
|
5
|
+
export function validateUsageLookupArguments(value) {
|
|
6
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
7
|
+
throw new Error(INVALID_ARGUMENTS_MESSAGE);
|
|
8
|
+
}
|
|
9
|
+
const record = value;
|
|
10
|
+
if (Object.keys(record).some((key) => !ARGUMENT_KEYS.has(key)) ||
|
|
11
|
+
!isSafeString(record.purpose) ||
|
|
12
|
+
record.purpose.trim() === "" ||
|
|
13
|
+
typeof record.dangerous !== "boolean" ||
|
|
14
|
+
!isSafeString(record.dangerReason) ||
|
|
15
|
+
(record.dangerous ? record.dangerReason.trim() === "" : record.dangerReason !== "")) {
|
|
16
|
+
throw new Error(INVALID_ARGUMENTS_MESSAGE);
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
args: validateUsageArgumentList(record.args),
|
|
20
|
+
purpose: record.purpose,
|
|
21
|
+
dangerous: record.dangerous,
|
|
22
|
+
dangerReason: record.dangerReason,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function validateUsageArgumentList(value) {
|
|
26
|
+
if (!Array.isArray(value)) {
|
|
27
|
+
throw new Error(INVALID_ARGUMENTS_MESSAGE);
|
|
28
|
+
}
|
|
29
|
+
const args = [];
|
|
30
|
+
for (const argument of value) {
|
|
31
|
+
if (!isSafeString(argument))
|
|
32
|
+
throw new Error(INVALID_ARGUMENTS_MESSAGE);
|
|
33
|
+
args.push(argument);
|
|
34
|
+
}
|
|
35
|
+
return args;
|
|
36
|
+
}
|
|
37
|
+
export function parseLiteralArguments(text) {
|
|
38
|
+
return validateUsageArgumentList(parseShellLiteralArguments(text));
|
|
39
|
+
}
|
|
40
|
+
export function formatLiteralArguments(args) {
|
|
41
|
+
return args.map(quoteLiteralArgument).join(" ");
|
|
42
|
+
}
|
|
43
|
+
export function formatUsageCommand(executable, args) {
|
|
44
|
+
return formatLiteralArguments([executable, ...args]);
|
|
45
|
+
}
|
|
46
|
+
function quoteLiteralArgument(value) {
|
|
47
|
+
if (/^[A-Za-z0-9_./:@%+,-]+$/.test(value))
|
|
48
|
+
return value;
|
|
49
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
50
|
+
}
|
|
51
|
+
function isSafeString(value) {
|
|
52
|
+
if (typeof value !== "string" || hasUnsafeTerminalControlCharacters(value))
|
|
53
|
+
return false;
|
|
54
|
+
// Node 会把未配对代理项编码为替代字符;拒绝它们才能保证回传 argv 与实际执行一致。
|
|
55
|
+
for (const character of value) {
|
|
56
|
+
const codePoint = character.codePointAt(0);
|
|
57
|
+
if (codePoint >= 0xd800 && codePoint <= 0xdfff)
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { UsageToolsUnsupportedError } from "../ai/errors.js";
|
|
2
|
+
import { createUsageGenerationRequest } from "../prompt.js";
|
|
3
|
+
import { InteractionCancelledError } from "../ui/tty.js";
|
|
4
|
+
import { AiResponseValidationError } from "../validation/ai-response.js";
|
|
5
|
+
import { validateUseCommandCandidates } from "../validation/command-tool.js";
|
|
6
|
+
import { generateValidatedCommandCandidates } from "../validation/generated-commands.js";
|
|
7
|
+
import { parseAndValidateUsageResponse, UsageGenerationFailureError, } from "../validation/usage-response.js";
|
|
8
|
+
import { validateUsageLookupArguments } from "./arguments.js";
|
|
9
|
+
import { resolveUsageCommandDanger } from "./risk.js";
|
|
10
|
+
import { sanitizeUsageLookupResult } from "./output.js";
|
|
11
|
+
import { createUsageLookupResult, executeUsageLookup, resolveUsageExecutable } from "./runner.js";
|
|
12
|
+
export const MAX_USAGE_LOOKUPS = 6;
|
|
13
|
+
export const USAGE_CAPABILITY_FALLBACK_NOTICE = "当前服务不支持此次原生用法查询;本次请求将保留已有信息,继续生成命令或说明无法生成的原因。";
|
|
14
|
+
export async function generateWithUsageLookup(provider, request, interaction, signal, dependencies = {}) {
|
|
15
|
+
if (request.useCommand === undefined || provider.createUsageSession === undefined) {
|
|
16
|
+
return generateValidatedCommandCandidates(provider, request, signal);
|
|
17
|
+
}
|
|
18
|
+
const session = provider.createUsageSession(createUsageGenerationRequest(request));
|
|
19
|
+
const commandName = request.useCommand;
|
|
20
|
+
// 本次请求只解析一次;审批期间 PATH 或符号链接变化不会替换已展示的程序路径。
|
|
21
|
+
const executable = (dependencies.resolveExecutable ?? resolveUsageExecutable)(request.useCommand);
|
|
22
|
+
const execute = dependencies.executeLookup ?? executeUsageLookup;
|
|
23
|
+
const cache = new Map();
|
|
24
|
+
let handled = 0;
|
|
25
|
+
let degraded = false;
|
|
26
|
+
let replies = [];
|
|
27
|
+
const credentials = () => [
|
|
28
|
+
...(interaction.knownCredentials ?? []),
|
|
29
|
+
...(session.getKnownCredentials?.() ?? []),
|
|
30
|
+
];
|
|
31
|
+
for (;;) {
|
|
32
|
+
checkCancelled(signal);
|
|
33
|
+
const toolsEnabled = !degraded && handled < MAX_USAGE_LOOKUPS && interaction.getExecutionPolicy() === "execute";
|
|
34
|
+
let turn;
|
|
35
|
+
try {
|
|
36
|
+
turn = await session.next(replies, { toolsEnabled }, signal);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
checkCancelled(signal);
|
|
40
|
+
if (toolsEnabled && !degraded && error instanceof UsageToolsUnsupportedError) {
|
|
41
|
+
degraded = true;
|
|
42
|
+
interaction.onCapabilityFallback?.(USAGE_CAPABILITY_FALLBACK_NOTICE);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
checkCancelled(signal);
|
|
48
|
+
if (turn.kind === "final") {
|
|
49
|
+
try {
|
|
50
|
+
const response = parseAndValidateUsageResponse(turn.rawText);
|
|
51
|
+
validateUseCommandCandidates(response, request.useCommand);
|
|
52
|
+
return response.commands;
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error instanceof UsageGenerationFailureError) {
|
|
56
|
+
// 明确失败也可能复述工具输出中的已知凭据,显示前统一脱敏。
|
|
57
|
+
const safe = sanitizeUsageLookupResult({ ...createUsageLookupResult(null, "success"), stdout: error.message }, credentials());
|
|
58
|
+
throw new UsageGenerationFailureError(safe.stdout);
|
|
59
|
+
}
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!toolsEnabled) {
|
|
64
|
+
throw new UsageGenerationFailureError("查询已关闭,AI 未能提供可靠的最终命令。");
|
|
65
|
+
}
|
|
66
|
+
if (turn.calls.length === 0) {
|
|
67
|
+
throw new AiResponseValidationError("usage tool response must contain at least one call");
|
|
68
|
+
}
|
|
69
|
+
replies = [];
|
|
70
|
+
for (const call of turn.calls) {
|
|
71
|
+
checkCancelled(signal);
|
|
72
|
+
const result = handled >= MAX_USAGE_LOOKUPS
|
|
73
|
+
? createUsageLookupResult(call.arguments, "budget_exhausted")
|
|
74
|
+
: await handleCall(call);
|
|
75
|
+
replies.push({ callId: call.id, result: sanitizeUsageLookupResult(result, credentials()) });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async function handleCall(call) {
|
|
79
|
+
handled++;
|
|
80
|
+
let lookup;
|
|
81
|
+
try {
|
|
82
|
+
if (call.name !== "lookup_command_usage")
|
|
83
|
+
throw new Error("invalid tool");
|
|
84
|
+
lookup = validateUsageLookupArguments(call.arguments);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return createUsageLookupResult(call.arguments, "invalid_arguments");
|
|
88
|
+
}
|
|
89
|
+
const key = JSON.stringify(lookup.args);
|
|
90
|
+
const cached = cache.get(key);
|
|
91
|
+
if (cached !== undefined)
|
|
92
|
+
return { ...cached, requested: call.arguments };
|
|
93
|
+
const remember = (result) => {
|
|
94
|
+
cache.set(key, result);
|
|
95
|
+
return result;
|
|
96
|
+
};
|
|
97
|
+
if (interaction.getExecutionPolicy() !== "execute") {
|
|
98
|
+
return remember(createUsageLookupResult(call.arguments, "permission_revoked"));
|
|
99
|
+
}
|
|
100
|
+
if (executable === null) {
|
|
101
|
+
return remember(createUsageLookupResult(call.arguments, "not_found"));
|
|
102
|
+
}
|
|
103
|
+
const decision = await interaction.approve({
|
|
104
|
+
commandName,
|
|
105
|
+
executable,
|
|
106
|
+
lookup,
|
|
107
|
+
danger: resolveUsageCommandDanger(commandName, executable, lookup.args, lookup),
|
|
108
|
+
knownCredentials: credentials(),
|
|
109
|
+
}, signal);
|
|
110
|
+
checkCancelled(signal);
|
|
111
|
+
if (interaction.getExecutionPolicy() !== "execute") {
|
|
112
|
+
return remember(createUsageLookupResult(call.arguments, "permission_revoked"));
|
|
113
|
+
}
|
|
114
|
+
if (decision.kind === "reject") {
|
|
115
|
+
return remember(createUsageLookupResult(call.arguments, "rejected"));
|
|
116
|
+
}
|
|
117
|
+
// 即使 UI 有漏洞或宿主回调被替换,非法编辑仍不能进入执行器。
|
|
118
|
+
let edited;
|
|
119
|
+
try {
|
|
120
|
+
edited = validateUsageLookupArguments({ ...lookup, args: decision.args });
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return remember(createUsageLookupResult(call.arguments, "invalid_arguments"));
|
|
124
|
+
}
|
|
125
|
+
interaction.onQueryRunning?.({
|
|
126
|
+
executable,
|
|
127
|
+
args: edited.args,
|
|
128
|
+
knownCredentials: credentials(),
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
const result = await execute({
|
|
132
|
+
requested: call.arguments,
|
|
133
|
+
executable,
|
|
134
|
+
argv0: commandName,
|
|
135
|
+
args: edited.args,
|
|
136
|
+
signal,
|
|
137
|
+
getExecutionPolicy: () => interaction.getExecutionPolicy(),
|
|
138
|
+
checkExecutionPolicy: () => interaction.checkExecutionPolicy?.() ?? interaction.getExecutionPolicy(),
|
|
139
|
+
subscribeExecutionPolicy: (listener) => interaction.subscribeExecutionPolicy(listener),
|
|
140
|
+
knownCredentials: credentials(),
|
|
141
|
+
});
|
|
142
|
+
checkCancelled(signal);
|
|
143
|
+
remember(result);
|
|
144
|
+
if (result.actualCommand !== null)
|
|
145
|
+
cache.set(JSON.stringify(edited.args), result);
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
interaction.onQueryRunning?.(null);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function checkCancelled(signal) {
|
|
154
|
+
if (signal.aborted)
|
|
155
|
+
throw new InteractionCancelledError();
|
|
156
|
+
}
|