cannbot-pilot 0.0.0-stage → 2.0.5

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 CHANGED
@@ -1,3 +1,175 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # cannbot
2
+
3
+ A terminal launcher for AI coding agents (starting with [opencode](https://opencode.ai)), built with [OpenTUI](https://github.com/msmps/opentui) and React, running on [Bun](https://bun.sh/). This repository is the new home of the `cannbot` npm package; releases go through three names — verification `cannbot-rehearsal`, pilot `cannbot-pilot` (current), and finally the official `cannbot`, whose switch will be handled by a subsequent change. The package ships a standalone TUI binary named `cannbot` and bundles the agent binary from the `cannbot-cli` repository as `cannbot-cli`. The project's upstream code repository is <https://gitcode.com/cann-dev/cannbot-ai>.
4
+
5
+ ## User guide (Chinese)
6
+
7
+ End-user documentation — install, login, sessions, groups, commands, shortcuts, data and troubleshooting — lives in [`docs/user-guide/`](https://gitcode.com/cann-dev/cannbot-ai/tree/main/docs/user-guide). Start with the [index](https://gitcode.com/cann-dev/cannbot-ai/blob/main/docs/user-guide/README.md) or jump straight to [Getting started](https://gitcode.com/cann-dev/cannbot-ai/blob/main/docs/user-guide/getting-started.md).
8
+
9
+ ## Requirements
10
+
11
+ - [Bun](https://bun.sh/) **1.3.0** or later — to run from source and to build
12
+ - Node.js 18+ — only to launch the tiny `cannbot` shim when installed from npm; the packaged executable embeds its own runtime and does not need Bun
13
+
14
+ ## Install
15
+
16
+ Pilot release (package `cannbot-pilot`, version from the root manifest; the installed command is still `cannbot`):
17
+
18
+ ```bash
19
+ npm install -g cannbot-pilot
20
+ # or run without installing
21
+ npx cannbot-pilot
22
+ ```
23
+
24
+ The official name `cannbot` will use the same command once the pilot release is promoted.
25
+
26
+ The npm package ships standalone executables per platform. Supported platforms:
27
+
28
+ | Platform | Suffix |
29
+ | --- | --- |
30
+ | Windows x64 | `windows-x64` |
31
+ | Windows x64 (AVX2 baseline) | `windows-x64-baseline` |
32
+ | Windows arm64 | `windows-arm64` |
33
+ | Linux x64 (glibc) | `linux-x64` |
34
+ | Linux x64 (glibc, AVX2 baseline) | `linux-x64-baseline` |
35
+ | Linux arm64 (glibc) | `linux-arm64` |
36
+ | Linux x64 (musl) | `linux-x64-musl` |
37
+ | Linux x64 (musl, AVX2 baseline) | `linux-x64-baseline-musl` |
38
+ | Linux arm64 (musl) | `linux-arm64-musl` |
39
+ | macOS x64 | `darwin-x64` |
40
+ | macOS x64 (AVX2 baseline) | `darwin-x64-baseline` |
41
+ | macOS arm64 | `darwin-arm64` |
42
+
43
+ The 12 suffixes map one-to-one to the built-in cannbot-cli variants. During the pilot the installed platform package is `cannbot-pilot-<suffix>`; after promotion to the official name it is `cannbot-<suffix>`. The launcher detects AVX2 and musl at startup and picks the matching variant, falling back to the other same-platform variants if the first choice is missing.
44
+
45
+ Notes:
46
+
47
+ - The installed command is `cannbot` (the launcher is `bin/cannbot.js`).
48
+ - Do not install with `--omit=optional`: the matching platform package is an optional dependency.
49
+ - Each platform package contains two executables in `bin/`: the TUI binary `cannbot` (`cannbot.exe` on Windows) and the built-in agent `cannbot-cli` (`cannbot-cli.exe` on Windows). The launcher never falls back to a `cannbot-cli` found on your `PATH`; if the bundled file is missing, launching `cannbot` fails with an inline error instead of starting a session. Expect the download/install size to grow by roughly 170 MB per platform.
50
+ - Linux ships both glibc and musl variants; Alpine/musl is selected automatically at startup. Machines without AVX2 use the `-baseline` variant (x64 only).
51
+ - The macOS binaries (both `cannbot` and `cannbot-cli`) are not codesigned/notarized. If Gatekeeper blocks them, clear the quarantine flag:
52
+ ```bash
53
+ for bin in cannbot cannbot-cli; do
54
+ xattr -d com.apple.quarantine "$(npm root -g)/cannbot-pilot-darwin-arm64/bin/$bin" 2>/dev/null || true
55
+ done
56
+ ```
57
+ If macOS still rejects the binary, ad-hoc re-sign it: `codesign --force --sign - "<path-to-binary>"`.
58
+
59
+ ### Command-line flags
60
+
61
+ ```bash
62
+ cannbot -h, --help # print usage and exit
63
+ cannbot -v, --version # print the installed version and exit
64
+ cannbot acp [args...] # start the built-in cannbot-cli ACP server
65
+ ```
66
+
67
+ Both flags are answered locally by the launcher before it resolves or starts the platform executable, so they also work when the platform package is missing. If both are given, help takes precedence over the version output.
68
+
69
+ `cannbot acp` does not start the TUI. The launcher locates the built-in `cannbot-cli` executable (`cannbot-cli.exe` on Windows) in the same platform package and passes `acp` plus all remaining arguments through unchanged, forwarding its exit code. This path never answers `-h`/`--help`/`-v`/`--version` locally and never runs the update check, so ACP stdio stays clean. If the built-in `cannbot-cli` is missing or empty, the command fails with a diagnostic instead of falling back to the TUI binary or to a `cannbot-cli` found on `PATH`.
70
+
71
+ ### Automatic update check
72
+
73
+ When you run `cannbot` in an interactive terminal, the launcher asks the npm registry whether a newer version exists. If one does, it prompts before the TUI starts:
74
+
75
+ - `[1] 更新` — runs `npm install -g <package>@latest` in place, then asks you to run `cannbot` again
76
+ - `[2] 跳过` — skips this time only; the same version will be offered again next launch
77
+ - `[3] 跳过此版本` — remembers this version and stops prompting for it (a newer version still prompts)
78
+
79
+ The check is skipped entirely for `cannbot -v` / `cannbot --version` / `cannbot -h` / `cannbot --help` / `cannbot acp`, on non-interactive terminals (stdin or stdout not a TTY), or when `CANNBOT_NO_UPDATE_CHECK=1` is set. Network failures never block startup — the launcher simply continues with the installed version.
80
+
81
+ ## Getting Started (from source)
82
+
83
+ Install dependencies:
84
+
85
+ ```bash
86
+ bun install
87
+ ```
88
+
89
+ Start the app in watch mode:
90
+
91
+ ```bash
92
+ bun dev
93
+ ```
94
+
95
+ `bun dev` has no bundled cannbot-cli binary: `process.execPath` is Bun itself, so the launcher cannot find a sibling `cannbot-cli`. To exercise the cannbot agent from source, build cannbot-cli first and point the override at it:
96
+
97
+ ```bash
98
+ # in ../cannbot-cli
99
+ cd packages/opencode && bun run build
100
+ # back in this repository
101
+ CANNBOT_CLI_BIN="../cannbot-cli/packages/opencode/dist/cannbot-<os>-<arch>/bin/cannbot-cli" bun dev
102
+ ```
103
+
104
+ Without the override, launching `cannbot` shows an inline error and does not create a session; it never falls back to `cannbot-cli` on `PATH`.
105
+
106
+ ## Credentials and login
107
+
108
+ - The access token stays in process memory only and is never written to `~/.cannbot-tui/cannbot.json`.
109
+ - The refresh token is encrypted with AES-256-GCM using a key derived from a stable machine fingerprint, then stored as `refreshTokenEnc`; `refreshTokenSavedAt` records when it was written and is metadata only.
110
+ - If the machine fingerprint changes (host identity or OS user), the stored refresh token can no longer be decrypted and you need to log in again.
111
+ - Multi-instance refreshes are serialized through a SQLite lease lock (`token_refresh_lock`). If the local database is unavailable, the launcher falls back to best-effort refreshes.
112
+
113
+ ## Scripts
114
+
115
+ | Script | Description |
116
+ | --- | --- |
117
+ | `bun dev` | Run the app with auto-reload on file changes |
118
+ | `bun run typecheck` | Type-check the source with `tsc --noEmit` |
119
+ | `bun run test` | Run the fast test suite (excludes the publish E2E test) |
120
+ | `bun run test:publish` | Run only the publish E2E test (`test/publish-all.test.ts`) |
121
+ | `bun run test:all` | Run the full test suite, including publish E2E |
122
+ | `bun run build` | Build a JS bundle (requires Bun on the target machine) |
123
+ | `bun run build:exe` | Build a standalone executable for the current platform |
124
+ | `bun run build:publish` | Cross-compile all 12 platform variants and assemble `dist/publish/<pkg>/` |
125
+ | `bun run release` | Check → build → publish all packages (sub-packages first) |
126
+
127
+ `bun test test/` (direct invocation) equals the full suite. Use `bun run test` for normal development; the release pre-check and `prepublishOnly` always run `bun run test:all`, so publish E2E tests still gate releases. New publish E2E tests should be added to the `test:publish` script.
128
+
129
+ Build artifacts are written to `dist/`.
130
+
131
+ `build:publish` prepares any missing target-platform native packages (`@opentui/core-*`) automatically by fetching them from npm into `node_modules`, so the build machine needs network access on first run. Pass `--manifests-only` to assemble manifests without compiling.
132
+
133
+ It also bundles **cannbot-cli** from a local `cannbot-cli` checkout. All twelve `packages/opencode/dist/<target>/package.json` manifests must declare a `version` equal to this repository's root `package.json` version (the release version), and the twelve target artifacts must already be built under `packages/opencode/dist/<target>/bin/`. Source resolution prefers `cannbot-cli` (`cannbot-cli.exe` on Windows) and falls back to the legacy `cannbot` (`cannbot.exe`) with a warning; the packaged file is always renamed to `cannbot-cli` (`cannbot-cli.exe`). This repository does not compile cannbot-cli: build those artifacts in `cannbot-cli` first. By default it looks for `<repo>/../cannbot-cli` and then `<repo>/../../cannbot-cli` (no global search); use `--cannbot-cli-dir <dir>` (or `CANNBOT_CLI_DIR`) to name a checkout explicitly. Explicit/env sources that are invalid abort immediately instead of falling back. A dirty checkout is not checked. Missing or empty target artifacts abort packaging before any upload.
134
+
135
+ ## Maintainer release runbook
136
+
137
+ Releases are published **manually by the maintainer** to <https://registry.npmjs.org/>. The current pilot release uses `cannbot-pilot` (version from the root manifest) and its 12 platform packages; after the pilot the root `name` switches to the official `cannbot` and the same 13-package flow is repeated. AI assistants and other automation must not run a real release — they may only read release files, run checks/tests/builds, and use `--dry-run`.
138
+
139
+ 1. Set `version` to the target release version and keep `name` as `cannbot-pilot` for the pilot (single source of truth); the official `cannbot` switch is handled by a subsequent change. The script never bumps the version or creates git tags for you. Make sure a local `cannbot-cli` checkout has the twelve prebuilt artifacts under `packages/opencode/dist/`, each with its `package.json` `version` set to the same target release version, and is reachable as `../cannbot-cli` / `../../cannbot-cli`, or pass `--cannbot-cli-dir <dir>`.
140
+ 2. `npm login` with an account that holds publish rights for the pilot name / official name.
141
+ 3. Optional preview: `bun run release --dry-run`. It prints the release plan (package names, version, package count, sub-packages-before-main order), runs typecheck + tests, cross-compiles, and verifies the packed artifacts **without uploading or asking for confirmation**.
142
+ 4. Real release: run `bun run release` in an **interactive terminal**. After checks, build, and artifact verification it prints the same plan and asks `确认发布 <name>@<version>…`; only `y` / `yes` continues. Any other input (including an empty line) cancels with exit code 0 and uploads nothing.
143
+ 5. The script publishes the 12 platform packages first, then the main package, and finally queries the registry for every package. It succeeds only when all 13 target versions are `live`. The check runs in concurrent rounds (default 30 rounds, 1 minute apart), prints per-round progress, and forces `npm view --prefer-online` so cached packuments cannot mask propagation. If any package is still staged (`0.0.0-stage`) or the query fails after the last round, the command exits non-zero, names the package, and tells you to wait for npm to promote it (or approve it on npmjs.com) before smoke-testing.
144
+ 6. Smoke-test in a clean directory: `npx cannbot-pilot` (the official `npx cannbot` smoke belongs to the subsequent switch change).
145
+ 7. Tag the release yourself (tagging is intentionally outside the script):
146
+ ```bash
147
+ git tag <version>
148
+ ```
149
+
150
+ ### Release script options
151
+
152
+ - `--dry-run` — plan, check, build, and pack without uploading or confirming.
153
+ - `--yes` — skip the interactive confirmation. Only for rehearsals or explicitly authorized automation; a real release without a TTY is rejected unless this flag is present.
154
+ - `--no-build` / `--skip-checks` — reuse existing artifacts / skip typecheck and tests (use with care).
155
+ - `--check-rounds <n>` — maximum registry-check rounds after publishing (default `30`).
156
+ - `--check-interval-ms <n>` — wait between registry-check rounds in milliseconds (default `60000`).
157
+ - `--root <dir>` — run against another checkout.
158
+ - `--cannbot-cli-dir <dir>` — use a specific local `cannbot-cli` checkout whose twelve `dist/<target>/package.json` manifests match this repository's version, with the twelve prebuilt `cannbot-cli` artifacts under `packages/opencode/dist/`, instead of the fixed probe order.
159
+
160
+ Rollback: `npm unpublish` the affected version within the allowed window; afterwards `npm deprecate` and publish a fixed version.
161
+
162
+ ## Project Structure
163
+
164
+ ```
165
+ ├── bin/
166
+ │ ├── cannbot.js # Node-compatible launcher shipped in the npm main package (`cannbot` command)
167
+ │ └── update-check.js # Pre-launch version check, prompt and global install
168
+ ├── scripts/ # cross-platform build and publish tooling
169
+ ├── src/
170
+ │ └── index.tsx # App entry, renders the TUI with @opentui/react
171
+ ├── openspec/ # OpenSpec change management workspace
172
+ ├── dist/ # Build output
173
+ ├── package.json
174
+ └── tsconfig.json
175
+ ```
package/bin/cannbot.js ADDED
@@ -0,0 +1,472 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import {
5
+ accessSync,
6
+ chmodSync,
7
+ constants,
8
+ readFileSync,
9
+ realpathSync,
10
+ statSync,
11
+ } from "node:fs";
12
+ import { dirname, join, resolve } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import {
15
+ askUpdateChoice,
16
+ checkForUpdate,
17
+ DISABLE_UPDATE_CHECK_ENV,
18
+ formatUpdateNotice,
19
+ manualInstallCommand,
20
+ readSkippedVersion,
21
+ runGlobalInstall,
22
+ writeSkippedVersion,
23
+ } from "./update-check.js";
24
+
25
+ // 12 个受支持平台变体,与 scripts/publish-layout.ts 的 PLATFORM_TARGETS 一一对应。
26
+ // 顺序与 cannbot-cli packages/opencode/script/build.ts 的 allTargets 一致。
27
+ export const SUPPORTED_TARGETS = Object.freeze([
28
+ "windows-x64",
29
+ "windows-x64-baseline",
30
+ "windows-arm64",
31
+ "linux-x64",
32
+ "linux-x64-baseline",
33
+ "linux-arm64",
34
+ "linux-x64-musl",
35
+ "linux-x64-baseline-musl",
36
+ "linux-arm64-musl",
37
+ "darwin-x64",
38
+ "darwin-x64-baseline",
39
+ "darwin-arm64",
40
+ ]);
41
+
42
+ const PLATFORM_SEGMENTS = Object.freeze({
43
+ win32: "windows",
44
+ darwin: "darwin",
45
+ linux: "linux",
46
+ });
47
+
48
+ const ARCH_SEGMENTS = Object.freeze({
49
+ x64: "x64",
50
+ arm64: "arm64",
51
+ arm: "arm",
52
+ });
53
+
54
+ export function platformSegment(os) {
55
+ return PLATFORM_SEGMENTS[os] ?? os;
56
+ }
57
+
58
+ export function archSegment(arch) {
59
+ return ARCH_SEGMENTS[arch] ?? arch;
60
+ }
61
+
62
+ function isValidMainName(name) {
63
+ if (typeof name !== "string" || name.length === 0) return false;
64
+ if (name.startsWith("@")) {
65
+ const slash = name.indexOf("/");
66
+ return slash > 1 && slash < name.length - 1;
67
+ }
68
+ return true;
69
+ }
70
+
71
+ export function subPackageName(mainName, suffix) {
72
+ if (!isValidMainName(mainName)) return null;
73
+ if (typeof suffix !== "string" || suffix.length === 0) return null;
74
+ return `${mainName}-${suffix}`;
75
+ }
76
+
77
+ // 候选变体后缀,规则与 cannbot-cli 的 bin/cannbot 入口脚本一致:
78
+ // baseline 仅对 x64 生效;musl 仅在 Linux 生效;候选按固定优先级降级。
79
+ export function candidateVariantSuffixes(platform, arch, options = {}) {
80
+ const avx2 = options.avx2 !== false;
81
+ const musl = options.musl === true;
82
+ const baseline = arch === "x64" && !avx2;
83
+ const base = `${platform}-${arch}`;
84
+
85
+ if (platform === "linux") {
86
+ if (musl) {
87
+ if (arch === "x64") {
88
+ return baseline
89
+ ? [`${base}-baseline-musl`, `${base}-musl`, `${base}-baseline`, base]
90
+ : [`${base}-musl`, `${base}-baseline-musl`, base, `${base}-baseline`];
91
+ }
92
+ return [`${base}-musl`, base];
93
+ }
94
+ if (arch === "x64") {
95
+ return baseline
96
+ ? [`${base}-baseline`, base, `${base}-baseline-musl`, `${base}-musl`]
97
+ : [base, `${base}-baseline`, `${base}-musl`, `${base}-baseline-musl`];
98
+ }
99
+ return [base, `${base}-musl`];
100
+ }
101
+
102
+ if (arch === "x64") {
103
+ return baseline ? [`${base}-baseline`, base] : [base, `${base}-baseline`];
104
+ }
105
+ return [base];
106
+ }
107
+
108
+ export function candidateSubPackageNames(mainName, platform, arch, options = {}) {
109
+ const names = [];
110
+ for (const suffix of candidateVariantSuffixes(platform, arch, options)) {
111
+ const name = subPackageName(mainName, suffix);
112
+ if (name !== null) names.push(name);
113
+ }
114
+ return names;
115
+ }
116
+
117
+ export function binarySubpath(os) {
118
+ return os === "win32" ? "bin/cannbot.exe" : "bin/cannbot";
119
+ }
120
+
121
+ // 内置 cannbot-cli 与 TUI 二进制 cannbot 同处平台子包的 bin/ 目录(变更 add-cannbot-acp-command):
122
+ // acp 子命令直接透传给该内置 agent,而非启动 cannbot TUI。
123
+ export function cannbotBinarySubpath(os) {
124
+ return os === "win32" ? "bin/cannbot-cli.exe" : "bin/cannbot-cli";
125
+ }
126
+
127
+ export function missingPackageMessage(mainName, candidateNames, os) {
128
+ const candidates = Array.isArray(candidateNames) && candidateNames.length > 0
129
+ ? candidateNames
130
+ : [`${mainName}-<platform>-<arch>`];
131
+ return [
132
+ `${mainName}: 缺少当前平台 (${os}) 的运行时包。`,
133
+ "",
134
+ ` 已尝试:${candidates.map((name) => `"${name}"`).join(", ")}`,
135
+ "",
136
+ " 可能原因:安装时使用了 --omit=optional,或该平台变体尚未提供预编译产物。",
137
+ ` 受支持平台变体:${SUPPORTED_TARGETS.join(", ")}`,
138
+ "",
139
+ " 修复:重新完整安装(保留可选依赖),例如",
140
+ ` npm install -g ${mainName}`,
141
+ "",
142
+ ].join("\n");
143
+ }
144
+
145
+ // 内置 cannbot-cli 缺失错误(变更 add-cannbot-acp-command):说明是内置 cannbot-cli
146
+ // 而非整个平台包缺失,并给出候选子包与期望文件路径,避免与 TUI 二进制缺失混淆。
147
+ export function missingBundledCannbotMessage(mainName, candidateNames, os, targetPath) {
148
+ const candidates = Array.isArray(candidateNames) && candidateNames.length > 0
149
+ ? candidateNames
150
+ : [`${mainName}-<platform>-<arch>`];
151
+ return [
152
+ "cannbot: 内置 cannbot-cli 不可用,无法启动 acp 服务。",
153
+ "",
154
+ ` 已尝试的平台子包:${candidates.map((name) => `"${name}"`).join(", ")}`,
155
+ ` 期望的内置 cannbot-cli 文件:${targetPath ?? cannbotBinarySubpath(os)}`,
156
+ "",
157
+ " 可能原因:安装时使用了 --omit=optional、该平台变体尚未提供预编译产物,或内置 cannbot-cli 文件缺失/为空。",
158
+ ` 受支持平台变体:${SUPPORTED_TARGETS.join(", ")}`,
159
+ "",
160
+ " 修复:重新完整安装(保留可选依赖),例如",
161
+ ` npm install -g ${mainName}`,
162
+ "",
163
+ ].join("\n");
164
+ }
165
+
166
+ function isNonEmptyFile(path) {
167
+ try {
168
+ const info = statSync(path);
169
+ return info.isFile() && info.size > 0;
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
174
+
175
+ // 从 startDir 向上逐级查找 node_modules/<候选包>/bin/cannbot[.exe],
176
+ // 取第一个命中(与 cannbot-cli 入口脚本的查找方式一致)。
177
+ // binaryPath 可覆盖默认的 TUI 子路径(acp 子命令以 cannbot-cli 子路径查找)。
178
+ export function findPlatformBinary(startDir, candidateNames, os, binaryPath = binarySubpath(os)) {
179
+ const subpath = binaryPath.split("/");
180
+ let current = startDir;
181
+ for (;;) {
182
+ const modules = join(current, "node_modules");
183
+ for (const name of candidateNames) {
184
+ const candidate = join(modules, ...name.split("/"), ...subpath);
185
+ if (isNonEmptyFile(candidate)) return candidate;
186
+ }
187
+ const parent = dirname(current);
188
+ if (parent === current) return null;
189
+ current = parent;
190
+ }
191
+ }
192
+
193
+ function ensureExecutable(binaryPath, os) {
194
+ if (os === "win32") return;
195
+ try {
196
+ accessSync(binaryPath, constants.X_OK);
197
+ } catch {
198
+ try {
199
+ chmodSync(binaryPath, 0o755);
200
+ } catch {
201
+ return;
202
+ }
203
+ }
204
+ }
205
+
206
+ export function spawnBinary(binaryPath, args) {
207
+ return new Promise((resolveCode) => {
208
+ let child;
209
+ try {
210
+ child = spawn(binaryPath, args, { stdio: "inherit", windowsHide: false });
211
+ } catch {
212
+ resolveCode(1);
213
+ return;
214
+ }
215
+ child.on("error", () => resolveCode(1));
216
+ child.on("exit", (code) => {
217
+ resolveCode(typeof code === "number" ? code : 1);
218
+ });
219
+ });
220
+ }
221
+
222
+ function supportsAvx2(platform) {
223
+ if (platform === "linux") {
224
+ try {
225
+ return /(^|\s)avx2(\s|$)/i.test(readFileSync("/proc/cpuinfo", "utf8"));
226
+ } catch {
227
+ return false;
228
+ }
229
+ }
230
+
231
+ if (platform === "darwin") {
232
+ try {
233
+ const result = spawnSync("sysctl", ["-n", "hw.optional.avx2_0"], {
234
+ encoding: "utf8",
235
+ timeout: 1500,
236
+ });
237
+ if (result.status !== 0) return false;
238
+ return (result.stdout || "").trim() === "1";
239
+ } catch {
240
+ return false;
241
+ }
242
+ }
243
+
244
+ if (platform === "windows") {
245
+ const cmd =
246
+ '(Add-Type -MemberDefinition "[DllImport(""kernel32.dll"")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);" -Name Kernel32 -Namespace Win32 -PassThru)::IsProcessorFeaturePresent(40)';
247
+
248
+ for (const exe of ["powershell.exe", "pwsh.exe", "pwsh", "powershell"]) {
249
+ try {
250
+ const result = spawnSync(exe, ["-NoProfile", "-NonInteractive", "-Command", cmd], {
251
+ encoding: "utf8",
252
+ timeout: 3000,
253
+ windowsHide: true,
254
+ });
255
+ if (result.status !== 0) continue;
256
+ const out = (result.stdout || "").trim().toLowerCase();
257
+ if (out === "true" || out === "1") return true;
258
+ if (out === "false" || out === "0") return false;
259
+ } catch {
260
+ continue;
261
+ }
262
+ }
263
+
264
+ return false;
265
+ }
266
+
267
+ return false;
268
+ }
269
+
270
+ function isMusl(platform) {
271
+ if (platform !== "linux") return false;
272
+ try {
273
+ if (libcAlpineExists()) return true;
274
+ } catch {
275
+ // ignore
276
+ }
277
+
278
+ try {
279
+ const result = spawnSync("ldd", ["--version"], { encoding: "utf8", timeout: 1500 });
280
+ const text = ((result.stdout || "") + (result.stderr || "")).toLowerCase();
281
+ return text.includes("musl");
282
+ } catch {
283
+ return false;
284
+ }
285
+ }
286
+
287
+ function libcAlpineExists() {
288
+ try {
289
+ statSync("/etc/alpine-release");
290
+ return true;
291
+ } catch {
292
+ return false;
293
+ }
294
+ }
295
+
296
+ // 帮助文本:版本号由主包清单插值(与 -v 同源),只列启动器真实支持的标志。
297
+ function helpText(version) {
298
+ return [
299
+ `cannbot ${version}`,
300
+ "",
301
+ "用法:",
302
+ " cannbot 启动交互式 TUI",
303
+ " cannbot acp [参数...] 启动 ACP(Agent Client Protocol)服务(转发给内置 cannbot-cli)",
304
+ " cannbot -h, --help 显示帮助",
305
+ " cannbot -v, --version 显示版本号",
306
+ "",
307
+ ].join("\n");
308
+ }
309
+
310
+ export async function run(argv = process.argv.slice(2), options = {}) {
311
+ const { platform: nodePlatform, arch: nodeArch } = process;
312
+ const os = options.platform ?? nodePlatform;
313
+ const arch = options.arch ?? nodeArch;
314
+ const stdin = options.stdin ?? process.stdin;
315
+ const stdout = options.stdout ?? process.stdout;
316
+ const stderr = options.stderr ?? process.stderr;
317
+ const env = options.env ?? process.env;
318
+
319
+ const requireFromHere = createRequire(import.meta.url);
320
+ let manifest;
321
+ try {
322
+ manifest = requireFromHere("../package.json");
323
+ } catch {
324
+ stderr.write("cannbot: 无法读取自身包清单,安装可能已损坏。\n");
325
+ return 1;
326
+ }
327
+ const mainName = manifest.name;
328
+
329
+ // 候选平台子包解析:保持惰性,仅在需要启动二进制时探测 AVX2/musl,
330
+ // 避免帮助/版本应答触发额外探测。
331
+ const resolveCandidates = () => {
332
+ const platform = platformSegment(os);
333
+ const archSegmentValue = archSegment(arch);
334
+ const avx2 = options.avx2 ?? (arch === "x64" ? supportsAvx2(platform) : false);
335
+ const musl = options.musl ?? isMusl(platform);
336
+ return candidateSubPackageNames(mainName, platform, archSegmentValue, { avx2, musl });
337
+ };
338
+
339
+ // acp 子命令透传(变更 add-cannbot-acp-command):首个位置参数为 acp 时,
340
+ // 定位同一平台子包内的内置 cannbot-cli 并以继承 stdio 方式启动,原样透传 argv 与退出码。
341
+ // 该分支位于帮助/版本/升级检查之前,既保证 acp 自身标志能到达被启动的 agent,
342
+ // 也避免启动器输出污染 ACP stdio;内置 cannbot-cli 缺失时 fail-fast,不回落 TUI/PATH。
343
+ if (argv[0] === "acp") {
344
+ const candidates = resolveCandidates();
345
+ const subpath = cannbotBinarySubpath(os);
346
+
347
+ let scriptDir;
348
+ try {
349
+ scriptDir = dirname(realpathSync(fileURLToPath(import.meta.url)));
350
+ } catch {
351
+ scriptDir = dirname(resolve(process.argv[1] ?? "."));
352
+ }
353
+
354
+ const cannbotPath =
355
+ options.findBinary !== undefined
356
+ ? options.findBinary(candidates, os, subpath)
357
+ : findPlatformBinary(scriptDir, candidates, os, subpath);
358
+
359
+ if (cannbotPath === null || cannbotPath === undefined) {
360
+ const first = candidates[0];
361
+ const targetPath =
362
+ first === undefined
363
+ ? subpath
364
+ : join(scriptDir, "node_modules", ...first.split("/"), ...subpath.split("/"));
365
+ stderr.write(missingBundledCannbotMessage(mainName, candidates, os, targetPath));
366
+ return 1;
367
+ }
368
+
369
+ ensureExecutable(cannbotPath, os);
370
+ const spawnChild = options.spawnBinary ?? spawnBinary;
371
+ return await spawnChild(cannbotPath, argv);
372
+ }
373
+
374
+ // 帮助优先于版本:两者同时出现时输出帮助,避免组合参数产生两种输出。
375
+ if (argv.includes("-h") || argv.includes("--help")) {
376
+ stdout.write(helpText(manifest.version));
377
+ return 0;
378
+ }
379
+
380
+ if (argv.includes("-v") || argv.includes("--version")) {
381
+ stdout.write(`${manifest.version}\n`);
382
+ return 0;
383
+ }
384
+
385
+ const interactive = stdin.isTTY === true && stdout.isTTY === true;
386
+ if (!options.skipUpdateCheck && interactive && env[DISABLE_UPDATE_CHECK_ENV] !== "1") {
387
+ try {
388
+ const result = await checkForUpdate({
389
+ name: mainName,
390
+ localVersion: manifest.version,
391
+ manifest,
392
+ fetchImpl: options.fetchImpl,
393
+ timeoutMs: options.timeoutMs,
394
+ });
395
+ if (result.updateAvailable) {
396
+ const stateDir = options.stateDir;
397
+ if (readSkippedVersion(stateDir) !== result.latestVersion) {
398
+ const notice = formatUpdateNotice({
399
+ name: mainName,
400
+ current: manifest.version,
401
+ latest: result.latestVersion,
402
+ });
403
+ const ask = options.askChoice ?? askUpdateChoice;
404
+ const choice = await ask({ notice, stdin, stdout });
405
+ if (choice === "update") {
406
+ const install = options.installGlobal ?? runGlobalInstall;
407
+ if (install(mainName)) {
408
+ stdout.write(`\n已更新到 ${result.latestVersion},请重新执行 cannbot。\n`);
409
+ return 0;
410
+ }
411
+ stderr.write(`\n更新失败。请手动执行:${manualInstallCommand(mainName)}\n\n`);
412
+ } else if (choice === "skip-version") {
413
+ writeSkippedVersion(result.latestVersion, stateDir);
414
+ }
415
+ }
416
+ }
417
+ } catch {
418
+ // 升级检查是可选增强:任何异常都静默放行,绝不阻断启动
419
+ }
420
+ }
421
+
422
+ const candidates = resolveCandidates();
423
+
424
+ let binaryPath;
425
+ if (options.findBinary !== undefined) {
426
+ binaryPath = options.findBinary(candidates, os);
427
+ } else {
428
+ let scriptDir;
429
+ try {
430
+ scriptDir = dirname(realpathSync(fileURLToPath(import.meta.url)));
431
+ } catch {
432
+ scriptDir = dirname(resolve(process.argv[1] ?? "."));
433
+ }
434
+ binaryPath = findPlatformBinary(scriptDir, candidates, os);
435
+ }
436
+
437
+ if (binaryPath === null || binaryPath === undefined) {
438
+ stderr.write(missingPackageMessage(mainName, candidates, os));
439
+ return 1;
440
+ }
441
+
442
+ ensureExecutable(binaryPath, os);
443
+ const spawnChild = options.spawnBinary ?? spawnBinary;
444
+ return await spawnChild(binaryPath, argv);
445
+ }
446
+
447
+ export const ENTRYPOINT_UNDETERMINED_MESSAGE =
448
+ "cannbot: 无法确认启动器入口,已跳过执行。\n";
449
+
450
+ export function entrypointStatus(metaUrl, argv1) {
451
+ if (typeof argv1 !== "string" || argv1.length === 0) return "not-entrypoint";
452
+ try {
453
+ const selfPath = realpathSync(fileURLToPath(metaUrl));
454
+ const argvPath = realpathSync(resolve(argv1));
455
+ return selfPath === argvPath ? "entrypoint" : "not-entrypoint";
456
+ } catch {
457
+ return "undetermined";
458
+ }
459
+ }
460
+
461
+ export function isEntrypoint(metaUrl, argv1) {
462
+ return entrypointStatus(metaUrl, argv1) === "entrypoint";
463
+ }
464
+
465
+ const entryStatus = entrypointStatus(import.meta.url, process.argv[1]);
466
+ if (entryStatus === "entrypoint") {
467
+ run().then((code) => {
468
+ process.exit(code);
469
+ });
470
+ } else if (entryStatus === "undetermined") {
471
+ process.stderr.write(ENTRYPOINT_UNDETERMINED_MESSAGE);
472
+ }
@@ -0,0 +1,206 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ export const DEFAULT_REGISTRY = "https://registry.npmjs.org/";
7
+ export const UPDATE_CHECK_TIMEOUT_MS = 1500;
8
+ export const DISABLE_UPDATE_CHECK_ENV = "CANNBOT_NO_UPDATE_CHECK";
9
+ export const SKIP_FILE_NAME = "upgrade.json";
10
+
11
+ const VERSION_PATTERN = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u;
12
+
13
+ export function parseVersion(raw) {
14
+ if (typeof raw !== "string") return null;
15
+ const match = VERSION_PATTERN.exec(raw.trim());
16
+ if (match === null) return null;
17
+ return {
18
+ major: Number(match[1]),
19
+ minor: Number(match[2]),
20
+ patch: Number(match[3]),
21
+ prerelease: match[4] ?? null,
22
+ };
23
+ }
24
+
25
+ function comparePrerelease(left, right) {
26
+ const leftIds = left.split(".");
27
+ const rightIds = right.split(".");
28
+ const length = Math.min(leftIds.length, rightIds.length);
29
+ for (let index = 0; index < length; index += 1) {
30
+ const leftId = leftIds[index] ?? "";
31
+ const rightId = rightIds[index] ?? "";
32
+ const leftNumeric = /^\d+$/u.test(leftId);
33
+ const rightNumeric = /^\d+$/u.test(rightId);
34
+ if (leftNumeric && rightNumeric) {
35
+ const diff = Number(leftId) - Number(rightId);
36
+ if (diff !== 0) return diff > 0 ? 1 : -1;
37
+ continue;
38
+ }
39
+ if (leftNumeric) return -1;
40
+ if (rightNumeric) return 1;
41
+ if (leftId !== rightId) return leftId < rightId ? -1 : 1;
42
+ }
43
+ if (leftIds.length === rightIds.length) return 0;
44
+ return leftIds.length < rightIds.length ? -1 : 1;
45
+ }
46
+
47
+ export function compareVersions(left, right) {
48
+ const a = parseVersion(left);
49
+ const b = parseVersion(right);
50
+ if (a === null || b === null) return null;
51
+ for (const key of ["major", "minor", "patch"]) {
52
+ if (a[key] !== b[key]) return a[key] > b[key] ? 1 : -1;
53
+ }
54
+ if (a.prerelease === null && b.prerelease === null) return 0;
55
+ if (a.prerelease === null) return 1;
56
+ if (b.prerelease === null) return -1;
57
+ return comparePrerelease(a.prerelease, b.prerelease);
58
+ }
59
+
60
+ export function isUpdateAvailable(localVersion, latestVersion) {
61
+ return compareVersions(latestVersion, localVersion) === 1;
62
+ }
63
+
64
+ export function resolveRegistry(manifest) {
65
+ const configured = manifest?.publishConfig?.registry;
66
+ return typeof configured === "string" && configured.trim().length > 0
67
+ ? configured.trim()
68
+ : DEFAULT_REGISTRY;
69
+ }
70
+
71
+ export function encodePackageName(name) {
72
+ return encodeURI(name).replace(/\//gu, "%2F");
73
+ }
74
+
75
+ export function packageLatestUrl(name, registry = DEFAULT_REGISTRY) {
76
+ const base =
77
+ typeof registry === "string" && registry.trim().length > 0 ? registry.trim() : DEFAULT_REGISTRY;
78
+ const withSlash = base.endsWith("/") ? base : `${base}/`;
79
+ return `${withSlash}${encodePackageName(name)}/latest`;
80
+ }
81
+
82
+ export async function fetchLatestVersion(name, options = {}) {
83
+ const {
84
+ registry = DEFAULT_REGISTRY,
85
+ timeoutMs = UPDATE_CHECK_TIMEOUT_MS,
86
+ fetchImpl = globalThis.fetch,
87
+ } = options;
88
+ if (typeof fetchImpl !== "function" || typeof name !== "string" || name.length === 0) {
89
+ return null;
90
+ }
91
+ const controller = new AbortController();
92
+ const timer = setTimeout(() => controller.abort(), Math.max(1, Number(timeoutMs) || 1));
93
+ try {
94
+ const response = await fetchImpl(packageLatestUrl(name, registry), {
95
+ headers: { Accept: "application/json" },
96
+ signal: controller.signal,
97
+ });
98
+ if (response === null || typeof response !== "object" || response.ok !== true) return null;
99
+ const body = await response.json();
100
+ const version = body?.version;
101
+ return typeof version === "string" && version.trim().length > 0 ? version.trim() : null;
102
+ } catch {
103
+ return null;
104
+ } finally {
105
+ clearTimeout(timer);
106
+ }
107
+ }
108
+
109
+ export async function checkForUpdate(options = {}) {
110
+ const {
111
+ name,
112
+ localVersion,
113
+ manifest,
114
+ fetchImpl,
115
+ timeoutMs = UPDATE_CHECK_TIMEOUT_MS,
116
+ } = options;
117
+ const latestVersion = await fetchLatestVersion(name, {
118
+ registry: resolveRegistry(manifest),
119
+ timeoutMs,
120
+ fetchImpl,
121
+ });
122
+ return {
123
+ latestVersion,
124
+ updateAvailable: latestVersion !== null && isUpdateAvailable(localVersion, latestVersion),
125
+ };
126
+ }
127
+
128
+ export function upgradeStateDir() {
129
+ return join(homedir(), ".cannbot-tui");
130
+ }
131
+
132
+ export function upgradeStatePath(dir = upgradeStateDir()) {
133
+ return join(dir, SKIP_FILE_NAME);
134
+ }
135
+
136
+ export function readSkippedVersion(dir = upgradeStateDir()) {
137
+ try {
138
+ const parsed = JSON.parse(readFileSync(upgradeStatePath(dir), "utf8"));
139
+ const value = parsed?.skippedVersion;
140
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
141
+ } catch {
142
+ return null;
143
+ }
144
+ }
145
+
146
+ export function writeSkippedVersion(version, dir = upgradeStateDir()) {
147
+ if (typeof version !== "string" || version.trim().length === 0) return false;
148
+ try {
149
+ mkdirSync(dir, { recursive: true });
150
+ writeFileSync(
151
+ upgradeStatePath(dir),
152
+ `${JSON.stringify({ skippedVersion: version.trim() }, null, 2)}\n`,
153
+ "utf8",
154
+ );
155
+ return true;
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+
161
+ export function parseUpdateChoice(raw) {
162
+ const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
163
+ if (value === "1" || value === "u" || value === "y") return "update";
164
+ if (value === "3" || value === "v") return "skip-version";
165
+ return "skip";
166
+ }
167
+
168
+ export function formatUpdateNotice({ name, current, latest }) {
169
+ return [
170
+ `发现 cannbot 新版本:${current} -> ${latest}`,
171
+ ` [1] 更新(执行 npm install -g ${name}@latest)`,
172
+ " [2] 跳过(仅本次)",
173
+ " [3] 跳过此版本(不再提示该版本)",
174
+ ].join("\n");
175
+ }
176
+
177
+ export async function askUpdateChoice({ notice, stdin = process.stdin, stdout = process.stdout }) {
178
+ const readline = await import("node:readline/promises");
179
+ const rl = readline.createInterface({ input: stdin, output: stdout });
180
+ try {
181
+ const answer = await rl.question(`${notice}\n请选择 [1/2/3]: `);
182
+ return parseUpdateChoice(answer);
183
+ } catch {
184
+ return "skip";
185
+ } finally {
186
+ rl.close();
187
+ }
188
+ }
189
+
190
+ export function manualInstallCommand(name) {
191
+ return `npm install -g ${name}@latest`;
192
+ }
193
+
194
+ export function runGlobalInstall(name, options = {}) {
195
+ const { spawnImpl = spawnSync, platform = process.platform } = options;
196
+ if (typeof name !== "string" || name.trim().length === 0) return false;
197
+ try {
198
+ const result = spawnImpl("npm", ["install", "-g", `${name.trim()}@latest`], {
199
+ stdio: "inherit",
200
+ shell: platform === "win32",
201
+ });
202
+ return result?.status === 0;
203
+ } catch {
204
+ return false;
205
+ }
206
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "cannbot-pilot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.5",
4
+ "type": "module",
5
+ "bin": {
6
+ "cannbot": "bin/cannbot.js"
7
+ },
8
+ "files": [
9
+ "bin",
10
+ "README.md"
11
+ ],
12
+ "optionalDependencies": {
13
+ "cannbot-pilot-windows-x64": "2.0.5",
14
+ "cannbot-pilot-windows-x64-baseline": "2.0.5",
15
+ "cannbot-pilot-windows-arm64": "2.0.5",
16
+ "cannbot-pilot-linux-x64": "2.0.5",
17
+ "cannbot-pilot-linux-x64-baseline": "2.0.5",
18
+ "cannbot-pilot-linux-arm64": "2.0.5",
19
+ "cannbot-pilot-linux-x64-musl": "2.0.5",
20
+ "cannbot-pilot-linux-x64-baseline-musl": "2.0.5",
21
+ "cannbot-pilot-linux-arm64-musl": "2.0.5",
22
+ "cannbot-pilot-darwin-x64": "2.0.5",
23
+ "cannbot-pilot-darwin-x64-baseline": "2.0.5",
24
+ "cannbot-pilot-darwin-arm64": "2.0.5"
25
+ },
26
+ "publishConfig": {
27
+ "registry": "https://registry.npmjs.org/",
28
+ "access": "public"
29
+ }
30
+ }