@unscientificjszhai/howto 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +88 -29
  2. package/{README.CN.md → README.zh-hans-cn.md} +84 -25
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/dist/ai/chatgpt-models.js +148 -0
  5. package/dist/ai/chatgpt.js +495 -0
  6. package/dist/ai/command-schema.js +8 -0
  7. package/dist/ai/errors.js +6 -0
  8. package/dist/ai/gemini.js +117 -4
  9. package/dist/ai/index.js +4 -1
  10. package/dist/ai/openai.js +105 -2
  11. package/dist/ai/usage-session.js +144 -0
  12. package/dist/auth/chatgpt/commands.js +90 -0
  13. package/dist/auth/chatgpt/errors.js +85 -0
  14. package/dist/auth/chatgpt/http.js +97 -0
  15. package/dist/auth/chatgpt/index.js +229 -0
  16. package/dist/auth/chatgpt/instructions.js +22 -0
  17. package/dist/auth/chatgpt/oauth.js +320 -0
  18. package/dist/auth/chatgpt/storage.js +366 -0
  19. package/dist/auth/chatgpt/types.js +1 -0
  20. package/dist/cli.js +77 -16
  21. package/dist/config-file.js +2 -0
  22. package/dist/config.js +10 -3
  23. package/dist/errors.js +4 -0
  24. package/dist/index.js +11 -4
  25. package/dist/init/ChatGptInitializationStep.js +223 -0
  26. package/dist/init/InitializationApp.js +71 -37
  27. package/dist/init/index.js +24 -5
  28. package/dist/init/state.js +14 -3
  29. package/dist/prompt.js +36 -6
  30. package/dist/shell/command-analysis.js +24 -4
  31. package/dist/ui/App.js +99 -10
  32. package/dist/ui/ConfirmView.js +6 -39
  33. package/dist/ui/InteractiveSessionProvider.js +7 -8
  34. package/dist/ui/ResolvePlaceholdersView.js +6 -1
  35. package/dist/ui/UsageApprovalView.js +320 -0
  36. package/dist/ui/interactive-session.js +180 -39
  37. package/dist/ui/keyboard-framing.js +102 -0
  38. package/dist/ui/paste-framing.js +69 -32
  39. package/dist/ui/resize-safe-output.js +2 -2
  40. package/dist/ui/run-interactive-command.js +2 -2
  41. package/dist/ui/text-input.js +4 -1
  42. package/dist/ui/use-keyboard-input.js +6 -1
  43. package/dist/ui/use-paste-aware-input.js +8 -3
  44. package/dist/usage/arguments.js +61 -0
  45. package/dist/usage/generate.js +156 -0
  46. package/dist/usage/output.js +216 -0
  47. package/dist/usage/risk.js +17 -0
  48. package/dist/usage/runner.js +238 -0
  49. package/dist/usage/types.js +1 -0
  50. package/dist/validation/usage-response.js +39 -0
  51. package/package.json +21 -19
