bingocode 1.0.30 → 1.0.32

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/bin/bingo-win.cjs CHANGED
@@ -71,6 +71,32 @@ if (!bunExists()) {
71
71
  // 安装后 bun.exe 在固定位置;若在 PATH 里则直接用 "bun"
72
72
  const bun = fs.existsSync(bunPath) ? bunPath : 'bun';
73
73
 
74
+ // ── 自动检测并安装 git ──
75
+ function gitExists() {
76
+ const result = spawnSync('git', ['--version'], { stdio: 'ignore', shell: true });
77
+ return result.status === 0;
78
+ }
79
+
80
+ function installGit() {
81
+ console.log('[bingo] git 未检测到,正在通过 winget 自动安装...');
82
+ const result = spawnSync(
83
+ 'winget',
84
+ ['install', '--id', 'Git.Git', '-e', '--source', 'winget',
85
+ '--accept-package-agreements', '--accept-source-agreements'],
86
+ { stdio: 'inherit', shell: true }
87
+ );
88
+ if (result.status !== 0) {
89
+ console.warn('[bingo] git 自动安装失败,请手动安装:https://git-scm.com');
90
+ // 不退出 —— git 不是启动必须依赖,缺少时仅降级部分功能
91
+ } else {
92
+ console.log('[bingo] git 安装完成,若 PATH 未生效请重启终端。');
93
+ }
94
+ }
95
+
96
+ if (!gitExists()) {
97
+ installGit();
98
+ }
99
+
74
100
  // Bingo Manager 入口(窗口管理控制台,不走 cli.tsx 完整启动流程)
75
101
  const entry = path.join(__dirname, '..', 'src', 'entrypoints', 'manager.tsx');
76
102
 
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const { spawn } = require('node:child_process');
3
+ const { spawn, spawnSync } = require('node:child_process');
4
4
  const path = require('path');
5
5
  const os = require('os');
6
6
  const fs = require('fs');
@@ -33,11 +33,63 @@ process.env.NoDefaultCurrentDirectoryInExePath = '1';
33
33
  }
34
34
  })();
35
35
 
36
- // 自动定位 bun 路径
37
- const bun =
36
+ // ── 自动定位并安装 bun ──
37
+ const bunPath =
38
38
  process.env.BUN_PATH ||
39
39
  path.join(os.homedir(), '.bun', 'bin', 'bun.exe');
40
40
 
41
+ function bunExists() {
42
+ if (fs.existsSync(bunPath)) return true;
43
+ const result = spawnSync('bun', ['--version'], { stdio: 'ignore', shell: true });
44
+ return result.status === 0;
45
+ }
46
+
47
+ function installBun() {
48
+ console.log('[bingocode] bun 未检测到,正在自动安装...');
49
+ const result = spawnSync(
50
+ 'powershell',
51
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
52
+ 'irm bun.sh/install.ps1 | iex'],
53
+ { stdio: 'inherit', shell: false }
54
+ );
55
+ if (result.status !== 0) {
56
+ console.error('[bingocode] bun 安装失败,请手动安装:https://bun.sh');
57
+ process.exit(1);
58
+ }
59
+ console.log('[bingocode] bun 安装完成,正在启动...');
60
+ }
61
+
62
+ if (!bunExists()) {
63
+ installBun();
64
+ }
65
+
66
+ const bun = fs.existsSync(bunPath) ? bunPath : 'bun';
67
+
68
+ // ── 自动检测并安装 git ──
69
+ function gitExists() {
70
+ const result = spawnSync('git', ['--version'], { stdio: 'ignore', shell: true });
71
+ return result.status === 0;
72
+ }
73
+
74
+ function installGit() {
75
+ console.log('[bingocode] git 未检测到,正在通过 winget 自动安装...');
76
+ const result = spawnSync(
77
+ 'winget',
78
+ ['install', '--id', 'Git.Git', '-e', '--source', 'winget',
79
+ '--accept-package-agreements', '--accept-source-agreements'],
80
+ { stdio: 'inherit', shell: true }
81
+ );
82
+ if (result.status !== 0) {
83
+ console.warn('[bingocode] git 自动安装失败,请手动安装:https://git-scm.com');
84
+ } else {
85
+ console.log('[bingocode] git 安装完成,若 PATH 未生效请重启终端。');
86
+ }
87
+ }
88
+
89
+ if (!gitExists()) {
90
+ installGit();
91
+ }
92
+
41
93
  // 主 CLI 入口
