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(cli): add amp (ampcode.com) as the tenth engine
0xken15f15924f9fe86
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 560380826..9f41ba6f0 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -29,6 +29,7 @@ import { cursorMessagesToEvents, windowCursorLines } from './engines/cursor/normimport { loadCursorReplayTaskLinks } from './engines/cursor/subagent.js'import { opencodeMessagesToEvents, windowOpencodeMessages } from './engines/opencode/normalizer.js'import { museMessagesToEvents } from './engines/muse/normalizer.js'+import { ampMessagesToEvents } from './engines/amp/normalizer.js'import { piMessagesToEvents, windowPiLines } from './engines/pi/normalizer.js'import { commandcodeMessagesToEvents, windowCommandCodeLines } from './engines/commandcode/normalizer.js'import { hermesMessagesToEvents, windowHermesMessages } from './engines/hermes/normalizer.js'@@ -98,11 +99,11 @@ function clipDeviceAgentName(input: string): string {export function deviceAgentListItem(raw: unknown,-): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse'; selectedModel?: string | null } {+): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp'; selectedModel?: string | null } {const o = (raw ?? {}) as Record<string, unknown>- const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse'; selectedModel?: string | null } = { id: o.id }+ const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp'; selectedModel?: string | null } = { id: o.id }if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)- if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse') item.engine = o.engine+ if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse' || o.engine === 'amp') item.engine = o.engine// Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModelreturn item@@ -749,12 +750,14 @@ export class BackendSocket {? cursorMessagesToEvents(lines, sessionId, await loadCursorReplayTaskLinks(env.CURSOR_HOME, sessionId)): s.engine === 'muse'? museMessagesToEvents(lines)+ : s.engine === 'amp'+ ? ampMessagesToEvents(lines): s.engine === 'pi'? piMessagesToEvents(lines): s.engine === 'commandcode'? commandcodeMessagesToEvents(lines): messagesToEvents(lines)- if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse') await enrichSubagentStats(fullEvents, s.transcriptPath)+ if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse' && s.engine !== 'amp') await enrichSubagentStats(fullEvents, s.transcriptPath)reply(type, requestId, {id: sessionId,title: projectDisplayName(s),@@ -770,11 +773,13 @@ export class BackendSocket {// pane opened blank with no error anywhere. Until a muse window exists, answer the page with// the whole transcript (`hasMore: false` ends the scroll honestly, and these sessions are// small: a real one measured 271 lines).- if (s.engine === 'muse') {+ // Amp is in the same position as muse and for the same reason: no windower, so falling+ // through would pair claude's line-uuid cursor with claude's normalizer and return nothing.+ if (s.engine === 'muse' || s.engine === 'amp') {reply(type, requestId, {id: sessionId,title: projectDisplayName(s),- events: museMessagesToEvents(lines),+ events: s.engine === 'amp' ? ampMessagesToEvents(lines) : museMessagesToEvents(lines),timestamp,engine: s.engine,hasMore: false,@@ -810,7 +815,7 @@ export class BackendSocket {: s.engine === 'commandcode'? commandcodeMessagesToEvents(w.window): messagesToEvents(w.window)- // muse is answered above and never reaches here, so it is absent from this list on purpose.+ // muse and amp are answered above and never reach here, so both are absent by design.if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode') await enrichSubagentStats(events, s.transcriptPath)// Older pages must not inject a spurious end-of-transcript marker mid-scroll.if (before && events[events.length - 1]?.type === 'done') events.pop()diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 340ddc95a..ca407874b 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -74,6 +74,7 @@ import { loadCursorPendingTasks, removeCursorPendingTasks } from './engines/cursimport { OpencodeReader, readOpencodeMessages } from './engines/opencode/reader.js'import { lastOpencodeTurnText } from './engines/opencode/normalizer.js'import { MuseNormalizer, lastMuseTurnText, museMessagesToEvents } from './engines/muse/normalizer.js'+import { AmpNormalizer, lastAmpTurnText, ampMessagesToEvents } from './engines/amp/normalizer.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'@@ -582,6 +583,7 @@ async function runForeground(token: string): Promise<void> {const opencodeReaders = new Map<string, OpencodeReader>()const piNormalizers = new Map<string, PiNormalizer>()const museNormalizers = new Map<string, MuseNormalizer>()+ const ampNormalizers = new Map<string, AmpNormalizer>()const hermesReaders = new Map<string, HermesReader>()const devinReaders = new Map<string, DevinReader>()const commandcodeNormalizers = new Map<string, CommandCodeNormalizer>()@@ -670,6 +672,7 @@ async function runForeground(token: string): Promise<void> {|| opencodeReaders.has(session.sessionId)|| piNormalizers.has(session.sessionId)|| museNormalizers.has(session.sessionId)+ || ampNormalizers.has(session.sessionId)|| hermesReaders.has(session.sessionId)|| devinReaders.has(session.sessionId)|| commandcodeNormalizers.has(session.sessionId)@@ -728,6 +731,13 @@ async function runForeground(token: string): Promise<void> {for (const line of lines) historyEvents.push(...normalizer.ingest(line))historyTurnOpen = normalizer.turnOpenmuseNormalizers.set(session.sessionId, normalizer)+ } else if (session.engine === 'amp') {+ // A JSONL tail like claude/muse — except the file is written by the adapter's own Amp plugin,+ // because Amp is the one engine that keeps no conversation on disk.+ const normalizer = new AmpNormalizer()+ for (const line of lines) historyEvents.push(...normalizer.ingest(line))+ historyTurnOpen = normalizer.turnOpen+ ampNormalizers.set(session.sessionId, normalizer)} else if (session.engine === 'pi') {const normalizer = new PiNormalizer('live')// Hydrate state silently; never replay history live — except a turn left open, below.@@ -872,6 +882,7 @@ async function runForeground(token: string): Promise<void> {if (s.engine === 'codex') return lastCodexTurnText(lines)if (s.engine === 'cursor') return lastCursorTurnText(lines)if (s.engine === 'muse') return lastMuseTurnText(lines)+ if (s.engine === 'amp') return lastAmpTurnText(lines)if (s.engine === 'pi') return lastPiTurnText(lines)if (s.engine === 'commandcode') return lastCommandCodeTurnText(lines)return lastTurnTextFromRawLines(lines)@@ -952,6 +963,7 @@ async function runForeground(token: string): Promise<void> {?? opencodeReaders.get(sessionId)?.turnOpen?? piNormalizers.get(sessionId)?.turnOpen?? museNormalizers.get(sessionId)?.turnOpen+ ?? ampNormalizers.get(sessionId)?.turnOpen?? hermesReaders.get(sessionId)?.turnOpen?? devinReaders.get(sessionId)?.turnOpen?? commandcodeNormalizers.get(sessionId)?.turnOpen@@ -1058,6 +1070,7 @@ async function runForeground(token: string): Promise<void> {opencodeReaders.delete(sessionId)piNormalizers.delete(sessionId)museNormalizers.delete(sessionId)+ ampNormalizers.delete(sessionId)hermesReaders.get(sessionId)?.stop()hermesReaders.delete(sessionId)devinReaders.get(sessionId)?.stop()@@ -1523,6 +1536,10 @@ async function runForeground(token: string): Promise<void> {let normalizer = museNormalizers.get(evt.sessionId)if (!normalizer) { normalizer = new MuseNormalizer(); museNormalizers.set(evt.sessionId, normalizer) }events = normalizer.ingest(evt.text)+ } else if (session.engine === 'amp') {+ let normalizer = ampNormalizers.get(evt.sessionId)+ if (!normalizer) { normalizer = new AmpNormalizer(); ampNormalizers.set(evt.sessionId, normalizer) }+ events = normalizer.ingest(evt.text)} else if (session.engine === 'pi') {let normalizer = piNormalizers.get(evt.sessionId)if (!normalizer) { normalizer = new PiNormalizer('live'); piNormalizers.set(evt.sessionId, normalizer) }@@ -1564,6 +1581,7 @@ async function runForeground(token: string): Promise<void> {?? opencodeReaders.get(session.sessionId)?.turnOpen?? piNormalizers.get(session.sessionId)?.turnOpen?? museNormalizers.get(session.sessionId)?.turnOpen+ ?? ampNormalizers.get(session.sessionId)?.turnOpen?? hermesReaders.get(session.sessionId)?.turnOpen?? devinReaders.get(session.sessionId)?.turnOpen?? commandcodeNormalizers.get(session.sessionId)?.turnOpen@@ -1678,6 +1696,7 @@ async function runForeground(token: string): Promise<void> {opencodeReaders.get(sessionId)?.closeTurn()piNormalizers.get(sessionId)?.closeTurn()museNormalizers.get(sessionId)?.closeTurn()+ ampNormalizers.get(sessionId)?.closeTurn()hermesReaders.get(sessionId)?.closeTurn()devinReaders.get(sessionId)?.closeTurn()commandcodeNormalizers.get(sessionId)?.closeTurn()diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 8f40109d8..fe13e86b5 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -130,6 +130,25 @@ const envSchema = z.object({// FIRST record of each file — which is why this engine is discovered by scanning rather than by a hook.MUSE_HOME: z.string().default(join(homedir(), '.local', 'share', 'muse')),MUSE_CONFIG_DIR: z.string().default(join(homedir(), '.config', 'muse')),+ // Amp plugin dir the adapter drops its discovery plugin into (honors XDG_CONFIG_HOME). Amp calls these+ // "system plugins" and loads every `*.ts` there for EVERY thread, which is what makes one install cover+ // all projects — the project-local `.amp/plugins/` alternative would need one copy per repo.+ AMP_PLUGIN_DIR: z+ .string()+ .default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'amp', 'plugins')),+ // Where the Amp plugin writes the transcripts this adapter tails.+ //+ // Amp is the only supported engine that keeps NO conversation on disk: threads live on the server and+ // the sole local artefacts are a metadata-only debug log (no message text at all — measured) and+ // `session.json`. `amp threads export` can fetch the content, but it costs a ~1.5s network round trip+ // per read and never shows a message before it is complete. So the plugin writes the transcript we tail,+ // and this directory — ours, not Amp's — is the trusted root for it.+ AMP_SESSIONS_DIR: z.string().default(join(adapterDataDir, 'amp-sessions')),+ // Amp's own state dir, read-only for us: `session.json` there maps a tmux pane to the thread started in+ // it, which is how a re-attaching daemon re-binds a pane without guessing.+ AMP_STATE_DIR: z+ .string()+ .default(join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'amp')),// Devin's user-level config, where the adapter merges its hooks under a "hooks" key. Devin reads// Claude's hook schema verbatim, so the installed block is shaped exactly like ~/.claude/settings.json.DEVIN_CONFIG_PATH: z.string().default(join(homedir(), '.config', 'devin', 'config.json')),@@ -155,6 +174,8 @@ const envSchema = z.object({// Path to the `devin` CLI for Devin recap one-shots (else `devin` is resolved from PATH).DEVIN_PATH: z.string().optional(),MUSE_PATH: z.string().optional(),+ // Path to the `amp` CLI for Amp recap one-shots (else `amp` is resolved from PATH).+ AMP_PATH: z.string().optional(),// Model for the device turn-recap one-shot.SUMMARY_MODEL: z.string().default('sonnet'),// Balanced Codex counterpart used only for recap workers; never inherits the interactive CLI model.@@ -172,6 +193,9 @@ const envSchema = z.object({// Devin recap model. Empty → use the user's own account default (their plan decides what is available).DEVIN_SUMMARY_MODEL: z.string().default(''),MUSE_SUMMARY_MODEL: z.string().default(''),+ // Amp recap agent mode. Amp exposes no model list — `-m` picks a MODE (low|medium|high|ultra) and the+ // mode picks the model. `low` is the cheapest, which is what a one-line recap should cost.+ AMP_SUMMARY_MODE: z.string().default('low'),// Shared recap reasoning level for Claude and Codex. Cursor effort is part of its model identifier.SUMMARY_EFFORT: z.enum(['low', 'medium', 'high']).default('low'),// Model for the voice router one-shot classifier (Overview voice → pick the agent). Small/fast by default.diff --git a/cli/src/engines/amp/askQuestion.spec.ts b/cli/src/engines/amp/askQuestion.spec.tsnew file mode 100644index 000000000..a72d8ec8f--- /dev/null+++ b/cli/src/engines/amp/askQuestion.spec.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest'+import { ampSelectionKeys, parseAmpQuestionPane } from './askQuestion.js'+import type { QuestionView } from '../../lib/askQuestion.js'++/**+ * Captured from a live pane (amp 0.0.1786064749) with `amp permissions add ask shell_command` in effect,+ * trimmed only in width. The scrollbar column (`█`), the wrapped `workdir` value and the unnumbered rows+ * are all exactly as Amp drew them.+ */+const PANE = `+ ╭─ Approval Required ──────────────────────────────────────────────────────────╮+ │ │+ │ shell_command: █ │+ │ { █ │+ │ "command": "echo probe123", █ │+ │ "workdir": █ │+ │ "/private/tmp/claude-502/-Users-nqhieu84-go-src-github-com-autonomous-ai-au█ │+ │ tonomous-code/4e2858a3/scratchpad/amp-probe" █ │+ │ } █ │+ │ █ │+ │ │+ │ ‣ Allow Once │+ │ Reject with feedback │+ │ Allow All for This Session │+ │ Allow All for Every Session │+ │ │+ ╰──────────── ↑/↓/j/k move · Enter select · Ctrl+E/Ctrl+Y scroll · Esc cancel ─╯+ ┃ run the shell command: echo probe123+`++describe('amp approval dialog', () => {+ it('reads all four options in the order Amp draws them', () => {+ const view = parseAmpQuestionPane(PANE) as QuestionView+ expect(view?.kind).toBe('question')+ expect(view.rows.map((r) => r.label)).toEqual([+ 'Allow Once', 'Reject with feedback', 'Allow All for This Session', 'Allow All for Every Session',+ ])+ expect(view.multi).toBe(false)+ })++ /**+ * "Reject with feedback" opens a free-text editor, which the device cannot type into — the same shape as+ * muse's "None of the above", which IS dropped. It is kept here because it is the only way to say no:+ * dropping it would leave a device user with four ways to approve and none to refuse.+ */+ it('keeps the refusal option even though it opens an editor', () => {+ const view = parseAmpQuestionPane(PANE) as QuestionView+ expect(view.rows.map((r) => r.label)).toContain('Reject with feedback')+ })++ it('names what is being approved, with the argument that fits on one line', () => {+ const view = parseAmpQuestionPane(PANE) as QuestionView+ // The wrapped `workdir` is deliberately not reassembled — only a whole pair on one line is used.+ expect(view.question).toBe('Approve shell_command: echo probe123')+ })++ it('walks to a row instead of pressing a digit', () => {+ const view = parseAmpQuestionPane(PANE) as QuestionView+ // Amp's list has no numbers: the first row is already highlighted, the rest are N presses away.+ expect(ampSelectionKeys(view.rows[0])).toEqual(['Enter'])+ expect(ampSelectionKeys(view.rows[1])).toEqual(['Down', 'Enter'])+ expect(ampSelectionKeys(view.rows[3])).toEqual(['Down', 'Down', 'Down', 'Enter'])+ })++ it('ignores a pane with no dialog on it', () => {+ expect(parseAmpQuestionPane('just some output\n$ ')).toBeNull()+ // A box that explains its own keys but is NOT an approval must not be scraped into a question —+ // the title is what proves it, and this is why the footer alone is not enough.+ expect(parseAmpQuestionPane('╭─ Something Else ─╮\n│ ‣ Yes │\n│ No │\n╰─ Enter select ─╯')).toBeNull()+ })++ it('anchors on the LAST dialog, so an answered one in the scrollback is not re-read', () => {+ const twice = `${PANE}\n${PANE.replace('echo probe123', 'echo second')}`+ const view = parseAmpQuestionPane(twice) as QuestionView+ expect(view.question).toBe('Approve shell_command: echo second')+ })+})diff --git a/cli/src/engines/amp/askQuestion.ts b/cli/src/engines/amp/askQuestion.tsnew file mode 100644index 000000000..504448800--- /dev/null+++ b/cli/src/engines/amp/askQuestion.ts@@ -0,0 +1,138 @@+/**+ * Amp's ask-the-user dialog — which is a PERMISSION prompt, not a question tool.+ *+ * Amp ships no ask-the-user tool at all (measured: 33 tools in a real session's `system/init`, none of+ * them asks anything). The only time it blocks on a person is when a permission rule says `ask`, and it+ * draws this, captured live:+ *+ * ╭─ Approval Required ───────────────────────────────────╮+ * │ │+ * │ shell_command: █ │ ← the tool, then its arguments as+ * │ { █ │ pretty-printed JSON, in a scroll box+ * │ "command": "echo probe123", █ │+ * │ "workdir": █ │ ← long values WRAP mid-string, which is+ * │ "/private/tmp/…/amp-probe" █ │ why the JSON is never re-parsed here+ * │ } █ │+ * │ │+ * │ ‣ Allow Once │ ← selection is a MARKER, not a number+ * │ Reject with feedback │+ * │ Allow All for This Session │+ * │ Allow All for Every Session │+ * ╰──── ↑/↓/j/k move · Enter select · Esc cancel ─────────╯+ *+ * Three things separate it from every other engine's dialog:+ *+ * - **The options are not numbered.** Nothing can be answered by pressing a digit; the caller has to+ * walk the list with `Down` and commit with `Enter`. `number` therefore carries the row's INDEX, and+ * `ampSelectionKeys` turns it into that walk.+ * - **The options are fixed**, so the row list is the same for every approval.+ * - **Nothing records it.** The thread log logs an approval queue with a COUNT and no content, and the+ * server export has no trace of a pending approval. The pane is the only place it exists.+ *+ * `Reject with feedback` is deliberately KEPT even though it opens a free-text editor the device cannot+ * type into. Dropping it — the rule the other engines' "None of the above" follows — would leave a device+ * user with four ways to say yes and none to say no.+ */++import type { PaneView, QuestionRow } from '../../lib/askQuestion.js'++/** The dialog's own footer. `Enter select` is the stable half; a narrow pane truncates from the end. */+const FOOTER_RE = /enter select|↑\/↓\/j\/k move/i+const TITLE_RE = /Approval Required/i+/** `‣` marks the highlighted row; the rest are indented by the same amount. */+const ROW_RE = /^\s*[‣>›]?\s{0,3}([A-Z][\w ]{2,60}?)\s*$/+/** `"command": "echo hi"` — one complete pair on one line. A wrapped value simply does not match. */+const ARG_RE = /"(?:command|path|file_path|name|query|url)"\s*:\s*"([^"]{1,120})"/++function stripAnsi(text: string): string {+ // eslint-disable-next-line no-control-regex+ return text.replace(/\[[0-9;?]*[A-Za-z]/g, '')+}++/**+ * Peel the box border AND the scrollbar column so the contents read as plain lines.+ *+ * The scrollbar is a separate trailing glyph inside the border (`… █ │`), so one pass that strips a+ * single trailing character is not enough — it left `shell_command: █`, which then matched+ * nothing and cost the dialog its question text.+ */+function unbox(line: string): string {+ return line+ .replace(/^[^│┃|]*[│┃|]/, '')+ .replace(/[│┃|█▌▐▁▂▃▄▅▆▇]+\s*$/, '')+ .replace(/[│┃|█▌▐]+\s*$/, '')+ .trimEnd()+}++/**+ * The keystrokes that select one row: walk down to it, then commit.+ *+ * Amp's list always opens on the first row, so the walk is the row's index. Returned as a list because+ * `sendKey` sends exactly one tmux key name per call.+ */+export function ampSelectionKeys(row: QuestionRow): string[] {+ const index = Number(row.number)+ const steps = Number.isFinite(index) && index > 0 ? index : 0+ return [...Array(steps).fill('Down'), 'Enter']+}++export function parseAmpQuestionPane(capture: string): PaneView {+ const raw = stripAnsi(capture).split('\n')+ // Anchor on the LAST dialog: an approval already answered stays in the scrollback above the live one.+ let footer = -1+ for (let i = raw.length - 1; i >= 0; i--) {+ if (FOOTER_RE.test(raw[i])) { footer = i; break }+ }+ if (footer < 0) return null+ // The footer regex alone is not enough — the title is what proves this is an approval and not some+ // other box that happens to explain its own key bindings.+ let title = -1+ for (let i = footer - 1; i >= 0 && footer - i < 60; i--) {+ if (TITLE_RE.test(raw[i])) { title = i; break }+ }+ if (title < 0) return null++ const lines = raw.slice(title, footer).map(unbox)++ // Options are the LAST run of label lines before the footer. Walking up from the bottom stops at the+ // JSON body, whose lines are punctuation-led (`{`, `"command": …`, `}`) and never match a label.+ const labels: string[] = []+ for (let i = lines.length - 1; i >= 0; i--) {+ const line = lines[i]+ if (!line.trim()) { if (labels.length) break; continue }+ const match = ROW_RE.exec(line)+ if (!match) break+ labels.unshift(match[1].trim())+ }+ if (labels.length < 2) return null++ const rows: QuestionRow[] = labels.map((label, index) => ({+ number: String(index),+ label,+ checked: false,+ }))++ // What is being approved. The tool is the line ending in `:` above the JSON; the argument preview is+ // whichever recognised key survived on a single line. Both are best-effort — the row list is what the+ // answer actually depends on.+ let tool = ''+ let arg = ''+ for (const line of lines) {+ const trimmed = line.trim()+ if (!tool) {+ const match = /^([a-zA-Z_][\w]*):$/.exec(trimmed)+ if (match) { tool = match[1]; continue }+ }+ if (!arg) {+ const match = ARG_RE.exec(trimmed)+ if (match) arg = match[1]+ }+ }+ const question = tool+ ? (arg ? `Approve ${tool}: ${arg}` : `Approve ${tool}?`)+ : 'Approval required'++ // Single-select: one Enter commits the highlighted row. `typeRow` stays null — "Reject with feedback"+ // is an option to be CHOSEN, not a free-text row to be typed into from here.+ return { kind: 'question', question, rows, multi: false, typeRow: null }+}diff --git a/cli/src/engines/amp/normalizer.spec.ts b/cli/src/engines/amp/normalizer.spec.tsnew file mode 100644index 000000000..416540da8--- /dev/null+++ b/cli/src/engines/amp/normalizer.spec.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import {+ AmpNormalizer, ampMessagesToEvents, ampRecord, ampToolName, ampToolOutput, ampWorkspaceRoot,+ lastAmpTurnText,+} from './normalizer.js'+import { parseAmpSession } from './runtimeProfile.js'++/**+ * Both fixtures are REAL transcripts, written by the adapter's own Amp plugin during a live tmux session+ * (amp 0.0.1786064749) with the home directory scrubbed. Nothing here is hand-written: Amp keeps no+ * conversation on disk, so these files are the only transcript that exists.+ */+function lines(name = 'amp-session'): string[] {+ const p = fileURLToPath(new URL(`../../lib/__fixtures__/${name}.jsonl`, import.meta.url))+ return readFileSync(p, 'utf-8').split('\n').filter((l) => l.trim())+}++describe('amp normalizer', () => {+ it('derives one turn from turn_start → turn_end', () => {+ const n = new AmpNormalizer()+ const events = lines().flatMap((l) => n.ingest(l))+ expect(events.filter((e) => e.type === 'turn_started')).toHaveLength(1)+ expect(events.filter((e) => e.type === 'turn_ended')).toHaveLength(1)+ expect(n.turnOpen).toBe(false)+ // The prompt reaches the turn, so web and device show what was asked.+ const started = events.find((e) => e.type === 'turn_started')+ expect(started).toMatchObject({ payload: { userMessage: 'cat a.txt' } })+ })++ it('pairs a tool call with its result under the SHARED tool name', () => {+ const n = new AmpNormalizer()+ const events = lines().flatMap((l) => n.ingest(l))+ const start = events.find((e) => e.type === 'tool_start')+ const end = events.find((e) => e.type === 'tool_end')+ expect(start).toMatchObject({ payload: { tool: 'Bash' } })+ expect(end).toMatchObject({ payload: { tool: 'Bash', isError: false } })+ // Same id on both halves — the card can only close if these match.+ expect((start as { payload: { id: string } }).payload.id)+ .toBe((end as { payload: { id: string } }).payload.id)+ })++ it("renders shell output as text, not as the JSON envelope Amp wraps it in", () => {+ const n = new AmpNormalizer()+ const end = n.ingest(lines().find((l) => l.includes('"t":"tool_result"')) as string)+ // Before this was unwrapped the card showed {"output":"hello\n","exitCode":0}.+ expect(end[0]).toMatchObject({ payload: { output: 'hello\n' } })+ })++ it('emits the assistant text', () => {+ const n = new AmpNormalizer()+ const events = lines().flatMap((l) => n.ingest(l))+ const text = events.filter((e) => e.type === 'text_delta')+ .map((e) => (e as { payload: { content: string } }).payload.content).join('')+ expect(text).toContain('hello')+ })++ /**+ * The case that made the backstop necessary. Measured: a prompt typed while Amp is still connecting is+ * queued, and the queued message is dispatched with NO `agent.start` — so the transcript opens straight+ * into `thinking`. Without an implicit open, this whole turn renders as nothing at all.+ */+ it('opens a turn for a queued prompt that never announced itself', () => {+ const n = new AmpNormalizer()+ const raw = lines('amp-session-queued')+ expect(raw.some((l) => l.includes('"t":"turn_start"'))).toBe(false)+ const events = raw.flatMap((l) => n.ingest(l))+ expect(events.filter((e) => e.type === 'turn_started')).toHaveLength(1)+ expect(events.filter((e) => e.type === 'turn_ended')).toHaveLength(1)+ expect(n.turnOpen).toBe(false)+ })++ it('replays a transcript as a conversation, not as a turn lifecycle', () => {+ const events = ampMessagesToEvents(lines())+ // The replay type has no turn frames at all — that it does not even typecheck is the point.+ expect(events.map((e) => e.type)).not.toContain('turn_started')+ expect(events[0]).toMatchObject({ type: 'user_message', payload: { content: 'cat a.txt' } })+ expect(events[events.length - 1]).toMatchObject({ type: 'done' })+ })++ it('reads the last turn for the recap', () => {+ const last = lastAmpTurnText(lines())+ expect(last?.userMessage).toBe('cat a.txt')+ expect(last?.assistantText).toContain('hello')+ })++ it('links a thread to its directory through the session record', () => {+ expect(ampWorkspaceRoot(lines()[0])).toBe('/home/user/demo')+ // Only the session record carries it; any other line must not be mistaken for one.+ expect(ampWorkspaceRoot(lines()[1])).toBeNull()+ expect(ampWorkspaceRoot('not json')).toBeNull()+ })++ it('ignores lines that are not records', () => {+ expect(ampRecord('')).toBeNull()+ expect(ampRecord('{"no":"type"}')).toBeNull()+ expect(new AmpNormalizer().ingest('garbage')).toEqual([])+ })+})++describe('amp tool names', () => {+ it('maps the measured tools onto the shared vocabulary', () => {+ expect(ampToolName('shell_command')).toBe('Bash')+ // The thread log spells the same tool differently from the wire; both must land on one card.+ expect(ampToolName('async_shell_command')).toBe('Bash')+ expect(ampToolName('apply_patch')).toBe('Edit')+ expect(ampToolName('Task')).toBe('Task')+ })++ it('leaves an unmeasured tool title-cased rather than guessing at it', () => {+ // `oracle` and `finder` are real Amp tools whose behaviour was never observed here. A wrong shared+ // name would draw a confidently wrong card; a title-cased one is merely plain.+ expect(ampToolName('oracle')).toBe('Oracle')+ expect(ampToolName('finder')).toBe('Finder')+ expect(ampToolName('')).toBe('Tool')+ })+})++describe('amp tool output', () => {+ it('unwraps both shapes Amp returns', () => {+ expect(ampToolOutput({ output: 'hello\n', exitCode: 0 })).toBe('hello\n')+ expect(ampToolOutput({ content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }] })).toBe('a\nb')+ expect(ampToolOutput('plain')).toBe('plain')+ expect(ampToolOutput(undefined)).toBe('')+ })+})++describe('amp runtime profile', () => {+ it('reports the agent mode, which is all Amp exposes', () => {+ expect(parseAmpSession('{"agentMode":"medium","lastThreadId":"T-1"}')).toEqual({ mode: 'medium' })+ expect(parseAmpSession('{"agentMode":"ultra"}')).toEqual({ mode: 'ultra' })+ })++ it('reports nothing rather than a value it cannot vouch for', () => {+ expect(parseAmpSession('{"agentMode":"turbo"}')).toEqual({ mode: null })+ expect(parseAmpSession('not json')).toEqual({ mode: null })+ expect(parseAmpSession(null)).toEqual({ mode: null })+ })+})diff --git a/cli/src/engines/amp/normalizer.ts b/cli/src/engines/amp/normalizer.tsnew file mode 100644index 000000000..f9c7dfaec--- /dev/null+++ b/cli/src/engines/amp/normalizer.ts@@ -0,0 +1,268 @@+/**+ * Amp JSONL → shared event vocabulary.+ *+ * The JSONL this reads is not Amp's — Amp keeps NO conversation on disk. Threads live on its server; the+ * only local artefacts are `session.json` and a debug log that records `blockCount` and `frameLength` and+ * not one character of message text (measured across two real sessions, 380 and 93k lines). So the+ * adapter's own plugin (see `installAmpPlugin`) writes the transcript, and this parses it.+ *+ * That makes the record vocabulary ours, and small:+ *+ * session {threadId, cwd} ← first line; `cwd` is what re-binds the session after a restart+ * turn_start {id, message} ← the user asked; opens a turn+ * text {id, i, text} ← assistant prose, one record per block+ * thinking {id, i, text}+ * tool_call {id, tool, input}+ * tool_result {id, tool, status, output} ← status is 'done' | 'error' | 'cancelled'+ * turn_end {id, status} ← closes the turn; a non-'done' status is a failed turn+ *+ * Tool calls pair by `id` (Amp's `toolUseID`), which both records carry verbatim.+ *+ * Two measured absences shape what this can render, and neither is a bug to be fixed here:+ *+ * - **Amp has no planning/todo tool.** The tool list a real session advertises has 33 entries and none+ * of them writes a checklist (the agent says so itself when asked). Nothing maps to `TodoWrite`, so+ * the device checklist stays empty for Amp — an absence, not a mis-mapping.+ * - **Amp has no ask-the-user tool.** What looks like a question is the permission prompt, drawn in the+ * TUI and recorded nowhere at all — not in the thread log, not in the export. It is read off the pane+ * instead; see `askQuestion.ts`.+ */++import type { EngineNormalizer } from '../types.js'+import type { LastTurnText, LiveEvent, SessionEvent } from '../../lib/normalize.js'++type JsonObject = Record<string, unknown>++const MAX_OUTPUT = 2_000+const MAX_THINKING = 500++/**+ * Amp's tool names → the vocabulary the web/device cards already render.+ *+ * MEASURED from a real session's `system/init` tool list and from live `tool.call` events — not carried+ * over from another engine, because Amp's names match no other CLI's. Only tools whose behaviour was+ * actually observed are mapped; the rest fall through to the title-cased default on purpose. Guessing+ * that `finder` is a Glob or `oracle` an Agent would put a wrong card on screen and report nothing.+ */+const TOOL_NAMES: Record<string, string> = {+ // The one tool Amp actually reads and writes files with in a normal turn — measured: asked to read a+ // file, it runs `cat` through this rather than through any read tool.+ shell_command: 'Bash',+ // The thread log spells the same tool `async_shell_command` while the wire calls it `shell_command`.+ // Both are mapped so a rename on either side cannot silently drop the card.+ async_shell_command: 'Bash',+ shell_command_status: 'BashOutput',+ apply_patch: 'Edit',+ web_search: 'WebSearch',+ read_web_page: 'WebFetch',+ // Amp's sub-agent tool already carries the shared name.+ Task: 'Task',+}++export function ampToolName(name: string): string {+ return TOOL_NAMES[name] ?? (name ? name.charAt(0).toUpperCase() + name.slice(1) : 'Tool')+}++function obj(value: unknown): JsonObject | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as JsonObject) : null+}++function str(value: unknown): string {+ return typeof value === 'string' ? value : ''+}++export function clip(value: string, limit: number): string {+ return value.length > limit ? `${value.slice(0, limit)}…` : value+}++/** One parsed record, or null for a line that is not one. */+export function ampRecord(line: string): JsonObject | null {+ let raw: JsonObject | null+ try { raw = obj(JSON.parse(line)) } catch { return null }+ if (!raw || !str(raw.t)) return null+ return raw+}++/** `cwd` from the session record — the link between a thread and a directory. */+export function ampWorkspaceRoot(firstLine: string): string | null {+ const record = ampRecord(firstLine)+ if (!record || str(record.t) !== 'session') return null+ return str(record.cwd) || null+}++/**+ * A tool result's output, as text.+ *+ * Amp's `output` is not a string. Measured, it is `{content:[{type:'text',text:…}]}` for the tools that+ * return prose and a bare object (`{output:'hello\n',exitCode:0}`) for shell. Rendering the JSON of the+ * first shape put a wall of escaped braces on the card where two lines of output belonged.+ */+export function ampToolOutput(output: unknown): string {+ if (typeof output === 'string') return output+ const body = obj(output)+ if (!body) return output === undefined || output === null ? '' : JSON.stringify(output)+ const content = body.content+ if (Array.isArray(content)) {+ const text = content+ .map((entry) => str(obj(entry)?.text))+ .filter(Boolean)+ .join('\n')+ if (text) return text+ }+ if (typeof body.output === 'string') return body.output+ return JSON.stringify(body)+}++export interface AmpTurnState {+ open: boolean+ /** tool id → the name it opened under, so the result reports the same one. */+ toolNames: Map<string, string>+ pendingTools: Set<string>+ thinkingCounter: number+}++export function newAmpTurnState(): AmpTurnState {+ return { open: false, toolNames: new Map(), pendingTools: new Set(), thinkingCounter: 0 }+}++/** One record → events. `mode: 'replay'` emits `user_message` instead of deriving the turn lifecycle. */+export function ampRecordToEvents(record: JsonObject, state: AmpTurnState, mode: 'live' | 'replay'): LiveEvent[] {+ const kind = str(record.t)+ const events: LiveEvent[] = []++ if (kind === 'turn_start') {+ const prompt = str(record.message).trim()+ if (mode === 'replay') return prompt ? [{ type: 'user_message', payload: { content: prompt } }] : []+ // A turn already open means the previous one never closed — close it rather than nest, so the tile+ // cannot be left spinning by a turn whose end was missed.+ if (state.open) events.push({ type: 'turn_ended', payload: {} })+ state.open = true+ state.pendingTools.clear()+ events.push({ type: 'turn_started', payload: { userMessage: prompt } })+ return events+ }++ // A turn whose `agent.start` never fired still has to render.+ //+ // MEASURED: a prompt submitted while Amp is still connecting is QUEUED, and the queued message is+ // dispatched WITHOUT an `agent.start` event — the captured transcript held `session`, then `thinking`,+ // `tool_call`, `tool_result`, `text` and a `turn_end` whose message id matched no start at all. Without+ // this backstop that whole turn is invisible: nothing opens it, and `turn_end` is then dropped below+ // because no turn is open, so the answer never reaches web or device.+ //+ // The prompt text is genuinely unknown here (it is the one thing the event would have carried), so the+ // turn opens with an empty message rather than a guessed one.+ if (mode === 'live' && !state.open && (kind === 'thinking' || kind === 'text' || kind === 'tool_call')) {+ state.open = true+ events.push({ type: 'turn_started', payload: { userMessage: '' } })+ }++ if (kind === 'thinking') {+ const text = str(record.text).trim()+ if (text) {+ events.push({+ type: 'thinking_delta',+ payload: { content: clip(text, MAX_THINKING), thinkingId: `thinking-amp-${state.thinkingCounter++}` },+ })+ }+ return events+ }++ if (kind === 'text') {+ const text = str(record.text)+ if (text) events.push({ type: 'text_delta', payload: { content: text } })+ return events+ }++ if (kind === 'tool_call') {+ const id = str(record.id)+ if (!id) return events+ const tool = ampToolName(str(record.tool))+ state.toolNames.set(id, tool)+ state.pendingTools.add(id)+ events.push({ type: 'tool_start', payload: { id, tool, input: record.input ?? {} } })+ return events+ }++ if (kind === 'tool_result') {+ const id = str(record.id)+ if (!id) return events+ const tool = state.toolNames.get(id) ?? ampToolName(str(record.tool))+ state.toolNames.delete(id)+ state.pendingTools.delete(id)+ const output = ampToolOutput(record.output)+ // Amp reports the outcome as a word, not a flag: 'done' | 'error' | 'cancelled' (measured).+ const status = str(record.status)+ const isError = status === 'error' || status === 'cancelled'+ events.push({+ type: 'tool_end',+ payload: { id, tool, output: clip(output, MAX_OUTPUT), isError, summary: isError ? status : '' },+ })+ return events+ }++ if (kind === 'turn_end') {+ if (mode === 'replay' || !state.open) return []+ state.open = false+ state.pendingTools.clear()+ // 'error' and 'cancelled' are both turns that produced no answer. Marking them aborted clears the+ // device tile without asking a recap worker to summarise nothing.+ const failed = str(record.status) !== 'done'+ events.push({ type: 'turn_ended', payload: failed ? { aborted: true } : {} })+ return events+ }++ return []+}++/** Live tail: one JSONL line → events. */+export class AmpNormalizer implements EngineNormalizer {+ private state = newAmpTurnState()++ get turnOpen(): boolean { return this.state.open }++ closeTurn(): void {+ this.state.open = false+ this.state.pendingTools.clear()+ }++ ingest(line: string): LiveEvent[] {+ const record = ampRecord(line)+ return record ? ampRecordToEvents(record, this.state, 'live') : []+ }++ finishReplay(): LiveEvent[] {+ return []+ }+}++/** Full-session replay (`session_get`) — the same render path as the live stream. */+export function ampMessagesToEvents(lines: string[]): SessionEvent[] {+ const state = newAmpTurnState()+ const events: SessionEvent[] = []+ for (const line of lines) {+ const record = ampRecord(line)+ if (record) events.push(...ampRecordToEvents(record, state, 'replay') as SessionEvent[])+ }+ events.push({ type: 'done', payload: { result: 'success' } })+ return events+}++/** Last user prompt + the assistant text that followed it — the recap's source of truth. */+export function lastAmpTurnText(lines: string[]): LastTurnText | null {+ let userMessage = ''+ let assistantText = ''+ for (const line of lines) {+ const record = ampRecord(line)+ if (!record) continue+ const kind = str(record.t)+ if (kind === 'turn_start') {+ userMessage = str(record.message).trim()+ assistantText = ''+ } else if (kind === 'text') {+ const text = str(record.text).trim()+ if (text) assistantText += `${assistantText ? '\n\n' : ''}${text}`+ }+ }+ return assistantText ? { userMessage, assistantText } : null+}diff --git a/cli/src/engines/amp/runtimeProfile.ts b/cli/src/engines/amp/runtimeProfile.tsnew file mode 100644index 000000000..5f77e440f--- /dev/null+++ b/cli/src/engines/amp/runtimeProfile.ts@@ -0,0 +1,26 @@+/**+ * Amp runtime profile.+ *+ * Amp exposes no model list at all — `amp -m <mode>` picks one of four AGENT MODES (low, medium, high,+ * ultra) and the mode decides the model, the system prompt and the tool set. So the mode is what the user+ * chooses and what the TUI prints in its footer (`─ medium ─`), and it is what the chip reports.+ *+ * It is read from `~/.local/share/amp/session.json`, the same file that maps panes to threads. Verified+ * content: {"agentMode":"medium","lastThreadId":"T-…","lastThreadByTerminal":{…}}.+ *+ * One honest limitation: `agentMode` there is GLOBAL, not per-thread. Two Amp agents started in different+ * modes both report whichever was written last. The per-thread value does exist — `meta.agentMode` in+ * `amp threads export` — but reading it costs a ~1.5s network round trip per poll, which is far too much+ * for a chip that only ever displays.+ */++const MODES = new Set(['low', 'medium', 'high', 'ultra'])++export function parseAmpSession(text: string | null): { mode: string | null } {+ if (!text) return { mode: null }+ let parsed: unknown+ try { parsed = JSON.parse(text) } catch { return { mode: null } }+ const obj = parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : {}+ const raw = typeof obj.agentMode === 'string' ? obj.agentMode.toLowerCase() : ''+ return { mode: MODES.has(raw) ? raw : null }+}diff --git a/cli/src/engines/types.ts b/cli/src/engines/types.tsindex 015d04a3c..cd262f179 100644--- a/cli/src/engines/types.ts+++ b/cli/src/engines/types.ts@@ -1,7 +1,7 @@import type { LiveEvent } from '../lib/normalize.js'import type { RegisteredSession } from '../lib/registry.js'-export type AgentEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse'+export type AgentEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp'export interface EngineNormalizer {ingest(line: string): LiveEvent[]diff --git a/cli/src/lib/__fixtures__/amp-session-queued.jsonl b/cli/src/lib/__fixtures__/amp-session-queued.jsonlnew file mode 100644index 000000000..15b560240--- /dev/null+++ b/cli/src/lib/__fixtures__/amp-session-queued.jsonl@@ -0,0 +1,6 @@+{"t":"session","threadId":"T-019fda6c-73b4-7025-91e6-27a08112a1a8","cwd":"/home/user/demo","at":1786075971671}+{"t":"thinking","id":"M-0342oiRx5e82AIK1p8OeDL","i":0,"text":"The user wants me to show the contents of b.txt."}+{"t":"tool_call","id":"TU-0342oiTMd20hJrYpMai6tr","tool":"shell_command","input":{"command":"cat b.txt","workdir":"/home/user/demo"}}+{"t":"tool_result","id":"TU-0342oiTMd20hJrYpMai6tr","tool":"shell_command","status":"done","output":{"output":"world\n","exitCode":0}}+{"t":"text","id":"M-0342oiXLpwPQzgSWmj3k35","i":0,"text":"Contents of `b.txt`:\n\n```\nworld\n```"}+{"t":"turn_end","id":"M-0342ohXN4hx0RHrqIU5XEM","status":"done","at":1786075976900}diff --git a/cli/src/lib/__fixtures__/amp-session.jsonl b/cli/src/lib/__fixtures__/amp-session.jsonlnew file mode 100644index 000000000..2421a0052--- /dev/null+++ b/cli/src/lib/__fixtures__/amp-session.jsonl@@ -0,0 +1,7 @@+{"t":"session","threadId":"T-019fda6e-7992-73eb-b60a-250f8f80beb6","cwd":"/home/user/demo","at":1786076104492}+{"t":"turn_start","id":"M-0342oktTFVCgnXAHmOvIRc","message":"cat a.txt","at":1786076104799}+{"t":"thinking","id":"M-0342olqMGdUlTYC9UaF56j","i":0,"text":"The user wants me to output the contents of a.txt."}+{"t":"tool_call","id":"TU-0342olrLgE28QhTlBOe0dc","tool":"shell_command","input":{"command":"cat a.txt","workdir":"/home/user/demo"}}+{"t":"tool_result","id":"TU-0342olrLgE28QhTlBOe0dc","tool":"shell_command","status":"done","output":{"output":"hello\n","exitCode":0}}+{"t":"text","id":"M-0342olvTZBQxpXnNPl14Pq","i":0,"text":"```\nhello\n```"}+{"t":"turn_end","id":"M-0342oktTFVCgnXAHmOvIRc","status":"done","at":1786076110762}diff --git a/cli/src/lib/askQuestion.ts b/cli/src/lib/askQuestion.tsindex 89840f177..b20c258d6 100644--- a/cli/src/lib/askQuestion.ts+++ b/cli/src/lib/askQuestion.ts@@ -24,6 +24,7 @@import type { RegisteredSession } from './registry.js'import type { AgentEngine } from '../engines/types.js'import { parseMuseQuestionPane } from '../engines/muse/askQuestion.js'+import { ampSelectionKeys, parseAmpQuestionPane } from '../engines/amp/askQuestion.js'import { parseDevinQuestionPane } from '../engines/devin/askQuestion.js'/** Device-facing question shape — byte-for-byte the hosted runtime’s `commanderQuestions()` output. */@@ -118,6 +119,8 @@ export function parseEngineQuestionPane(engine: AgentEngine, capture: string): P// Muse pairs each option with a description on the same line and floats a live Preview box above the// rows — both confuse the shared parser, so it reads its own.if (engine === 'muse') return parseMuseQuestionPane(capture)+ // Amp's is a permission prompt with unnumbered rows — nothing the shared parser can anchor on.+ if (engine === 'amp') return parseAmpQuestionPane(capture)// Hermes and OpenCode paint Claude's dialog inside a box; peel the border and the shared parser fits.if (engine === 'hermes') return parseQuestionPane(unframe(capture))if (engine === 'opencode') {@@ -312,6 +315,17 @@ export function parseQuestionPane(capture: string): PaneView {/** Match an answer to a row. The device stores option labels in an 80-byte buffer, so a long label comes* back truncated — prefix matches count, in both directions. */+/**+ * The keystrokes that commit one row.+ *+ * Every engine but Amp numbers its options, so the digit both selects and submits in one press. Amp+ * draws an unnumbered list navigated with the arrow keys, so its rows carry an index and are reached by+ * walking down to them.+ */+function rowKeys(engine: AgentEngine, row: QuestionRow): string[] {+ return engine === 'amp' ? ampSelectionKeys(row) : [row.number]+}+export function matchRow(rows: QuestionRow[], answer: string): QuestionRow | null {const a = norm(answer)if (!a) return null@@ -445,7 +459,12 @@ export class AskQuestionController {const row = matchRow(view.rows, picked.value)if (row) {- await this.deps.sendKey(pane, row.number) // selects AND submits this question+ // One digit selects AND submits — except on Amp, whose rows are unnumbered and reached by+ // walking the list, so this is a short sequence rather than a single key.+ for (const key of rowKeys(engine, row)) {+ await this.deps.sendKey(pane, key)+ await wait(TEXT_MS)+ }await wait(STEP_MS)continue}@@ -485,7 +504,9 @@ export interface QuestionWatcherDeps {}const POLL_MS = 1500-const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'devin', 'hermes', 'opencode', 'muse'])+// Amp is here for its PERMISSION prompt, not a question tool — it has none. That prompt is drawn only in+// the pane and recorded nowhere, so polling the pane is the only way it is ever seen.+const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'devin', 'hermes', 'opencode', 'muse', 'amp'])/** Does this engine ever paint a question dialog? Callers use it to decide whether to watch its pane. */export function pollsQuestions(engine: AgentEngine): boolean {diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.tsindex bcccdb8f7..0e5aa52a4 100644--- a/cli/src/lib/engineBin.ts+++ b/cli/src/lib/engineBin.ts@@ -12,7 +12,7 @@ import type { AgentEngine } from '../engines/types.js'/** Every engine the adapter can drive — also the set of `harness <engine>` launch subcommands. */export const ENGINES: readonly AgentEngine[] = [- 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse',+ 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp',] as const/**@@ -82,5 +82,6 @@ export function engineBin(engine: AgentEngine): string {case 'commandcode': return env.COMMANDCODE_PATH || 'cmd'case 'devin': return env.DEVIN_PATH || 'devin'case 'muse': return env.MUSE_PATH || 'muse'+ case 'amp': return env.AMP_PATH || 'amp'}}diff --git a/cli/src/lib/enginePermissions.spec.ts b/cli/src/lib/enginePermissions.spec.tsindex 1c9fd4754..bab04fa8e 100644--- a/cli/src/lib/enginePermissions.spec.ts+++ b/cli/src/lib/enginePermissions.spec.ts@@ -27,6 +27,10 @@ describe('default permission flags', () => {// Muse's `--yolo` also trusts the workspace for the run, so one flag clears approval, sandbox and// trust in one go — measured from `muse --help`, 0.1.0-R708.1.muse: ['--yolo'],+ // Amp's flag is UNDOCUMENTED — not in `--help`, found in the binary — and verified three ways on+ // 0.0.1786064749: an unknown flag is rejected while this one is accepted, an `ask` rule blocks the+ // tool without it ("blocked by a permissions rule"), and the same command runs with it.+ amp: ['--dangerously-allow-all'],})})diff --git a/cli/src/lib/enginePermissions.ts b/cli/src/lib/enginePermissions.tsindex 8aa8fd154..babcde9d1 100644--- a/cli/src/lib/enginePermissions.ts+++ b/cli/src/lib/enginePermissions.ts@@ -111,6 +111,20 @@ const PERMISSIONS: Readonly<Record<AgentEngine, EnginePermissions>> = {add: [{ axis: 'permission', args: ['--yolo'] }],owned: { permission: ['--yolo', '--disable-approval', '--disable-sandbox', '--trust-workspace', '--approval-mode'] },},+ // `--dangerously-allow-all` is UNDOCUMENTED — absent from `--help`, found in the binary's strings — and+ // it is real. Measured all three ways on 0.0.1786064749: an unknown flag is rejected outright+ // (`error: unknown option`) while this one is accepted; with an `ask shell_command` rule in settings and+ // no flag the tool is refused mid-turn ("blocked by a permissions rule … rule 0: ask shell_command");+ // with the flag the same command runs and returns its output.+ //+ // That refusal is why the flag matters: Amp does not stall waiting for someone, it tells the model no+ // and carries on, so an unattended agent produces a turn that quietly did nothing. There is no config+ // edit here either — the rules live in `amp.permissions` in settings.json, which this launcher leaves+ // alone. A user who passes the flag themselves keeps their own choice.+ amp: {+ add: [{ axis: 'permission', args: ['--dangerously-allow-all'] }],+ owned: { permission: ['--dangerously-allow-all'] },+ },}/** Whole-argv-entry match; `--flag=value` is the same choice as `--flag value`. */diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex 771f7cc44..68d3a1854 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -574,6 +574,173 @@ export function installPiExtension(port: number): void {}}+const AMP_PLUGIN_PATH = join(env.AMP_PLUGIN_DIR, 'launcher-register.ts')++/**+ * Amp's plugin does more than discovery — it WRITES the transcript, because Amp keeps none.+ *+ * Every other engine here leaves a conversation on disk and the adapter tails it. Amp does not: threads+ * live on its server, and the only local artefacts are `session.json` and a debug log that records+ * `blockCount`/`frameLength` and no message text whatsoever (measured across two real sessions).+ * `amp threads export` can fetch the content, but it is a ~1.5s network round trip that never shows a+ * message before it is complete — useless for a live tail.+ *+ * The plugin API is the way in. Five events fire (measured, in the TUI, not read off a doc):+ * `session.start`, `agent.start`, `tool.call`, `tool.result`, `agent.end`. So this plugin writes the+ * JSONL the watcher tails, and from there Amp is an ordinary file-backed engine.+ *+ * Two details are load-bearing:+ *+ * - **Text comes from `ctx.thread.messages()`, not from the events.** No event carries assistant text.+ * But the thread handle reads the client's own local state, and at `tool.call` it ALREADY contains+ * the in-flight assistant message (measured) — so snapshotting on each event emits a message's text+ * BEFORE the tool it called, which is the order a transcript has to be in. Nothing is fetched.+ * - **Blocks are emitted once, keyed `<messageId>#<index>`.** Each snapshot re-reads the same recent+ * messages, so without that key every event would re-emit the whole tail of the conversation.+ *+ * Being a SYSTEM plugin it loads in every `amp` the user runs, including ones this adapter knows nothing+ * about. The `TMUX_PANE` + `MACHINE_ID` guard is what keeps it inert there — same rule as pi/opencode.+ */+function ampPluginSource(port: number, sessionsDir: string): string {+ return `// launcher-register — auto-installed by the machine adapter. Registers this Amp thread with the local+// machine daemon (127.0.0.1:${port}) and writes the transcript the daemon tails, because Amp keeps none+// on disk. No-op unless started by \`harness amp\` (MACHINE_ID) inside tmux.+import { appendFileSync, existsSync, mkdirSync } from 'node:fs'+import { join } from 'node:path'++export const description = 'Mirrors this Amp thread to the machine adapter (web + device)'++const SESSIONS_DIR = ${JSON.stringify(sessionsDir)}++export default function (amp: any) {+ const pane = process.env.TMUX_PANE+ // The launcher (\`harness amp\`) mints a UUID per launch and exports it as MACHINE_ID; the daemon binds+ // a session's lifetime to that launcher and REFUSES a registration without one. An amp started outside+ // the launcher inherits neither variable, which is exactly when this plugin must do nothing at all.+ const launcherId = process.env.MACHINE_ID+ if (!pane || !launcherId) return++ // NOT \`process.cwd()\`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports+ // \`<project>/.amp/plugins\` (measured). \`harness amp\` exports the real one; \`PWD\` from the launching+ // shell is the fallback for an amp the launcher did not start — which the MACHINE_ID guard above has+ // already excluded, so it is only ever a belt-and-braces third choice.+ const workdir = process.env.HARNESS_AGENT_CWD || process.env.PWD || process.cwd()++ const emitted = new Set()+ let registered = false+ let file = ''++ const line = (record: any) => {+ try {+ mkdirSync(SESSIONS_DIR, { recursive: true })+ appendFileSync(file, JSON.stringify(record) + '\\n')+ } catch {}+ }++ const open = (threadId: string) => {+ if (file) return+ file = join(SESSIONS_DIR, threadId + '.jsonl')+ // \`cwd\` on the first line is what lets the daemon re-find this session by directory after a restart,+ // the same way it reads claude's and pi's transcripts. It must be a top-level string field.+ line({ t: 'session', threadId, cwd: workdir, at: Date.now() })+ }++ const register = async (threadId: string) => {+ open(threadId)+ if (registered || !existsSync(file)) return+ try {+ const res = await fetch('http://127.0.0.1:${port}/api/hook/session-start', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ engine: 'amp',+ launcherId,+ sessionId: threadId,+ transcriptPath: file,+ cwd: workdir,+ tmuxPane: pane,+ }),+ })+ if (res.ok) registered = true+ } catch {}+ }++ // Emit any assistant text/thinking not written yet. Tool blocks are deliberately skipped: tool.call and+ // tool.result own those cards, and emitting them here too would double every tool in the transcript.+ const drain = async (ctx: any) => {+ let messages: any[] = []+ try { messages = await ctx.thread.messages({ from: 'end', limit: 20 }) } catch { return }+ for (const message of messages) {+ if (!message || message.role !== 'assistant') continue+ const blocks = Array.isArray(message.content) ? message.content : []+ for (let i = 0; i < blocks.length; i++) {+ const block = blocks[i]+ if (!block || (block.type !== 'text' && block.type !== 'thinking')) continue+ const key = String(message.id) + '#' + i+ if (emitted.has(key)) continue+ const text = typeof block.text === 'string' ? block.text : block.thinking+ if (typeof text !== 'string' || !text) continue+ emitted.add(key)+ line({ t: block.type, id: message.id, i, text })+ }+ }+ }++ amp.on('session.start', async (event: any) => { await register(event.thread.id) })++ amp.on('agent.start', async (event: any, ctx: any) => {+ await register(event.thread.id)+ line({ t: 'turn_start', id: event.id, message: event.message, at: Date.now() })+ await drain(ctx)+ })++ amp.on('tool.call', async (event: any, ctx: any) => {+ await register(event.thread.id)+ await drain(ctx)+ line({ t: 'tool_call', id: event.toolUseID, tool: event.tool, input: event.input })+ })++ amp.on('tool.result', async (event: any, ctx: any) => {+ line({+ t: 'tool_result',+ id: event.toolUseID,+ tool: event.tool,+ status: event.status,+ output: event.output,+ })+ await drain(ctx)+ })++ amp.on('agent.end', async (event: any, ctx: any) => {+ await drain(ctx)+ line({ t: 'turn_end', id: event.id, status: event.status, at: Date.now() })+ })+}+`+}++/** Idempotently drop the Amp plugin into ~/.config/amp/plugins/. */+export function installAmpPlugin(port: number): void {+ const source = ampPluginSource(port, env.AMP_SESSIONS_DIR)+ try {+ if (existsSync(AMP_PLUGIN_PATH) && readFileSync(AMP_PLUGIN_PATH, 'utf-8') === source) {+ console.log('[hooks] Amp plugin already installed')+ return+ }+ } catch { /* unreadable — rewrite it */ }+ try {+ mkdirSync(dirname(AMP_PLUGIN_PATH), { recursive: true })+ mkdirSync(env.AMP_SESSIONS_DIR, { recursive: true })+ const tmp = `${AMP_PLUGIN_PATH}.${process.pid}.tmp`+ writeFileSync(tmp, source)+ renameSync(tmp, AMP_PLUGIN_PATH)+ console.log(`[hooks] installed Amp plugin → ${AMP_PLUGIN_PATH}`)+ console.log('[hooks] (takes effect on the next amp session start)')+ } catch (err) {+ console.error('[hooks] failed to write Amp plugin:', err)+ }+}+/** Idempotently drop the OpenCode discovery plugin into ~/.config/opencode/plugin/. */export function installOpencodePlugin(port: number): void {const source = opencodePluginSource(port)@@ -616,5 +783,6 @@ export function installHooksFor(engine: AgentEngine, port: number): void {case 'hermes': installHermesHooks(port); breakcase 'commandcode': installCommandCodeHooks(port); breakcase 'devin': installDevinHooks(port); break+ case 'amp': installAmpPlugin(port); break}}diff --git a/cli/src/lib/launch.ts b/cli/src/lib/launch.tsindex 96af30ede..dcc26897a 100644--- a/cli/src/lib/launch.ts+++ b/cli/src/lib/launch.ts@@ -454,6 +454,11 @@ export async function launchEngine(engine: AgentEngine, argv: string[]): Promise// script and the binary while the user is mid-session. Pin it: an agent must not change under// the person using it....(engine === 'muse' ? { MUSE_NO_AUTO_UPDATE: '1' } : {}),+ // Amp's plugin runs under Bun with its own directory as `process.cwd()` — measured: it reported+ // `<project>/.amp/plugins`, not the project. The transcript's `cwd` is what re-binds a session+ // after a restart, so a wrong one there means an agent that can never be re-found. The launcher is+ // standing in the right directory, so it simply says which one.+ ...(engine === 'amp' ? { HARNESS_AGENT_CWD: process.cwd() } : {}),},})diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.tsindex 031cc56a4..ffb878abe 100644--- a/cli/src/lib/oneshot.ts+++ b/cli/src/lib/oneshot.ts@@ -915,6 +915,69 @@ export function runMuseOneShot(opts: OneShotOptions): Promise<OneShotResult> {})}+/**+ * One-shot recap through `amp -x`.+ *+ * The prompt goes as ARGV, so like muse this worker cannot be pre-warmed and stays outside the pool.+ *+ * `model` here is an agent MODE, not a model name: Amp exposes no model list and `-m low|medium|high|ultra`+ * is what chooses one. `low` is both the cheapest and plenty for a one-sentence recap.+ *+ * Self-registration is prevented twice over. The adapter's Amp plugin already refuses to do anything+ * without `MACHINE_ID` and `TMUX_PANE`, and both are scrubbed here; `AMP_DISABLE_PLUGINS` then stops it+ * loading at all, which also keeps a user's own plugins out of a recap. `-x` archives the thread it+ * creates once it finishes, so recaps do not accumulate in the user's thread list.+ */+export function runAmpOneShot(opts: OneShotOptions): Promise<OneShotResult> {+ if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('amp one-shot aborted'), { name: 'AbortError' }))+ const args = ['-x', opts.prompt, '--no-notifications', '-m', opts.model || env.AMP_SUMMARY_MODE]+ const processEnv: NodeJS.ProcessEnv = { ...process.env, AMP_DISABLE_PLUGINS: '1' }+ delete processEnv.TMUX+ delete processEnv.TMUX_PANE+ delete processEnv.MACHINE_ID+ const timeoutMs = opts.timeoutMs ?? 60_000++ return new Promise<OneShotResult>((resolve, reject) => {+ const child = spawn(env.AMP_PATH || 'amp', args, {+ cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],+ })+ let stdout = ''+ let stderr = ''+ let settled = false+ const finish = (fn: () => void): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ opts.signal?.removeEventListener('abort', onAbort)+ fn()+ }+ const kill = (): void => {+ if (child.pid == null || child.exitCode != null) return+ try { process.kill(-child.pid, 'SIGKILL') } catch { try { child.kill('SIGKILL') } catch { /* gone */ } }+ }+ const onAbort = (): void => {+ finish(() => reject(Object.assign(new Error('amp one-shot aborted'), { name: 'AbortError' })))+ kill()+ }+ const timer = setTimeout(() => {+ finish(() => reject(new Error(`amp one-shot timed out after ${timeoutMs}ms`)))+ kill()+ }, timeoutMs)+ opts.signal?.addEventListener('abort', onAbort)++ child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })+ child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })+ child.on('error', (err) => finish(() => reject(err)))+ child.on('close', (code) => {+ const text = stdout.trim()+ finish(() => {+ if (!text && code !== 0) reject(new Error(`amp one-shot exited ${code}: ${stderr.slice(0, 500)}`))+ else resolve({ text, sessionId: null })+ })+ })+ })+}+export function runHermesOneShot(opts: OneShotOptions): Promise<OneShotResult> {if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('hermes one-shot aborted'), { name: 'AbortError' }))const args = ['chat', '-q', opts.prompt, '-Q', '--source', 'tool', ...(opts.model ? ['-m', opts.model] : [])]diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 8f14e3845..129571524 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -113,7 +113,11 @@ export function validTranscriptPath(engine: AgentEngine, filePath: string): booltry {const actual = realpathSync(filePath)const root = realpathSync(- engine === 'muse'+ // Amp's root is OURS, not Amp's: the transcript is written by the adapter's own plugin because Amp+ // keeps no conversation on disk (see installAmpPlugin).+ engine === 'amp'+ ? env.AMP_SESSIONS_DIR+ : engine === 'muse'? join(env.MUSE_HOME, 'sessions'): engine === 'codex'? join(env.CODEX_HOME, 'sessions')@@ -195,7 +199,7 @@ class Registry {}let changed = falsefor (const raw of Array.isArray(arr) ? arr : []) {- const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' ? raw.engine : 'claude'+ const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' ? raw.engine : 'claude'const pane = typeof raw?.tmuxPane === 'string' && PANE_RE.test(raw.tmuxPane) ? raw.tmuxPane : ''let transcriptPath =typeof raw?.transcriptPath === 'string' && raw.transcriptPath@@ -362,7 +366,7 @@ class Registry {const sessionId =input.sessionId || (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')const engine: AgentEngine =- input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' ? input.engine : 'claude'+ input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' || input.engine === 'amp' ? input.engine : 'claude'const pane = input.tmuxPane// The machine id may be omitted only when re-registering a session we already know (the catch hook// fires on every prompt and older payloads carried no id) — a NEW session always needs one, becausediff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.tsindex ad4c5a1b4..15f459413 100644--- a/cli/src/lib/runtimeProfile.ts+++ b/cli/src/lib/runtimeProfile.ts@@ -4,6 +4,7 @@ import { execFile } from 'child_process'import { promisify } from 'util'import { env } from '../config/env.js'import { parseMuseSettings } from '../engines/muse/runtimeProfile.js'+import { parseAmpSession } from '../engines/amp/runtimeProfile.js'import type { AgentEngine } from '../engines/types.js'import type { RegisteredSession } from './registry.js'import {@@ -101,7 +102,7 @@ interface CodexCache {models?: CodexCacheModel[]}-const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse):([^@]+)@([a-z0-9_-]+)$/i+const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp):([^@]+)@([a-z0-9_-]+)$/iconst CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])const CLAUDE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])const CURSOR_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])@@ -676,6 +677,22 @@ export class RuntimeProfileManager {}return before !== after}+ if (session.engine === 'amp') {+ // Amp has no models — only agent MODES — so the mode is reported as the model and there is no+ // second axis to report. `~/.local/share/amp/session.json` is the only local place it is written.+ const before = this.selectedModel(session)+ const state = this.state(session.sessionId)+ const parsed = parseAmpSession(await readText(join(env.AMP_STATE_DIR, 'session.json')))+ if (parsed.mode) state.model = parsed.mode+ state.effort = 'auto'+ state.observedAt = Date.now()+ const after = this.selectedModel(session)+ this.wake(session.sessionId)+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {+ this.scheduleChanged(session.sessionId)+ }+ return before !== after+ }if (session.engine === 'opencode') {// The footer only resolves against the catalog, so warm it here — `ingestPane` is synchronous and// cannot fetch, and without this the chip stays blank until the web happens to ask for models.diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex 9ef7f4b6b..e6e49581d 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -29,6 +29,9 @@ const DEVIN_SUBMIT_VERIFY_MS = 2_500// Muse writes the `started` record as soon as it accepts the prompt, so the transcript answers within// one poll — same window as the other store-verified engines.const MUSE_SUBMIT_VERIFY_MS = 6_000+// Amp's plugin writes `turn_start` from the agent.start event, which fires the instant the prompt is+// accepted — no model round trip in between, so the same store-verified window fits.+const AMP_SUBMIT_VERIFY_MS = 6_000const CURSOR_TURN_SETTLE_MS = 750const SUBMIT_MAX_RETRIES = 2// Non-cursor engines re-observe the pane (instead of erroring) while an accepted-but-not-yet-started@@ -279,7 +282,9 @@ export class SessionInputController {? DEVIN_SUBMIT_VERIFY_MS: session.engine === 'muse'? MUSE_SUBMIT_VERIFY_MS- : SUBMIT_VERIFY_MS)+ : session.engine === 'amp'+ ? AMP_SUBMIT_VERIFY_MS+ : SUBMIT_VERIFY_MS)}private async retrySubmit(sessionId: string, session: RegisteredSession, state: InputState): Promise<void> {@@ -299,7 +304,8 @@ export class SessionInputController {this.deps.onError(sessionId, 'The agent did not accept the message. Please try again.')return}- } else if (session.engine === 'opencode' || session.engine === 'pi' || session.engine === 'hermes' || session.engine === 'muse') {+ } else if (session.engine === 'opencode' || session.engine === 'pi' || session.engine === 'hermes' || session.engine === 'muse'+ || session.engine === 'amp') {// OpenCode has no composer glyph, and the submitted text stays visible in the message area, so a// pane scrape can't tell "still in the composer" from "already sent". Rely purely on the reader-// derived turn_started (a new user row in opencode.db) to clear awaitingFingerprint; if it hasn'tdiff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex bccc8a2ab..d7d7290dc 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -255,6 +255,16 @@ export async function findLiveSession(if (!hasRun(lines)) return nullreturn { cwd: root, sessionId: basename(dirname(path)) }}, opts)+ case 'amp':+ // The transcripts scanned here are the adapter's own — Amp keeps no conversation on disk, so its+ // plugin writes one per thread as `<AMP_SESSIONS_DIR>/<threadId>.jsonl` with `cwd` on the first+ // line. That makes the ordinary file scan work unchanged, and the file name IS the session id.+ //+ // Amp also offers a second, exact answer that this deliberately does not use: `session.json` maps+ // `tmux:<pane>@<server-pid>,<session>` to the thread started in that pane. It is a better key than a+ // directory — but `findLiveSession` is asked about a cwd, not a pane, and a repair that silently+ // needed a different question would be the kind of split path this file exists to avoid.+ return fileEngineSession(env.AMP_SESSIONS_DIR, cwd, startedAtMs, readTranscriptMeta, opts)case 'opencode':// time_created is epoch MILLISECONDS here.return dbEngineSession(diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.tsindex 0acaec1b9..168b5be5a 100644--- a/cli/src/lib/summarize.ts+++ b/cli/src/lib/summarize.ts@@ -24,6 +24,7 @@ import {runCommandCodeOneShot,runDevinOneShot,runMuseOneShot,+ runAmpOneShot,setOneShotPoolActiveCounts,setOneShotPoolDeviceConnected,shutdownOneShotPool,@@ -53,9 +54,10 @@ configureOneShotPool({export function syncSummaryPoolSessions(sessions: Array<{ engine: AgentEngine }>): void {const counts = { claude: 0, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 }for (const session of sessions) {- // Hermes, Devin and Muse take their recap prompt as argv (`muse exec <prompt>`), so they cannot be- // pre-warmed the way a stdin-fed CLI can — no pooled worker for them.- if (session.engine === 'hermes' || session.engine === 'devin' || session.engine === 'muse') continue+ // Hermes, Devin, Muse and Amp take their recap prompt as argv (`muse exec <prompt>`, `amp -x <prompt>`),+ // so they cannot be pre-warmed the way a stdin-fed CLI can — no pooled worker for them.+ if (session.engine === 'hermes' || session.engine === 'devin' || session.engine === 'muse'+ || session.engine === 'amp') continuecounts[session.engine]++}setOneShotPoolActiveCounts(counts)@@ -300,7 +302,10 @@ export async function summarizeTurnText(? env.DEVIN_SUMMARY_MODEL: engine === 'muse'? env.MUSE_SUMMARY_MODEL- : env.OPENCODE_SUMMARY_MODEL+ // Amp's is an agent MODE (low|medium|high|ultra), not a model name — it exposes no models.+ : engine === 'amp'+ ? env.AMP_SUMMARY_MODE+ : env.OPENCODE_SUMMARY_MODELconst effort = engine === 'cursor' ? 'model-defined' : env.SUMMARY_EFFORTconsole.log(`[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`)const run = engine === 'claude'@@ -319,7 +324,9 @@ export async function summarizeTurnText(? runDevinOneShot: engine === 'muse'? runMuseOneShot- : runOpencodeOneShot+ : engine === 'amp'+ ? runAmpOneShot+ : runOpencodeOneShotlet r = await run({ prompt, model, effort: env.SUMMARY_EFFORT, cwd: scratch, signal })console.log(`[recap] one-shot returned in ${Date.now() - t0}ms · rawLen=${(r.text || '').length}`)await cleanupRecapSession(engine, scratch, r.sessionId)diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex f5832ac5e..6a9b11254 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -204,6 +204,13 @@ export function engineProcessMatchScore(if (executable === 'muse' || /^muse-bin-/.test(executable)) return 3return /(^|[\/\s])muse(?:-bin-[^\s]+)?(?:[\s]|$)/.test(haystack) ? 1 : 0}+ if (engine === 'amp') {+ // `~/.local/bin/amp` symlinks to `~/.amp/bin/amp`, a single compiled binary that does NOT re-exec:+ // measured live, the pane process is `amp` with argv `amp` and no children at all.+ if (executable === 'amp') return 3+ if (/\.amp[\/\\]bin[\/\\]amp(?:\s|$)/.test(haystack)) return 3+ return /(^|[\/\s])amp(?:[\s]|$)/.test(haystack) ? 1 : 0+ }if (executable === 'claude') return 3return /(^|[\/\s])claude(?:[\s]|$)/.test(haystack) ? 1 : 0}@@ -259,6 +266,9 @@ const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]// `muse resume <uuid>` names the session; `muse resume --last` does not, so that form falls through// to the scan in sessionRepair instead.muse: { flags: ['resume', '--session-id'], id: /^[0-9a-f-]{16,}$/i },+ // `amp threads continue <id>` names the thread; the bare `amp last` does not. Amp's ids are the only+ // ones here with a fixed prefix (`T-019fda49-…`), so the pattern doubles as proof it IS an amp id.+ amp: { flags: ['continue', '-c'], id: /^T-[0-9a-f-]{16,}$/i },}/** The session id an engine was told to resume, or null when argv does not name one. */