package/README.md CHANGED
@@ -7,7 +7,7 @@ _Use AI to quickly find commands within the terminal._
7
7
  [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
8
8
  [![License](https://img.shields.io/github/license/UnscientificJsZhai/HowTo)](LICENSE)
9
9
 
10
- English | [简体中文](README.CN.md)
10
+ English | [简体中文](README.zh-hans-cn.md)
11
11
 
12
12
  [Features](#features) • [Install](#install) • [Usage](#usage) • [Configuration](#configuration) • [Development](#development) • [Troubleshooting](#troubleshooting)
13
13
 
@@ -22,7 +22,7 @@ English | [简体中文](README.CN.md)
22
22
  - **Tool-constrained mode** - use `howto use <command>` to require candidates around a specific CLI tool.
23
23
  - **Interactive review flow** - select a candidate, resolve placeholders, and confirm the final command before execution.
24
24
  - **Non-interactive print mode** - use `--print` to output candidates without TTY interaction or command execution.
25
- - **OpenAI and Gemini support** - configure either provider from CLI flags, environment variables, or `~/.howto/config.json`.
25
+ - **ChatGPT, OpenAI, and Gemini support** - sign in with ChatGPT to use an eligible plan, or keep using API keys and OpenAI-compatible services.
26
26
  - **Local validation first** - AI JSON output, placeholder references, `use <command>` candidates, and obvious dangerous commands are checked locally.
27
27
 
28
28
  ## Install
@@ -61,6 +61,22 @@ howto --init
61
61
 
62
62
  The initializer writes a user-level config file at `~/.howto/config.json`.
63
63
 
64
+ Choose **Continue with ChatGPT** to sign in through the system browser, select a saved account or add one, and choose a model from that account's live catalog. The official open-source Sign in with ChatGPT flow uses a local callback on `127.0.0.1`. It requires neither a client secret nor a Codex installation. Existing API key settings are preserved when switching providers.
65
+
66
+ For account management outside initialization:
67
+
68
+ ```bash
69
+ howto --chatgpt-login
70
+ howto --chatgpt-status
71
+ howto --chatgpt-models --chatgpt-account <account-id>
72
+ howto --chatgpt-login --chatgpt-account <account-id>
73
+ howto --chatgpt-logout --chatgpt-account <account-id>
74
+ ```
75
+
76
+ Login without `--chatgpt-account` adds a registration; with an account ID it renews that registration. Login alone does not change the selected provider or model. Run `howto --init` to save those choices. Ordinary generation and `--print` never start browser authorization. ChatGPT uses the account's current visible model slugs; it never silently switches models or falls back to API key billing.
77
+
78
+ ChatGPT credentials are stored separately in `~/.howto/chatgpt/` (private directory, owner-only files), with serialized refresh and logout across processes. Tokens are never put in `config.json`. If a refresh response is lost, sign in again rather than replaying a potentially consumed refresh token. Logout retains the registration for later sign-in and reports when remote revocation was not confirmed. Review app usage and permissions in [ChatGPT Settings](https://chatgpt.com/settings/usage). Eligibility and available models depend on the account; see the [official open-source flow](https://developers.openai.com/siwc/token-sharing-open-source).
79
+
64
80
  Initialization and placeholder input delete complete characters on Backspace, including emoji and combining sequences. Alt/Meta shortcuts are not inserted into configuration fields as text.
65
81
  Key release events never confirm, cancel, navigate, or delete; pressing and releasing Enter once cannot skip the final confirmation.
66
82
  Keyboard text and Enter are processed in order even when the terminal delivers them together. Once a step finishes, remaining keys in that batch cannot skip the next confirmation screen. Newlines inside paste remain data.
@@ -71,13 +87,13 @@ Keyboard text and Enter are processed in order even when the terminal delivers t
71
87
  Ask for a command:
72
88
 
73
89
  ```bash
74
- howto "find files modified in the last 7 days" .
90
+ howto find files modified in the last 7 days under .
75
91
  ```
76
92
 
77
93
  Limit candidates to a specific tool:
78
94
 
79
95
  ```bash
80
- howto use git "show commits from last week"
96
+ howto use git show commits from last week
81
97
  ```
82
98
 
83
99
  `use` checks the first actual tool exactly after environment assignments and supported `sudo`/`env` options. For example, `sudo -u root git status` satisfies `use git`, while `sudo -u git id` does not. Unknown wrapper options, missing option values, dynamic executable prefixes, and complex shell structures are rejected. This constraint applies to the first command segment, not subsequent segments.
@@ -87,24 +103,47 @@ Declared placeholders may appear after the first tool, as in `git log -n {{count
87
103
  Print command candidates without entering the interactive UI:
88
104
 
89
105
  ```bash
90
- howto --print "list the largest files" /var/log
106
+ howto --print list the largest files under /var/log
107
+ ```
108
+
109
+ ### ChatGPT login over SSH
110
+
111
+ On your computer with a browser, connect to the server with a loopback port forward:
112
+
113
+ ```bash
114
+ ssh -o ExitOnForwardFailure=yes -L 127.0.0.1:1455:127.0.0.1:1455 user@server
115
+ ```
116
+
117
+ In that remote shell, start login:
118
+
119
+ ```bash
120
+ howto --chatgpt-login --no-browser --callback-port 1455
91
121
  ```
92
122
 
123
+ Open the printed authorization URL in your local browser. Keep both the SSH connection and HowTo running until login completes. Replace `user@server` with your SSH destination. The browser redirects to its own `127.0.0.1`; the tunnel forwards that callback to HowTo on the server. No public callback listener is needed. The server still needs outbound HTTPS access to OpenAI's authentication and API services.
124
+
125
+ To sign in and save your provider/model choices in one interactive session, run `howto --init --no-browser --callback-port 1455` instead, then choose **Continue with ChatGPT**. Initialization requires a TTY; the standalone login command does not.
126
+
127
+ Both options are optional and apply only to `--chatgpt-login` or `--init`, only for the current invocation. `--no-browser` skips the browser launcher entirely and prints a link even when renewing an existing account. `--callback-port` accepts a decimal integer from `1` to `65535`; without it, HowTo chooses an available port and prints forwarding instructions for that port. These options are not saved in configuration and do not affect API key providers.
128
+
129
+ If either end cannot bind the chosen port, choose another available port and use it on both ends of the tunnel and in `--callback-port`. HowTo does not silently change an explicitly requested port. If already connected over SSH, use the printed `ssh -N ...` command in another local terminal before opening the URL. Login waits up to 10 minutes; Ctrl+C cancels it and releases the callback listener. Once authenticated, ordinary requests and token refreshes need no browser. This flow still requires browser approval on your local computer; it does not use device codes or accept pasted callback URLs.
130
+
93
131
  ## Usage
94
132
 
95
133
  ```text
96
- howto [options] [use <command>] <question> [<argument>...]
97
- howto --init
134
+ howto [options] [use <command>] <question...>
135
+ howto --init [--no-browser] [--callback-port <port>]
98
136
  howto --version
137
+ howto --chatgpt-login [--chatgpt-account <id>] [--no-browser] [--callback-port <port>]
99
138
  ```
100
139
 
101
140
  Examples:
102
141
 
103
142
  ```bash
104
- howto "find package.json under the current directory"
105
- howto use find "find a filename" package.json
106
- howto "explain this option" -- --force
107
- howto --ai-provider openai --print "show listening ports"
143
+ howto find package.json under the current directory
144
+ howto use find find report.txt under /tmp
145
+ howto explain this option -- --force
146
+ howto --ai-provider openai --print show listening ports
108
147
  ```
109
148
 
110
149
  Options:
@@ -112,7 +151,10 @@ Options:
112
151
  - `--init` - start interactive provider setup and save `~/.howto/config.json`.
113
152
  - `--version` - use alone to print the current package version and exit successfully; requires no configuration or TTY and makes no AI request.
114
153
  - `--print` - print validated command candidates and exit without executing.
115
- - `--ai-provider <openai|gemini>` - select the AI provider.
154
+ - `--ai-provider <openai|gemini|chatgpt>` - select the AI provider.
155
+ - `--chatgpt-account <id>` / `--chatgpt-model <slug>` - choose a local registration and an available ChatGPT model.
156
+ - `--no-browser` - skip the ChatGPT browser launcher and print the authorization URL; only with `--chatgpt-login` or `--init`.
157
+ - `--callback-port <port>` - use a specific ChatGPT loopback callback port (`1`–`65535`, random available port by default); only with `--chatgpt-login` or `--init`.
116
158
  - `--gemini-api-key <key>` - provide a Gemini API key.
117
159
  - `--gemini-model <model>` - override the Gemini model.
118
160
  - `--openai-api-url <url>` - use a custom OpenAI-compatible base URL.
@@ -122,17 +164,25 @@ Options:
122
164
 
123
165
  ### Argument Parsing
124
166
 
125
- `question` is one shell argument. Quote it when it contains spaces:
167
+ All question fragments are joined with one ASCII space. In `use` mode, the first positional token is `use`, the next is the tool name, and all remaining fragments form the question. Global options may appear anywhere before `--`; unknown long options are rejected. Everything after `--` is positional text.
126
168
 
127
- ```bash
128
- howto "find recently changed files" /tmp
129
- ```
169
+ | Input | Final question |
170
+ | ------------------------------------------- | ---------------------------- |
171
+ | `howto list files changed today` | `list files changed today` |
172
+ | `howto "list files" /tmp` | `list files /tmp` |
173
+ | `howto use find find report.txt under /tmp` | `find report.txt under /tmp` |
174
+ | `howto list files --print` | `list files` (print mode) |
175
+ | `howto explain -- --force` | `explain --force` |
176
+ | `howto find files "/tmp/my files"` | `find files /tmp/my files` |
177
+ | `howto "" " "` | Usage error |
130
178
 
131
- Everything after the question is passed to the AI as `argument[]`. Use `--` when an argument starts with `--`:
179
+ Whitespace and line breaks inside each fragment are preserved. Missing or entirely whitespace questions exit with code `2` and Usage before configuration loading or AI requests. The question itself is never trimmed, and quotes or fragment boundaries are not reconstructed or sent separately.
132
180
 
133
- ```bash
134
- howto "explain this flag" -- --force
135
- ```
181
+ The model infers paths, filenames, counts, and options from the complete question. Clear values become command parameters; required values that are missing or ambiguous become placeholders for the existing fill-and-confirm flow.
182
+
183
+ Quoted questions remain valid. Older “question + extra parameters” invocations now form one question, with no separate parameter grouping. Original shell argument boundaries cannot be recovered after joining, so paths containing spaces are interpreted from the question's meaning; describe their purpose clearly.
184
+
185
+ Unquoted input is convenient for ordinary question text. Your shell still processes variables, wildcards, redirections, and other special syntax before howto receives it; quote or escape these when you need literal text. Existing management actions and repeated-option rules are unchanged; no configuration migration is needed.
136
186
 
137
187
  ## Configuration
138
188
 
@@ -147,12 +197,14 @@ The config path uses `HOME` when it is an absolute path. If `HOME` is missing or
147
197
 
148
198
  For each setting, the first configured source in that order wins:
149
199
 
150
- - `--ai-provider` / `HOWTO_AI_PROVIDER` / `aiProvider` - `openai` or `gemini`; no default.
200
+ - `--ai-provider` / `HOWTO_AI_PROVIDER` / `aiProvider` - `openai`, `gemini`, or `chatgpt`; no default.
201
+ - `--chatgpt-account` / `HOWTO_CHATGPT_ACCOUNT` / `chatgptAccount` - local ChatGPT registration ID; required when more than one account is saved.
202
+ - `--chatgpt-model` / `HOWTO_CHATGPT_MODEL` / `chatgptModel` - visible model slug from `--chatgpt-models`; no static default.
151
203
  - `--gemini-api-key` / `HOWTO_GEMINI_API_KEY` / `geminiApiKey` - Gemini API key; required for Gemini.
152
204
  - `--gemini-model` / `HOWTO_GEMINI_MODEL` / `geminiModel` - Gemini model; default `gemini-3.5-flash-lite`.
153
205
  - `--openai-api-url` / `HOWTO_OPENAI_API_URL` / `openaiApiUrl` - OpenAI-compatible base URL; defaults to `https://api.openai.com/v1`.
154
206
  - `--openai-api-key` / `HOWTO_OPENAI_API_KEY` / `openaiApiKey` - OpenAI API key; defaults to an empty string for local services.
155
- - `--openai-model` / `HOWTO_OPENAI_MODEL` / `openaiModel` - OpenAI model; default `gpt-5.4-mini`.
207
+ - `--openai-model` / `HOWTO_OPENAI_MODEL` / `openaiModel` - OpenAI model; default `gpt-6-luna`.
156
208
  - `--structured-output` / `HOWTO_STRUCTURED_OUTPUT` / `structuredOutput` - use provider schema structured output; default `true`.
157
209
 
158
210
  howto sets the request endpoint and Gemini API mode explicitly. `OPENAI_BASE_URL`, `GOOGLE_GEMINI_BASE_URL`, `GOOGLE_VERTEX_BASE_URL`, and the Google SDK's Vertex/Enterprise environment switches do not override them. Gemini uses the official `generativelanguage.googleapis.com` `v1beta` API. Use the HOWTO settings above for a custom OpenAI endpoint.
@@ -163,7 +215,7 @@ Example:
163
215
 
164
216
  ```bash
165
217
  HOWTO_AI_PROVIDER=openai \
166
- HOWTO_OPENAI_MODEL=gpt-5.4-mini \
218
+ HOWTO_OPENAI_MODEL=gpt-6-luna \
167
219
  howto --print "show current branch"
168
220
  ```
169
221
 
@@ -198,9 +250,11 @@ Homebrew uninstall aliases such as `rm/uninstal`, and yum/dnf upgrade or removal
198
250
 
199
251
  Linux checks also cover system package changes through apk, pacman, and zypper, and OpenRC service or runlevel changes, such as `apk upgrade`, `pacman -Syu`, `zypper dup`, `rc-service sshd stop`, and `rc-update del sshd`. Common queries and apk/zypper metadata refreshes keep ordinary confirmation; unsupported options, dynamic arguments, and additional service commands conservatively require `EXECUTE`. Query arguments are also checked: `zypper repos --export …`, which writes to a file, still requires additional confirmation.
200
252
 
201
- If howto detects bracketed paste during an interactive run, including automatic initialization, that run permanently switches to printing the final command for manual execution. At final confirmation, Enter prints the command without running it, and the terminal shows an explanation. Returning to selection or resizing the terminal does not restore execution. Keyboard-only runs keep the usual Enter or `EXECUTE` confirmation.
253
+ Pasting does not disable command execution or `use` lookups. API key, placeholder, and query argument fields accept complete paste blocks; CR/LF remain data and never submit a field. Submitting a field discards remaining keys and pastes from that input batch. Selection, query approval, and final confirmation screens ignore paste. Type `EXECUTE` on the keyboard for dangerous commands; execution still requires a separate confirmation.
202
254
 
203
- Paste spanning a hidden terminal view is discarded as a whole. These rules apply to recognized bracketed-paste input; the terminal protocol cannot authenticate arbitrary pasted keystrokes or embedded end markers. The execution restriction applies to howto's own command launch.
255
+ Paste containing unsupported control characters (including Tab), or spanning a field, screen, or hidden view, is discarded with an explanation. Each paste is limited to 256 KiB. An unfinished paste cancels the interaction after 5 seconds without new data or 30 seconds in total, restores the terminal, and exits with status 1 without executing a command.
256
+
257
+ These rules cover complete, valid bracketed paste. The terminal protocol cannot authenticate embedded end markers or delayed bytes after them, or reliably distinguish unframed paste from typing. Screen isolation does not guarantee that arbitrary forged protocol input cannot trigger execution.
204
258
 
205
259
  > [!WARNING]
206
260
  > A command that passes local checks and is not flagged by AI is not guaranteed to be safe. These checks add confirmation requirements; they do not provide a complete safety proof or guarantee AI assessment accuracy.
@@ -211,6 +265,8 @@ This project is built with TypeScript, React, Ink, OpenAI SDK, Gemini GenAI SDK,
211
265
 
212
266
  For development and the full test suite, use **Node.js 22.x (22.22.1 or later) or 24.x (24.3.0 or later)**. These versions satisfy the development dependencies.
213
267
 
268
+ Builds use TypeScript 7 through the `@typescript/native` npm alias. ESLint retains the TypeScript 6 JavaScript API through `typescript` → `@typescript/typescript6` (currently forwarding to 6.0.3), following the [official side-by-side setup](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0). Build scripts invoke the native compiler explicitly because incremental npm installs can change the shared `tsc` symlink. `npm run check:toolchain` verifies compiler versions, compatibility API resolution, and explicit build compiler paths. Run `npm run lint` to check project code with the existing type-aware rules. Keep both compilers compatible with the project until typescript-eslint supports the new API; this does not give ESLint TypeScript 7-only language support.
269
+
214
270
  ```bash
215
271
  npm ci
216
272
  npm run build
@@ -228,16 +284,19 @@ Useful paths:
228
284
  - `src/validation/` - AI response and command-tool validation.
229
285
  - `src/safety/` - dangerous command rules.
230
286
  - `src/ui/` - Ink-based terminal UI.
231
- - `tests/unit/` - unit tests for CLI argument parsing, configuration, validation, prompt building, and UI logic.
232
- - `tests/integration/` - integration tests for full CLI processes, loopback HTTP providers, and PTY sessions.
287
+ - `tests/unit/` - argument parsing, configuration merging, validation, prompts, pure UI logic and static rendering, and providers with dependency stubs.
288
+ - `tests/integration/` - filesystem and credential storage, real SDK serialization, Ink component interactions and complete UI flows, CLI processes, loopback HTTP providers, and PTY sessions.
289
+ - `tests/helpers/` - input streams, request data, and rendering helpers shared by both suites.
290
+
291
+ `npm test` runs both suites; use `npm run test:unit` or `npm run test:integration` to run one suite independently.
233
292
 
234
293
  ### Linux validation
235
294
 
236
295
  The 1.0.2 local validation used Debian 13.6 x86_64 in a Cloud container, Node 22.22.1 / 24.19.0, and real kernel PTYs with dash (`/bin/sh`), bash 5.2.37 and zsh 5.9. Both Node versions passed 719 tests without skips, including 42 PTY cases; stability rounds and additional boundary evidence are recorded in the validation report. The installed package was checked separately on Node 22.0.0 with npm 10.5.1. Evidence, fixes and coverage limits are recorded in the validation report delivered separately with this task.
237
296
 
238
- The full POSIX suite requires Python 3 available on `/usr/bin:/bin`, sh/bash/zsh, an allocatable PTY, and a non-root user for permission checks. Some Linux process-group checks use a subprocess supervisor and are explicitly inapplicable to macOS. Tests use isolated temporary homes and fake providers; they do not require API keys. To verify a separately installed package, run `npm run test:package -- /absolute/path/to/bin/howto`; this compiles and runs `tests/package-smoke.ts`, uses a local HTTP fixture, and only executes a harmless print command after confirmation. CI uploads the compiled smoke entry alongside the candidate package so the minimum-Node package check requires no development dependencies.
297
+ The full POSIX suite requires Python 3 available on `/usr/bin:/bin`, sh/bash/zsh, an allocatable PTY, and a non-root user for permission checks. Some Linux process-group checks use a subprocess supervisor and are explicitly inapplicable to macOS. Tests use isolated temporary homes and fake providers; they do not require API keys. To verify a separately installed package, run `npm run test:package -- /absolute/path/to/bin/howto`; this compiles and runs `tests/package-smoke.ts`, uses a local HTTP fixture, and only executes a harmless print command after confirmation.
239
298
 
240
- The CI configuration adds Ubuntu 24.04 with Node 22.22.1 / 24.19.0, macOS 14 regression, and installed-package checks on Node 22.0.0 / 24.19.0. These jobs were not run remotely in this local task. Alpine, native arm64, WSL, and real terminal-emulator visuals remain unverified; a PTY or a configured job is not evidence for those platforms. A separate environment passed bounded live Gemini native and OpenAI-compatible protocol smoke checks; native structured-output OFF, the default model, and the full live CLI remain unverified.
299
+ Test CI runs only on Ubuntu 24.04 with Node 24.19.0. Pushes run unit tests; pull requests and manual runs execute both unit and integration tests. All runs also build the project and check lint and formatting. macOS runners, Node 22 jobs, and installed-package smoke jobs are excluded from CI; the local package smoke command remains available. Alpine, native arm64, WSL, and real terminal-emulator visuals remain unverified; a PTY or a configured job is not evidence for those platforms. A separate environment passed bounded live Gemini native and OpenAI-compatible protocol smoke checks; native structured-output OFF, the default model, and the full live CLI remain unverified.
241
300
 
242
301
  ## Troubleshooting
243
302
 
@@ -22,7 +22,7 @@ _在终端中用 AI 快速找到可执行命令。_
22
22
  - **指定工具模式** - 使用 `howto use <command>` 要求候选项围绕某个 CLI 工具生成。
23
23
  - **交互式确认流程** - 选择候选项、填写占位符,并在执行前确认最终命令。
24
24
  - **非交互打印模式** - 使用 `--print` 输出候选命令,不进入 TTY 交互,也不执行命令。
25
- - **支持 OpenAI 和 Gemini** - 可通过 CLI 参数、环境变量或 `~/.howto/config.json` 配置 provider。
25
+ - **支持 ChatGPT、OpenAI 和 Gemini** - 可使用 ChatGPT 登录与符合条件的账户额度,也可继续使用 API key 和 OpenAI 兼容服务。
26
26
  - **本地优先校验** - 本地校验 AI JSON 输出、占位符引用、`use <command>` 候选项以及明显危险命令。
27
27
 
28
28
  ## 安装
@@ -61,6 +61,22 @@ howto --init
61
61
 
62
62
  初始化程序会把用户级配置写入 `~/.howto/config.json`。
63
63
 
64
+ 选择 **Continue with ChatGPT** 后,在系统浏览器完成登录和额度授权,再选择账号及该账号实时可用的模型。使用官方开源 Sign in with ChatGPT 流程,本机回调仅监听 `127.0.0.1`,无需 client secret 或安装 Codex。重新初始化会保留其他 provider 的 API key 和既有 `structuredOutput` 设置。
65
+
66
+ 也可单独管理账号:
67
+
68
+ ```bash
69
+ howto --chatgpt-login
70
+ howto --chatgpt-status
71
+ howto --chatgpt-models --chatgpt-account <账号ID>
72
+ howto --chatgpt-login --chatgpt-account <账号ID>
73
+ howto --chatgpt-logout --chatgpt-account <账号ID>
74
+ ```
75
+
76
+ 不带账号 ID 的登录会新增注册;指定 ID 则复用该注册重新登录。单独登录不改变 provider、默认账号或模型,使用 `howto --init` 保存选择。普通生成和 `--print` 不会自动打开登录页。模型来自该账号目录中的可见 slug,不自动换模型,也不回退到 API key 计费。
77
+
78
+ 凭证独立保存在 `~/.howto/chatgpt/`,目录仅本人可访问、文件仅本人可读写,刷新和注销跨进程互斥;`config.json` 只保存账号与模型选择。刷新响应丢失时需要重新登录,避免重放可能已经消费的旋转 token。注销会保留注册映射,并在远程撤销未确认时明确提示。额度及授权在 [ChatGPT 设置](https://chatgpt.com/settings/usage) 中管理;可用性取决于账号资格和当前模型目录,参见[官方开源流程](https://developers.openai.com/siwc/token-sharing-open-source)。
79
+
64
80
  初始化和占位符输入支持按完整字符退格,包括 emoji 和组合字符;Alt/Meta 快捷键不会作为文本写入配置字段。
65
81
  按键释放事件不会触发确认、取消、导航或再次删除;一次 Enter 的按下和释放不能跳过最终确认。
66
82
  终端将键盘文本与 Enter 合并送达时,输入仍按顺序处理;当前步骤结束后,同批剩余按键不能跳过下一页确认。粘贴中的换行保留为数据。
@@ -71,7 +87,7 @@ howto --init
71
87
  询问一个命令:
72
88
 
73
89
  ```bash
74
- howto 找到最近7天修改的文件 .
90
+ howto 找到当前目录中最近7天修改的文件
75
91
  ```
76
92
 
77
93
  限制候选项必须使用某个工具:
@@ -87,23 +103,46 @@ howto use git 看看上周的提交
87
103
  不进入交互 UI,只打印候选命令:
88
104
 
89
105
  ```bash
90
- howto --print 列出最大的文件 /var/log
106
+ howto --print 列出 /var/log 中最大的文件
107
+ ```
108
+
109
+ ### 通过 SSH 登录 ChatGPT
110
+
111
+ 在有浏览器的本地电脑上建立 SSH 连接和回环端口转发:
112
+
113
+ ```bash
114
+ ssh -o ExitOnForwardFailure=yes -L 127.0.0.1:1455:127.0.0.1:1455 user@server
115
+ ```
116
+
117
+ 进入远程 shell 后启动登录:
118
+
119
+ ```bash
120
+ howto --chatgpt-login --no-browser --callback-port 1455
91
121
  ```
92
122
 
123
+ 在本地浏览器打开输出的授权链接,保持 SSH 连接与 HowTo 运行,直到登录完成。将 `user@server` 替换为实际 SSH 目标。浏览器会回调本地电脑的 `127.0.0.1`,隧道再将回调转发给服务器上的 HowTo,无需向公网开放回调端口。服务器仍需能通过 HTTPS 访问 OpenAI 认证与 API 服务。
124
+
125
+ 若希望在同一次交互中完成登录并保存 provider、账号和模型选择,可改用 `howto --init --no-browser --callback-port 1455`,再选择 **Continue with ChatGPT**。初始化要求 TTY,独立登录命令不要求 TTY。
126
+
127
+ 两个选项均可单独使用,仅允许搭配 `--chatgpt-login` 或 `--init`,只影响本次调用。`--no-browser` 完全跳过浏览器启动器,已有账号重新登录时也会输出授权链接。`--callback-port` 接受 `1`–`65535` 的十进制整数;省略时随机分配可用端口,并输出对应端口的转发指引。选项不会写入配置,也不影响 API key provider。
128
+
129
+ 本地或远程端口无法绑定时,应选择另一个可用端口,同时修改隧道两端与 `--callback-port`;HowTo 不会静默替换明确指定的端口。已通过 SSH 连接时,可在另一个本地终端运行输出的 `ssh -N ...` 指令,再打开授权链接。登录最多等待 10 分钟,Ctrl+C 可取消并释放回调监听。登录后的普通请求和令牌刷新无需浏览器。本流程仍需在本地电脑的浏览器中授权,不使用设备码,也不接受粘贴回调地址。
130
+
93
131
  ## 使用
94
132
 
95
133
  ```text
96
- howto [options] [use <command>] <question> [<argument>...]
97
- howto --init
134
+ howto [options] [use <command>] <question...>
135
+ howto --init [--no-browser] [--callback-port <port>]
98
136
  howto --version
137
+ howto --chatgpt-login [--chatgpt-account <id>] [--no-browser] [--callback-port <port>]
99
138
  ```
100
139
 
101
140
  示例:
102
141
 
103
142
  ```bash
104
143
  howto 找到当前目录的package.json
105
- howto use find 寻找特定文件名的文件 package.json
106
- howto 解释这个命令 -- --force
144
+ howto use find 在 /tmp 中查找 report.txt
145
+ howto 解释这个选项 -- --force
107
146
  howto --ai-provider openai --print 列出监听的端口
108
147
  ```
109
148
 
@@ -112,7 +151,10 @@ howto --ai-provider openai --print 列出监听的端口
112
151
  - `--init` - 启动交互式 provider 配置,并保存 `~/.howto/config.json`。
113
152
  - `--version` - 单独使用,输出当前包版本号并成功退出;无需配置或 TTY,不调用 AI。
114
153
  - `--print` - 打印已校验的命令候选项并退出,不执行命令。
115
- - `--ai-provider <openai|gemini>` - 选择 AI provider。
154
+ - `--ai-provider <openai|gemini|chatgpt>` - 选择 AI provider。
155
+ - `--chatgpt-account <id>` / `--chatgpt-model <slug>` - 选择已保存的 ChatGPT 注册和当前可用模型。
156
+ - `--no-browser` - 跳过 ChatGPT 浏览器启动器并输出授权链接,仅用于 `--chatgpt-login` 或 `--init`。
157
+ - `--callback-port <port>` - 指定 ChatGPT 回环回调端口(`1`–`65535`,默认随机分配可用端口),仅用于 `--chatgpt-login` 或 `--init`。
116
158
  - `--gemini-api-key <key>` - 提供 Gemini API key。
117
159
  - `--gemini-model <model>` - 覆盖 Gemini 模型。
118
160
  - `--openai-api-url <url>` - 使用自定义 OpenAI 兼容 base URL。
@@ -122,17 +164,25 @@ howto --ai-provider openai --print 列出监听的端口
122
164
 
123
165
  ### 参数解析
124
166
 
125
- `question` 是一个 shell 参数。包含空格时需要加引号:
167
+ 全部问题片段以一个 ASCII 空格连接为 `question`。首个位置参数是 `use` 时,其后一个参数作为工具名,其余片段组成问题。全局选项在 `--` 之前仍可穿插使用,未知长选项报错;`--` 之后全部作为位置文本。
126
168
 
127
- ```bash
128
- howto "find recently changed files" /tmp
129
- ```
169
+ | 输入 | 最终 question |
170
+ | ------------------------------------------- | ---------------------------- |
171
+ | `howto list files changed today` | `list files changed today` |
172
+ | `howto "list files" /tmp` | `list files /tmp` |
173
+ | `howto use find find report.txt under /tmp` | `find report.txt under /tmp` |
174
+ | `howto list files --print` | `list files`,同时启用打印 |
175
+ | `howto explain -- --force` | `explain --force` |
176
+ | `howto find files "/tmp/my files"` | `find files /tmp/my files` |
177
+ | `howto "" " "` | 用法错误 |
130
178
 
131
- `question` 后面的内容会作为 `argument[]` 传给 AI。如果参数以 `--` 开头,请使用 `--` 结束 option 解析:
179
+ 片段内部的原始空格、换行及其他内容均保留。缺失或全空白问题在配置加载和 AI 请求之前返回退出码 `2` 与 Usage;仅用 `trim()` 判断是否全为空白,不修剪实际问题,不重建引号,也不额外传递分段信息。
132
180
 
133
- ```bash
134
- howto "explain this flag" -- --force
135
- ```
181
+ 模型根据完整问题识别路径、文件名、数量和选项。用途明确的值填入候选命令,缺失或含糊的必要值生成占位符,沿用现有填写和确认流程。
182
+
183
+ 原有带引号的问题仍可使用;原来的“问题 + 附加参数”写法会整体进入 `question`,不再保留参数分组语义。拼接后无法恢复 shell 参数边界,含空格路径由模型结合问题语义理解,建议明确描述路径的用途。
184
+
185
+ 免引号适用于普通提问文本。变量、通配符、重定向等特殊语法仍先由 shell 处理,需要传递字面内容时继续引用或转义。管理动作和重复选项规则保持不变,无需配置迁移。
136
186
 
137
187
  ## 配置
138
188
 
@@ -147,12 +197,14 @@ howto "explain this flag" -- --force
147
197
 
148
198
  对每个配置项,优先级中第一个已配置的来源生效:
149
199
 
150
- - `--ai-provider` / `HOWTO_AI_PROVIDER` / `aiProvider` - `openai` 或 `gemini`;无默认值。
200
+ - `--ai-provider` / `HOWTO_AI_PROVIDER` / `aiProvider` - `openai`、`gemini` 或 `chatgpt`;无默认值。
201
+ - `--chatgpt-account` / `HOWTO_CHATGPT_ACCOUNT` / `chatgptAccount` - 本机 ChatGPT 注册 ID;保存了多个账号时必须明确指定。
202
+ - `--chatgpt-model` / `HOWTO_CHATGPT_MODEL` / `chatgptModel` - `--chatgpt-models` 返回的可见模型 slug;没有固定默认值。
151
203
  - `--gemini-api-key` / `HOWTO_GEMINI_API_KEY` / `geminiApiKey` - Gemini API key;Gemini 必填。
152
204
  - `--gemini-model` / `HOWTO_GEMINI_MODEL` / `geminiModel` - Gemini 模型;默认 `gemini-3.5-flash-lite`。
153
205
  - `--openai-api-url` / `HOWTO_OPENAI_API_URL` / `openaiApiUrl` - OpenAI 兼容 base URL;默认 `https://api.openai.com/v1`。
154
206
  - `--openai-api-key` / `HOWTO_OPENAI_API_KEY` / `openaiApiKey` - OpenAI API key;默认为空字符串以支持本地服务。
155
- - `--openai-model` / `HOWTO_OPENAI_MODEL` / `openaiModel` - OpenAI 模型;默认 `gpt-5.4-mini`。
207
+ - `--openai-model` / `HOWTO_OPENAI_MODEL` / `openaiModel` - OpenAI 模型;默认 `gpt-6-luna`。
156
208
  - `--structured-output` / `HOWTO_STRUCTURED_OUTPUT` / `structuredOutput` - 使用 provider schema 结构化输出;默认 `true`。
157
209
 
158
210
  请求地址和 Gemini API 模式由 howto 显式设置。`OPENAI_BASE_URL`、`GOOGLE_GEMINI_BASE_URL`、`GOOGLE_VERTEX_BASE_URL` 及 Google SDK 的 Vertex/Enterprise 模式环境开关不会改写它们。Gemini 使用官方 `generativelanguage.googleapis.com` 的 `v1beta` API;自定义 OpenAI 地址请使用上述 HOWTO 配置项。
@@ -163,7 +215,7 @@ OpenAI 的 Authorization 使用 howto 配置的 key,空白 key 时不发送该
163
215
 
164
216
  ```bash
165
217
  HOWTO_AI_PROVIDER=openai \
166
- HOWTO_OPENAI_MODEL=gpt-5.4-mini \
218
+ HOWTO_OPENAI_MODEL=gpt-6-luna \
167
219
  howto --print "show current branch"
168
220
  ```
169
221
 
@@ -198,9 +250,11 @@ Homebrew 的 `rm/uninstal` 卸载别名,以及 yum/dnf 的 `update/erase` 升
198
250
 
199
251
  Linux 还覆盖 apk、pacman、zypper 的系统包变更及 OpenRC 的服务和运行级别变更,例如 `apk upgrade`、`pacman -Syu`、`zypper dup`、`rc-service sshd stop`、`rc-update del sshd`。常见查询及 apk/zypper 索引更新保留普通确认;未支持的选项、动态参数和额外服务命令保守要求 `EXECUTE`。查询动作也检查参数,例如会写入文件的 `zypper repos --export …` 仍需额外确认。
200
252
 
201
- 一次交互调用中只要识别到 bracketed paste(包括自动初始化阶段),本次调用就永久改为输出最终命令供手动运行。最终确认页按 Enter 只输出命令,终端会显示说明;返回候选选择或调整终端大小都不会恢复执行权限。全程键盘输入仍使用原有的 Enter 或 `EXECUTE` 确认。
253
+ 交互粘贴不会关闭命令执行或 `use` 用法查询。API key、占位符和查询参数编辑字段接收完整粘贴,CR/LF 作为数据保留,不触发提交;每个字段提交后,同批剩余按键和粘贴都会丢弃。候选选择、查询审批及最终确认页忽略粘贴,危险确认短语 `EXECUTE` 必须键盘输入,最终执行仍需独立确认。
202
254
 
203
- 跨越终端视图隐藏阶段的粘贴会整块丢弃。这些规则针对已识别的 bracketed-paste 输入;终端协议无法认证任意粘贴按键或内容中的结束标记。执行限制针对 howto 自身启动候选命令的行为。
255
+ 包含禁用控制字符(包括 Tab),或跨越字段、页面、隐藏阶段的粘贴整块丢弃,终端会显示原因。每块粘贴最多 256 KiB;未闭合粘贴连续 5 秒无新数据或总时长达到 30 秒时,howto 会取消本次交互、恢复终端并退出 1,不执行命令。
256
+
257
+ 这些规则针对完整有效的 bracketed-paste 输入。终端协议无法认证内容中的伪结束标记及其后延迟字节,也不能严格区分未使用该协议的粘贴与连续键入;页面隔离不构成任意伪造输入均不能触发执行的保证。
204
258
 
205
259
  > [!WARNING]
206
260
  > 静态检查未命中且 AI 未标记危险,也不表示命令一定安全。两者用于增加确认要求,不构成完整安全证明或 AI 判断准确率保证。
@@ -211,6 +265,8 @@ Linux 还覆盖 apk、pacman、zypper 的系统包变更及 OpenRC 的服务和
211
265
 
212
266
  开发和运行完整测试使用 **Node.js 22.x(22.22.1 及以上)或 24.x(24.3.0 及以上)**。这些版本满足开发依赖的要求。
213
267
 
268
+ 构建使用 `@typescript/native` npm alias 提供的 TypeScript 7;ESLint 通过 `typescript` → `@typescript/typescript6` 保留 TypeScript 6 JavaScript API(目前转发到 6.0.3),采用[官方双版本方案](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0)。构建脚本显式调用原生编译器,避免增量 npm 安装改变共享 `tsc` 链接。`npm run check:toolchain` 检查编译器版本、兼容 API 解析和显式构建编译器路径。使用 `npm run lint` 按现有类型感知规则检查项目代码。在 typescript-eslint 支持新 API 前,需要保持项目同时兼容两套编译器;这不会让 ESLint 获得 TypeScript 7 独有语法的支持。
269
+
214
270
  ```bash
215
271
  npm ci
216
272
  npm run build
@@ -228,16 +284,19 @@ npm run format:check
228
284
  - `src/validation/` - AI 响应和命令工具校验。
229
285
  - `src/safety/` - 危险命令规则。
230
286
  - `src/ui/` - 基于 Ink 的终端 UI。
231
- - `tests/unit/` - CLI 参数解析、配置、校验、Prompt 构建与 UI 状态的单元测试。
232
- - `tests/integration/` - 完整 CLI 进程、本地回环 HTTP Provider 及 PTY 终端会话的集成测试。
287
+ - `tests/unit/` - 参数解析、配置合并、校验、Prompt、UI 纯逻辑与静态渲染,以及使用依赖替身的 provider 测试。
288
+ - `tests/integration/` - 文件系统与凭据存储、真实 SDK 序列化、Ink 组件交互及完整 UI 流程、CLI 进程、本地回环 HTTP Provider 与 PTY 终端会话测试。
289
+ - `tests/helpers/` - 两类测试共享的输入流、请求数据及渲染辅助工具。
290
+
291
+ `npm test` 运行单元与集成测试;仅运行其中一类可使用 `npm run test:unit` 或 `npm run test:integration`。
233
292
 
234
293
  ### Linux 验证范围
235
294
 
236
295
  1.0.2 本地验证使用 Cloud 容器中的 Debian 13.6 x86_64、Node 22.22.1 / 24.19.0,以及 dash(`/bin/sh`)、bash 5.2.37、zsh 5.9 和真实内核 PTY。两个 Node 版本均通过 719 项测试且无跳过,其中 42 项为 PTY 用例;稳定性轮次和新增边界证据见验收报告。已安装发行包另以 Node 22.0.0 和 npm 10.5.1 验证。证据、修复及覆盖边界记录在随本次任务单独交付的验收报告中。
237
296
 
238
- 完整 POSIX 测试需要 `/usr/bin:/bin` 中可找到的 Python 3、sh/bash/zsh、可分配的 PTY,以及用于权限检查的非 root 用户。部分 Linux 进程组测试使用监督子进程,明确不适用于 macOS。测试使用隔离临时主目录和假 provider,不需要 API Key。单独验证已安装包可运行 `npm run test:package -- /absolute/path/to/bin/howto`;该命令将 `tests/package-smoke.ts` 编译后运行,使用本地 HTTP fixture,确认后只执行无害打印命令。CI 随候选包上传编译后的验收入口,最低 Node 版本的包验收无需安装开发依赖。
297
+ 完整 POSIX 测试需要 `/usr/bin:/bin` 中可找到的 Python 3、sh/bash/zsh、可分配的 PTY,以及用于权限检查的非 root 用户。部分 Linux 进程组测试使用监督子进程,明确不适用于 macOS。测试使用隔离临时主目录和假 provider,不需要 API Key。单独验证已安装包可运行 `npm run test:package -- /absolute/path/to/bin/howto`;该命令将 `tests/package-smoke.ts` 编译后运行,使用本地 HTTP fixture,确认后只执行无害打印命令。
239
298
 
240
- CI 配置已增加 Ubuntu 24.04 的 Node 22.22.1 / 24.19.0、macOS 14 回归,以及 Node 22.0.0 / 24.19.0 已安装包检查。本地任务未运行这些远端 job。Alpine、原生 arm64、WSL、真实终端模拟器视觉体验仍未验收;PTY 或已配置的 job 不能替代这些平台的运行证据。独立新版环境已完成有限的 Gemini 原生及 OpenAI 兼容协议实网烟测;原生结构化 OFF、默认模型和完整 CLI 实网仍未验证。
299
+ 测试 CI 统一使用 Ubuntu 24.04 和 Node 24.19.0。推送仅运行单元测试,PR 和手动触发运行单元测试及集成测试;所有触发均保留构建、Lint 和格式检查。CI 不再使用 macOS Runner、Node 22 或独立的安装包烟测 job,本地包验收命令继续保留。Alpine、原生 arm64、WSL、真实终端模拟器视觉体验仍未验收;PTY 或已配置的 job 不能替代这些平台的运行证据。独立新版环境已完成有限的 Gemini 原生及 OpenAI 兼容协议实网烟测;原生结构化 OFF、默认模型和完整 CLI 实网仍未验证。
241
300
 
242
301
  ## 故障排查
243
302
 
@@ -9,6 +9,7 @@ Each dependency is distributed under its own license.
9
9
  | --------------- | -------- | ---------- |
10
10
  | `@google/genai` | `2.18.0` | Apache-2.0 |
11
11
  | `ink` | `7.1.1` | MIT |
12
+ | `jose` | `6.2.13` | MIT |
12
13
  | `openai` | `7.5.0` | Apache-2.0 |
13
14
  | `react` | `19.2.8` | MIT |
14
15
  | `signal-exit` | `3.0.7` | ISC |
@@ -0,0 +1,148 @@
1
+ import { getChatGptAccessToken } from "../auth/chatgpt/index.js";
2
+ import { ChatGptError, classifyChatGptHttpError } from "../auth/chatgpt/errors.js";
3
+ import { ConfigError } from "../config.js";
4
+ import { hasUnsafeTerminalControlCharacters } from "../terminal-text.js";
5
+ import { InteractionCancelledError } from "../ui/tty.js";
6
+ import { AiProviderError, UsageToolsUnsupportedError } from "./errors.js";
7
+ const MODEL_CATALOG_URL = "https://api.openai.com/v1/models";
8
+ const MAX_CATALOG_BYTES = 1024 * 1024;
9
+ const MAX_ERROR_BYTES = 64 * 1024;
10
+ const REQUEST_TIMEOUT_MILLISECONDS = 120_000;
11
+ export async function listChatGptModels(options = {}, dependencies = {}) {
12
+ return runChatGptRequest("models", options.signal, dependencies, async (signal) => {
13
+ const credentials = await (dependencies.getAccessToken ?? getChatGptAccessToken)({
14
+ accountId: options.accountId,
15
+ signal,
16
+ });
17
+ return requestChatGptModels(credentials.accessToken, signal, dependencies.fetch ?? globalThis.fetch);
18
+ });
19
+ }
20
+ export async function requestChatGptModels(accessToken, signal, fetch) {
21
+ signal.throwIfAborted();
22
+ const response = await fetch(MODEL_CATALOG_URL, {
23
+ method: "GET",
24
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
25
+ redirect: "error",
26
+ signal,
27
+ });
28
+ if (!response.ok) {
29
+ throw await chatGptHttpError(response, signal);
30
+ }
31
+ return parseChatGptModels(await readChatGptJson(response, signal, MAX_CATALOG_BYTES));
32
+ }
33
+ export function parseChatGptModels(value) {
34
+ if (!isRecord(value) || !Array.isArray(value.models)) {
35
+ throw new AiProviderError("chatgpt", "models");
36
+ }
37
+ const models = [];
38
+ const slugs = new Set();
39
+ for (const entry of value.models) {
40
+ if (!isRecord(entry))
41
+ throw new AiProviderError("chatgpt", "models");
42
+ if (entry.visibility !== "list")
43
+ continue;
44
+ if (!isModelLabel(entry.slug) || !isModelLabel(entry.display_name) || slugs.has(entry.slug)) {
45
+ throw new AiProviderError("chatgpt", "models");
46
+ }
47
+ models.push({ slug: entry.slug, displayName: entry.display_name });
48
+ slugs.add(entry.slug);
49
+ }
50
+ return models;
51
+ }
52
+ function isModelLabel(value) {
53
+ return (typeof value === "string" &&
54
+ value.trim() !== "" &&
55
+ value === value.trim() &&
56
+ value.length <= 256 &&
57
+ !/[\r\n]/.test(value) &&
58
+ !hasUnsafeTerminalControlCharacters(value));
59
+ }
60
+ export function isRecord(value) {
61
+ return typeof value === "object" && value !== null && !Array.isArray(value);
62
+ }
63
+ // 统一限制整个操作(凭证、模型目录和推理)的时长,并在出口隔离原始异常。
64
+ export async function runChatGptRequest(model, signal, dependencies, operation) {
65
+ if (signal?.aborted)
66
+ throw new InteractionCancelledError();
67
+ const controller = new AbortController();
68
+ const cancel = () => controller.abort();
69
+ signal?.addEventListener("abort", cancel, { once: true });
70
+ let rejectAborted;
71
+ const aborted = new Promise((_, reject) => {
72
+ rejectAborted = () => reject(new AiProviderError("chatgpt", model));
73
+ });
74
+ controller.signal.addEventListener("abort", rejectAborted, { once: true });
75
+ const timeout = setTimeout(cancel, dependencies.timeoutMilliseconds ?? REQUEST_TIMEOUT_MILLISECONDS);
76
+ try {
77
+ const result = await Promise.race([operation(controller.signal), aborted]);
78
+ controller.signal.throwIfAborted();
79
+ return result;
80
+ }
81
+ catch (error) {
82
+ if (signal?.aborted || error instanceof InteractionCancelledError) {
83
+ throw new InteractionCancelledError();
84
+ }
85
+ if (error instanceof ChatGptError ||
86
+ error instanceof ConfigError ||
87
+ error instanceof UsageToolsUnsupportedError)
88
+ throw error;
89
+ throw new AiProviderError("chatgpt", model);
90
+ }
91
+ finally {
92
+ clearTimeout(timeout);
93
+ signal?.removeEventListener("abort", cancel);
94
+ controller.signal.removeEventListener("abort", rejectAborted);
95
+ controller.abort();
96
+ }
97
+ }
98
+ export async function chatGptHttpError(response, signal) {
99
+ let code;
100
+ try {
101
+ const body = await readChatGptJson(response, signal, MAX_ERROR_BYTES);
102
+ if (isRecord(body) && isRecord(body.error) && typeof body.error.code === "string") {
103
+ code = body.error.code;
104
+ }
105
+ }
106
+ catch {
107
+ // 非 JSON、过大或 detail 字符串错误只按状态分类,不展示上游正文。
108
+ }
109
+ return classifyChatGptHttpError(response.status, code);
110
+ }
111
+ async function readChatGptJson(response, signal, maximumBytes) {
112
+ const decoder = new TextDecoder("utf-8", { fatal: true });
113
+ let text = "";
114
+ for await (const bytes of readChatGptBody(response, signal, maximumBytes)) {
115
+ text += decoder.decode(bytes, { stream: true });
116
+ }
117
+ text += decoder.decode();
118
+ return JSON.parse(text);
119
+ }
120
+ // 字节上限位于 JSON/SSE 解码之前,避免单个未结束事件无限占用内存。
121
+ export async function* readChatGptBody(response, signal, maximumBytes) {
122
+ if (response.body === null)
123
+ throw new Error("Missing response body");
124
+ const reader = response.body.getReader();
125
+ const cancel = () => {
126
+ void reader.cancel().catch(() => undefined);
127
+ };
128
+ signal.addEventListener("abort", cancel, { once: true });
129
+ let received = 0;
130
+ try {
131
+ while (true) {
132
+ signal.throwIfAborted();
133
+ const chunk = await reader.read();
134
+ signal.throwIfAborted();
135
+ if (chunk.done)
136
+ return;
137
+ received += chunk.value.byteLength;
138
+ if (received > maximumBytes)
139
+ throw new Error("Response body too large");
140
+ yield chunk.value;
141
+ }
142
+ }
143
+ finally {
144
+ signal.removeEventListener("abort", cancel);
145
+ cancel();
146
+ reader.releaseLock();
147
+ }
148
+ }