42
94
  const entry = path.join(__dirname, '..', 'src', 'entrypoints', 'cli.tsx');
43
95
 
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const { spawn } = require('node:child_process');
3
+ const { spawn, spawnSync } = require('node:child_process');
4
4
  const path = require('path');
5
5
  const os = require('os');
6
6
  const fs = require('fs');
@@ -32,11 +32,63 @@ process.env.NoDefaultCurrentDirectoryInExePath = '1';
32
32
  }
33
33
  })();
34
34
 
35
- // 自动定位 bun 路径
36
- const bun =
35
+ // ── 自动定位并安装 bun ──
36
+ const bunPath =
37
37
  process.env.BUN_PATH ||
38
38
  path.join(os.homedir(), '.bun', 'bin', 'bun.exe');
39
39
 
40
+ function bunExists() {
41
+ if (fs.existsSync(bunPath)) return true;
42
+ const result = spawnSync('bun', ['--version'], { stdio: 'ignore', shell: true });
43
+ return result.status === 0;
44
+ }
45
+
46
+ function installBun() {
47
+ console.log('[claude] bun 未检测到,正在自动安装...');
48
+ const result = spawnSync(
49
+ 'powershell',
50
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
51
+ 'irm bun.sh/install.ps1 | iex'],
52
+ { stdio: 'inherit', shell: false }
53
+ );
54
+ if (result.status !== 0) {
55
+ console.error('[claude] bun 安装失败,请手动安装:https://bun.sh');
56
+ process.exit(1);
57
+ }
58
+ console.log('[claude] bun 安装完成,正在启动...');
59
+ }
60
+
61
+ if (!bunExists()) {
62
+ installBun();
63
+ }
64
+
65
+ const bun = fs.existsSync(bunPath) ? bunPath : 'bun';
66
+
67
+ // ── 自动检测并安装 git ──
68
+ function gitExists() {
69
+ const result = spawnSync('git', ['--version'], { stdio: 'ignore', shell: true });
70
+ return result.status === 0;
71
+ }
72
+
73
+ function installGit() {
74
+ console.log('[claude] git 未检测到,正在通过 winget 自动安装...');
75
+ const result = spawnSync(
76
+ 'winget',
77
+ ['install', '--id', 'Git.Git', '-e', '--source', 'winget',
78
+ '--accept-package-agreements', '--accept-source-agreements'],
79
+ { stdio: 'inherit', shell: true }
80
+ );
81
+ if (result.status !== 0) {
82
+ console.warn('[claude] git 自动安装失败,请手动安装:https://git-scm.com');
83
+ } else {
84
+ console.log('[claude] git 安装完成,若 PATH 未生效请重启终端。');
85
+ }
86
+ }
87
+
88
+ if (!gitExists()) {
89
+ installGit();
90
+ }
91
+
40
92
  // 主 CLI 入口
41
93
  const entry = path.join(__dirname, '..', 'src', 'entrypoints', 'cli.tsx');
42
94
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bingocode",
3
- "version": "1.0.30",
3
+ "version": "1.0.32",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "claude": "bin/claude-win.cjs",
@@ -9,6 +9,7 @@
9
9
  "bingo": "bin/bingo-win.cjs"
10
10
  },
