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
fix(cli): follow Copilot's /resume, which switches session in-process
0xken155f99e8b83cd3
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 9c6be8edb..eee5f86df 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -88,7 +88,7 @@ import { AgyNormalizer, lastAgyTurnText } from './engines/agy/normalizer.js'import { findAgyTranscript } from './engines/agy/session.js'import { agyPaneIdle } from './engines/agy/runtimeProfile.js'import { CopilotNormalizer, copilotHistoryTurnOpen, lastCopilotTurnText } from './engines/copilot/normalizer.js'-import { findCopilotTranscript } from './engines/copilot/session.js'+import { copilotSessionForPid, findCopilotTranscript } from './engines/copilot/session.js'import { PiNormalizer, lastPiTurnText } from './engines/pi/normalizer.js'import { HermesReader, readHermesMessages } from './engines/hermes/reader.js'import { DevinReader, readDevinMessages } from './engines/devin/reader.js'@@ -1552,7 +1552,34 @@ async function runForeground(token: string): Promise<void> {const repairAttempts = new Map<string, number>()const bindObservedAgent = async (observed: DiscoveredTerminalAgent): Promise<void> => {const agent = registry.byProcess(observed.engine, observed.processIdentity)- if (!agent || agent.sessionId) return+ if (!agent) return++ // Copilot can change session WITHOUT changing process: `/resume` inside the CLI opens another one,+ // and the pane then shows a conversation the daemon is not streaming. Every other engine here+ // starts a new process for that, which is why this path used to stop at `agent.sessionId`.+ //+ // The switch leaves exactly one trace — the `inuse.<pid>.lock` Copilot takes on the new session+ // directory. It writes nothing to the transcript and fires no hook until the next prompt.+ if (agent.sessionId) {+ if (observed.engine !== 'copilot') return+ const current = await copilotSessionForPid(env.COPILOT_HOME, observed.processIdentity.pid)+ if (!current || current === agent.sessionId || isRecentlyDeleted(current)) return+ const transcript = await findCopilotTranscript(env.COPILOT_HOME, current)+ console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(current)} (/resume)`)+ const rotated = registry.register({+ engine: 'copilot',+ sessionId: current,+ transcriptPath: transcript ?? undefined,+ cwd: observed.cwd,+ source: 'copilot-resume',+ runtimes: observed.runtimes,+ primaryRuntimeKey: observed.primaryRuntimeKey,+ processIdentity: observed.processIdentity,+ hookEvent: 'CopilotResume',+ })+ if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)+ return+ }let sessionId = observed.resumeSessionIdlet transcriptPath: string | undefined@@ -1584,6 +1611,7 @@ async function runForeground(token: string): Promise<void> {const startedAtMs = Date.parse(observed.processIdentity.startMarker)if (!Number.isFinite(startedAtMs)) return// agy cannot be found by directory — its repair reads the presence lock the process holds open.+ //const found = await findLiveSession(observed.engine, observed.cwd, startedAtMs, {bornOnly: true,pid: observed.processIdentity.pid,diff --git a/cli/src/engines/README.md b/cli/src/engines/README.mdindex 1d37f431c..b4ca71a04 100644--- a/cli/src/engines/README.md+++ b/cli/src/engines/README.md@@ -300,6 +300,20 @@ conversation reports the last turn as still open and nothing is ever coming to c`turn_heartbeat` every second, indefinitely). Its pane knows — `? for shortcuts` when idle,`esc to cancel` while busy — so attach reads the pane once and closes the folded turn.+**One process can change session underneath you.** Every engine here but Copilot starts a new process+to switch conversations, so `bindObservedAgent` stops at the first `agent.sessionId` and never looks+again. Copilot's `/resume` switches IN PROCESS: same pid, same pane, different conversation — and the+pane then shows something the daemon is not streaming.++Worse, the switch leaves almost no trace. Measured: resuming writes not one byte to `events.jsonl`+and fires no hook until the next prompt, so neither a transcript tail nor a directory scan can see it.+The one thing it does is take a lock, `session-state/<id>/inuse.<pid>.lock` — and it does NOT release+the old one, so a process holds several and the NEWEST is the current session.++When adding an engine, ask whether switching conversations requires a new process. If it does not, the+bind path needs a re-check for an already-bound agent, and something that identifies the CURRENT+session of a live pid.+**A fold is not a live stream, and `--resume` is where that bites.** Every engine here whose turn isclosed by a HOOK has the same hole: attaching to an existing conversation folds its transcript, thefold opens a turn on the last user message, and no hook is coming to close it — the tile spins on adiff --git a/cli/src/engines/copilot/normalizer.spec.ts b/cli/src/engines/copilot/normalizer.spec.tsindex 370c287f2..9a4c2e98b 100644--- a/cli/src/engines/copilot/normalizer.spec.ts+++ b/cli/src/engines/copilot/normalizer.spec.ts@@ -134,3 +134,26 @@ describe('resuming a finished conversation', () => {expect(copilotHistoryTurnOpen([...LINES, JSON.stringify({ type: 'session.shutdown', data: {} })])).toBe(false)})})++describe('the session a Copilot process is in', () => {+ it('picks the NEWEST lock: /resume adds one without releasing the old', async () => {+ const { mkdtempSync, mkdirSync, writeFileSync, utimesSync } = await import('node:fs')+ const { tmpdir } = await import('node:os')+ const { join } = await import('node:path')+ const { copilotSessionForPid } = await import('./session.js')++ const home = mkdtempSync(join(tmpdir(), 'copilot-home-'))+ const started = '11111111-1111-4111-8111-111111111111'+ const resumed = '22222222-2222-4222-8222-222222222222'+ for (const id of [started, resumed]) {+ mkdirSync(join(home, 'session-state', id), { recursive: true })+ writeFileSync(join(home, 'session-state', id, 'inuse.4242.lock'), '')+ }+ // measured on a real pid: both locks survive, so recency is what distinguishes them+ utimesSync(join(home, 'session-state', started, 'inuse.4242.lock'), new Date(1000), new Date(1000))+ utimesSync(join(home, 'session-state', resumed, 'inuse.4242.lock'), new Date(9000), new Date(9000))++ expect(await copilotSessionForPid(home, 4242)).toBe(resumed)+ expect(await copilotSessionForPid(home, 9999)).toBeNull() // another process holds nothing here+ })+})diff --git a/cli/src/engines/copilot/session.ts b/cli/src/engines/copilot/session.tsindex bde875310..985b91bbf 100644--- a/cli/src/engines/copilot/session.ts+++ b/cli/src/engines/copilot/session.ts@@ -67,3 +67,28 @@ export function copilotSessionCwd(firstLines: string[]): string | null {}return null}++/**+ * The session a live Copilot process is CURRENTLY in, read from the lock it takes on the directory.+ *+ * Copilot writes `session-state/<sessionId>/inuse.<pid>.lock` when a process opens a session, and+ * `/resume` inside the CLI opens another one — measured: pid 63310 held two locks at once, the session+ * it started with and the one it switched to. So the lock is not one-per-process, and the NEWEST is+ * the answer.+ *+ * This is the only trace a resume leaves. It writes nothing to the transcript (measured: pick a+ * session and not one byte of `events.jsonl` changes) and fires no hook until the first prompt, which+ * is why a directory scan cannot find it and why the agent used to sit unbound after `/resume`.+ */+export async function copilotSessionForPid(copilotHome: string, pid: number): Promise<string | null> {+ const root = join(copilotHome, 'session-state')+ const entries = await readdir(root, { withFileTypes: true }).catch(() => [])+ let best: { sessionId: string; mtimeMs: number } | null = null+ for (const entry of entries) {+ if (!entry.isDirectory() || !SESSION_ID.test(entry.name)) continue+ const info = await stat(join(root, entry.name, `inuse.${pid}.lock`)).catch(() => null)+ if (!info) continue+ if (!best || info.mtimeMs > best.mtimeMs) best = { sessionId: entry.name, mtimeMs: info.mtimeMs }+ }+ return best?.sessionId ?? null+}diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 46d44d47b..69b329376 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -23,7 +23,7 @@ import { museEvent, museWorkspaceRoot } from '../engines/muse/normalizer.js'import type { AgentEngine } from '../engines/types.js'import { readCodexRolloutMeta } from '../engines/codex/rollout.js'import { agyConversationForPid, findAgyTranscript } from '../engines/agy/session.js'-import { copilotSessionCwd } from '../engines/copilot/session.js'+import { copilotSessionCwd, copilotSessionForPid, findCopilotTranscript } from '../engines/copilot/session.js'const execFileAsync = promisify(execFile)@@ -204,6 +204,25 @@ function quote(value: string): string {* transcripts are located by id rather than listed by directory, and its resumes already have a* dedicated discovery path.*/++/**+ * Copilot names its session directory by uuid, so the cwd lives inside the file — on the first record,+ * `session.start.data.context.cwd`. `readTranscriptMeta` scans the first lines for a bare `cwd`, but+ * Copilot nests it, so this reads it out itself.+ */+async function copilotDirectoryScan(+ cwd: string,+ startedAtMs: number,+ opts?: { bornOnly?: boolean },+): Promise<RepairedSession | null> {+ return fileEngineSession(join(env.COPILOT_HOME, 'session-state'), cwd, startedAtMs, async (path) => {+ if (basename(path) !== 'events.jsonl') return null+ const head = (await readFile(path, 'utf8').catch(() => '')).split('\n', 5)+ const root = copilotSessionCwd(head)+ return root ? { cwd: root, sessionId: basename(dirname(path)) } : null+ }, opts)+}+export async function findLiveSession(engine: AgentEngine,cwd: string,@@ -306,16 +325,18 @@ export async function findLiveSession(+ ` AND (created_at >= ${Math.trunc(sinceMs / 1000)} OR last_activity_at >= ${Math.trunc(sinceMs / 1000)})`+ ` ORDER BY last_activity_at DESC LIMIT 2;`,)- case 'copilot':- // Copilot names its session directory by uuid, so the cwd lives inside the file — on the first- // record, `session.start.data.context.cwd`. readTranscriptMeta scans the first lines for a- // `cwd`, but Copilot nests it, so this reads it out itself.- return fileEngineSession(join(env.COPILOT_HOME, 'session-state'), cwd, startedAtMs, async (path) => {- if (basename(path) !== 'events.jsonl') return null- const head = (await readFile(path, 'utf8').catch(() => '')).split('\n', 5)- const root = copilotSessionCwd(head)- return root ? { cwd: root, sessionId: basename(dirname(path)) } : null- }, opts)+ case 'copilot': {+ // The lock the process holds is the only thing a `/resume` leaves behind, and it is exact.+ // Fall through to the directory scan when there is no pid or no lock yet (a brand-new session+ // takes its lock only once Copilot creates it).+ const locked = opts?.pid ? await copilotSessionForPid(env.COPILOT_HOME, opts.pid) : null+ if (locked) {+ const transcriptPath = await findCopilotTranscript(env.COPILOT_HOME, locked)+ return { sessionId: locked, transcriptPath: transcriptPath ?? undefined }+ }+ return copilotDirectoryScan(cwd, startedAtMs, opts)+ }+case 'agy':// The one engine here that cannot be found by directory. agy's transcript records no cwd, its// brain directory is named by the conversation id, and `conversation_summaries.db` — which looks