coxpit 5.27.1 → 5.27.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
@@ -151,14 +151,14 @@ One daemon, one SQLite file, zero external services. Machines are reached over S
151
151
 
152
152
  ## Status
153
153
 
154
- `v4.5` — **greenfield + remote access**. Point Coxpit at an empty folder and a fleet scaffolds a brand-new project across N agents on an empty initial commit — compare the foundations, keep the best (existing folders are never touched). Remote access detects your Tailscale and puts the board on `https://<machine>.<tailnet>.ts.net` in one click (Funnel for public, behind a warning; copy-paste Cloudflare/Caddy recipes otherwise) — Coxpit drives the tool, never hosts a relay. Builds on v4.3's Active-first board + Archive. All shipped and e2e-tested (45 checks). Roadmap: ROADMAP.md.
154
+ `v4.5` — **greenfield + remote access**. Point Coxpit at an empty folder and a fleet scaffolds a brand-new project across N agents on an empty initial commit — compare the foundations, keep the best (existing folders are never touched). Remote access detects your Tailscale and puts the board on `https://<machine>.<tailnet>.ts.net` in one click (Funnel for public, behind a warning; copy-paste Cloudflare/Caddy recipes otherwise) — Coxpit drives the tool, never hosts a relay. Builds on v4.3's Active-first board + Archive. All shipped and e2e-tested (45 checks). Roadmap: docs/ROADMAP.md.
155
155
 
156
156
  ## Contributing
157
157
 
158
158
  Issues and PRs are welcome. Start with **[CONTRIBUTING.md](CONTRIBUTING.md)** for
159
159
  dev setup (`COXPIT_AUTH_DISABLED=1 npm run dev`), the verify gate (`npm run
160
160
  typecheck` + `bash test/e2e.sh`), and the house rules. Please read the
