@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.
- package/README.md +127 -31
- package/README.zh-hans-cn.md +331 -0
- package/THIRD_PARTY_NOTICES.md +2 -0
- package/dist/ai/chatgpt-models.js +148 -0
- package/dist/ai/chatgpt.js +495 -0
- package/dist/ai/command-schema.js +15 -1
- 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 +11 -4
- package/dist/errors.js +6 -1
- package/dist/execute.js +4 -13
- package/dist/index.js +32 -12
- package/dist/init/ChatGptInitializationStep.js +223 -0
- package/dist/init/InitializationApp.js +74 -38
- package/dist/init/index.js +24 -5
- package/dist/init/state.js +14 -3
- package/dist/prompt.js +56 -10
- package/dist/safety/command-risk.js +11 -0
- package/dist/safety/dangerous-command.js +209 -0
- package/dist/shell/command-analysis.js +25 -5
- package/dist/shell/execution-environment.js +25 -0
- package/dist/shell/runtime-environment.js +61 -0
- package/dist/ui/App.js +104 -15
- package/dist/ui/ConfirmView.js +8 -41
- package/dist/ui/InteractiveSessionProvider.js +7 -8
- package/dist/ui/ResolvePlaceholdersView.js +8 -3
- package/dist/ui/SelectCommandView.js +2 -2
- package/dist/ui/UsageApprovalView.js +320 -0
- package/dist/ui/interactive-session.js +243 -33
- 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 +17 -2
- package/dist/ui/use-paste-aware-input.js +12 -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/ai-response.js +24 -3
- package/dist/validation/command-tool.js +7 -6
- package/dist/validation/usage-response.js +39 -0
- package/package.json +31 -17
- package/README.CN.md +0 -235
package/dist/index.js
CHANGED
|
@@ -10,37 +10,47 @@ import { checkCommandInPath } from "./validation/command-tool.js";
|
|
|
10
10
|
import { generateValidatedCommandCandidates } from "./validation/generated-commands.js";
|
|
11
11
|
import { ensureInteractiveTty } from "./ui/tty.js";
|
|
12
12
|
import { toAppError } from "./errors.js";
|
|
13
|
-
import { createInteractiveSession } from "./ui/interactive-session.js";
|
|
14
|
-
import { runInteractiveCommand } from "./ui/run-interactive-command.js";
|
|
15
|
-
import { initializeConfig } from "./init/index.js";
|
|
16
13
|
import { renderTerminalSafeText } from "./terminal-text.js";
|
|
17
14
|
import { readPackageVersion } from "./version.js";
|
|
15
|
+
import { assertSupportedPlatform, resolveExecutionShell } from "./shell/execution-environment.js";
|
|
18
16
|
async function run(argv) {
|
|
19
17
|
let session;
|
|
20
|
-
const getSession = () => {
|
|
18
|
+
const getSession = async () => {
|
|
21
19
|
ensureInteractiveTty(process.stdin, process.stdout);
|
|
20
|
+
const { createInteractiveSession } = await import("./ui/interactive-session.js");
|
|
22
21
|
session ??= createInteractiveSession({ input: process.stdin, output: process.stdout });
|
|
23
22
|
return session;
|
|
24
23
|
};
|
|
25
24
|
try {
|
|
25
|
+
assertSupportedPlatform();
|
|
26
26
|
const parsedCli = parseCliArgs(argv);
|
|
27
27
|
if (parsedCli.options.version) {
|
|
28
28
|
console.log(readPackageVersion());
|
|
29
29
|
return { exitCode: 0 };
|
|
30
30
|
}
|
|
31
|
+
if (parsedCli.options.chatgptAction !== undefined) {
|
|
32
|
+
const { runChatGptAction } = await import("./auth/chatgpt/commands.js");
|
|
33
|
+
await runChatGptAction(parsedCli.options);
|
|
34
|
+
return { exitCode: 0 };
|
|
35
|
+
}
|
|
31
36
|
if (parsedCli.options.init) {
|
|
32
37
|
ensureInteractiveTty(process.stdin, process.stdout);
|
|
38
|
+
const { initializeConfig } = await import("./init/index.js");
|
|
33
39
|
await initializeConfig({
|
|
34
40
|
cliOptions: parsedCli.options,
|
|
35
41
|
env: process.env,
|
|
36
|
-
session: getSession(),
|
|
42
|
+
session: await getSession(),
|
|
43
|
+
chatgptService: (await import("./auth/chatgpt/commands.js")).chatGptInitializationService,
|
|
37
44
|
});
|
|
38
45
|
return { exitCode: 0 };
|
|
39
46
|
}
|
|
40
|
-
const fileConfig = await readUserConfigFile();
|
|
41
47
|
if (parsedCli.question === undefined) {
|
|
42
48
|
throw new CliParseError("missing question");
|
|
43
49
|
}
|
|
50
|
+
if (!parsedCli.options.print) {
|
|
51
|
+
resolveExecutionShell();
|
|
52
|
+
}
|
|
53
|
+
const fileConfig = await readUserConfigFile();
|
|
44
54
|
if (!hasExplicitAiProvider(parsedCli.options, process.env, fileConfig)) {
|
|
45
55
|
if (parsedCli.options.print) {
|
|
46
56
|
throw new ConfigError("AI provider is not configured. --print cannot run initialization; run howto --init or set --ai-provider, HOWTO_AI_PROVIDER, or ~/.howto/config.json.");
|
|
@@ -49,10 +59,11 @@ async function run(argv) {
|
|
|
49
59
|
}
|
|
50
60
|
const config = hasExplicitAiProvider(parsedCli.options, process.env, fileConfig)
|
|
51
61
|
? loadConfig(parsedCli.options, process.env, fileConfig)
|
|
52
|
-
: await initializeConfig({
|
|
62
|
+
: await (await import("./init/index.js")).initializeConfig({
|
|
53
63
|
cliOptions: parsedCli.options,
|
|
54
64
|
env: process.env,
|
|
55
|
-
session: getSession(),
|
|
65
|
+
session: await getSession(),
|
|
66
|
+
chatgptService: (await import("./auth/chatgpt/commands.js")).chatGptInitializationService,
|
|
56
67
|
});
|
|
57
68
|
const useCommandPathCheck = parsedCli.useCommand === undefined
|
|
58
69
|
? undefined
|
|
@@ -62,7 +73,6 @@ async function run(argv) {
|
|
|
62
73
|
}
|
|
63
74
|
const promptRequest = createProviderPromptRequest({
|
|
64
75
|
question: parsedCli.question,
|
|
65
|
-
arguments: parsedCli.arguments,
|
|
66
76
|
useCommand: parsedCli.useCommand,
|
|
67
77
|
structuredOutput: config.structuredOutput,
|
|
68
78
|
});
|
|
@@ -82,10 +92,12 @@ async function run(argv) {
|
|
|
82
92
|
if (useCommandPathCheck !== undefined && !useCommandPathCheck.found) {
|
|
83
93
|
console.error(`Warning: requested command "${renderTerminalSafeText(useCommandPathCheck.command)}" was not found in PATH. Review before executing any generated command.`);
|
|
84
94
|
}
|
|
95
|
+
const { runInteractiveCommand } = await import("./ui/run-interactive-command.js");
|
|
85
96
|
const exitCode = await runInteractiveCommand({
|
|
86
|
-
session: getSession(),
|
|
97
|
+
session: await getSession(),
|
|
87
98
|
provider,
|
|
88
99
|
request: { ...promptRequest, systemPrompt, userPrompt },
|
|
100
|
+
knownCredentials: [config.openai.apiKey, config.gemini.apiKey].filter((value) => typeof value === "string" && value !== ""),
|
|
89
101
|
});
|
|
90
102
|
return { exitCode };
|
|
91
103
|
}
|
|
@@ -111,16 +123,24 @@ function resolveEntrypointPath(path) {
|
|
|
111
123
|
const isMain = process.argv[1] !== undefined &&
|
|
112
124
|
fileURLToPath(import.meta.url) === resolveEntrypointPath(process.argv[1]);
|
|
113
125
|
if (isMain) {
|
|
126
|
+
let outputFailed = false;
|
|
127
|
+
process.stdout.on("error", () => {
|
|
128
|
+
if (!outputFailed) {
|
|
129
|
+
outputFailed = true;
|
|
130
|
+
console.error("Error: failed to write standard output.");
|
|
131
|
+
}
|
|
132
|
+
process.exitCode = 1;
|
|
133
|
+
});
|
|
114
134
|
run(process.argv.slice(2))
|
|
115
135
|
.then((result) => {
|
|
116
|
-
process.exitCode = result.exitCode;
|
|
136
|
+
process.exitCode = outputFailed ? 1 : result.exitCode;
|
|
117
137
|
})
|
|
118
138
|
.catch((error) => {
|
|
119
139
|
const appError = toAppError(error);
|
|
120
140
|
if (appError.message !== "") {
|
|
121
141
|
console.error(appError.message);
|
|
122
142
|
}
|
|
123
|
-
process.exitCode = appError.exitCode;
|
|
143
|
+
process.exitCode = outputFailed ? 1 : appError.exitCode;
|
|
124
144
|
});
|
|
125
145
|
}
|
|
126
146
|
export { run };
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import React, { useEffect, useRef, useState, useLayoutEffect } from "react";
|
|
2
|
+
import { Box, Text, useStdout } from "ink";
|
|
3
|
+
import { getUserVisibleErrorMessage } from "../errors.js";
|
|
4
|
+
import { formatChatGptAuthorizationInstructions } from "../auth/chatgpt/instructions.js";
|
|
5
|
+
import { toSingleLinePreview } from "../ui/single-line-preview.js";
|
|
6
|
+
import { isTextInputEvent } from "../ui/text-input.js";
|
|
7
|
+
import { usePasteAwareInput } from "../ui/use-paste-aware-input.js";
|
|
8
|
+
import { useInteractiveSession } from "../ui/InteractiveSessionProvider.js";
|
|
9
|
+
export const ChatGptInitializationStep = ({ service, loginOptions, frameRows, onComplete, onBack, onCancel, }) => {
|
|
10
|
+
const session = useInteractiveSession();
|
|
11
|
+
const { write: writeStdout } = useStdout();
|
|
12
|
+
const writeStdoutRef = useRef(writeStdout);
|
|
13
|
+
writeStdoutRef.current = writeStdout;
|
|
14
|
+
const [state, setState] = useState({
|
|
15
|
+
step: "loading",
|
|
16
|
+
message: "Loading ChatGPT accounts...",
|
|
17
|
+
});
|
|
18
|
+
const stateRef = useRef(state);
|
|
19
|
+
const operationRef = useRef(undefined);
|
|
20
|
+
const finishedRef = useRef(false);
|
|
21
|
+
useLayoutEffect(() => session.beginView(), [session, state.step]);
|
|
22
|
+
const updateState = (next) => {
|
|
23
|
+
if (next.step !== stateRef.current.step)
|
|
24
|
+
session.suspendViewInput();
|
|
25
|
+
stateRef.current = next;
|
|
26
|
+
setState(next);
|
|
27
|
+
};
|
|
28
|
+
const startOperation = (run) => {
|
|
29
|
+
operationRef.current?.abort();
|
|
30
|
+
const controller = new AbortController();
|
|
31
|
+
operationRef.current = controller;
|
|
32
|
+
void run(controller.signal).catch((error) => {
|
|
33
|
+
if (controller.signal.aborted || finishedRef.current)
|
|
34
|
+
return;
|
|
35
|
+
updateState({
|
|
36
|
+
step: "error",
|
|
37
|
+
message: error instanceof Error
|
|
38
|
+
? getUserVisibleErrorMessage(error)
|
|
39
|
+
: "ChatGPT setup failed. Please retry.",
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
const loadAccounts = () => {
|
|
44
|
+
updateState({ step: "loading", message: "Loading ChatGPT accounts..." });
|
|
45
|
+
startOperation(async (signal) => {
|
|
46
|
+
if (service === undefined)
|
|
47
|
+
throw new Error("ChatGPT sign-in is unavailable.");
|
|
48
|
+
const accounts = await service.listAccounts({ signal });
|
|
49
|
+
if (signal.aborted || finishedRef.current)
|
|
50
|
+
return;
|
|
51
|
+
updateState({ step: "accounts", accounts, selectedIndex: 0 });
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
finishedRef.current = false;
|
|
56
|
+
loadAccounts();
|
|
57
|
+
return () => {
|
|
58
|
+
finishedRef.current = true;
|
|
59
|
+
operationRef.current?.abort();
|
|
60
|
+
};
|
|
61
|
+
// 一次挂载对应一次初始化,返回 provider 页后重新挂载才重新读取账号。
|
|
62
|
+
}, []);
|
|
63
|
+
const loadModels = async (account, signal) => {
|
|
64
|
+
if (service === undefined)
|
|
65
|
+
throw new Error("ChatGPT sign-in is unavailable.");
|
|
66
|
+
if (!account.signedIn || !account.planUsageEnabled) {
|
|
67
|
+
throw new Error("ChatGPT plan usage is not enabled. Sign in again and allow plan usage.");
|
|
68
|
+
}
|
|
69
|
+
updateState({ step: "loading", message: "Loading ChatGPT models..." });
|
|
70
|
+
const models = await service.listModels({ accountId: account.id, signal });
|
|
71
|
+
if (signal.aborted || finishedRef.current)
|
|
72
|
+
return;
|
|
73
|
+
if (models.length === 0)
|
|
74
|
+
throw new Error("No ChatGPT models are available for this account.");
|
|
75
|
+
updateState({ step: "models", account, models, selectedIndex: 0 });
|
|
76
|
+
};
|
|
77
|
+
const selectAccount = (account) => {
|
|
78
|
+
session.suspendViewInput();
|
|
79
|
+
startOperation(async (signal) => {
|
|
80
|
+
if (service === undefined)
|
|
81
|
+
throw new Error("ChatGPT sign-in is unavailable.");
|
|
82
|
+
if (account?.signedIn && account.planUsageEnabled) {
|
|
83
|
+
await loadModels(account, signal);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
updateState({
|
|
87
|
+
step: "loading",
|
|
88
|
+
message: "Complete ChatGPT sign-in in your browser...",
|
|
89
|
+
});
|
|
90
|
+
const publishedUrls = new Set();
|
|
91
|
+
const signedInAccount = await service.login({
|
|
92
|
+
...loginOptions,
|
|
93
|
+
accountId: account?.id,
|
|
94
|
+
signal,
|
|
95
|
+
onAuthorizationUrl: (url) => {
|
|
96
|
+
if (signal.aborted || finishedRef.current)
|
|
97
|
+
return;
|
|
98
|
+
// 再授权 URL 可能携带 ID token;即便适配层误传也不渲染这类地址。
|
|
99
|
+
let authorizationUrl;
|
|
100
|
+
try {
|
|
101
|
+
const parsed = new URL(url);
|
|
102
|
+
if (parsed.searchParams.has("id_token_hint"))
|
|
103
|
+
return;
|
|
104
|
+
parsed.searchParams.delete("login_hint");
|
|
105
|
+
authorizationUrl = parsed.toString();
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
// 通过 Ink 的外部输出入口写完整链接,保留在滚动历史中,不受帧高度或缩放裁剪。
|
|
111
|
+
if (!publishedUrls.has(authorizationUrl)) {
|
|
112
|
+
publishedUrls.add(authorizationUrl);
|
|
113
|
+
writeStdoutRef.current(`${formatChatGptAuthorizationInstructions(authorizationUrl)}\n`);
|
|
114
|
+
}
|
|
115
|
+
updateState({
|
|
116
|
+
step: "loading",
|
|
117
|
+
message: "Open the sign-in URL above in your browser...",
|
|
118
|
+
});
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
if (signal.aborted || finishedRef.current)
|
|
122
|
+
return;
|
|
123
|
+
await loadModels(signedInAccount, signal);
|
|
124
|
+
});
|
|
125
|
+
};
|
|
126
|
+
const finish = (callback) => {
|
|
127
|
+
if (finishedRef.current)
|
|
128
|
+
return;
|
|
129
|
+
finishedRef.current = true;
|
|
130
|
+
session.suspendViewInput();
|
|
131
|
+
operationRef.current?.abort();
|
|
132
|
+
callback();
|
|
133
|
+
};
|
|
134
|
+
const ready = usePasteAwareInput({
|
|
135
|
+
onInput: (input, key) => {
|
|
136
|
+
if (finishedRef.current || key.eventType === "release" || frameRows === 0)
|
|
137
|
+
return;
|
|
138
|
+
if (key.ctrl && input === "c") {
|
|
139
|
+
finish(onCancel);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (key.escape) {
|
|
143
|
+
finish(onBack);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const current = stateRef.current;
|
|
147
|
+
if (current.step === "loading")
|
|
148
|
+
return;
|
|
149
|
+
if (current.step === "error") {
|
|
150
|
+
if (key.return)
|
|
151
|
+
loadAccounts();
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const count = current.step === "accounts" ? current.accounts.length + 1 : current.models.length;
|
|
155
|
+
if (key.upArrow || key.downArrow) {
|
|
156
|
+
updateState({
|
|
157
|
+
...current,
|
|
158
|
+
selectedIndex: (current.selectedIndex + (key.upArrow ? -1 : 1) + count) % count,
|
|
159
|
+
});
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
let selectedIndex = current.selectedIndex;
|
|
163
|
+
if (isTextInputEvent(input, key) && /^[1-9]$/.test(input)) {
|
|
164
|
+
selectedIndex = Number(input) - 1;
|
|
165
|
+
if (selectedIndex >= count)
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
else if (!key.return) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (current.step === "accounts") {
|
|
172
|
+
selectAccount(current.accounts[selectedIndex]);
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
finish(() => onComplete({
|
|
176
|
+
provider: "chatgpt",
|
|
177
|
+
account: current.account.id,
|
|
178
|
+
model: current.models[selectedIndex].slug,
|
|
179
|
+
}));
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
onPaste: session.reportIgnoredPaste,
|
|
183
|
+
isPasteActive: frameRows > 0,
|
|
184
|
+
});
|
|
185
|
+
if (!ready || frameRows === 0)
|
|
186
|
+
return null;
|
|
187
|
+
const choices = state.step === "accounts"
|
|
188
|
+
? [
|
|
189
|
+
...state.accounts.map((account) => `${account.label}${account.signedIn && account.planUsageEnabled ? "" : " (sign in)"}`),
|
|
190
|
+
"Continue with ChatGPT",
|
|
191
|
+
]
|
|
192
|
+
: state.step === "models"
|
|
193
|
+
? state.models.map((model) => model.displayName || model.slug)
|
|
194
|
+
: [];
|
|
195
|
+
const selectedIndex = state.step === "accounts" || state.step === "models" ? state.selectedIndex : 0;
|
|
196
|
+
const selectedLine = choices[selectedIndex];
|
|
197
|
+
const status = state.step === "loading" || state.step === "error" ? state.message : `> ${selectedLine}`;
|
|
198
|
+
if (frameRows === 1) {
|
|
199
|
+
return (React.createElement(Box, { height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
|
|
200
|
+
React.createElement(Box, { flexGrow: 1, flexShrink: 1, minWidth: 1, overflowX: "hidden" },
|
|
201
|
+
React.createElement(Text, null, toSingleLinePreview(status))),
|
|
202
|
+
React.createElement(Box, { flexShrink: 0 },
|
|
203
|
+
React.createElement(Text, { dimColor: true }, " Ent Esc ^C"))));
|
|
204
|
+
}
|
|
205
|
+
const help = state.step === "loading" ? "Esc back ^C cancel" : "UD Ent Esc back ^C";
|
|
206
|
+
const title = state.step === "accounts"
|
|
207
|
+
? "? ChatGPT account"
|
|
208
|
+
: state.step === "models"
|
|
209
|
+
? "? ChatGPT model"
|
|
210
|
+
: state.step === "error"
|
|
211
|
+
? "ChatGPT setup failed"
|
|
212
|
+
: "ChatGPT sign-in";
|
|
213
|
+
const availableChoices = Math.max(1, frameRows - 2);
|
|
214
|
+
const firstChoice = Math.min(selectedIndex, Math.max(0, choices.length - availableChoices));
|
|
215
|
+
return (React.createElement(Box, { flexDirection: "column", maxHeight: frameRows, overflowX: "hidden", overflowY: "hidden" },
|
|
216
|
+
frameRows >= 3 && (React.createElement(SetupLine, { color: state.step === "error" ? "red" : "green" }, title)),
|
|
217
|
+
choices.length > 0 ? (choices
|
|
218
|
+
.slice(firstChoice, firstChoice + availableChoices)
|
|
219
|
+
.map((choice, index) => (React.createElement(SetupLine, { key: firstChoice + index }, `${firstChoice + index === selectedIndex ? ">" : " "} ${toSingleLinePreview(choice)}`)))) : (React.createElement(SetupLine, null, toSingleLinePreview(status))),
|
|
220
|
+
React.createElement(SetupLine, null, state.step === "error" ? "Ent retry Esc back ^C" : help)));
|
|
221
|
+
};
|
|
222
|
+
const SetupLine = ({ children, color, }) => (React.createElement(Box, { height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
|
|
223
|
+
React.createElement(Text, { color: color }, children)));
|
|
@@ -1,13 +1,19 @@
|
|
|
1
|
-
import React, { useRef, useState } from "react";
|
|
1
|
+
import React, { useRef, useState, useLayoutEffect } from "react";
|
|
2
2
|
import { Box, Text } from "ink";
|
|
3
3
|
import { getUserVisibleErrorMessage } from "../errors.js";
|
|
4
4
|
import { usePhysicalStdoutRows } from "../ui/resize-safe-output.js";
|
|
5
5
|
import { toSingleLinePreview } from "../ui/single-line-preview.js";
|
|
6
6
|
import { useInteractiveSession } from "../ui/InteractiveSessionProvider.js";
|
|
7
7
|
import { usePasteAwareInput } from "../ui/use-paste-aware-input.js";
|
|
8
|
+
import { ChatGptInitializationStep } from "./ChatGptInitializationStep.js";
|
|
8
9
|
import { applyInitializationInput, createInitialInitializationState, getProviderOptions, } from "./state.js";
|
|
9
10
|
const RICH_LAYOUT_MIN_ROWS = 15;
|
|
10
|
-
|
|
11
|
+
const PROVIDER_LABELS = {
|
|
12
|
+
openai: "OpenAI API",
|
|
13
|
+
gemini: "Gemini API",
|
|
14
|
+
chatgpt: "Sign in with ChatGPT",
|
|
15
|
+
};
|
|
16
|
+
export const InitializationApp = ({ onSubmit, onComplete, onCancel, onError, chatgptService, chatgptLoginOptions, }) => {
|
|
11
17
|
const session = useInteractiveSession();
|
|
12
18
|
const rows = usePhysicalStdoutRows();
|
|
13
19
|
const [state, setState] = useState(createInitialInitializationState);
|
|
@@ -16,6 +22,32 @@ export const InitializationApp = ({ onSubmit, onComplete, onCancel, onError }) =
|
|
|
16
22
|
const submitStatusRef = useRef(submitStatus);
|
|
17
23
|
const [errorMessage, setErrorMessage] = useState("");
|
|
18
24
|
const frameRows = Math.max(0, rows - 1);
|
|
25
|
+
const inputField = state.step === "input" ? `${state.provider}:${state.fieldIndex}` : state.step;
|
|
26
|
+
useLayoutEffect(() => session.beginView(), [session, inputField]);
|
|
27
|
+
const cancel = () => {
|
|
28
|
+
session.suspendViewInput();
|
|
29
|
+
submitStatusRef.current = "cancelled";
|
|
30
|
+
setSubmitStatus("cancelled");
|
|
31
|
+
onCancel();
|
|
32
|
+
};
|
|
33
|
+
const submit = (values) => {
|
|
34
|
+
if (submitStatusRef.current !== "editing")
|
|
35
|
+
return;
|
|
36
|
+
session.suspendViewInput();
|
|
37
|
+
submitStatusRef.current = "saving";
|
|
38
|
+
setSubmitStatus("saving");
|
|
39
|
+
onSubmit(values)
|
|
40
|
+
.then((config) => {
|
|
41
|
+
onComplete(config);
|
|
42
|
+
})
|
|
43
|
+
.catch((error) => {
|
|
44
|
+
const appError = normalizeError(error);
|
|
45
|
+
setErrorMessage(getUserVisibleErrorMessage(appError));
|
|
46
|
+
submitStatusRef.current = "error";
|
|
47
|
+
setSubmitStatus("error");
|
|
48
|
+
onError(appError);
|
|
49
|
+
});
|
|
50
|
+
};
|
|
19
51
|
const handleInput = (event) => {
|
|
20
52
|
if (frameRows === 0) {
|
|
21
53
|
return;
|
|
@@ -23,42 +55,35 @@ export const InitializationApp = ({ onSubmit, onComplete, onCancel, onError }) =
|
|
|
23
55
|
if (submitStatusRef.current !== "editing") {
|
|
24
56
|
return;
|
|
25
57
|
}
|
|
26
|
-
const
|
|
58
|
+
const previous = stateRef.current;
|
|
59
|
+
const update = applyInitializationInput(previous, event);
|
|
60
|
+
if (update.state.step !== previous.step ||
|
|
61
|
+
(update.state.step === "input" &&
|
|
62
|
+
previous.step === "input" &&
|
|
63
|
+
(update.state.fieldIndex !== previous.fieldIndex ||
|
|
64
|
+
update.state.provider !== previous.provider)))
|
|
65
|
+
session.suspendViewInput();
|
|
66
|
+
if (event.type === "paste" && previous.step !== "input")
|
|
67
|
+
session.reportIgnoredPaste();
|
|
27
68
|
stateRef.current = update.state;
|
|
28
69
|
setState(update.state);
|
|
29
70
|
if (update.cancelled) {
|
|
30
|
-
|
|
31
|
-
submitStatusRef.current = "cancelled";
|
|
32
|
-
setSubmitStatus("cancelled");
|
|
33
|
-
onCancel();
|
|
71
|
+
cancel();
|
|
34
72
|
return;
|
|
35
73
|
}
|
|
36
74
|
if (update.completedValues !== undefined) {
|
|
37
|
-
|
|
38
|
-
submitStatusRef.current = "saving";
|
|
39
|
-
setSubmitStatus("saving");
|
|
40
|
-
onSubmit(update.completedValues)
|
|
41
|
-
.then((config) => {
|
|
42
|
-
onComplete(config);
|
|
43
|
-
})
|
|
44
|
-
.catch((error) => {
|
|
45
|
-
const appError = normalizeError(error);
|
|
46
|
-
setErrorMessage(getUserVisibleErrorMessage(appError));
|
|
47
|
-
submitStatusRef.current = "error";
|
|
48
|
-
setSubmitStatus("error");
|
|
49
|
-
onError(appError);
|
|
50
|
-
});
|
|
75
|
+
submit(update.completedValues);
|
|
51
76
|
}
|
|
52
77
|
};
|
|
53
|
-
usePasteAwareInput({
|
|
78
|
+
const inputReady = usePasteAwareInput({
|
|
54
79
|
onInput: (input, key) => {
|
|
55
80
|
handleInput({ type: "keyboard", input, key });
|
|
56
81
|
},
|
|
57
82
|
onPaste: (input) => {
|
|
58
83
|
handleInput({ type: "paste", input });
|
|
59
84
|
},
|
|
60
|
-
isInputActive: frameRows === 0 || submitStatus === "editing",
|
|
61
|
-
isPasteActive: frameRows > 0 && submitStatus === "editing",
|
|
85
|
+
isInputActive: state.step !== "chatgpt" && (frameRows === 0 || submitStatus === "editing"),
|
|
86
|
+
isPasteActive: state.step !== "chatgpt" && frameRows > 0 && submitStatus === "editing",
|
|
62
87
|
});
|
|
63
88
|
let content;
|
|
64
89
|
if (submitStatus === "saving") {
|
|
@@ -73,9 +98,18 @@ export const InitializationApp = ({ onSubmit, onComplete, onCancel, onError }) =
|
|
|
73
98
|
else if (state.step === "provider") {
|
|
74
99
|
content = React.createElement(ProviderStep, { selectedIndex: state.selectedIndex, frameRows: frameRows });
|
|
75
100
|
}
|
|
101
|
+
else if (state.step === "chatgpt") {
|
|
102
|
+
content = (React.createElement(ChatGptInitializationStep, { service: chatgptService, loginOptions: chatgptLoginOptions, frameRows: frameRows, onComplete: submit, onBack: () => {
|
|
103
|
+
const nextState = createInitialInitializationState();
|
|
104
|
+
stateRef.current = nextState;
|
|
105
|
+
setState(nextState);
|
|
106
|
+
}, onCancel: cancel }));
|
|
107
|
+
}
|
|
76
108
|
else {
|
|
77
109
|
content = React.createElement(InputStep, { state: state, frameRows: frameRows });
|
|
78
110
|
}
|
|
111
|
+
if (!inputReady)
|
|
112
|
+
return null;
|
|
79
113
|
return (React.createElement(Box, { display: frameRows > 0 ? "flex" : "none", flexDirection: "column", maxHeight: frameRows, overflowX: "hidden", overflowY: "hidden" }, content));
|
|
80
114
|
};
|
|
81
115
|
const ClippedLine = ({ children, color, dimColor = false, prefix, prefixWidth }) => (React.createElement(Box, { width: "100%", height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" }, prefix === undefined ? (React.createElement(Text, { color: color, dimColor: dimColor }, children)) : (React.createElement(React.Fragment, null,
|
|
@@ -86,45 +120,47 @@ const ClippedLine = ({ children, color, dimColor = false, prefix, prefixWidth })
|
|
|
86
120
|
const ProviderStep = ({ selectedIndex, frameRows, }) => {
|
|
87
121
|
const providers = getProviderOptions();
|
|
88
122
|
const selectedProvider = selectedIndex === null ? undefined : providers[selectedIndex];
|
|
89
|
-
const providerSelectionLine =
|
|
90
|
-
? ">
|
|
91
|
-
|
|
92
|
-
? "1 openai > gemini"
|
|
93
|
-
: "1 openai 2 gemini";
|
|
123
|
+
const providerSelectionLine = ["OAI", "G", "ChatGPT"]
|
|
124
|
+
.map((name, index) => `${selectedIndex === index ? ">" : index + 1} ${name}`)
|
|
125
|
+
.join(" ");
|
|
94
126
|
if (frameRows < RICH_LAYOUT_MIN_ROWS) {
|
|
95
127
|
if (frameRows === 1) {
|
|
96
|
-
const compactSelection = selectedProvider === "openai"
|
|
128
|
+
const compactSelection = selectedProvider === "openai"
|
|
129
|
+
? "O"
|
|
130
|
+
: selectedProvider === "gemini"
|
|
131
|
+
? "G"
|
|
132
|
+
: selectedProvider === "chatgpt"
|
|
133
|
+
? "C"
|
|
134
|
+
: "-";
|
|
97
135
|
return (React.createElement(Box, { height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
|
|
98
|
-
React.createElement(Text, null, `O/G:${compactSelection}
|
|
136
|
+
React.createElement(Text, null, `O/G/C:${compactSelection} 123 Ent Esc`)));
|
|
99
137
|
}
|
|
100
138
|
if (frameRows <= 3) {
|
|
101
139
|
return (React.createElement(Box, { flexDirection: "column", height: frameRows, maxHeight: frameRows, overflowX: "hidden", overflowY: "hidden" },
|
|
102
140
|
frameRows === 3 && React.createElement(Text, { color: "green" }, "? Choose provider"),
|
|
103
141
|
React.createElement(ClippedLine, null, providerSelectionLine),
|
|
104
|
-
React.createElement(Text, { dimColor: true }, "UD
|
|
142
|
+
React.createElement(Text, { dimColor: true }, "UD Ent 1/2/3 Esc ^C")));
|
|
105
143
|
}
|
|
106
144
|
return (React.createElement(Box, { flexDirection: "column", maxHeight: 4, overflowX: "hidden", overflowY: "hidden" },
|
|
107
145
|
React.createElement(ClippedLine, null, "howto needs an AI provider before it can call AI."),
|
|
108
146
|
React.createElement(ClippedLine, { color: "green" }, "? Choose provider"),
|
|
109
147
|
React.createElement(ClippedLine, null, providerSelectionLine),
|
|
110
|
-
React.createElement(ClippedLine, { dimColor: true }, "UD
|
|
148
|
+
React.createElement(ClippedLine, { dimColor: true }, "UD Ent 1/2/3 Esc ^C")));
|
|
111
149
|
}
|
|
112
150
|
return (React.createElement(Box, { flexDirection: "column", marginY: 1 },
|
|
113
151
|
React.createElement(Text, null, "howto needs an AI provider before it can call AI."),
|
|
114
|
-
React.createElement(Box, { height: 1 },
|
|
115
|
-
React.createElement(Text, null, " ")),
|
|
116
152
|
React.createElement(Text, { color: "green" }, "? Choose AI provider"),
|
|
117
|
-
React.createElement(Box, { flexDirection: "column"
|
|
153
|
+
React.createElement(Box, { flexDirection: "column" }, providers.map((provider, index) => {
|
|
118
154
|
const isSelected = selectedIndex === index;
|
|
119
155
|
return (React.createElement(Box, { key: provider },
|
|
120
156
|
React.createElement(Text, { color: isSelected ? "cyan" : undefined }, isSelected ? "> " : " "),
|
|
121
157
|
React.createElement(Text, { inverse: isSelected, bold: isSelected },
|
|
122
158
|
index + 1,
|
|
123
159
|
". ",
|
|
124
|
-
provider)));
|
|
160
|
+
PROVIDER_LABELS[provider])));
|
|
125
161
|
})),
|
|
126
162
|
React.createElement(Box, { flexShrink: 0, marginTop: 1 },
|
|
127
|
-
React.createElement(Text, { dimColor: true }, "Use Up/Down or 1/2 to choose, Enter to continue, Esc or Ctrl+C to cancel."))));
|
|
163
|
+
React.createElement(Text, { dimColor: true }, "Use Up/Down or 1/2/3 to choose, Enter to continue, Esc or Ctrl+C to cancel."))));
|
|
128
164
|
};
|
|
129
165
|
const InputStep = ({ state, frameRows }) => {
|
|
130
166
|
const currentField = state.fields[state.fieldIndex];
|
package/dist/init/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import React from "react";
|
|
2
2
|
import { render } from "ink";
|
|
3
3
|
import { loadConfig } from "../config.js";
|
|
4
|
-
import { getConfigFilePath, writeUserConfigFile } from "../config-file.js";
|
|
4
|
+
import { getConfigFilePath, readUserConfigFile, writeUserConfigFile, } from "../config-file.js";
|
|
5
5
|
import { InteractiveSessionProvider } from "../ui/InteractiveSessionProvider.js";
|
|
6
6
|
import { InteractionCancelledError } from "../ui/tty.js";
|
|
7
7
|
import { InitializationApp } from "./InitializationApp.js";
|
|
8
|
-
export async function initializeConfig({ cliOptions, env, session, }) {
|
|
8
|
+
export async function initializeConfig({ cliOptions, env, session, chatgptService, }) {
|
|
9
9
|
return await new Promise((resolve, reject) => {
|
|
10
10
|
let settled = false;
|
|
11
11
|
let unsubscribe = () => { };
|
|
@@ -22,7 +22,10 @@ export async function initializeConfig({ cliOptions, env, session, }) {
|
|
|
22
22
|
void exitPromise.then(result, result);
|
|
23
23
|
};
|
|
24
24
|
const instance = render(React.createElement(InteractiveSessionProvider, { session: session },
|
|
25
|
-
React.createElement(InitializationApp, {
|
|
25
|
+
React.createElement(InitializationApp, { chatgptService: chatgptService, chatgptLoginOptions: {
|
|
26
|
+
noBrowser: cliOptions.noBrowser,
|
|
27
|
+
callbackPort: cliOptions.callbackPort,
|
|
28
|
+
}, onSubmit: async (values) => {
|
|
26
29
|
return validateAndPersistInitializationConfig(values, cliOptions, env);
|
|
27
30
|
}, onComplete: (config) => {
|
|
28
31
|
settle(() => {
|
|
@@ -47,9 +50,18 @@ export async function initializeConfig({ cliOptions, env, session, }) {
|
|
|
47
50
|
});
|
|
48
51
|
}
|
|
49
52
|
export async function validateAndPersistInitializationConfig(values, cliOptions, env) {
|
|
50
|
-
const fileConfig = createFileConfig(values);
|
|
51
|
-
const config = loadConfig(cliOptions, env, fileConfig);
|
|
52
53
|
const configFilePath = getConfigFilePath(env);
|
|
54
|
+
const fileConfig = await readUserConfigFile(configFilePath);
|
|
55
|
+
// 仅替换当前 provider 的字段;其他 provider 与已保存的输出设置继续保留。
|
|
56
|
+
const providerFields = {
|
|
57
|
+
openai: ["openaiApiKey", "openaiModel", "openaiApiUrl"],
|
|
58
|
+
gemini: ["geminiApiKey", "geminiModel"],
|
|
59
|
+
chatgpt: ["chatgptAccount", "chatgptModel"],
|
|
60
|
+
};
|
|
61
|
+
for (const field of providerFields[values.provider])
|
|
62
|
+
delete fileConfig[field];
|
|
63
|
+
Object.assign(fileConfig, createFileConfig(values));
|
|
64
|
+
const config = loadConfig(cliOptions, env, fileConfig);
|
|
53
65
|
await writeUserConfigFile(fileConfig, configFilePath);
|
|
54
66
|
return config;
|
|
55
67
|
}
|
|
@@ -86,6 +98,13 @@ function getOutputColumns(output) {
|
|
|
86
98
|
return typeof columns === "number" && columns > 0 ? columns : 80;
|
|
87
99
|
}
|
|
88
100
|
export function createFileConfig(values) {
|
|
101
|
+
if (values.provider === "chatgpt") {
|
|
102
|
+
return {
|
|
103
|
+
aiProvider: "chatgpt",
|
|
104
|
+
chatgptAccount: values.account,
|
|
105
|
+
chatgptModel: values.model,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
89
108
|
if (values.provider === "gemini") {
|
|
90
109
|
return {
|
|
91
110
|
aiProvider: "gemini",
|
package/dist/init/state.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DEFAULT_GEMINI_MODEL, DEFAULT_OPENAI_MODEL } from "../config.js";
|
|
2
2
|
import { hasUnsafeTerminalControlCharacters } from "../terminal-text.js";
|
|
3
3
|
import { deleteLastGrapheme, isTextInputEvent } from "../ui/text-input.js";
|
|
4
|
-
const PROVIDERS = ["openai", "gemini"];
|
|
4
|
+
const PROVIDERS = ["openai", "gemini", "chatgpt"];
|
|
5
5
|
export function createInitialInitializationState() {
|
|
6
6
|
return {
|
|
7
7
|
step: "provider",
|
|
@@ -26,6 +26,9 @@ export function applyInitializationInput(state, event) {
|
|
|
26
26
|
if (state.step === "provider") {
|
|
27
27
|
return applyProviderInput(state, event);
|
|
28
28
|
}
|
|
29
|
+
if (state.step === "chatgpt") {
|
|
30
|
+
return { state: event.key.escape ? createInitialInitializationState() : state };
|
|
31
|
+
}
|
|
29
32
|
return applyFieldInput(state, event);
|
|
30
33
|
}
|
|
31
34
|
function applyProviderInput(state, event) {
|
|
@@ -37,7 +40,7 @@ function applyProviderInput(state, event) {
|
|
|
37
40
|
: null;
|
|
38
41
|
if (numericSelection !== null) {
|
|
39
42
|
return {
|
|
40
|
-
state:
|
|
43
|
+
state: createProviderState(PROVIDERS[numericSelection]),
|
|
41
44
|
};
|
|
42
45
|
}
|
|
43
46
|
if (event.key.upArrow) {
|
|
@@ -60,7 +63,7 @@ function applyProviderInput(state, event) {
|
|
|
60
63
|
}
|
|
61
64
|
if (event.key.return && state.selectedIndex !== null) {
|
|
62
65
|
return {
|
|
63
|
-
state:
|
|
66
|
+
state: createProviderState(PROVIDERS[state.selectedIndex]),
|
|
64
67
|
};
|
|
65
68
|
}
|
|
66
69
|
return { state };
|
|
@@ -72,6 +75,9 @@ function getNumericProviderSelection(input) {
|
|
|
72
75
|
if (input === "2") {
|
|
73
76
|
return 1;
|
|
74
77
|
}
|
|
78
|
+
if (input === "3") {
|
|
79
|
+
return 2;
|
|
80
|
+
}
|
|
75
81
|
return null;
|
|
76
82
|
}
|
|
77
83
|
function applyFieldInput(state, event) {
|
|
@@ -110,6 +116,11 @@ function applyFieldInput(state, event) {
|
|
|
110
116
|
}
|
|
111
117
|
return { state };
|
|
112
118
|
}
|
|
119
|
+
function createProviderState(provider) {
|
|
120
|
+
if (provider === "chatgpt")
|
|
121
|
+
return { step: "chatgpt" };
|
|
122
|
+
return createInputState(provider);
|
|
123
|
+
}
|
|
113
124
|
function createInputState(provider) {
|
|
114
125
|
return {
|
|
115
126
|
step: "input",
|