thinkpool-pair 0.7.61 → 0.7.63
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/account.mjs +59 -3
- package/bridge.mjs +28 -101
- package/launcher.mjs +3 -20
- package/package.json +1 -2
- package/cmux.mjs +0 -148
package/account.mjs
CHANGED
|
@@ -61,6 +61,25 @@ export function releaseSingleton(lockPath = LOCK) {
|
|
|
61
61
|
try { if ((parseInt(fs.readFileSync(lockPath, 'utf8').trim(), 10) || 0) === process.pid) fs.rmSync(lockPath, { force: true }) } catch { /* noop */ }
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
// ── machine-wide single-bridge lock ─────────────────────────────────────────
|
|
65
|
+
// The SAME pidfile is now the machine-wide "one live bridge" lock, not just the
|
|
66
|
+
// account-supervisor guard: a standalone `npx thinkpool-pair <ROOM>` takes it too
|
|
67
|
+
// (see bridge.mjs, post-`--supervise`). Two bridges serving one room race its
|
|
68
|
+
// terminal reconcile, which reaps + CASCADE-deletes terminal history (the XE3IQ
|
|
69
|
+
// "flat search" loss, 2026-06-25). Account mode and standalone room mode share
|
|
70
|
+
// this lock; an account-spawned room child skips it because its parent
|
|
71
|
+
// supervisor already holds it. Wrappers so bridge.mjs need not know the path.
|
|
72
|
+
export function acquireMachineLock(lockPath = LOCK) { return acquireSingleton(lockPath) }
|
|
73
|
+
export function releaseMachineLock(lockPath = LOCK) { return releaseSingleton(lockPath) }
|
|
74
|
+
|
|
75
|
+
// A served bridge process must hold the machine lock UNLESS it's a room child the
|
|
76
|
+
// account supervisor spawned (THINKPOOL_PAIR_ACCOUNT_CHILD=1) — the parent holds
|
|
77
|
+
// it, and a child fighting its parent for the lock would refuse itself and break
|
|
78
|
+
// account mode. Pure (env in) so the policy is unit-testable.
|
|
79
|
+
export function shouldHoldMachineLock(env = process.env) {
|
|
80
|
+
return env.THINKPOOL_PAIR_ACCOUNT_CHILD !== '1'
|
|
81
|
+
}
|
|
82
|
+
|
|
64
83
|
// ── login: OAuth-style DEVICE-CODE flow (hardened) ──────────────────────────
|
|
65
84
|
// The bridge asks Postgres (start_device_code) for a secret device_code + a short
|
|
66
85
|
// human user_code, prints the user_code + URL, then POLLS claim_device_code with
|
|
@@ -248,8 +267,8 @@ export async function runAccount(SUPABASE_URL, SUPABASE_ANON) {
|
|
|
248
267
|
})
|
|
249
268
|
// Dashboard "Restart" → broadcast restart → graceful stop with a NON-ZERO exit so
|
|
250
269
|
// EVERY supervisor respawns us: launchd KeepAlive / systemd Restart=always respawn
|
|
251
|
-
// regardless of exit code, and the bridge.mjs --supervise
|
|
252
|
-
//
|
|
270
|
+
// regardless of exit code, and the bridge.mjs --supervise wrapper (room tier)
|
|
271
|
+
// respawns on non-zero but treats 0 as a clean stop. Children persist + resume
|
|
253
272
|
// their sessions (session-store), so the bounce is invisible in-room. Unlike shutdown
|
|
254
273
|
// we do NOT uninstall the service. A plain foreground bridge has no supervisor, so it
|
|
255
274
|
// just stops — restart is meaningful for the always-on bridge. Old bridges (pre-0.7.60)
|
|
@@ -287,7 +306,44 @@ export async function runAccount(SUPABASE_URL, SUPABASE_ANON) {
|
|
|
287
306
|
forceMs: parseInt(process.env.TP_TOKEN_REFRESH_FORCE_MS, 10) || 0,
|
|
288
307
|
})
|
|
289
308
|
|
|
309
|
+
// ── cross-machine single active bridge (INV-2) ──────────────────────────────
|
|
310
|
+
// account.lock guards THIS Mac; this claim guards the ACCOUNT across Macs. We
|
|
311
|
+
// serve rooms ONLY while we hold the claim. A non-holder stands by (stays alive
|
|
312
|
+
// for launchd KeepAlive, serves nothing) and takes over only when the holder's
|
|
313
|
+
// heartbeat goes stale — so two launchd bridges never flap respawning. Two Macs
|
|
314
|
+
// both serving one account is the cross-machine half of the terminal-reconcile
|
|
315
|
+
// reap that lost room XE3IQ's history.
|
|
316
|
+
// Spec: docs/specs/2026-06-25-single-bridge-durable-history.md (INV-2)
|
|
317
|
+
const BRIDGE_ID = randomUUID()
|
|
318
|
+
let claimHeld = false
|
|
319
|
+
let standbyHost = null
|
|
320
|
+
const refreshClaim = async () => {
|
|
321
|
+
try {
|
|
322
|
+
const { data } = await sb.rpc('claim_bridge', { p_bridge_id: BRIDGE_ID, p_hostname: machine })
|
|
323
|
+
const c = Array.isArray(data) ? data[0] : data
|
|
324
|
+
const held = !!c?.held
|
|
325
|
+
const host = c?.holder_host || '?'
|
|
326
|
+
if (held && !claimHeld) process.stderr.write(`\n ◆ holding this account — serving your sessions (single active bridge).\n`)
|
|
327
|
+
else if (!held && claimHeld) process.stderr.write(`\n ◇ another device (${host}) took over this account — standing by.\n`)
|
|
328
|
+
else if (!held && standbyHost !== host) process.stderr.write(`\n ◇ another device (${host}) is serving this account — standing by.\n (this Mac takes over automatically if that device goes offline.)\n`)
|
|
329
|
+
claimHeld = held
|
|
330
|
+
standbyHost = held ? null : host
|
|
331
|
+
return held
|
|
332
|
+
} catch {
|
|
333
|
+
// Transient claim error: keep serving if we already hold; never START
|
|
334
|
+
// serving on an unknown claim (that's the double-serve we're preventing).
|
|
335
|
+
return claimHeld
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
290
339
|
const tick = async () => {
|
|
340
|
+
// Hold the account claim before serving anything (cross-machine guard). When
|
|
341
|
+
// standing by, make sure we're serving nothing and wait for the next tick.
|
|
342
|
+
if (!(await refreshClaim())) {
|
|
343
|
+
if (children.size) for (const [, ch] of children) { try { ch.kill('SIGTERM') } catch { /* noop */ } }
|
|
344
|
+
pushPresence()
|
|
345
|
+
return
|
|
346
|
+
}
|
|
291
347
|
let rooms = []
|
|
292
348
|
try {
|
|
293
349
|
// Owner-only discovery (Contract C-CODE-2): a host bridges ONLY the sessions
|
|
@@ -351,7 +407,7 @@ export async function runAccount(SUPABASE_URL, SUPABASE_ANON) {
|
|
|
351
407
|
for (const c of children.values()) { try { c.kill(sig || 'SIGTERM') } catch { /* noop */ } }
|
|
352
408
|
// Flush the presence LEAVE before exiting so the dashboard flips to
|
|
353
409
|
// "not connected" in realtime (don't fire-and-forget the untrack).
|
|
354
|
-
;(async () => { try { await acct.untrack() } catch { /* noop */ } try { await sb.removeChannel(acct) } catch { /* noop */ } process.exit(code) })()
|
|
410
|
+
;(async () => { try { if (claimHeld) await sb.rpc('release_bridge', { p_bridge_id: BRIDGE_ID }) } catch { /* noop */ } try { await acct.untrack() } catch { /* noop */ } try { await sb.removeChannel(acct) } catch { /* noop */ } process.exit(code) })()
|
|
355
411
|
setTimeout(() => process.exit(code), 1500) // hard backstop if the flush hangs
|
|
356
412
|
}
|
|
357
413
|
for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => stop(sig))
|
package/bridge.mjs
CHANGED
|
@@ -150,14 +150,7 @@ if (argv[0] === 'install-service' || argv[0] === 'uninstall-service') {
|
|
|
150
150
|
const autoUpdate = argv.includes('--auto-update')
|
|
151
151
|
const svc = await import('./service.mjs')
|
|
152
152
|
if (argv[0] === 'install-service') svc.installService(svcRoom, svcCmd, { autoUpdate })
|
|
153
|
-
else
|
|
154
|
-
// Account scope (room=null) may be the cmux-hosted tier (cmux-service.json) —
|
|
155
|
-
// that's torn down via cmux, not launchctl/systemctl. Room scope is always OS.
|
|
156
|
-
const cmux = await import('./cmux.mjs')
|
|
157
|
-
if (svcRoom === null && cmux.isCmuxServiceInstalled()) {
|
|
158
|
-
cmux.uninstallCmuxService(); process.stderr.write(' ◆ removed the cmux-hosted account service.\n')
|
|
159
|
-
} else svc.uninstallService(svcRoom)
|
|
160
|
-
}
|
|
153
|
+
else svc.uninstallService(svcRoom)
|
|
161
154
|
process.exit(0)
|
|
162
155
|
}
|
|
163
156
|
|
|
@@ -166,10 +159,7 @@ if (argv[0] === 'install-service' || argv[0] === 'uninstall-service') {
|
|
|
166
159
|
if (argv[0] === 'restart-service') {
|
|
167
160
|
const arg1 = argv[1] || ''
|
|
168
161
|
const svcRoom = (!arg1 || arg1.startsWith('-')) ? null : arg1.toUpperCase().trim()
|
|
169
|
-
const
|
|
170
|
-
if (svcRoom === null && cmux.isCmuxServiceInstalled()) {
|
|
171
|
-
cmux.restartCmuxService(); process.stderr.write(' ◆ restarted the cmux-hosted account service — sessions resume in place.\n')
|
|
172
|
-
} else { const svc = await import('./service.mjs'); svc.restartService(svcRoom) }
|
|
162
|
+
const svc = await import('./service.mjs'); svc.restartService(svcRoom)
|
|
173
163
|
process.exit(0)
|
|
174
164
|
}
|
|
175
165
|
|
|
@@ -190,62 +180,6 @@ if (argv[0] === 'login') { const { runLogin } = await import('./account.mjs'); a
|
|
|
190
180
|
if (argv[0] === 'bind') { const { runBind } = await import('./account.mjs'); runBind(argv[1], argv[2]) }
|
|
191
181
|
if (argv[0] === 'provider') { const { runProvider } = await import('./provider.mjs'); await runProvider(argv.slice(1)); process.exit(0) }
|
|
192
182
|
|
|
193
|
-
// Explicit account-serve entrypoint — used by the cmux-hosted service tier (cmux.mjs).
|
|
194
|
-
// A cmux surface HAS a TTY, so a bare invocation would open the interactive launcher
|
|
195
|
-
// instead of serving; `serve` runs account mode directly, regardless of TTY. With
|
|
196
|
-
// `--supervise` it first wraps itself in a crash-restart loop (re-execing `serve`
|
|
197
|
-
// without the flag): cmux, unlike launchd KeepAlive, will not relaunch a surface
|
|
198
|
-
// whose command exits, so the account supervisor must restart itself.
|
|
199
|
-
if (argv[0] === 'serve') {
|
|
200
|
-
if (argv.includes('--supervise') || argv.includes('--keep-alive')) {
|
|
201
|
-
const childArgs = process.argv.slice(1).filter((a) => a !== '--supervise' && a !== '--keep-alive')
|
|
202
|
-
let backoff = 1000, stopping = false, child = null
|
|
203
|
-
const spawnChild = () => {
|
|
204
|
-
const t0 = Date.now()
|
|
205
|
-
child = spawn(process.execPath, childArgs, { stdio: 'inherit' })
|
|
206
|
-
child.on('exit', (code, signal) => {
|
|
207
|
-
if (stopping || code === 0) process.exit(code || 0)
|
|
208
|
-
const ranLong = Date.now() - t0 > 60000
|
|
209
|
-
const wait = ranLong ? 1000 : backoff
|
|
210
|
-
backoff = ranLong ? 1000 : Math.min(backoff * 2, 30000)
|
|
211
|
-
process.stderr.write(`\n ⚠ account supervisor exited (${signal || `code ${code}`}); restarting in ${Math.round(wait / 1000)}s…\n`)
|
|
212
|
-
setTimeout(spawnChild, wait)
|
|
213
|
-
})
|
|
214
|
-
child.on('error', () => { /* spawn failure → exit handler retries */ })
|
|
215
|
-
}
|
|
216
|
-
for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => { stopping = true; try { child?.kill(sig) } catch { /* noop */ } setTimeout(() => process.exit(0), 400) })
|
|
217
|
-
process.stderr.write('\n ◆ supervisor up — keeping the account bridge alive (auto-restart on crash).\n')
|
|
218
|
-
spawnChild()
|
|
219
|
-
await new Promise(() => {}) // block forever; the child IS the account supervisor
|
|
220
|
-
}
|
|
221
|
-
const { runAccount } = await import('./account.mjs')
|
|
222
|
-
await runAccount(SUPABASE_URL, SUPABASE_ANON)
|
|
223
|
-
process.exit(0)
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// `npx thinkpool-pair cmux-doctor` — explain why the cmux service tier did/didn't engage.
|
|
227
|
-
// Detection is env-based (CMUX_WORKSPACE_ID/SURFACE_ID); the socket is only needed for the
|
|
228
|
-
// actual surface spawn. This prints both so a "it didn't detect cmux" report is one command.
|
|
229
|
-
if (argv[0] === 'cmux-doctor') {
|
|
230
|
-
const cmux = await import('./cmux.mjs')
|
|
231
|
-
const env = process.env
|
|
232
|
-
const w = (s) => process.stderr.write(s + '\n')
|
|
233
|
-
const reachable = cmux.cmuxReachable()
|
|
234
|
-
w('\n thinkpool-pair · cmux doctor')
|
|
235
|
-
w(` CMUX_WORKSPACE_ID : ${env.CMUX_WORKSPACE_ID || '(unset)'}`)
|
|
236
|
-
w(` CMUX_SURFACE_ID : ${env.CMUX_SURFACE_ID || '(unset)'}`)
|
|
237
|
-
w(` CMUX_SOCKET_PATH : ${env.CMUX_SOCKET_PATH || '(unset)'}`)
|
|
238
|
-
w(` cmux on PATH : ${onPath('cmux')}`)
|
|
239
|
-
w(` inCmux() : ${cmux.inCmux()}`)
|
|
240
|
-
w(` cmux ping : ${reachable ? 'ok' : 'FAILED (socket unreachable)'}`)
|
|
241
|
-
w(` detectCmux() : ${cmux.detectCmux()} ${cmux.detectCmux() ? '→ cmux-surface offered' : '→ falls back to OS service'}`)
|
|
242
|
-
w(` cmux service set : ${cmux.isCmuxServiceInstalled()}`)
|
|
243
|
-
if (!cmux.inCmux()) w('\n ⚠ not launched from cmux (no CMUX_WORKSPACE_ID/SURFACE_ID). Run this INSIDE a cmux\n terminal surface — a plain Terminal/iTerm window will not be detected.')
|
|
244
|
-
else if (!reachable) w('\n ⚠ in cmux, but the automation socket is unreachable. detectCmux() is env-based so\n the surface is still offered, but the actual spawn needs the socket — if install\n falls back to the OS service, enable cmux automation/socket access in cmux settings.')
|
|
245
|
-
else w('\n ✓ cmux detected and drivable — the cmux-surface service tier is available.')
|
|
246
|
-
process.exit(0)
|
|
247
|
-
}
|
|
248
|
-
|
|
249
183
|
// One-command launcher: a bare invocation on a TTY (or the `setup` alias) opens the
|
|
250
184
|
// interactive menu instead of going straight to account mode. The menu only ASSEMBLES
|
|
251
185
|
// existing commands — it re-execs `<ROOM>`, or calls installService / runLogin /
|
|
@@ -255,7 +189,6 @@ if (argv[0] === 'cmux-doctor') {
|
|
|
255
189
|
if ((!argv[0] || argv[0] === 'setup') && process.stdin.isTTY) {
|
|
256
190
|
const { runLauncher, detectState } = await import('./launcher.mjs')
|
|
257
191
|
const svc = await import('./service.mjs')
|
|
258
|
-
const cmux = await import('./cmux.mjs')
|
|
259
192
|
const PKG_VERSION = (() => { try { return JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version } catch { return 'latest' } })()
|
|
260
193
|
const BRIDGE = fileURLToPath(import.meta.url)
|
|
261
194
|
const io = {
|
|
@@ -278,39 +211,14 @@ if ((!argv[0] || argv[0] === 'setup') && process.stdin.isTTY) {
|
|
|
278
211
|
// notes, and RETURN so the launcher loop drops you back at the menu (the service
|
|
279
212
|
// runs in its own launchd/systemd process; this launcher isn't itself a bridge).
|
|
280
213
|
installService: ({ room = null, agentCmd } = {}) => { svc.installService(room, agentCmd ? [agentCmd] : []) },
|
|
281
|
-
uninstallService: ({ room = null } = {}) => {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
if (room === null && cmux.isCmuxServiceInstalled()) { cmux.restartCmuxService(); process.stderr.write('\n ◆ restarted the cmux-hosted account service — sessions resume in place.\n') }
|
|
287
|
-
else svc.restartService(room)
|
|
288
|
-
},
|
|
289
|
-
// "Restart & update the bridge" — re-pin the service to THIS launcher's version
|
|
290
|
-
// (you launched via @latest, so it's the newest publish) and restart. The cmux
|
|
291
|
-
// surface re-pins + respawns; the OS service is reinstalled (rewrites the plist/unit
|
|
292
|
-
// to the new version and reloads). Pinned throughout — no auto-roll.
|
|
214
|
+
uninstallService: ({ room = null } = {}) => { svc.uninstallService(room) },
|
|
215
|
+
restartService: ({ room = null } = {}) => { svc.restartService(room) },
|
|
216
|
+
// "Restart & update the bridge" — re-pin the OS service to THIS launcher's version
|
|
217
|
+
// (you launched via @latest, so it's the newest publish) and restart: the service is
|
|
218
|
+
// reinstalled (rewrites the plist/unit to the new version and reloads). Pinned — no auto-roll.
|
|
293
219
|
restartUpdateService: ({ room = null } = {}) => {
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
process.stderr.write(`\n ◆ updated the cmux account service to v${PKG_VERSION} and restarted it — sessions resume in place.\n`)
|
|
297
|
-
} else {
|
|
298
|
-
process.stderr.write(`\n ◆ updating the background service to v${PKG_VERSION} and restarting…\n`)
|
|
299
|
-
svc.installService(room, []) // rewrites the plist/unit at this version + reloads = update + restart
|
|
300
|
-
}
|
|
301
|
-
},
|
|
302
|
-
// Account service hosted as a cmux surface — offered only inside cmux, with its
|
|
303
|
-
// weaker-persistence caveat shown first (launcher.mjs serveAccount). Falls back to
|
|
304
|
-
// the OS service if the cmux socket can't actually be driven (detection is env-based).
|
|
305
|
-
detectCmux: () => cmux.detectCmux(),
|
|
306
|
-
installAccountCmux: () => {
|
|
307
|
-
try {
|
|
308
|
-
const rec = cmux.installCmuxService({ version: PKG_VERSION })
|
|
309
|
-
process.stderr.write(`\n ◆ account service now runs as a cmux surface ("${cmux.WS_NAME}") — visible and killable.\n ◆ it restarts itself on crash; stop it with: npx thinkpool-pair uninstall-service\n ◆ pinned to v${rec.version}.\n\n`)
|
|
310
|
-
} catch (e) {
|
|
311
|
-
process.stderr.write(`\n ⚠ couldn't spawn a cmux surface (${e.message || e}). The cmux automation socket may be\n disabled — run 'npx thinkpool-pair cmux-doctor' to check. Falling back to the system service.\n`)
|
|
312
|
-
svc.installService(null, [])
|
|
313
|
-
}
|
|
220
|
+
process.stderr.write(`\n ◆ updating the background service to v${PKG_VERSION} and restarting…\n`)
|
|
221
|
+
svc.installService(room, []) // rewrites the plist/unit at this version + reloads = update + restart
|
|
314
222
|
},
|
|
315
223
|
login: async () => { const { runLogin } = await import('./account.mjs'); await runLogin(SUPABASE_URL, SUPABASE_ANON, WEB_BASE) },
|
|
316
224
|
// Provider config is NOT terminal — it writes provider.json and returns to the
|
|
@@ -361,6 +269,25 @@ if (_superOwn.includes('--supervise') || _superOwn.includes('--keep-alive')) {
|
|
|
361
269
|
await new Promise(() => {}) // block forever; the child IS the bridge
|
|
362
270
|
}
|
|
363
271
|
|
|
272
|
+
// ── machine-wide single-bridge lock ─────────────────────────────────────────
|
|
273
|
+
// Reached only by the ACTUAL serving process: a direct run, the supervised child
|
|
274
|
+
// (the `--supervise` wrapper above blocks forever at line ~269 and never gets
|
|
275
|
+
// here), or an account-spawned room child. Only one live bridge per machine —
|
|
276
|
+
// a second standalone bridge serving the same rooms races their terminal
|
|
277
|
+
// reconcile, which reaps + CASCADE-deletes terminal history (the XE3IQ "flat
|
|
278
|
+
// search" loss, 2026-06-25). Account children skip the lock (parent holds it).
|
|
279
|
+
// Acquiring HERE — not in the supervisor wrapper — keeps a respawn able to
|
|
280
|
+
// re-acquire and stops the wrapper fighting its own child.
|
|
281
|
+
// Spec: docs/specs/2026-06-25-single-bridge-durable-history.md
|
|
282
|
+
{
|
|
283
|
+
const { acquireMachineLock, releaseMachineLock, shouldHoldMachineLock } = await import('./account.mjs')
|
|
284
|
+
if (shouldHoldMachineLock(process.env) && !acquireMachineLock()) {
|
|
285
|
+
console.error('\n ◇ A thinkpool-pair bridge is already running on this machine\n (~/.thinkpool-pair/account.lock). Only one can be active, and the running\n one already serves every room you are in — use it, or stop it first.\n (If you are certain none is running, delete that stale lock file.)\n')
|
|
286
|
+
process.exit(1)
|
|
287
|
+
}
|
|
288
|
+
if (shouldHoldMachineLock(process.env)) process.on('exit', () => { try { releaseMachineLock() } catch { /* noop */ } })
|
|
289
|
+
}
|
|
290
|
+
|
|
364
291
|
const headless = argv.includes('--headless')
|
|
365
292
|
// Account-mode children pass --auto=<agent> so a served session opens a live
|
|
366
293
|
// terminal automatically (headless, no TTY/picker) instead of an empty room.
|
package/launcher.mjs
CHANGED
|
@@ -13,7 +13,6 @@
|
|
|
13
13
|
import os from 'node:os'
|
|
14
14
|
import fs from 'node:fs'
|
|
15
15
|
import path from 'node:path'
|
|
16
|
-
import { isCmuxServiceInstalled } from './cmux.mjs'
|
|
17
16
|
|
|
18
17
|
const HOME = os.homedir()
|
|
19
18
|
const CFG_DIR = path.join(HOME, '.thinkpool-pair')
|
|
@@ -61,11 +60,7 @@ export function detectState() {
|
|
|
61
60
|
provider: isCustom ? `Custom (${provider.baseUrl || 'endpoint'})` : 'Anthropic (default)',
|
|
62
61
|
providerModel: isCustom ? (provider.model || null) : null,
|
|
63
62
|
agents: KNOWN_AGENTS.filter(a => onPath(a.cmd)),
|
|
64
|
-
accountSvc: fs.existsSync(serviceFile(null))
|
|
65
|
-
// Which tier hosts the account service, so the menu can label it honestly.
|
|
66
|
-
// Cheap, read-only (file existence) — no cmux socket call here; the live
|
|
67
|
-
// cmux detection (which pings) happens in serveAccount at install time.
|
|
68
|
-
accountSvcKind: isCmuxServiceInstalled() ? 'cmux' : (fs.existsSync(serviceFile(null)) ? 'os' : null),
|
|
63
|
+
accountSvc: fs.existsSync(serviceFile(null)),
|
|
69
64
|
cwd: process.cwd(),
|
|
70
65
|
}
|
|
71
66
|
}
|
|
@@ -100,7 +95,7 @@ export async function runLauncher({ actions, io, state = detectState(), refresh
|
|
|
100
95
|
io.print(` ${C.dim('│ provider ')} ${state.provider}`)
|
|
101
96
|
io.print(` ${C.dim('│ agents ')} ${state.agents.length ? state.agents.map(a => a.label).join(', ') : C.yellow('none on PATH')}`)
|
|
102
97
|
io.print(` ${C.dim('│ directory')} ${C.dim(state.cwd)}`)
|
|
103
|
-
io.print(` ${C.dim('│ service ')} ${state.accountSvc ? C.green('account service installed'
|
|
98
|
+
io.print(` ${C.dim('│ service ')} ${state.accountSvc ? C.green('account service installed') : 'none'}`)
|
|
104
99
|
io.print(' ' + C.dim('└' + '─'.repeat(54)) + '\n')
|
|
105
100
|
}
|
|
106
101
|
|
|
@@ -134,19 +129,7 @@ export async function runLauncher({ actions, io, state = detectState(), refresh
|
|
|
134
129
|
])
|
|
135
130
|
if (how === 2) return
|
|
136
131
|
if (how === 1) { await actions.serveAccountForeground(); return }
|
|
137
|
-
// how === 0 — always-on
|
|
138
|
-
// surface (visible + killable) — but flag its weaker persistence FIRST and let
|
|
139
|
-
// the user opt back into the durable OS service.
|
|
140
|
-
if (actions.detectCmux && actions.detectCmux()) {
|
|
141
|
-
io.print('\n ' + C.cyan('Detected cmux') + ' — I can run the service as a cmux surface you can see and kill,')
|
|
142
|
-
io.print(' alongside your other terminals. Heads up — this is ' + C.yellow('less durable') + ' than the system service:')
|
|
143
|
-
io.print(' ' + C.dim('•') + ' stays up while cmux is running')
|
|
144
|
-
io.print(' ' + C.dim('•') + ' restarts itself on crash (--supervise)')
|
|
145
|
-
io.print(' ' + C.dim('•') + ' best-effort return via cmux session-restore')
|
|
146
|
-
io.print(' ' + C.dim('•') + ' ' + C.yellow('does NOT survive logout/reboot') + ' unless cmux launches at login')
|
|
147
|
-
const useCmux = await askYesNo('\n Run it as a cmux surface? (n = always-on system service)', true)
|
|
148
|
-
if (useCmux) { await actions.installAccountCmux(); resync(); return }
|
|
149
|
-
}
|
|
132
|
+
// how === 0 — always-on durable OS service (launchd / systemd / Windows Startup).
|
|
150
133
|
await actions.installService({ room: null }); resync()
|
|
151
134
|
}
|
|
152
135
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "thinkpool-pair",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.63",
|
|
4
4
|
"description": "Share a local coding-agent CLI (Claude Code, Codex, Gemini, Aider, …) into a ThinkPool Code room, live.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -15,7 +15,6 @@
|
|
|
15
15
|
"transcript-sanitize.mjs",
|
|
16
16
|
"session-store.mjs",
|
|
17
17
|
"service.mjs",
|
|
18
|
-
"cmux.mjs",
|
|
19
18
|
"presence.mjs",
|
|
20
19
|
"account.mjs",
|
|
21
20
|
"auth-store.mjs",
|
package/cmux.mjs
DELETED
|
@@ -1,148 +0,0 @@
|
|
|
1
|
-
/* ─────────────────────────────────────────────────────────────
|
|
2
|
-
cmux.mjs — host the ACCOUNT service as a cmux surface instead of
|
|
3
|
-
a detached launchd/systemd daemon, when the bridge was launched
|
|
4
|
-
from inside cmux.
|
|
5
|
-
|
|
6
|
-
Why a separate tier: the OS service (service.mjs) is invisible —
|
|
7
|
-
it logs to a file and is supervised by launchd KeepAlive. Inside
|
|
8
|
-
cmux, the user would rather see the service running in a normal
|
|
9
|
-
surface they can watch and kill, alongside everything else. cmux,
|
|
10
|
-
unlike launchd, does NOT relaunch a surface whose command exits,
|
|
11
|
-
so the surface runs `serve --supervise` (bridge.mjs) which restarts
|
|
12
|
-
the account supervisor itself on crash.
|
|
13
|
-
|
|
14
|
-
Detection is deliberately strict: being on $PATH is NOT proof cmux
|
|
15
|
-
spawned us (claude-session.mjs makes the same distinction). Only the
|
|
16
|
-
CMUX_WORKSPACE_ID / CMUX_SURFACE_ID env vars — which cmux injects
|
|
17
|
-
into every surface it creates — prove it, and we additionally confirm
|
|
18
|
-
the socket actually answers before committing to this tier. If either
|
|
19
|
-
check fails the caller falls back to the OS service.
|
|
20
|
-
|
|
21
|
-
Persistence trade-off (flagged to the user in launcher.mjs before
|
|
22
|
-
install): up while cmux runs · crash-restart via --supervise ·
|
|
23
|
-
best-effort return on cmux session-restore · does NOT survive
|
|
24
|
-
logout/reboot unless cmux launches at login.
|
|
25
|
-
|
|
26
|
-
Spec: docs/specs/2026-06-23-cmux-hosted-account-service.md
|
|
27
|
-
───────────────────────────────────────────────────────────── */
|
|
28
|
-
|
|
29
|
-
import os from 'node:os'
|
|
30
|
-
import fs from 'node:fs'
|
|
31
|
-
import path from 'node:path'
|
|
32
|
-
import { execFileSync } from 'node:child_process'
|
|
33
|
-
|
|
34
|
-
const HOME = os.homedir()
|
|
35
|
-
const CFG_DIR = path.join(HOME, '.thinkpool-pair')
|
|
36
|
-
// One stable record per machine → exactly one cmux-hosted account service.
|
|
37
|
-
export const RECORD = path.join(CFG_DIR, 'cmux-service.json')
|
|
38
|
-
export const WS_NAME = 'thinkpool-pair service'
|
|
39
|
-
|
|
40
|
-
// Run a cmux CLI command; return trimmed stdout, or throw. Isolated so the rest
|
|
41
|
-
// of the module (and its tests) can run without the socket by injecting `run`.
|
|
42
|
-
function cmux(args, { timeout = 6000 } = {}) {
|
|
43
|
-
return execFileSync('cmux', args, { encoding: 'utf8', timeout, stdio: ['ignore', 'pipe', 'ignore'] }).trim()
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// cmux injects these into every surface it spawns. PATH containing a cmux shim is
|
|
47
|
-
// NOT enough — only the env proves cmux launched this shell.
|
|
48
|
-
export function inCmux(env = process.env) {
|
|
49
|
-
return !!(env.CMUX_WORKSPACE_ID || env.CMUX_SURFACE_ID)
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// Can we actually drive cmux right now? (socket answers a ping.) Returns false on
|
|
53
|
-
// any failure — a broken/absent socket means we cannot host a surface, so fall back.
|
|
54
|
-
export function cmuxReachable(run = cmux) {
|
|
55
|
-
try { run(['ping'], { timeout: 4000 }); return true } catch { return false }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Detection keys ONLY on the env cmux injects into every surface it spawns — NOT on
|
|
59
|
-
// whether the socket answers. The socket ping proved flaky (it needs CMUX_SOCKET_PASSWORD
|
|
60
|
-
// and can broken-pipe even from a real surface), and gating detection on it silently
|
|
61
|
-
// killed the cmux offer in 0.7.57. If the env says cmux we offer the cmux tier; if the
|
|
62
|
-
// actual new-workspace spawn then can't reach the socket, installCmuxService throws and
|
|
63
|
-
// the caller falls back to the OS service. (cmuxReachable stays exported for cmux-doctor.)
|
|
64
|
-
export function detectCmux(env = process.env) {
|
|
65
|
-
return inCmux(env)
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export function readRecord(recordFile = RECORD) {
|
|
69
|
-
try { return JSON.parse(fs.readFileSync(recordFile, 'utf8')) } catch { return null }
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
export function isCmuxServiceInstalled(recordFile = RECORD) {
|
|
73
|
-
return !!readRecord(recordFile)
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// The command the cmux surface runs. PINNED to the installing version (same safety
|
|
77
|
-
// default as service.mjs — a bad publish can't auto-roll to the always-on bridge).
|
|
78
|
-
// `serve` runs account mode regardless of TTY (a cmux surface has a TTY, so a bare
|
|
79
|
-
// invocation would open the interactive launcher instead). `--supervise` restarts
|
|
80
|
-
// the account supervisor on crash, since cmux won't re-run a dead surface.
|
|
81
|
-
export function serviceCommand(version) {
|
|
82
|
-
return `npx -y thinkpool-pair@${version || 'latest'} serve --supervise`
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// Pull a stable handle out of cmux output. Prefer a UUID (stable across reorders);
|
|
86
|
-
// fall back to a positional `workspace:N` ref; null if neither is present.
|
|
87
|
-
export function parseWorkspaceRef(out) {
|
|
88
|
-
const uuid = (String(out).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i) || [])[0]
|
|
89
|
-
if (uuid) return uuid
|
|
90
|
-
const ref = (String(out).match(/workspace:\d+/) || [])[0]
|
|
91
|
-
return ref || null
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// Best-effort: find the service workspace by its name when we have no stored ref
|
|
95
|
-
// (e.g. the record predates ref capture, or parsing failed at install time).
|
|
96
|
-
function resolveByName(run, name = WS_NAME) {
|
|
97
|
-
try {
|
|
98
|
-
const out = run(['--id-format', 'uuids', 'list-workspaces'])
|
|
99
|
-
const line = String(out).split('\n').find((l) => l.includes(name))
|
|
100
|
-
return line ? parseWorkspaceRef(line) : null
|
|
101
|
-
} catch { return null }
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function spawnSurface(run, command, cwd = HOME) {
|
|
105
|
-
// --focus false: never steal focus from the user's current surface.
|
|
106
|
-
const out = run(['--id-format', 'uuids', 'new-workspace', '--name', WS_NAME, '--cwd', cwd, '--command', command, '--focus', 'false'])
|
|
107
|
-
return parseWorkspaceRef(out)
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function closeSurface(run, rec) {
|
|
111
|
-
const ref = rec.workspace || resolveByName(run)
|
|
112
|
-
if (!ref) return
|
|
113
|
-
try { run(['close-workspace', '--workspace', ref]) } catch { /* may already be gone */ }
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
export function installCmuxService({ version, cwd = HOME, run = cmux, recordFile = RECORD } = {}) {
|
|
117
|
-
const command = serviceCommand(version)
|
|
118
|
-
const workspace = spawnSurface(run, command, cwd)
|
|
119
|
-
const rec = { kind: 'cmux', version: version || 'latest', name: WS_NAME, command, workspace, installedAt: new Date().toISOString() }
|
|
120
|
-
fs.mkdirSync(path.dirname(recordFile), { recursive: true })
|
|
121
|
-
fs.writeFileSync(recordFile, JSON.stringify(rec, null, 2))
|
|
122
|
-
return rec
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Restart = close the surface + spawn a fresh one. The account supervisor restores
|
|
126
|
-
// every active session from disk (session-store crash-resume), so sessions resume
|
|
127
|
-
// in place — same contract as an OS-service restart. Passing `version` re-pins the
|
|
128
|
-
// surface command to that version first (the "Restart & update the bridge" path):
|
|
129
|
-
// the command stays PINNED (never @latest — no auto-roll), just bumped to the version
|
|
130
|
-
// the user explicitly launched.
|
|
131
|
-
export function restartCmuxService({ run = cmux, recordFile = RECORD, version } = {}) {
|
|
132
|
-
const rec = readRecord(recordFile)
|
|
133
|
-
if (!rec) return false
|
|
134
|
-
closeSurface(run, rec)
|
|
135
|
-
if (version) { rec.version = version; rec.command = serviceCommand(version) }
|
|
136
|
-
rec.workspace = spawnSurface(run, rec.command)
|
|
137
|
-
rec.installedAt = new Date().toISOString()
|
|
138
|
-
fs.writeFileSync(recordFile, JSON.stringify(rec, null, 2))
|
|
139
|
-
return true
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
export function uninstallCmuxService({ run = cmux, recordFile = RECORD } = {}) {
|
|
143
|
-
const rec = readRecord(recordFile)
|
|
144
|
-
if (!rec) return false
|
|
145
|
-
closeSurface(run, rec)
|
|
146
|
-
try { fs.rmSync(recordFile, { force: true }) } catch { /* noop */ }
|
|
147
|
-
return true
|
|
148
|
-
}
|