11
11
  "scripts": {
12
+ "preinstall": "node scripts/preinstall-stop.cjs",
12
13
  "start": "bun run ./bin/bingo-win.cjs",
13
14
  "bingo": "bun run ./bin/bingo-win.cjs",
14
15
  "bingocode": "bun run ./bin/bingocode-win.cjs",
@@ -0,0 +1,164 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * npm preinstall hook: gracefully stop running bingo/bingocode processes
5
+ * so that npm can overwrite files without EBUSY/EPERM on Windows.
6
+ *
7
+ * On Windows, running processes hold mandatory file locks on their loaded .js
8
+ * files and dependencies. When `npm install -g bingocode` tries to overwrite
9
+ * these files, it fails with EBUSY or EPERM. This script discovers all running
10
+ * bingo/bingocode processes via their PID files and stops them before npm
11
+ * writes any files.
12
+ *
13
+ * PID file locations (matching the runtime code):
14
+ * - Singleton server: ~/.claude-cli/runtime/server.lock.json { pid, port, ... }
15
+ * - Active sessions: ~/.claude/sessions/<pid>.json { pid, sessionId, ... }
16
+ *
17
+ * Must be CJS (.cjs) because npm executes lifecycle scripts with node,
18
+ * and package.json has "type": "module".
19
+ */
20
+
21
+ const { spawnSync } = require('child_process');
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const os = require('os');
25
+
26
+ // ── Paths (mirroring the runtime code) ──────────────────────────────────────
27
+
28
+ const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
29
+ const runtimeDir = path.join(os.homedir(), '.claude-cli', 'runtime');
30
+ const serverLockPath = path.join(runtimeDir, 'server.lock.json');
31
+ const leasesDir = path.join(runtimeDir, 'leases');
32
+ const sessionsDir = path.join(configDir, 'sessions');
33
+
34
+ // ── Helpers ─────────────────────────────────────────────────────────────────
35
+
36
+ function isPidAlive(pid) {
37
+ try {
38
+ process.kill(pid, 0);
39
+ return true;
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ function killPid(pid) {
46
+ try {
47
+ if (process.platform === 'win32') {
48
+ // /T = kill the entire process tree; /F = force
49
+ spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
50
+ stdio: 'ignore',
51
+ });
52
+ } else {
53
+ process.kill(pid, 'SIGTERM');
54
+ }
55
+ } catch {
56
+ // Process may have already exited
57
+ }
58
+ }
59
+
60
+ function readJsonSafe(filePath) {
61
+ try {
62
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+
68
+ function sleepMs(ms) {
69
+ // Cross-platform synchronous sleep via spawnSync
70
+ if (process.platform === 'win32') {
71
+ // "ping -n 2 127.0.0.1" sleeps ~1s (more reliable than timeout in non-interactive)
72
+ spawnSync('ping', ['-n', '2', '127.0.0.1'], { stdio: 'ignore' });
73
+ } else {
74
+ spawnSync('sleep', [String(ms / 1000)], { stdio: 'ignore' });
75
+ }
76
+ }
77
+
78
+ // ── Collect PIDs ────────────────────────────────────────────────────────────
79
+
80
+ const pidsToKill = new Set();
81
+
82
+ // 1. Singleton server PID from server.lock.json
83
+ const serverLock = readJsonSafe(serverLockPath);
84
+ if (serverLock && serverLock.pid && isPidAlive(serverLock.pid)) {
85
+ pidsToKill.add(serverLock.pid);
86
+ }
87
+
88
+ // 2. Active session PIDs from ~/.claude/sessions/<pid>.json
89
+ try {
90
+ const files = fs.readdirSync(sessionsDir);
91
+ for (const f of files) {
92
+ // Strict filename guard: only "<digits>.json" files are PID files
93
+ if (!/^\d+\.json$/.test(f)) continue;
94
+ const data = readJsonSafe(path.join(sessionsDir, f));
95
+ if (data && data.pid && isPidAlive(data.pid)) {
96
+ pidsToKill.add(data.pid);
97
+ }
98
+ }
99
+ } catch {
100
+ // sessionsDir may not exist yet — that's fine
101
+ }
102
+
103
+ // ── Nothing to do ───────────────────────────────────────────────────────────
104
+
105
+ if (pidsToKill.size === 0) {
106
+ // No running processes, npm can proceed safely
107
+ process.exit(0);
108
+ }
109
+
110
+ // ── Kill processes ──────────────────────────────────────────────────────────
111
+
112
+ console.log(
113
+ `[bingocode] 检测到 ${pidsToKill.size} 个运行中的进程,正在停止以便安装...`
114
+ );
115
+
116
+ for (const pid of pidsToKill) {
117
+ console.log(` 停止 PID ${pid}`);
118
+ killPid(pid);
119
+ }
120
+
121
+ // ── Wait for processes to exit (max 5 seconds) ─────────────────────────────
122
+
123
+ const MAX_WAIT_MS = 5000;
124
+ const deadline = Date.now() + MAX_WAIT_MS;
125
+
126
+ while (Date.now() < deadline) {
127
+ const alive = [...pidsToKill].filter(isPidAlive);
128
+ if (alive.length === 0) break;
129
+ sleepMs(500);
130
+ }
131
+
132
+ // Check if any processes are still alive after timeout
133
+ const stillAlive = [...pidsToKill].filter(isPidAlive);
134
+ if (stillAlive.length > 0) {
135
+ console.warn(
136
+ `[bingocode] 警告:${stillAlive.length} 个进程未能在 ${MAX_WAIT_MS / 1000} 秒内停止 (PIDs: ${stillAlive.join(', ')})`
137
+ );
138
+ console.warn(
139
+ '[bingocode] 安装可能仍会因文件锁定而失败,请手动关闭这些进程后重试'
140
+ );
141
+ }
142
+
143
+ // ── Clean up stale lock/lease files ─────────────────────────────────────────
144
+
145
+ try {
146
+ fs.rmSync(serverLockPath, { force: true });
147
+ } catch {
148
+ // Ignore — file may not exist or may already be cleaned up
149
+ }
150
+
151
+ try {
152
+ const leaseFiles = fs.readdirSync(leasesDir);
153
+ for (const f of leaseFiles) {
154
+ try {
155
+ fs.rmSync(path.join(leasesDir, f), { force: true });
156
+ } catch {
157
+ // Best-effort cleanup
158
+ }
159
+ }
160
+ } catch {
161
+ // leasesDir may not exist
162
+ }
163
+
164
+ console.log('[bingocode] 进程已停止,继续安装...');
@@ -30,13 +30,15 @@ if (feature('ABLATION_BASELINE') && process.env.CLAUDE_CODE_ABLATION_BASELINE) {
30
30
  * All imports are dynamic to minimize module evaluation for fast paths.
31
31
  * Fast-path for --version has zero imports beyond this file.
32
32
  */
33
- import { CliMenuManager } from '../manager/CliMenuManager';
34
- import { render } from 'ink';
35
33
 
36
34
  async function main(): Promise<void> {
37
35
  const args = process.argv.slice(2);
38
36
  // 兼容demo参数:只渲染CLI新主菜单管理器,不影响原有逻辑
37
+ // CliMenuManager 和 ink 改为动态 import,避免顶层 import 导致模块副作用
38
+ // 抢占 stdin,使新电脑首次启动时 TrustDialog 卡死
39
39
  if (args.includes('--cli-menu-demo')) {
40
+ const { CliMenuManager } = await import('../manager/CliMenuManager');
41
+ const { render } = await import('ink');
40
42
  render(<CliMenuManager />);
41
43
  return;
42
44
  }
@@ -280,19 +280,33 @@ export const CliMenuManager: React.FC = () => {
280
280
  // 配置就绪探测(用于避免 Logo 早期读取)
281
281
  const [configReady, setConfigReady] = useState(false);
282
282
 
283
- // 启动/复用本地唯一服务,并注入 apiUrl
283
+ // 启动/复用本地唯一服务,并注入 apiUrl(含重试机制)
284
284
  useEffect(() => {
285
285
  let mounted = true;
286
286
  (async () => {
287
- try {
288
- if (apiUrl) return;
289
- const entry = path.resolve(import.meta.dir, '../server/index.ts');
290
- const handle = await ensureSingletonLocalServer({ serverEntry: entry });
291
- if (!mounted) { await handle.stopIfLast(); return; }
292
- setApiUrl(handle.baseUrl);
293
- setStopIfLast(() => handle.stopIfLast);
294
- } catch (e: any) {
295
- setBootErr(e.message || '本地服务启动失败');
287
+ if (apiUrl) return;
288
+ const entry = path.resolve(import.meta.dir, '../server/index.ts');
289
+ const MAX_RETRIES = 3;
290
+ const RETRY_DELAYS = [0, 2000, 5000]; // 首次无延迟,第2次2秒,第3次5秒
291
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
292
+ if (!mounted) return;
293
+ if (attempt > 0) {
294
+ setBootErr(`第 ${attempt} 次启动失败,${RETRY_DELAYS[attempt] / 1000}秒后重试...`);
295
+ await new Promise(r => setTimeout(r, RETRY_DELAYS[attempt]));
296
+ }
297
+ if (!mounted) return;
298
+ try {
299
+ const handle = await ensureSingletonLocalServer({ serverEntry: entry });
300
+ if (!mounted) { await handle.stopIfLast(); return; }
301
+ setApiUrl(handle.baseUrl);
302
+ setStopIfLast(() => handle.stopIfLast);
303
+ setBootErr(null);
304
+ return; // 成功,退出重试
305
+ } catch (e: any) {
306
+ if (attempt === MAX_RETRIES - 1) {
307
+ setBootErr(e.message || '本地服务启动失败');
308
+ }
309
+ }
296
310
  }
297
311
  })();
298
312
  return () => { mounted = false; if (stopIfLast) stopIfLast(); };
@@ -653,7 +667,8 @@ export const CliMenuManager: React.FC = () => {
653
667
  }
654
668
 
655
669
  // 新增:会话恢复(供快捷键和右侧菜单复用)
656
- async function resumeSession(sessionId: string) {
670
+ // workDir: 会话原始工作目录,用于跨文件夹恢复(确保新进程能找到 session 文件)
671
+ async function resumeSession(sessionId: string, workDir?: string | null) {
657
672
  try {
658
673
  const fsReq = require('fs');
659
674
  const pathReq = require('path');
@@ -673,7 +688,7 @@ export const CliMenuManager: React.FC = () => {
673
688
  : ['-c', `${binName} --resume ${sessionId}`];
674
689
  const spawnEnv = await buildSpawnEnv();
675
690
  spawn(spawnCmd, spawnArgs, {
676
- cwd: process.env.CALLER_DIR || process.cwd(),
691
+ cwd: workDir || process.env.CALLER_DIR || process.cwd(),
677
692
  env: spawnEnv,
678
693
  detached: true,
679
694
  stdio: 'ignore'
@@ -749,7 +764,7 @@ export const CliMenuManager: React.FC = () => {
749
764
  toggleMarkSession(selectedHistory.id);
750
765
  break;
751
766
  case '__continue':
752
- resumeSession(selectedHistory.id);
767
+ resumeSession(selectedHistory.id, selectedHistory.workDir);
753
768
  break;
754
769
  case '__delete':
755
770
  setHistoryMenuStage('deleteConfirm');
@@ -810,7 +825,7 @@ export const CliMenuManager: React.FC = () => {
810
825
  setSelectedHistory(null);
811
826
  setMsgsPage(0);
812
827
  } else if (item.value === '__continue') {
813
- resumeSession(selectedHistory.id);
828
+ resumeSession(selectedHistory.id, selectedHistory.workDir);
814
829
  } else if (item.value === '__delete') {
815
830
  setHistoryMenuStage('deleteConfirm');
816
831
  } else if (item.value === '__toggle_mark') {
@@ -870,9 +885,17 @@ export const CliMenuManager: React.FC = () => {
870
885
  const WELCOME_W = 58;
871
886
  const leftPad = Math.max(0, Math.floor((VIEW_W - WELCOME_W) / 2));
872
887
  return (
873
- <Box flexDirection="row" width={VIEW_W} height={MID_H}>
874
- <Box width={leftPad} flexShrink={0} />
875
- <WelcomeV2 />
888
+ <Box flexDirection="column" width={VIEW_W} height={MID_H}>
889
+ <Box flexDirection="row" width={VIEW_W} flexGrow={1}>
890
+ <Box width={leftPad} flexShrink={0} />
891
+ <WelcomeV2 />
892
+ </Box>
893
+ {!apiUrl && !bootErr && (
894
+ <Text color="yellow">⏳ 服务启动中...</Text>
895
+ )}
896
+ {bootErr && (
897
+ <Text color="red">服务启动失败: {bootErr}</Text>
898
+ )}
876
899
  </Box>
877
900
  );
878
901
  }
@@ -1014,6 +1037,14 @@ export const CliMenuManager: React.FC = () => {
1014
1037
 
1015
1038
  // Provider
1016
1039
  if (page === 'provider') {
1040
+ if (!apiUrl) {
1041
+ return (
1042
+ <Box width={VIEW_W} height={MID_H} flexDirection="column">
1043
+ <Text color="yellow">{bootErr ? `服务启动失败: ${bootErr}` : '⏳ 服务启动中,请稍候...'}</Text>
1044
+ <Text dimColor>ESC 返回主菜单</Text>
1045
+ </Box>
1046
+ );
1047
+ }
1017
1048
  return (
1018
1049
  <Box width={VIEW_W} height={MID_H} flexDirection="column">
1019
1050
  <ProviderPanel apiUrl={apiUrl} onBack={() => setPage(null)} />
@@ -19,7 +19,7 @@
19
19
 
20
20
  const DEFAULT_HOST = '127.0.0.1';
21
21
  const DEFAULT_PORT = Number(process.env.SERVER_PORT || 3456);
22
- const HEALTH_TIMEOUT_MS = 12000;
22
+ const HEALTH_TIMEOUT_MS = Number(process.env.HEALTH_TIMEOUT_MS || 20000);
23
23
  const HEALTH_RETRY_MS = 300;
24
24
 
25
25
  function mkdirp(p: string) { fs.mkdirSync(p, { recursive: true }); }
@@ -720,6 +720,21 @@ function computeTrustDialogAccepted(): boolean {
720
720
  return true
721
721
  }
722
722
 
723
+ // Fallback: also check the raw original CWD path directly.
724
+ // This handles the case where trust was saved under CWD (no .git at the time),
725
+ // but now .git exists so getProjectPathForConfig() returns the git root instead.
726
+ // Without this fallback the old trust entry would never be found, causing the
727
+ // trust dialog to reappear after `git init` / `git clone`.
728
+ const normalizedOriginalCwd = normalizePathForConfigKey(
729
+ resolve(getOriginalCwd()),
730
+ )
731
+ if (normalizedOriginalCwd !== projectPath) {
732
+ const cwdConfig = config.projects?.[normalizedOriginalCwd]
733
+ if (cwdConfig?.hasTrustDialogAccepted) {
734
+ return true
735
+ }
736
+ }
737
+
723
738
  // Now check from current working directory and its parents
724
739
  // Normalize paths for consistent JSON key lookup
725
740
  let currentPath = normalizePathForConfigKey(getCwd())