Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(byoa): keep live engine inventory in sync (#80)
LILACcdd2ac5aaec6
diff --git a/server/src/__tests__/agents-computer-engine-inventory.test.ts b/server/src/__tests__/agents-computer-engine-inventory.test.tsnew file mode 100644index 0000000..f97c088--- /dev/null+++ b/server/src/__tests__/agents-computer-engine-inventory.test.ts@@ -0,0 +1,34 @@+/**+ * Runtime engine selection must use the daemon's current PATH inventory, not+ * the snapshot captured when the process started.+ */+import { test } from 'node:test'+import assert from 'node:assert/strict'+import {+ replaceEngineInventory,+ resolveAvailableEngine,+ type EngineInventory,+} from '../agents/computer/daemon.js'++test('a newly detected requested engine is selected without a daemon restart', () => {+ const inventory: EngineInventory = { current: ['claude'] }++ assert.equal(replaceEngineInventory(inventory, ['claude', 'cursor']), true)+ assert.equal(resolveAvailableEngine('cursor', inventory.current), 'cursor')+})++test('no installed engines leaves the agent without a runnable fallback', () => {+ const inventory: EngineInventory = { current: ['claude'] }++ assert.equal(replaceEngineInventory(inventory, []), true)+ assert.equal(resolveAvailableEngine('claude', inventory.current), null)+})++test('an unchanged scan does not replace the shared inventory', () => {+ const current = ['claude', 'codex'] as const+ const inventory: EngineInventory = { current: [...current] }+ const before = inventory.current++ assert.equal(replaceEngineInventory(inventory, current), false)+ assert.equal(inventory.current, before)+})diff --git a/server/src/__tests__/computer-engine-redetect.test.ts b/server/src/__tests__/computer-engine-redetect.test.tsindex 85f699f..91c54c9 100644--- a/server/src/__tests__/computer-engine-redetect.test.ts+++ b/server/src/__tests__/computer-engine-redetect.test.ts@@ -9,7 +9,7 @@** Run: node --import tsx --test server/src/__tests__/computer-engine-redetect.test.ts*/-import { test } from 'node:test'+import { afterEach, test } from 'node:test'import assert from 'node:assert/strict'// Same shape as agent-computer-pairing-token.test.ts: pin the HTTP runtime@@ -17,7 +17,14 @@ import assert from 'node:assert/strict'// client's dependency graph into a unit run.process.env.CUMORA_RUNTIME_CLIENT = 'http'-const { mergeDetectedEngines } = await import('../agents/computer/registry.js')+const { heartbeatComputer, mergeDetectedEngines } = await import('../agents/computer/registry.js')+const { pool } = await import('../db/pool.js')++const originalQuery = pool.query.bind(pool)++afterEach(() => {+ ;(pool as unknown as { query: typeof originalQuery }).query = originalQuery+})test('a newly installed engine is appended without re-pairing', () => {// The reported case: the user installs another CLI after pairing.@@ -47,10 +54,14 @@ test('an unchanged list writes nothing', () => {assert.equal(mergeDetectedEngines(['claude', 'codex'], ['claude', 'codex']), null)})-test('an empty detection never wipes the stored engines', () => {- // A broken PATH or a half-finished CLI upgrade must not un-assign every agent- // on the machine.- assert.equal(mergeDetectedEngines(['claude'], []), null)+test('a successful empty detection clears the last uninstalled engine', () => {+ // The daemon retains its last-good list when `which` / `where` fails, so an+ // explicitly reported [] is a trustworthy scan where no engine remains.+ assert.deepEqual(mergeDetectedEngines(['claude'], []), [])+})++test('an unchanged empty list writes nothing', () => {+ assert.equal(mergeDetectedEngines([], []), null)})test('a detection of only unknown ids is treated as empty', () => {@@ -73,3 +84,24 @@ test('duplicates in a detection are collapsed', () => {test('a computer with no stored engines adopts the detection order', () => {assert.deepEqual(mergeDetectedEngines([], ['claude', 'codex']), ['claude', 'codex'])})++test('heartbeat persists a successful empty detection', async () => {+ const calls: Array<{ sql: string; params: unknown[] }> = []+ ;(pool as unknown as {+ query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[]; rowCount: number }>+ }).query = async (sql: string, params: unknown[] = []) => {+ calls.push({ sql, params })+ if (/SELECT available_engines/.test(sql)) {+ return { rows: [{ available_engines: ['claude'], kind: 'local' }], rowCount: 1 }+ }+ if (/UPDATE computers SET available_engines/.test(sql)) return { rows: [], rowCount: 1 }+ if (/UPDATE computers SET last_seen_at/.test(sql)) return { rows: [], rowCount: 1 }+ throw new Error(`unexpected query: ${sql}`)+ }++ await heartbeatComputer('comp-1', undefined, undefined, [])++ const inventoryUpdate = calls.find((c) => /UPDATE computers SET available_engines/.test(c.sql))+ assert.ok(inventoryUpdate)+ assert.equal(inventoryUpdate.params[1], '[]')+})diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 1fcc29a..192b772 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -27,7 +27,7 @@ import { promisify } from 'node:util'const execFileP = promisify(execFile)import { parseSseStream, wakeStreamWasStable } from '../runtime/sse-parse.js'-import { detectEngines, getAdapter, ENGINE_IDS, runEngineDoctor, type EngineId, type EngineSession, type EngineRunResult, type EngineUsage, type EngineHopReport } from './engine.js'+import { detectEngines, detectEnginesWithStatus, getAdapter, ENGINE_IDS, runEngineDoctor, type EngineId, type EngineSession, type EngineRunResult, type EngineUsage, type EngineHopReport } from './engine.js'import { usageFromClaude, type TokenUsage } from '../cost.js'import { parseTriage, finalizeTriage, isRateLimited } from '../triage-core.js'import { GLANCE_YIELD_RULES } from '../glance-protocol.js'@@ -694,6 +694,26 @@ async function requireLocalEngine(): Promise<EngineId[]> {return engines}+/** Resolve the engine a daemon can actually run from its LIVE PATH inventory. */+export function resolveAvailableEngine(+ requested: EngineId | null | undefined,+ available: readonly EngineId[],+): EngineId | null {+ return requested && available.includes(requested) ? requested : (available[0] ?? null)+}++export interface EngineInventory {+ current: EngineId[]+}++/** Replace the shared engine inventory after a trustworthy PATH scan. */+export function replaceEngineInventory(inventory: EngineInventory, next: readonly EngineId[]): boolean {+ const current = inventory.current+ const changed = next.length !== current.length || next.some((engine, i) => engine !== current[i])+ if (changed) inventory.current = [...next]+ return changed+}+// ─── config ─────────────────────────────────────────────────────────────async function loadConfig(): Promise<DaemonConfig | null> {@@ -2409,15 +2429,16 @@ async function doRun(serverOverride?: string): Promise<void> {return}if (serverOverride) cfg.serverUrl = serverOverride- let available: EngineId[]+ let initialEngines: EngineId[]try {- available = await requireLocalEngine()+ initialEngines = await requireLocalEngine()} catch (err) {console.error(`[computer] ${err instanceof Error ? err.message : String(err)}`)process.exitCode = 70return}- console.log(`[computer] cumora ${CURRENT_VERSION} · starting ${cfg.computerId} @ ${cfg.serverUrl} (engines: ${available.join(', ')})`)+ const engineInventory: EngineInventory = { current: initialEngines }+ console.log(`[computer] cumora ${CURRENT_VERSION} · starting ${cfg.computerId} @ ${cfg.serverUrl} (engines: ${engineInventory.current.join(', ')})`)// Record what THIS process is running, keyed by pid, so `--status` can report// the version of the live service instance reliably (cross-checked against the// running pid — survives log rotation, no log-scraping).@@ -2442,10 +2463,21 @@ async function doRun(serverOverride?: string): Promise<void> {console.warn('[computer] agent sync failed:', err instanceof Error ? err.message : err)return}+ const available = engineInventory.currentfor (const agent of agents) {- const engine: EngineId | null =- agent.engine && available.includes(agent.engine) ? agent.engine : (available[0] ?? null)- if (!engine) continue+ const engine = resolveAvailableEngine(agent.engine, available)+ if (!engine) {+ // A successful rescan may legitimately find that the last installed CLI+ // was removed. Stop an existing runner instead of leaving it alive on an+ // engine this machine no longer has.+ const existing = runners.get(agent.id)+ if (existing) {+ console.log(`[computer] no installed engine remains for ${agent.name} (${agent.id}) → stopping runner`)+ existing.stop()+ runners.delete(agent.id)+ }+ continue+ }const existing = runners.get(agent.id)if (existing) {if (existing.configMatches(agent, engine)) continue@@ -2471,14 +2503,17 @@ async function doRun(serverOverride?: string): Promise<void> {// on every heartbeat so installing another supported CLI takes effect without// re-pairing — the daemon is already online and can see PATH itself, so there// is no reason to make the user mint a new pairing token for it.- let detectedEngines: EngineId[] = await detectEngines()const rescanEngines = async (): Promise<void> => {try {- const next = await detectEngines()- if (next.length === 0) return // broken PATH / mid-upgrade — keep the last good list- const changed = next.length !== detectedEngines.length || next.some((e, i) => e !== detectedEngines[i])- if (changed) console.log(`[computer] engines on PATH changed: ${detectedEngines.join(', ') || 'none'} → ${next.join(', ')}`)- detectedEngines = next+ const detected = await detectEnginesWithStatus()+ if (!detected.reliable) return // broken `which` / `where` — keep the last good list+ const next = detected.engines+ const previous = engineInventory.current+ const changed = replaceEngineInventory(engineInventory, next)+ if (changed) console.log(`[computer] engines on PATH changed: ${previous.join(', ') || 'none'} → ${next.join(', ') || 'none'}`)+ // This is the same live inventory sync() uses to choose an agent's+ // adapter. Updating only a heartbeat cache would advertise a newly+ // installed engine while silently running that agent on the old default.} catch { /* transient — the next tick retries */ }}@@ -2493,7 +2528,7 @@ async function doRun(serverOverride?: string): Promise<void> {// `supervised` tells the server HOW this daemon runs (service vs. a// foreground command), so the app's upgrade banner can show the right// update instructions for this machine.- body: JSON.stringify({ version: CURRENT_VERSION, supervised: SUPERVISED, engines: detectedEngines }),+ body: JSON.stringify({ version: CURRENT_VERSION, supervised: SUPERVISED, engines: engineInventory.current }),})} catch { /* transient — next tick retries */ }}diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 9d69158..4a43873 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -326,15 +326,26 @@ export interface EngineAdapter {/** The trivial prompt a `doctor` probe sends — one token of real work. */const DOCTOR_PROMPT = 'Connectivity check. Reply with exactly: OK'-/** True if a binary is resolvable on PATH. */-export async function binOnPath(bin: string): Promise<boolean> {+type BinPathProbe = 'present' | 'absent' | 'error'++/** Probe a binary without conflating "not installed" with an inability to run+ * the platform's PATH resolver at all. The distinction matters to the daemon's+ * periodic refresh: a healthy scan that finds nothing should clear a stale+ * inventory, while a missing/broken `which` or `where` should retain the last+ * known-good result. */+async function probeBinOnPath(bin: string): Promise<BinPathProbe> {return new Promise((resolve) => {const probe = spawn(process.platform === 'win32' ? 'where' : 'which', [bin], { stdio: 'ignore' })- probe.on('error', () => resolve(false))- probe.on('close', (code) => resolve(code === 0))+ probe.on('error', () => resolve('error'))+ probe.on('close', (code) => resolve(code === 0 ? 'present' : code === 1 ? 'absent' : 'error'))})}+/** True if a binary is resolvable on PATH. */+export async function binOnPath(bin: string): Promise<boolean> {+ return (await probeBinOnPath(bin)) === 'present'+}+async function exists(p: string): Promise<boolean> {try { await access(p); return true } catch { return false }}@@ -2673,15 +2684,31 @@ export function getAdapter(id: EngineId): EngineAdapter {return ADAPTERS[id]}-/** Probe which engines are installed on this machine. */-export async function detectEngines(): Promise<EngineId[]> {+export interface EngineDetection {+ engines: EngineId[]+ /** False when `which` / `where` itself failed, so missing engines cannot be+ * distinguished from a broken scan and callers should keep their last good+ * inventory. */+ reliable: boolean+}++/** Probe which engines are installed and whether absence is trustworthy. */+export async function detectEnginesWithStatus(): Promise<EngineDetection> {const ids = Object.keys(ADAPTERS) as EngineId[]- const present = await Promise.all(ids.map(async (id) => {- if (await binOnPath(ADAPTERS[id].bin)) return id- if (id === 'grok' && resolveGrokBin()) return id- return null+ const probes = await Promise.all(ids.map(async (id) => {+ const status = await probeBinOnPath(ADAPTERS[id].bin)+ const installed = status === 'present' || (id === 'grok' && resolveGrokBin() != null)+ return { id, installed, status }}))- return present.filter((x): x is EngineId => x !== null)+ return {+ engines: probes.filter((p) => p.installed).map((p) => p.id),+ reliable: probes.every((p) => p.status !== 'error'),+ }+}++/** Probe which engines are installed on this machine. */+export async function detectEngines(): Promise<EngineId[]> {+ return (await detectEnginesWithStatus()).engines}/** Resolve a bin's absolute path on PATH (the first hit), or null if absent. */diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex 085d679..c1bff33 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -56,15 +56,18 @@ const PAIRABLE_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex', 'grok'* stays first, and the rest follow detection order. Installing a new CLI adds* it to the tail; uninstalling one drops it.*- * Returns null when there is nothing to write — an empty or fully-unknown- * detection, or a list identical to what is stored. A daemon that reports no- * engines (a broken PATH, a half-finished upgrade) must NOT wipe a computer's- * engines and un-assign every agent on it.+ * Returns null when there is nothing to write — a fully-unknown detection or a+ * list identical to what is stored. An explicitly empty detection is valid:+ * the daemon only reports it after a successful scan, so it means the final+ * supported CLI was uninstalled and the stale inventory must be cleared.** Exported for tests. */export function mergeDetectedEngines(current: string[], detected: string[]): string[] | null {const fresh = detected.filter((e) => PAIRABLE_ENGINES.has(e))- if (fresh.length === 0) return null+ // Non-empty but entirely unknown means a newer daemon is naming only engines+ // this server cannot run yet. Do not let that compatibility case wipe known+ // state; [] itself remains a trustworthy, successful empty PATH scan.+ if (detected.length > 0 && fresh.length === 0) return nullconst seen = new Set<string>()const next: string[] = []const currentDefault = current[0]@@ -315,7 +318,7 @@ export async function heartbeatComputer(// already online and re-scans PATH, so installing another supported CLI shows// up here instead of requiring the user to mint a new pairing token. Only for// paired computers: a cloud computer advertises 'managed' and has no PATH.- if (detectedEngines && detectedEngines.length > 0) {+ if (detectedEngines) {const { rows } = await pool.query<{ available_engines: string[]; kind: ComputerKind }>(`SELECT available_engines, kind FROM computers WHERE id = $1 AND revoked_at IS NULL`,[computerId],