161
- [non-goals](ROADMAP.md#non-goals) before proposing a feature, and report security
161
+ [non-goals](docs/ROADMAP.md#non-goals) before proposing a feature, and report security
162
162
  issues privately per **[SECURITY.md](SECURITY.md)** (Coxpit exposes shells).
163
163
 
164
164
  ## License
package/bin/coxpit.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coxpit",
3
- "version": "5.27.1",
3
+ "version": "5.27.5",
4
4
  "description": "Self-hosted cockpit for running a fleet of AI coding agents across your own machines — parallel worktree runs, live board, compare & merge, web terminal, design capture.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
package/src/index.ts CHANGED
@@ -5,8 +5,13 @@ import { machines } from './db/schema';
5
5
  import { acquireDaemonLock, updateLockPort } from './lock';
6
6
  import { reconcileOrphanRuns } from './orchestrator';
7
7
  import { buildServer } from './server';
8
+ import { augmentPathForGuiLaunch } from './paths';
8
9
  import type { AddressInfo } from 'node:net';
9
10
 
11
+ // macOS: GUI/launchd 로 뜨면 PATH 에 Homebrew 가 없어 로컬 tmux 를 못 찾는다(issue #10).
12
+ // 어떤 로컬 spawn 보다 먼저 PATH 를 보강한다.
13
+ augmentPathForGuiLaunch();
14
+
10
15
  // Windows 네이티브는 에이전트 실행 계층(sh·tmux·git worktree over sh)이 성립하지 않는다.
11
16
  // 보드/원격 머신 관제는 되지만 로컬 run 은 불가 — WSL 데몬을 안내한다.
12
17
  if (process.platform === 'win32') {
package/src/paths.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+
4
+ // GUI/launchd 로 뜬 macOS 데몬은 PATH 가 `/usr/bin:/bin:/usr/sbin:/sbin` 뿐이라
5
+ // Homebrew(`/opt/homebrew/bin`·`/usr/local/bin`) 가 빠진다. tmux 는 macOS 기본 제공이
6
+ // 아니라 로컬 터미널이 `spawn tmux ENOENT` 로 죽는다(remote 는 ssh 가 /usr/bin 에 있어 동작).
7
+ // → issue #10. 시작 시 한 번 PATH 를 보강하면 로컬 `pty().spawn('tmux')` 와
8
+ // runShellOn 의 `sh -c` 프로브(둘 다 process.env.PATH 상속)가 함께 해결된다.
9
+ // 시스템 경로 우선순위는 건드리지 않고 없는 디렉터리만 뒤에 덧붙인다(시스템 툴 그림자 방지).
10
+ export function augmentPathForGuiLaunch(): void {
11
+ if (process.platform !== 'darwin') return;
12
+ const have = new Set((process.env.PATH ?? '').split(':').filter(Boolean));
13
+ const add: string[] = [];
14
+ const push = (d: string): void => {
15
+ const dir = d.trim();
16
+ if (dir && !have.has(dir) && existsSync(dir)) { have.add(dir); add.push(dir); }
17
+ };
18
+
19
+ // 1) 로그인 셸의 PATH — 사용자 환경(asdf·nvm·커스텀 tmux 위치)까지 포괄. best-effort.
20
+ try {
21
+ const shell = process.env.SHELL || '/bin/zsh';
22
+ const out = execFileSync(shell, ['-lc', 'printf %s "$PATH"'], { timeout: 4000, encoding: 'utf8' });
23
+ for (const d of out.split(':')) push(d);
24
+ } catch { /* 로그인 셸 실패 → 아래 알려진 경로로 보강 */ }
25
+
26
+ // 2) 알려진 Homebrew/local 경로 — 로그인 셸이 안 되는 환경 대비.
27
+ for (const d of ['/opt/homebrew/bin', '/opt/homebrew/sbin', '/usr/local/bin']) push(d);
28
+
29
+ if (add.length) {
30
+ process.env.PATH = `${process.env.PATH}:${add.join(':')}`;
31
+ console.log(`[coxpit] PATH augmented for GUI/launchd launch (+${add.length}: ${add.join(', ')})`);
32
+ }
33
+ }
package/src/server.ts CHANGED
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { resolve as presolve, dirname as pdirname, join as pjoin, sep as psep } from 'node:path';
5
5
  import { createRequire } from 'node:module';
6
6
  import { randomBytes } from 'node:crypto';
7
+ import { execFileSync } from 'node:child_process';
7
8
  import Fastify, { type FastifyInstance, type FastifyReply } from 'fastify';
8
9
  import websocket from '@fastify/websocket';
9
10
  import { eq, inArray, and, like, desc } from 'drizzle-orm';
@@ -185,8 +186,26 @@ function sharePageHTML(
185
186
  </div></body></html>`;
186
187
  }
187
188
 
189
+ // macOS 의 machine-wide pty 상한(kern.tty.ptmx_max). 1회 캐시. 다른 OS 는 null.
190
+ let cachedPtyMax: number | null | undefined;
191
+ function ptyMax(): number | null {
192
+ if (cachedPtyMax !== undefined) return cachedPtyMax;
193
+ cachedPtyMax = null;
194
+ if (process.platform === 'darwin') {
195
+ try {
196
+ const n = Number(execFileSync('sysctl', ['-n', 'kern.tty.ptmx_max'], { timeout: 2000 }).toString().trim());
197
+ cachedPtyMax = Number.isFinite(n) && n > 0 ? n : null;
198
+ } catch { cachedPtyMax = null; }
199
+ }
200
+ return cachedPtyMax;
201
+ }
202
+
188
203
  export async function buildServer(): Promise<FastifyInstance> {
189
204
  const app = Fastify({ logger: true });
205
+ // 살아있는 웹 터미널 수 — pty 압력 조기경보(/api/health)용. openTerm 성공 시 +1, 소켓 close 시 -1.
206
+ // 누수가 재발하면 이 값이 실제 열린 탭보다 커지지 않아도(닫을 때 감소), machine-wide ptmx 대비
207
+ // 이 데몬의 부하를 노출한다. leak 재발 자체는 회귀 테스트(test/pty-fd.mjs)가 잡는다.
208
+ let liveTerminals = 0;
190
209
  await app.register(websocket);
191
210
  // urlencoded 본문 파서(deps 0) — login/setup 폼이 real navigation POST 를 보내면
192
211
  // 브라우저가 그 응답의 Set-Cookie 를 확정 커밋한다(Safari fetch-then-replace 레이스 회피).
@@ -205,7 +224,10 @@ export async function buildServer(): Promise<FastifyInstance> {
205
224
  app.addHook('onRequest', authGate);
206
225
 
207
226
  // 무인증 헬스(외부 감시용)
208
- app.get('/api/health', async () => ({ ok: true, name: 'coxpit', version: config.version }));
227
+ app.get('/api/health', async () => {
228
+ const max = ptyMax();
229
+ return { ok: true, name: 'coxpit', version: config.version, terminals: liveTerminals, ...(max ? { ptyMax: max } : {}) };
230
+ });
209
231
 
210
232
  // 플릿 보드(단일 페이지). 인증 게이트 적용됨(무인증 요청은 게이트가 login/setup 페이지로 응답).
211
233
  app.get('/', async (_req, reply) => reply.type('text/html').send(BOARD_HTML));
@@ -1603,10 +1625,25 @@ export async function buildServer(): Promise<FastifyInstance> {
1603
1625
  try {
1604
1626
  term = openTerm(info.machine, info.session, cols, rows);
1605
1627
  } catch (e) {
1606
- socket.send(JSON.stringify({ t: 'err', d: 'pty spawn failed: ' + String(e).slice(0, 200) }));
1628
+ // 에러 문구를 실행 가능한 사유로 번역(원문은 원인을 가린다 issue #9/#10).
1629
+ const raw = String(e);
1630
+ let d: string;
1631
+ if (raw.includes('posix_spawnp failed')) {
1632
+ d = 'no free pty on this machine (kern.tty.ptmx_max reached) — restart the coxpit daemon';
1633
+ req.log.warn({ err: raw }, 'pty exhausted (posix_spawnp failed) — machine out of ptys');
1634
+ } else if (raw.includes('ENOENT')) {
1635
+ const bin = /spawn (\S+) ENOENT/.exec(raw)?.[1] ?? 'tmux';
1636
+ d = `terminal binary "${bin}" not found on the daemon PATH — install it, or set COXPIT_TMUX / launch the app with Homebrew on PATH`;
1637
+ req.log.warn({ err: raw }, 'terminal binary not on PATH (ENOENT)');
1638
+ } else {
1639
+ d = 'pty spawn failed: ' + raw.slice(0, 200);
1640
+ }
1641
+ socket.send(JSON.stringify({ t: 'err', d }));
1607
1642
  socket.close();
1608
1643
  return;
1609
1644
  }
1645
+ liveTerminals++; // pty 압력 지표(/api/health) — close 에서 정확히 1회 감소
1646
+ let closed = false;
1610
1647
  // 백프레셔 — WS 송신 버퍼가 차면 pty 를 잠시 멈춰 폭주 방지
1611
1648
  let paused = false;
1612
1649
  term.onData((d) => {
@@ -1629,6 +1666,7 @@ export async function buildServer(): Promise<FastifyInstance> {
1629
1666
  } catch { /* ignore */ }
1630
1667
  });
1631
1668
  socket.on('close', () => {
1669
+ if (!closed) { closed = true; liveTerminals = Math.max(0, liveTerminals - 1); }
1632
1670
  clearInterval(drain); clearInterval(keepalive);
1633
1671
  try { term.kill(); } catch { /* gone */ }
1634
1672
  });
package/src/term.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'node:module';
2
- import { chmodSync } from 'node:fs';
2
+ import { chmodSync, closeSync, fstatSync, readdirSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import type { IPty } from 'node-pty';
5
5
  import { config } from './config';
@@ -13,8 +13,15 @@ function fixSpawnHelper(): void {
13
13
  try {
14
14
  const ptyPkg = require_.resolve('node-pty/package.json');
15
15
  const base = dirname(ptyPkg);
16
+ const candidates = [
17
+ join(base, 'build', 'Release', 'spawn-helper'), // 소스빌드(node-gyp) 경로
18
+ join(base, 'build', 'Debug', 'spawn-helper'),
19
+ ];
16
20
  for (const dir of [`darwin-${process.arch}`, `linux-${process.arch}`]) {
17
- try { chmodSync(join(base, 'prebuilds', dir, 'spawn-helper'), 0o755); } catch { /* absent */ }
21
+ candidates.push(join(base, 'prebuilds', dir, 'spawn-helper'));
22
+ }
23
+ for (const p of candidates) {
24
+ try { chmodSync(p, 0o755); } catch { /* absent or read-only bundle */ }
18
25
  }
19
26
  } catch { /* node-pty missing — openTerm 에서 에러 */ }
20
27
  }
@@ -28,6 +35,39 @@ function pty(): PtyModule {
28
35
  return ptyMod;
29
36
  }
30
37
 
38
+ // node-pty 1.1.0 의 macOS(posix_spawn) 경로는 spawn 마다 pty master 를 하나 더 열고 안 닫는다
39
+ // (src/unix/pty.cc pty_posix_spawn: low_fds 정리 루프가 count==0 이면 아무것도 닫지 않음).
40
+ // 터미널을 열 때마다 /dev/ptmx 가 하나씩 새어 kern.tty.ptmx_max(맥 기본 511) 가 마르면
41
+ // 그 뒤로는 모든 spawn 이 "posix_spawnp failed." 로 죽는다 (2026-09-10 맥미니 데몬 256개 누수).
42
+ // spawn 전후의 fd 를 비교해, 새로 생긴 pty master(term.fd 와 같은 major 의 문자 디바이스) 중
43
+ // term.fd 가 아닌 것만 닫는다. 슬레이브·kqueue·/dev/null 은 major 가 달라 건드리지 않고,
44
+ // 스레드풀이 동시에 여는 일반 파일도 문자 디바이스가 아니라 안전하다. Linux 는 forkpty 경로라 해당 없음.
45
+ function liveFds(): Set<number> {
46
+ const s = new Set<number>();
47
+ for (const n of readdirSync('/dev/fd')) {
48
+ const fd = Number(n);
49
+ try { fstatSync(fd); s.add(fd); } catch { /* readdir 자신의 fd 등 이미 닫힌 것 */ }
50
+ }
51
+ return s;
52
+ }
53
+ export function spawnPty(file: string, args: string[], opts: Parameters<PtyModule['spawn']>[2]): IPty {
54
+ if (process.platform !== 'darwin') return pty().spawn(file, args, opts);
55
+ const before = liveFds();
56
+ const term = pty().spawn(file, args, opts);
57
+ const fd = (term as unknown as { fd?: number }).fd;
58
+ if (typeof fd !== 'number') return term;
59
+ let masterMajor: number;
60
+ try { masterMajor = (fstatSync(fd).rdev >> 24) & 0xff; } catch { return term; }
61
+ for (const n of liveFds()) {
62
+ if (n === fd || before.has(n)) continue;
63
+ try {
64
+ const st = fstatSync(n);
65
+ if (st.isCharacterDevice() && ((st.rdev >> 24) & 0xff) === masterMajor) closeSync(n);
66
+ } catch { /* 그 사이 닫힘 */ }
67
+ }
68
+ return term;
69
+ }
70
+
31
71
  function isLocal(m: MachineTarget): boolean {
32
72
  return m.kind === 'local' || m.address === '';
33
73
  }
@@ -45,7 +85,7 @@ export function openTerm(m: MachineTarget, session: string, cols: number, rows:
45
85
  env: { ...process.env, TERM: 'xterm-256color', LANG: config.lang } as Record<string, string>,
46
86
  };
47
87
  if (isLocal(m)) {
48
- return pty().spawn('tmux', ['attach-session', '-t', '=' + session], opts);
88
+ return spawnPty('tmux', ['attach-session', '-t', '=' + session], opts);
49
89
  }
50
90
  const args: string[] = [
51
91
  '-tt',
@@ -58,5 +98,5 @@ export function openTerm(m: MachineTarget, session: string, cols: number, rows:
58
98
  // 세션명은 우리가 만든 coxpit-rN 형식이라 셸 주입 여지 없음 — 그래도 인용.
59
99
  // 원격도 UTF-8 로케일 명시 (비대화 ssh 는 LANG 미설정이 보통)
60
100
  args.push(target, `export LANG='${config.lang.replace(/'/g, '')}'; tmux attach-session -t '=${session.replace(/'/g, "'\\''")}'`);
61
- return pty().spawn('ssh', args, opts);
101
+ return spawnPty('ssh', args, opts);
62
102
  }