The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: add per-agent Muse data root tracking to resolve transcript paths correctly across custom XDG configurations
0xken15b85a90715842
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 340ddc95a..9aec0ac18 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1181,7 +1181,7 @@ async function runForeground(token: string): Promise<void> {// `bornOnly`: this agent has never had a session, so only accept one this engine CREATED. Taking a// merely-recently-written transcript handed the new agent the previous run's conversation — exit the// launcher, start it again in the same pane, and the fresh tab opened full of old messages.- const found = await findLiveSession(agent.engine, cwd, startedAtMs, { bornOnly: true })+ const found = await findLiveSession(agent.engine, cwd, startedAtMs, { bornOnly: true, dataHome: agent.dataHome })if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) continueconst result = registry.register({engine: agent.engine,@@ -1263,6 +1263,7 @@ async function runForeground(token: string): Promise<void> {engine: launcher.engine,tmuxPane: launcher.tmuxPane,cwd: launcher.cwd ?? null,+ dataHome: launcher.dataHome ?? null,})if (opened?.evicted) console.log(`[agent] ${sid(launcher.launcherId)} took pane ${launcher.tmuxPane} from ${sid(opened.evicted)}`)if (opened?.isNew) {diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 2733d9a46..570f3597c 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -41,7 +41,7 @@ export interface HookServerHandlers {* engine's own hook knows that, and resuming an existing session fires no hook — so the caller uses* this to go look (see adoptResumedSessions). Without it, a resumed agent stays invisible.*/- onLauncherOpened?: (session: { launcherId: string; engine: RegisteredSession['engine']; tmuxPane: string; cwd?: string | null }) => void+ onLauncherOpened?: (session: { launcherId: string; engine: RegisteredSession['engine']; tmuxPane: string; cwd?: string | null; dataHome?: string | null }) => void/** Turn a launcher away before it spawns anything; the string returned is shown to the person in the* pane. Used for engines that cannot have two agents in one directory (see `refuseDuplicateAgent`). */refuseLauncher?: (session: {@@ -478,6 +478,7 @@ function handleLauncherSocket(ws: WebSocket, handlers: HookServerHandlers, port:// reply to spawn the engine.handlers.onLauncherOpened?.({launcherId: opened.launcherId, engine: opened.engine, tmuxPane: opened.tmuxPane, cwd: opened.cwd ?? null,+ dataHome: opened.dataHome ?? null,})})diff --git a/cli/src/lib/launch.ts b/cli/src/lib/launch.tsindex 96af30ede..b19b78af8 100644--- a/cli/src/lib/launch.ts+++ b/cli/src/lib/launch.ts@@ -18,6 +18,7 @@import { execFile, spawn } from 'child_process'import { refusalMessage } from './duplicateAgent.js'+import { join } from 'path'import { randomUUID } from 'crypto'import { WebSocket } from 'ws'import { env } from '../config/env.js'@@ -42,6 +43,25 @@ const NOTICE_MS = 6_000/** How long to wait for the daemon's `opened` ack before falling back to this build's own answers. */const ACK_WAIT_MS = 2_000+/**+ * Where this launcher's engine will keep its data, or undefined when that is the daemon's own default.+ *+ * muse only, and it resolves the way MUSE ITSELF does — measured: muse honours `XDG_DATA_HOME` and puts+ * everything under `<xdg>/muse`, which is how a second provider (a local router in front of another+ * model) gets its own catalog cache and session tree. The daemon scans ONE root, so unless the launcher+ * reports the root it actually used, that agent's transcripts sit somewhere nobody looks: it binds to+ * nothing, and web and device stay blank without an error.+ *+ * Undefined for every other engine — none of them relocate this way, and sending a value the daemon would+ * then have to second-guess is worse than sending nothing.+ */+function engineDataHome(engine: AgentEngine): string | undefined {+ if (engine !== 'muse') return undefined+ if (process.env.MUSE_HOME) return process.env.MUSE_HOME+ if (process.env.XDG_DATA_HOME) return join(process.env.XDG_DATA_HOME, 'muse')+ return undefined // the daemon's default is the same place; let it decide+}+function fail(lines: string[]): never {for (const line of lines) console.error(line)process.exit(1)@@ -218,7 +238,7 @@ class LauncherLink {try {ws.send(JSON.stringify({t: 'open', v: LAUNCHER_PROTOCOL_V, launcherId: this.launcherId, engine: this.engine,- tmuxPane: this.pane, cwd: this.cwd, version: VERSION,+ tmuxPane: this.pane, cwd: this.cwd, version: VERSION, dataHome: engineDataHome(this.engine),}))} catch { /* the close handler will retry */ }if (wasDown) this.onState(true)diff --git a/cli/src/lib/launcherProtocol.ts b/cli/src/lib/launcherProtocol.tsindex 6d068c4c8..70d9c9623 100644--- a/cli/src/lib/launcherProtocol.ts+++ b/cli/src/lib/launcherProtocol.ts@@ -38,6 +38,15 @@ export interface LauncherOpenFrame {engine?: AgentEnginetmuxPane?: stringcwd?: string+ /**+ * Where this launcher's engine keeps its data, when that is not the daemon's default.+ *+ * muse only: it writes sessions under `XDG_DATA_HOME`, so a launcher started with a different one puts+ * its transcripts somewhere the daemon does not scan — the agent then binds to nothing and web and+ * device stay empty, with no error anywhere. The launcher is the only party that knows the environment+ * it was run with, so it says so here. Absent on older launchers, which means "the daemon's default".+ */+ dataHome?: string/** The launcher's BUILD, for the stale-build notice. Never used for compatibility decisions. */version?: string}diff --git a/cli/src/lib/launcherSessions.ts b/cli/src/lib/launcherSessions.tsindex 237a3f6e6..1e26177b6 100644--- a/cli/src/lib/launcherSessions.ts+++ b/cli/src/lib/launcherSessions.ts@@ -34,6 +34,8 @@ export interface LauncherSession {engine: AgentEnginetmuxPane: stringcwd: string | null+ /** muse only: the data root this launcher's engine actually uses (see LauncherOpenFrame). */+ dataHome: string | nullsocket: LauncherSocketopenedAt: number}@@ -43,6 +45,7 @@ export interface LauncherOpenInput {engine?: AgentEnginetmuxPane?: stringcwd?: string+ dataHome?: string}const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i@@ -71,6 +74,7 @@ class LauncherSessionBook {engine: input.engine,tmuxPane: pane,cwd: input.cwd ?? null,+ dataHome: typeof input.dataHome === 'string' && input.dataHome ? input.dataHome : null,socket,openedAt: previous?.openedAt ?? Date.now(),}diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex d0abbd993..8707d92ff 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -552,3 +552,51 @@ describe('agent identity: the launcher owns the agent, the session is bound to iexpect(saved[0]).toMatchObject({ agentId: 'legacy-agent', launcherId: 'legacy-agent' })})})++/**+ * The transcript gate confines a session file to its engine's root — it is what stops a session id from a+ * request being resolved into an arbitrary path. Per-agent muse roots widen WHICH root is legitimate, so+ * these tests exist to prove the gate still shuts.+ */+describe('transcript gate with per-agent muse roots', () => {+ let museA = ''+ let museB = ''++ beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-'))+ museA = mkdtempSync(join(tmpdir(), 'muse-a-'))+ museB = mkdtempSync(join(tmpdir(), 'muse-b-'))+ })+ afterEach(() => {+ for (const d of [dataDir, museA, museB]) rmSync(d, { recursive: true, force: true })+ })++ function writeSession(home: string, id: string): string {+ const dir = join(home, 'sessions', '2026', '08', '06', id)+ mkdirSync(dir, { recursive: true })+ const file = join(dir, 'session.jsonl')+ writeFileSync(file, '{}\n')+ return file+ }++ it('accepts a transcript under the agent\'s own root', async () => {+ process.env.MUSE_HOME = museA+ const { validTranscriptPath } = await loadRegistryModule()+ expect(validTranscriptPath('muse', writeSession(museB, 's-b'), museB)).toBe(true)+ })++ it('REFUSES a transcript belonging to a different agent\'s root', async () => {+ // Without this the widening would be a back door: any agent could name any other agent's file.+ process.env.MUSE_HOME = museA+ const { validTranscriptPath } = await loadRegistryModule()+ expect(validTranscriptPath('muse', writeSession(museB, 's-b'), museA)).toBe(false)+ })++ it('falls back to the daemon default when an agent declares no root', async () => {+ // Old launchers send nothing, and their agents must keep working exactly as before.+ process.env.MUSE_HOME = museA+ const { validTranscriptPath } = await loadRegistryModule()+ expect(validTranscriptPath('muse', writeSession(museA, 's-a'))).toBe(true)+ expect(validTranscriptPath('muse', writeSession(museB, 's-b2'))).toBe(false)+ })+})diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 8f14e3845..9eebce30c 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -46,6 +46,14 @@ export interface RegisteredSession {* identity while the engine underneath rotates its session (`/clear`, `/new`). Immutable.*/agentId: string+ /**+ * muse only: the engine data root this agent actually uses, when it is not the daemon's default.+ *+ * The daemon scans ONE root per engine, so an agent launched with a different `XDG_DATA_HOME` writes+ * transcripts nowhere anybody looks — it binds to nothing and the web pane stays blank. The launcher+ * reports the root it ran with; absent means "the daemon's default".+ */+ dataHome?: string | null/*** The engine session currently BOUND to this agent — internal mapping, not identity. It changes on a* rotation and is only ever addressed through the session index.@@ -109,12 +117,18 @@ function isWithin(root: string, file: string): boolean {return rel === '' || (!rel.startsWith('..') && !rel.startsWith(`/`) && !rel.startsWith(`\\`))}-export function validTranscriptPath(engine: AgentEngine, filePath: string): boolean {+/**+ * `dataHome` is the AGENT's engine data root, and it must come from the registry — i.e. from what the+ * launcher told the daemon when it opened — never from anything a client sent. This function is the gate+ * that stops a request-supplied session id from being resolved into an arbitrary path; taking the root+ * from the request would hand that gate its own key.+ */+export function validTranscriptPath(engine: AgentEngine, filePath: string, dataHome?: string | null): boolean {try {const actual = realpathSync(filePath)const root = realpathSync(engine === 'muse'- ? join(env.MUSE_HOME, 'sessions')+ ? join(dataHome || env.MUSE_HOME, 'sessions'): engine === 'codex'? join(env.CODEX_HOME, 'sessions'): engine === 'cursor'@@ -226,7 +240,7 @@ class Registry {if (!pane|| (bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)- || (bound && transcriptPath !== null && !validTranscriptPath(engine, transcriptPath))+ || (bound && transcriptPath !== null && !validTranscriptPath(engine, transcriptPath, typeof raw?.dataHome === 'string' ? raw.dataHome : null))) {changed = truecontinue@@ -302,7 +316,7 @@ class Registry {** An agent whose `sessionId` is empty is UNBOUND: known, addressable, not yet mapped to a transcript.*/- openAgent(input: { agentId: string; engine: AgentEngine; tmuxPane: string; cwd?: string | null }):+ openAgent(input: { agentId: string; engine: AgentEngine; tmuxPane: string; cwd?: string | null; dataHome?: string | null }):{ entry: RegisteredSession; isNew: boolean; evicted: string | null } | null {const { agentId, engine, tmuxPane } = inputif (!agentId || !tmuxPane || !PANE_RE.test(tmuxPane)) return null@@ -310,6 +324,7 @@ class Registry {if (existing) {existing.tmuxPane = tmuxPaneexisting.cwd = input.cwd ?? existing.cwd+ existing.dataHome = input.dataHome ?? existing.dataHomeexisting.updatedAt = Date.now()this.save()return { entry: existing, isNew: false, evicted: null }@@ -329,6 +344,7 @@ class Registry {transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,+ dataHome: input.dataHome ?? null,tmuxPane,source: null,title: null,@@ -374,7 +390,9 @@ class Registry {|| !pane|| !PANE_RE.test(pane)|| (engine !== 'cursor' && engine !== 'opencode' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)- || (transcriptPath && !validTranscriptPath(engine, transcriptPath))+ // The root comes from the AGENT the daemon already knows — never from this payload, which a+ // hook (and so anything that can reach the hook port) supplies.+ || (transcriptPath && !validTranscriptPath(engine, transcriptPath, this.agents.get(agentId)?.dataHome))) return nullif (engine === 'codex' && transcriptPath && readCodexRolloutMeta(transcriptPath)?.isSubagent) return nulldiff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex 2f3f510ac..8484a436e 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -219,6 +219,23 @@ describe('session repair — muse', () => {.resolves.toMatchObject({ sessionId: 'real-session' })})+ it('scans the AGENT\'s own data root, so two providers can run side by side', async () => {+ // muse follows XDG_DATA_HOME, which is how a second provider (a local router in front of another+ // model) gets its own catalog cache and session tree. The daemon used to scan one global root, so an+ // agent launched with a different one wrote transcripts nowhere anybody looked: it bound to nothing+ // and web and device stayed blank. Same cwd on purpose — the ROOT is the only thing telling them apart.+ const dflt = tempRoot()+ const other = tempRoot()+ writeMuseSession(dflt, 'default-session', CWD, [runTurn], STARTED_AT + 5_000)+ writeMuseSession(other, 'router-session', CWD, [runTurn], STARTED_AT + 5_000)+ const { findLiveSession } = await loadMuse(dflt)++ await expect(findLiveSession('muse', CWD, STARTED_AT, { bornOnly: true }))+ .resolves.toMatchObject({ sessionId: 'default-session' })+ await expect(findLiveSession('muse', CWD, STARTED_AT, { bornOnly: true, dataHome: other }))+ .resolves.toMatchObject({ sessionId: 'router-session' })+ })+it('binds a SCHEDULED run, whose prompt is empty because nobody typed it', async () => {// The filter must key on the run lifecycle, not on the presence of a prompt: a scheduled run is a// real turn the scheduler triggered. Requiring a prompt would leave those sessions unbindable.diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex bccc8a2ab..6fc39e26b 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -213,7 +213,7 @@ export async function findLiveSession(engine: AgentEngine,cwd: string,startedAtMs: number,- opts?: { bornOnly?: boolean },+ opts?: { bornOnly?: boolean; dataHome?: string | null },): Promise<RepairedSession | null> {const sinceMs = startedAtMs - START_SLACK_MS// The DB engines match on a directory STRING, so ask for both spellings of it (see sameDir).@@ -241,7 +241,9 @@ export async function findLiveSession(// `sessions/YYYY/MM/DD/<session-uuid>/session.jsonl` (4 levels — exactly MAX_DEPTH) and nothing in// the path names the project: `workspace_root` in the first record is the only link. Sub-agent// files live one level deeper under `subagent/`, and must never be adopted as agents of their own.- return fileEngineSession(join(env.MUSE_HOME, 'sessions'), cwd, startedAtMs, async (path) => {+ // The agent's OWN data root: muse follows XDG_DATA_HOME, so two agents can legitimately keep+ // their sessions in different trees, and scanning one global root loses whichever is elsewhere.+ return fileEngineSession(join(opts?.dataHome || env.MUSE_HOME, 'sessions'), cwd, startedAtMs, async (path) => {if (path.includes(`${sep}subagent${sep}`)) return nullconst lines = (await readFile(path, 'utf-8').catch(() => '')).split('\n')const root = museWorkspaceRoot(lines[0] ?? '')