@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,366 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, readdir, realpath, rename, unlink, } from "node:fs/promises";
4
+ import { createServer } from "node:net";
5
+ import { dirname, isAbsolute, join } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { getConfigFilePath } from "../../config-file.js";
8
+ const MAX_FILE_BYTES = 1_048_576;
9
+ const LOCK_TIMEOUT_MS = 35_000;
10
+ const TEMPORARY_FILE = /^\.(?:host|accounts)-[0-9a-f-]{36}\.tmp$/;
11
+ export class ChatGptStorageError extends Error {
12
+ code;
13
+ constructor(code = "storage_failed") {
14
+ super("failed to access ChatGPT credentials");
15
+ this.name = "ChatGptStorageError";
16
+ this.code = code;
17
+ }
18
+ }
19
+ export function createChatGptStore(homeDirectory) {
20
+ let home;
21
+ try {
22
+ home = homeDirectory ?? dirname(dirname(getConfigFilePath()));
23
+ if (!isAbsolute(home))
24
+ throw new ChatGptStorageError();
25
+ }
26
+ catch {
27
+ throw new ChatGptStorageError();
28
+ }
29
+ const store = {
30
+ async listAccounts(signal) {
31
+ return store.withLock(async (transaction) => (await transaction.read()).accounts, signal);
32
+ },
33
+ async withLock(fn, signal) {
34
+ throwIfAborted(signal);
35
+ const directory = await protectStorageErrors(() => prepareDirectory(home));
36
+ let lock;
37
+ let active = true;
38
+ let pending = Promise.resolve();
39
+ const run = (operation) => {
40
+ if (!active)
41
+ return Promise.reject(new ChatGptStorageError());
42
+ const result = pending.then(() => protectStorageErrors(operation));
43
+ pending = result.then(() => undefined, () => undefined);
44
+ return result;
45
+ };
46
+ try {
47
+ lock = await acquireLock(directory, signal);
48
+ throwIfAborted(signal);
49
+ await protectStorageErrors(async () => {
50
+ await assertDirectoryUnchanged(directory);
51
+ await removeAbandonedWrites(directory);
52
+ });
53
+ const lockAddress = lock.address();
54
+ if (lockAddress === null || typeof lockAddress === "string")
55
+ throw new ChatGptStorageError();
56
+ const transaction = {
57
+ lockPort: lockAddress.port,
58
+ read: () => run(() => readAccounts(directory)),
59
+ save: (value) => run(async () => {
60
+ const validated = parseAccountStore(value);
61
+ await writeRecord(directory, "accounts", validated);
62
+ }),
63
+ getHostId: () => run(async () => {
64
+ const record = await readRecord(directory, "host");
65
+ if (record !== undefined)
66
+ return parseHostRecord(record).hostId;
67
+ const host = { version: 1, hostId: `urn:uuid:${randomUUID()}` };
68
+ await writeRecord(directory, "host", host);
69
+ return host.hostId;
70
+ }),
71
+ };
72
+ // 持锁后的取消由调用方处理;凭据提交不能因取消而被中途释放锁。
73
+ return await fn(transaction);
74
+ }
75
+ finally {
76
+ active = false;
77
+ // 即使调用方漏掉 await,也必须等已开始的文件操作结束后再释放锁。
78
+ await pending;
79
+ if (lock !== undefined)
80
+ await closeLock(lock);
81
+ await directory.handle.close().catch(() => undefined);
82
+ }
83
+ },
84
+ };
85
+ return store;
86
+ }
87
+ async function prepareDirectory(home) {
88
+ const uid = process.getuid?.();
89
+ if (uid === undefined)
90
+ throw new ChatGptStorageError();
91
+ const homeIdentity = await lstat(home);
92
+ if (!homeIdentity.isDirectory() ||
93
+ homeIdentity.uid !== uid ||
94
+ (homeIdentity.mode & 0o022) !== 0) {
95
+ throw new ChatGptStorageError();
96
+ }
97
+ const canonicalHome = await realpath(home);
98
+ const parentPath = join(canonicalHome, ".howto");
99
+ const parent = await openPrivateDirectory(parentPath, uid);
100
+ try {
101
+ const parentIdentity = await parent.stat();
102
+ const path = join(parentPath, "chatgpt");
103
+ const handle = await openPrivateDirectory(path, uid);
104
+ try {
105
+ const directory = {
106
+ path,
107
+ parentPath,
108
+ parentIdentity,
109
+ identity: await handle.stat(),
110
+ handle,
111
+ uid,
112
+ };
113
+ await assertDirectoryUnchanged(directory);
114
+ return directory;
115
+ }
116
+ catch (error) {
117
+ await handle.close();
118
+ throw error;
119
+ }
120
+ }
121
+ finally {
122
+ await parent.close();
123
+ }
124
+ }
125
+ async function openPrivateDirectory(path, uid) {
126
+ await mkdir(path, { mode: 0o700 }).catch((error) => {
127
+ if (!hasCode(error, "EEXIST"))
128
+ throw error;
129
+ });
130
+ const handle = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
131
+ try {
132
+ const identity = await handle.stat();
133
+ if (!identity.isDirectory() || identity.uid !== uid)
134
+ throw new ChatGptStorageError();
135
+ await handle.chmod(0o700);
136
+ return handle;
137
+ }
138
+ catch (error) {
139
+ await handle.close();
140
+ throw error;
141
+ }
142
+ }
143
+ async function assertDirectoryUnchanged(directory) {
144
+ const parent = await lstat(directory.parentPath);
145
+ const current = await lstat(directory.path);
146
+ for (const [actual, expected] of [
147
+ [parent, directory.parentIdentity],
148
+ [current, directory.identity],
149
+ ]) {
150
+ if (!actual.isDirectory() ||
151
+ actual.uid !== directory.uid ||
152
+ actual.dev !== expected.dev ||
153
+ actual.ino !== expected.ino ||
154
+ (actual.mode & 0o777) !== 0o700) {
155
+ throw new ChatGptStorageError();
156
+ }
157
+ }
158
+ }
159
+ async function acquireLock(directory, signal) {
160
+ // 内核监听锁在进程退出时自动释放;不按时间抢占活跃刷新,也没有 PID 文件重收竞态。
161
+ // 同一目录固定使用同一端口。碰撞时只等待/失败,绝不换端口绕过互斥。
162
+ const key = `${directory.uid}:${directory.identity.dev}:${directory.identity.ino}`;
163
+ const port = 16_384 + (createHash("sha256").update(key).digest().readUInt32BE(0) % 49_152);
164
+ const startedAt = performance.now();
165
+ while (true) {
166
+ throwIfAborted(signal);
167
+ const server = await protectStorageErrors(() => tryListen(port));
168
+ if (server !== undefined)
169
+ return server;
170
+ if (performance.now() - startedAt >= LOCK_TIMEOUT_MS) {
171
+ throw new ChatGptStorageError("lock_timeout");
172
+ }
173
+ try {
174
+ await delay(50, undefined, { signal });
175
+ }
176
+ catch {
177
+ throwIfAborted(signal);
178
+ throw new ChatGptStorageError();
179
+ }
180
+ }
181
+ }
182
+ function tryListen(port) {
183
+ return new Promise((resolve, reject) => {
184
+ const server = createServer((socket) => socket.destroy());
185
+ server.once("error", (error) => {
186
+ if (hasCode(error, "EADDRINUSE"))
187
+ resolve(undefined);
188
+ else
189
+ reject(error);
190
+ });
191
+ server.listen({ host: "127.0.0.1", port, exclusive: true }, () => resolve(server));
192
+ });
193
+ }
194
+ function closeLock(server) {
195
+ return new Promise((resolve) => server.close(() => resolve()));
196
+ }
197
+ async function readAccounts(directory) {
198
+ const record = await readRecord(directory, "accounts");
199
+ return record === undefined ? { version: 1, accounts: [] } : parseAccountStore(record);
200
+ }
201
+ async function readRecord(directory, name) {
202
+ await assertDirectoryUnchanged(directory);
203
+ let handle;
204
+ try {
205
+ handle = await open(join(directory.path, `${name}.json`), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
206
+ }
207
+ catch (error) {
208
+ if (hasCode(error, "ENOENT"))
209
+ return undefined;
210
+ throw error;
211
+ }
212
+ try {
213
+ assertPrivateFile(await handle.stat(), directory.uid);
214
+ const bytes = await handle.readFile();
215
+ if (bytes.length > MAX_FILE_BYTES)
216
+ throw new ChatGptStorageError();
217
+ return JSON.parse(bytes.toString("utf8"));
218
+ }
219
+ finally {
220
+ await handle.close();
221
+ }
222
+ }
223
+ function assertPrivateFile(identity, uid) {
224
+ if (!identity.isFile() ||
225
+ identity.uid !== uid ||
226
+ identity.nlink !== 1 ||
227
+ (identity.mode & 0o777) !== 0o600 ||
228
+ identity.size > MAX_FILE_BYTES) {
229
+ throw new ChatGptStorageError();
230
+ }
231
+ }
232
+ async function writeRecord(directory, name, value) {
233
+ await assertDirectoryUnchanged(directory);
234
+ const contents = `${JSON.stringify(value, null, 2)}\n`;
235
+ if (Buffer.byteLength(contents) > MAX_FILE_BYTES)
236
+ throw new ChatGptStorageError();
237
+ const temporary = join(directory.path, `.${name}-${randomUUID()}.tmp`);
238
+ const target = join(directory.path, `${name}.json`);
239
+ let handle;
240
+ try {
241
+ handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
242
+ await handle.chmod(0o600);
243
+ await handle.writeFile(contents, "utf8");
244
+ await handle.sync();
245
+ await handle.close();
246
+ handle = undefined;
247
+ await assertDirectoryUnchanged(directory);
248
+ await lstat(target)
249
+ .then((identity) => assertPrivateFile(identity, directory.uid))
250
+ .catch((error) => {
251
+ if (!hasCode(error, "ENOENT"))
252
+ throw error;
253
+ });
254
+ await rename(temporary, target);
255
+ await directory.handle.sync();
256
+ }
257
+ finally {
258
+ await handle?.close().catch(() => undefined);
259
+ await unlink(temporary).catch(() => undefined);
260
+ }
261
+ }
262
+ async function removeAbandonedWrites(directory) {
263
+ for (const name of await readdir(directory.path)) {
264
+ if (!TEMPORARY_FILE.test(name))
265
+ continue;
266
+ const path = join(directory.path, name);
267
+ assertPrivateFile(await lstat(path), directory.uid);
268
+ await unlink(path);
269
+ }
270
+ }
271
+ function parseHostRecord(value) {
272
+ const record = asObject(value);
273
+ if (record.version !== 1)
274
+ throw new ChatGptStorageError();
275
+ return { version: 1, hostId: nonEmptyString(record.hostId) };
276
+ }
277
+ function parseAccountStore(value) {
278
+ const record = asObject(value);
279
+ if (record.version !== 1 || !Array.isArray(record.accounts))
280
+ throw new ChatGptStorageError();
281
+ const accounts = record.accounts.map(parseAccount);
282
+ if (new Set(accounts.map((account) => account.id)).size !== accounts.length) {
283
+ throw new ChatGptStorageError();
284
+ }
285
+ return { version: 1, accounts };
286
+ }
287
+ function parseAccount(value) {
288
+ const record = asObject(value);
289
+ if (record.issuer !== "https://auth.openai.com")
290
+ throw new ChatGptStorageError();
291
+ const account = {
292
+ id: nonEmptyString(record.id),
293
+ label: nonEmptyString(record.label),
294
+ clientId: nonEmptyString(record.clientId),
295
+ issuer: record.issuer,
296
+ generation: timestamp(record.generation),
297
+ };
298
+ if (record.subject !== undefined)
299
+ account.subject = nonEmptyString(record.subject);
300
+ if (record.email !== undefined)
301
+ account.email = nonEmptyString(record.email);
302
+ if (record.refreshState !== undefined) {
303
+ if (record.refreshState !== "refreshing" && record.refreshState !== "reauth_required") {
304
+ throw new ChatGptStorageError();
305
+ }
306
+ account.refreshState = record.refreshState;
307
+ }
308
+ if (record.tokens !== undefined) {
309
+ if (account.subject === undefined)
310
+ throw new ChatGptStorageError();
311
+ account.tokens = parseTokens(record.tokens);
312
+ }
313
+ return account;
314
+ }
315
+ function parseTokens(value) {
316
+ const record = asObject(value);
317
+ if (!Array.isArray(record.scopes))
318
+ throw new ChatGptStorageError();
319
+ const tokens = {
320
+ accessToken: nonEmptyString(record.accessToken),
321
+ idToken: nonEmptyString(record.idToken),
322
+ scopes: record.scopes.map(nonEmptyString),
323
+ expiresAt: timestamp(record.expiresAt),
324
+ savedAt: timestamp(record.savedAt),
325
+ };
326
+ if (record.refreshToken !== undefined)
327
+ tokens.refreshToken = nonEmptyString(record.refreshToken);
328
+ if (record.earliestRefreshAt !== undefined) {
329
+ tokens.earliestRefreshAt = timestamp(record.earliestRefreshAt);
330
+ }
331
+ return tokens;
332
+ }
333
+ function asObject(value) {
334
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
335
+ throw new ChatGptStorageError();
336
+ }
337
+ return value;
338
+ }
339
+ function nonEmptyString(value) {
340
+ if (typeof value !== "string" || value.trim() === "")
341
+ throw new ChatGptStorageError();
342
+ return value;
343
+ }
344
+ function timestamp(value) {
345
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
346
+ throw new ChatGptStorageError();
347
+ }
348
+ return value;
349
+ }
350
+ function hasCode(error, code) {
351
+ return error instanceof Error && "code" in error && error.code === code;
352
+ }
353
+ function throwIfAborted(signal) {
354
+ if (signal?.aborted)
355
+ throw new DOMException("ChatGPT authentication cancelled", "AbortError");
356
+ }
357
+ async function protectStorageErrors(operation) {
358
+ try {
359
+ return await operation();
360
+ }
361
+ catch (error) {
362
+ if (error instanceof ChatGptStorageError)
363
+ throw error;
364
+ throw new ChatGptStorageError();
365
+ }
366
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.js CHANGED
@@ -11,26 +11,45 @@ const VALUE_OPTIONS = new Set([
11
11
  "--openai-api-url",
12
12
  "--openai-api-key",
13
13
  "--openai-model",
14
+ "--chatgpt-account",
15
+ "--chatgpt-model",
16
+ "--callback-port",
14
17
  "--structured-output",
15
18
  ]);
16
- const BOOLEAN_OPTIONS = new Set(["--print", "--init", "--version"]);
17
- export const USAGE = `Usage: howto [options] [use <command>] <question> [<argument>...]
18
- howto --init
19
+ const CHATGPT_ACTION_OPTIONS = new Map([
20
+ ["--chatgpt-login", "login"],
21
+ ["--chatgpt-logout", "logout"],
22
+ ["--chatgpt-status", "status"],
23
+ ["--chatgpt-models", "models"],
24
+ ]);
25
+ const BOOLEAN_OPTIONS = new Set(["--print", "--init", "--version", "--no-browser"]);
26
+ export const USAGE = `Usage: howto [options] [use <command>] <question...>
27
+ howto --init [--no-browser] [--callback-port <port>]
19
28
  howto --version
29
+ howto --chatgpt-login [--chatgpt-account <account>] [--no-browser] [--callback-port <port>]
30
+ howto --chatgpt-logout|--chatgpt-status|--chatgpt-models [--chatgpt-account <account>]
20
31
 
21
32
  Options:
22
33
  --init
23
34
  --version
24
35
  --print
25
- --ai-provider <openai|gemini>
36
+ --ai-provider <openai|gemini|chatgpt>
26
37
  --gemini-api-key <key>
27
38
  --gemini-model <model>
28
39
  --openai-api-url <url>
29
40
  --openai-api-key <key>
30
41
  --openai-model <model>
42
+ --chatgpt-login
43
+ --chatgpt-logout
44
+ --chatgpt-status
45
+ --chatgpt-models
46
+ --chatgpt-account <account>
47
+ --chatgpt-model <model>
48
+ --no-browser Skip opening the browser for ChatGPT login or --init
49
+ --callback-port <1-65535> ChatGPT callback port (default: a random available port)
31
50
  --structured-output <true|false>
32
51
 
33
- Try: howto "list files changed today"`;
52
+ Try: howto list files changed today`;
34
53
  export function parseCliArgs(argv) {
35
54
  const options = { print: false };
36
55
  const positionals = [];
@@ -45,6 +64,17 @@ export function parseCliArgs(argv) {
45
64
  const equalIndex = token.indexOf("=");
46
65
  const optionName = equalIndex === -1 ? token : token.slice(0, equalIndex);
47
66
  const inlineValue = equalIndex === -1 ? undefined : token.slice(equalIndex + 1);
67
+ const chatgptAction = CHATGPT_ACTION_OPTIONS.get(optionName);
68
+ if (chatgptAction !== undefined) {
69
+ if (inlineValue !== undefined) {
70
+ throw new CliParseError(`${optionName} does not accept a value`);
71
+ }
72
+ if (options.chatgptAction !== undefined) {
73
+ throw new CliParseError("only one ChatGPT action may be specified");
74
+ }
75
+ options.chatgptAction = chatgptAction;
76
+ continue;
77
+ }
48
78
  if (BOOLEAN_OPTIONS.has(optionName)) {
49
79
  if (inlineValue !== undefined) {
50
80
  throw new CliParseError(`${optionName} does not accept a value`);
@@ -68,7 +98,22 @@ export function parseCliArgs(argv) {
68
98
  if (argv.length !== 1) {
69
99
  throw new CliParseError("--version must be used alone");
70
100
  }
71
- return { options, arguments: [] };
101
+ return { options };
102
+ }
103
+ if ((options.noBrowser || options.callbackPort !== undefined) &&
104
+ options.chatgptAction !== "login" &&
105
+ !(options.init && options.chatgptAction === undefined)) {
106
+ throw new CliParseError("--no-browser and --callback-port require --chatgpt-login or --init");
107
+ }
108
+ if (options.chatgptAction !== undefined) {
109
+ const unsupportedOption = Object.keys(options).find((key) => key !== "print" &&
110
+ key !== "chatgptAction" &&
111
+ key !== "chatgptAccount" &&
112
+ !(options.chatgptAction === "login" && (key === "noBrowser" || key === "callbackPort")));
113
+ if (positionals.length > 0 || options.print || unsupportedOption !== undefined) {
114
+ throw new CliParseError("ChatGPT actions accept --chatgpt-account and no question; only login also accepts --no-browser and --callback-port");
115
+ }
116
+ return { options };
72
117
  }
73
118
  return parsePositionals(options, positionals);
74
119
  }
@@ -99,6 +144,20 @@ function assignOptionValue(options, optionName, value) {
99
144
  case "--openai-model":
100
145
  options.openaiModel = value;
101
146
  return;
147
+ case "--chatgpt-account":
148
+ options.chatgptAccount = value;
149
+ return;
150
+ case "--chatgpt-model":
151
+ options.chatgptModel = value;
152
+ return;
153
+ case "--callback-port": {
154
+ const port = Number(value);
155
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(port) || port < 1 || port > 65535) {
156
+ throw new CliParseError("--callback-port must be an integer from 1 to 65535");
157
+ }
158
+ options.callbackPort = port;
159
+ return;
160
+ }
102
161
  case "--structured-output":
103
162
  options.structuredOutput = value;
104
163
  return;
@@ -117,6 +176,9 @@ function assignBooleanOption(options, optionName) {
117
176
  case "--version":
118
177
  options.version = true;
119
178
  return;
179
+ case "--no-browser":
180
+ options.noBrowser = true;
181
+ return;
120
182
  default:
121
183
  throw new CliParseError(`unsupported option: ${optionName}`);
122
184
  }
@@ -129,28 +191,27 @@ function parsePositionals(options, positionals) {
129
191
  if (positionals.length > 0) {
130
192
  throw new CliParseError("--init cannot be combined with a question or use mode");
131
193
  }
132
- return { options, arguments: [] };
194
+ return { options };
133
195
  }
134
196
  if (positionals.length === 0) {
135
197
  throw new CliParseError("missing question");
136
198
  }
137
- if (positionals[0] === "use") {
199
+ const isUseMode = positionals[0] === "use";
200
+ if (isUseMode) {
138
201
  if (positionals.length === 1) {
139
202
  throw new CliParseError("use mode requires <command> and <question>");
140
203
  }
141
204
  if (positionals.length === 2) {
142
205
  throw new CliParseError("use mode requires <question>");
143
206
  }
144
- return {
145
- options,
146
- useCommand: positionals[1],
147
- question: positionals[2],
148
- arguments: positionals.slice(3),
149
- };
207
+ }
208
+ const question = (isUseMode ? positionals.slice(2) : positionals).join(" ");
209
+ if (question.trim() === "") {
210
+ throw new CliParseError("question must not be blank");
150
211
  }
151
212
  return {
152
213
  options,
153
- question: positionals[0],
154
- arguments: positionals.slice(1),
214
+ ...(isUseMode ? { useCommand: positionals[1] } : {}),
215
+ question,
155
216
  };
156
217
  }
@@ -9,6 +9,8 @@ const CONFIG_FILE_FIELDS = new Set([
9
9
  "openaiApiUrl",
10
10
  "openaiApiKey",
11
11
  "openaiModel",
12
+ "chatgptAccount",
13
+ "chatgptModel",
12
14
  "structuredOutput",
13
15
  ]);
14
16
  export function getConfigFilePath(env = process.env, getSystemHomeDirectory = () => userInfo().homedir) {
package/dist/config.js CHANGED
@@ -4,8 +4,8 @@ export class ConfigError extends Error {
4
4
  this.name = "ConfigError";
5
5
  }
6
6
  }
7
- const DEFAULT_OPENAI_MODEL = "gpt-5.4-mini";
8
- const DEFAULT_GEMINI_MODEL = "gemini-3.1-flash-lite";
7
+ const DEFAULT_OPENAI_MODEL = "gpt-6-luna";
8
+ const DEFAULT_GEMINI_MODEL = "gemini-3.5-flash-lite";
9
9
  export { DEFAULT_GEMINI_MODEL, DEFAULT_OPENAI_MODEL };
10
10
  export function hasExplicitAiProvider(options, env, fileConfig = {}) {
11
11
  return (pickConfigValue(options.aiProvider, env.HOWTO_AI_PROVIDER, fileConfig.aiProvider) !== undefined);
@@ -30,21 +30,28 @@ export function loadConfig(options, env, fileConfig = {}) {
30
30
  DEFAULT_OPENAI_MODEL,
31
31
  baseUrl: pickConfigValue(options.openaiApiUrl, env.HOWTO_OPENAI_API_URL, fileConfig.openaiApiUrl),
32
32
  },
33
+ chatgpt: {
34
+ account: pickConfigValue(options.chatgptAccount, env.HOWTO_CHATGPT_ACCOUNT, fileConfig.chatgptAccount),
35
+ model: pickConfigValue(options.chatgptModel, env.HOWTO_CHATGPT_MODEL, fileConfig.chatgptModel),
36
+ },
33
37
  structuredOutput: parseStructuredOutput(pickConfigValue(options.structuredOutput, env.HOWTO_STRUCTURED_OUTPUT, fileConfig.structuredOutput)),
34
38
  };
35
39
  if (config.aiProvider === "gemini" && isBlank(config.gemini.apiKey)) {
36
40
  throw new ConfigError("Gemini provider requires --gemini-api-key or HOWTO_GEMINI_API_KEY");
37
41
  }
42
+ if (config.aiProvider === "chatgpt" && isBlank(config.chatgpt.model)) {
43
+ throw new ConfigError("ChatGPT model is not configured. Run howto --init or howto --chatgpt-models, then set --chatgpt-model or HOWTO_CHATGPT_MODEL.");
44
+ }
38
45
  return config;
39
46
  }
40
47
  function pickConfigValue(cliValue, envValue, fileValue) {
41
48
  return cliValue ?? envValue ?? fileValue;
42
49
  }
43
50
  function parseAiProvider(value) {
44
- if (value === "openai" || value === "gemini") {
51
+ if (value === "openai" || value === "gemini" || value === "chatgpt") {
45
52
  return value;
46
53
  }
47
- throw new ConfigError("invalid AI provider; expected openai or gemini");
54
+ throw new ConfigError("invalid AI provider; expected openai, gemini, or chatgpt");
48
55
  }
49
56
  function isBlank(value) {
50
57
  return value === undefined || value.trim() === "";
package/dist/errors.js CHANGED
@@ -5,6 +5,8 @@ import { AiResponseValidationError } from "./validation/ai-response.js";
5
5
  import { InteractionCancelledError, InteractiveTtyError } from "./ui/tty.js";
6
6
  import { PlaceholderResolutionError } from "./ui/placeholder-logic.js";
7
7
  import { sanitizeUserVisibleErrorMessage } from "./user-visible-error.js";
8
+ import { UnsupportedEnvironmentError } from "./shell/execution-environment.js";
9
+ import { ChatGptError } from "./auth/chatgpt/errors.js";
8
10
  export { sanitizeUserVisibleErrorMessage };
9
11
  export function getUserVisibleErrorMessage(error) {
10
12
  if (error instanceof AiProviderError) {
@@ -24,6 +26,9 @@ export function toAppError(error) {
24
26
  if (error instanceof AppError) {
25
27
  return new AppError(sanitizeUserVisibleErrorMessage(error.message), error.exitCode);
26
28
  }
29
+ if (error instanceof ChatGptError) {
30
+ return new AppError(error.message, error.exitCode);
31
+ }
27
32
  if (error instanceof CliParseError) {
28
33
  return new AppError(`Error: ${sanitizeUserVisibleErrorMessage(error.message)}\n${USAGE}`, 2);
29
34
  }
@@ -36,7 +41,7 @@ export function toAppError(error) {
36
41
  if (error instanceof AiResponseValidationError) {
37
42
  return new AppError(`AI response format error: ${sanitizeUserVisibleErrorMessage(error.message)}`, 2);
38
43
  }
39
- if (error instanceof InteractiveTtyError) {
44
+ if (error instanceof InteractiveTtyError || error instanceof UnsupportedEnvironmentError) {
40
45
  return new AppError(`Error: ${sanitizeUserVisibleErrorMessage(error.message)}`, 2);
41
46
  }
42
47
  if (error instanceof PlaceholderResolutionError) {
package/dist/execute.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { spawn } from "child_process";
2
2
  import { constants as osConstants } from "os";
3
+ import { resolveExecutionShell } from "./shell/execution-environment.js";
3
4
  export async function executeCommand(command, options = {}) {
4
5
  const env = options.env ?? process.env;
5
6
  const platform = options.platform ?? process.platform;
6
- const spawnCommand = options.spawnCommand ?? spawnCommandWithNodeSpawn;
7
- const child = platform === "win32"
8
- ? spawnCommand(command, { shell: env.SHELL || true, stdio: "inherit" }, { stdio: "inherit" })
9
- : spawnCommand(resolveShell(env), ["-c", command], { stdio: "inherit" });
7
+ const shell = resolveExecutionShell(env, platform);
8
+ const spawnCommand = options.spawnCommand ?? spawn;
9
+ const child = spawnCommand(shell, ["-c", command], { stdio: "inherit" });
10
10
  return new Promise((resolve, reject) => {
11
11
  child.once("error", reject);
12
12
  child.once("close", (code, signal) => {
@@ -23,12 +23,3 @@ export function resolveProcessExitCode(code, signal) {
23
23
  }
24
24
  return 1;
25
25
  }
26
- function resolveShell(env) {
27
- return env.SHELL && env.SHELL.trim() !== "" ? env.SHELL : "/bin/sh";
28
- }
29
- const spawnCommandWithNodeSpawn = (command, args, options) => {
30
- if (Array.isArray(args)) {
31
- return options === undefined ? spawn(command, args) : spawn(command, args, options);
32
- }
33
- return spawn(command, args);
34
- };