@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
@@ -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
+ }