Skip to content

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.

fix(cli): history keeps the prompt, and a stale in-process plugin stops being silent

0xken1565558f4c0aba
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index ca407874b..6883bad73 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -24,7 +24,7 @@ import { homedir } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
-import { installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installHermesHooks, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
+import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installHermesHooks, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
import { ENGINES, aliasesFor, engineBin, engineCommand, resolveEngine } from './lib/engineBin.js'
import { refuseDuplicateAgent } from './lib/duplicateAgent.js'
@@ -1498,6 +1498,10 @@ async function runForeground(token: string): Promise<void> {
installCursorHooks(hookPort)
installOpencodePlugin(hookPort)
installPiExtension(hookPort)
+ // Amp belongs here with the other plugin-based engines, and it was missed. It matters most after a
+ // SELF-UPDATE: the daemon restarts, and this is what puts the new plugin on disk immediately rather
+ // than leaving it until someone next runs `harness amp`.
+ installAmpPlugin(hookPort)
installHermesHooks(hookPort)
installDevinHooks(hookPort)
installCommandCodeHooks(hookPort)
diff --git a/cli/src/engines/amp/normalizer.ts b/cli/src/engines/amp/normalizer.ts
index 7b161a869..35dcada7b 100644
--- a/cli/src/engines/amp/normalizer.ts
+++ b/cli/src/engines/amp/normalizer.ts
@@ -167,6 +167,8 @@ export function ampToolOutput(output: unknown): string {
export interface AmpTurnState {
open: boolean
+ /** Replay only: a `turn_start` was seen for the turn now being read. */
+ sawStart: boolean
/** tool id → the name it opened under, so the result reports the same one. */
toolNames: Map<string, string>
pendingTools: Set<string>
@@ -174,7 +176,7 @@ export interface AmpTurnState {
}
export function newAmpTurnState(): AmpTurnState {
- return { open: false, toolNames: new Map(), pendingTools: new Set(), thinkingCounter: 0 }
+ return { open: false, sawStart: false, toolNames: new Map(), pendingTools: new Set(), thinkingCounter: 0 }
}
/** One record → events. `mode: 'replay'` emits `user_message` instead of deriving the turn lifecycle. */
@@ -184,7 +186,10 @@ export function ampRecordToEvents(record: JsonObject, state: AmpTurnState, mode:
if (kind === 'turn_start') {
const prompt = str(record.message).trim()
- if (mode === 'replay') return prompt ? [{ type: 'user_message', payload: { content: prompt } }] : []
+ if (mode === 'replay') {
+ state.sawStart = true
+ 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: {} })
@@ -254,7 +259,8 @@ export function ampRecordToEvents(record: JsonObject, state: AmpTurnState, mode:
}
if (kind === 'turn_end') {
- if (mode === 'replay' || !state.open) return []
+ if (mode === 'replay') return []
+ if (!state.open) return []
state.open = false
state.pendingTools.clear()
// 'error' and 'cancelled' are both turns that produced no answer. Marking them aborted clears the
@@ -288,14 +294,44 @@ export class AmpNormalizer implements EngineNormalizer {
}
}
+/**
+ * Where each turn begins, for the turns that never announced themselves.
+ *
+ * A prompt queued while Amp is connecting arrives with no `agent.start`, so its turn has no `turn_start`
+ * record and history opened straight into an answer with nothing showing what was asked. `turn_end`
+ * carries that prompt — but emitting it there would print the question AFTER its answer, so this finds
+ * the first record of each such turn and the caller injects the user message in front of it.
+ */
+function recoveredPrompts(records: JsonObject[]): Map<number, string> {
+ const out = new Map<number, string>()
+ let first = -1 // first record of the turn being scanned
+ let sawStart = false
+ for (let i = 0; i < records.length; i++) {
+ const kind = str(records[i].t)
+ if (kind === 'session') continue
+ if (first < 0) first = i
+ if (kind === 'turn_start') sawStart = true
+ if (kind === 'turn_end') {
+ const prompt = str(records[i].message).trim()
+ if (!sawStart && prompt) out.set(first, prompt)
+ first = -1
+ sawStart = false
+ }
+ }
+ return out
+}
+
/** Full-session replay (`session_get`) — the same render path as the live stream. */
export function ampMessagesToEvents(lines: string[]): SessionEvent[] {
const state = newAmpTurnState()
+ const records = lines.map(ampRecord).filter((r): r is JsonObject => r !== null)
+ const recovered = recoveredPrompts(records)
const events: SessionEvent[] = []
- for (const line of lines) {
- const record = ampRecord(line)
- if (record) events.push(...ampRecordToEvents(record, state, 'replay') as SessionEvent[])
- }
+ records.forEach((record, i) => {
+ const prompt = recovered.get(i)
+ if (prompt) events.push({ type: 'user_message', payload: { content: prompt } })
+ events.push(...ampRecordToEvents(record, state, 'replay') as SessionEvent[])
+ })
events.push({ type: 'done', payload: { result: 'success' } })
return events
}
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 2733d9a46..f4efbbd95 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -204,6 +204,17 @@ export function startHookServer(
json(200, { ignored: true, reason })
}
if (!body.tmuxPane) { ignore('not_in_tmux'); return }
+ // A plugin/extension is loaded ONCE per engine process, so a pane opened before an update keeps
+ // running the old copy — silently, and for hours. Measured on amp: a pane started at 11:49 was
+ // still writing transcripts with no tool calls long after the fix reached disk. The engines that
+ // use shell hooks re-read the file on every call and cannot drift like this; these three can, so
+ // they stamp their build and the mismatch is said out loud instead of being discovered later.
+ const pluginVersion = (body as { pluginVersion?: unknown }).pluginVersion
+ if (typeof pluginVersion === 'string' && pluginVersion && pluginVersion !== VERSION) {
+ console.warn(`[hooks] ${sid(body.sessionId ?? '?')} ${body.engine ?? '?'} plugin is v${pluginVersion}`
+ + ` but this machine is v${VERSION} — that pane loaded an older copy.`)
+ console.warn('[hooks] restart the pane (or reload its plugins) to pick up the current build')
+ }
// Machine-launched only: a session with no LIVE machine id is not an agent. This is what makes
// lifetime deterministic — a CLI the user started outside `harness <engine>` is ignored here,
// exactly like a non-tmux one above.
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index a0bcf86fe..434416ba1 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -10,6 +10,7 @@ import { join, dirname } from 'path'
import { homedir } from 'os'
import { fileURLToPath } from 'url'
import { env } from '../config/env.js'
+import { VERSION } from '../version.js'
import type { AgentEngine } from '../engines/types.js'
const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
@@ -246,6 +247,7 @@ export const MachineRegister = async ({ directory, worktree, project }) => {
headers: { "content-type": "application/json" },
body: JSON.stringify({
engine: "opencode",
+ pluginVersion: ${JSON.stringify(VERSION)},
launcherId,
sessionId: sessionID,
cwd: directory || worktree || (project && project.worktree) || null,
@@ -532,6 +534,7 @@ export default function (pi: ExtensionAPI) {
headers: { "content-type": "application/json" },
body: JSON.stringify({
engine: "pi",
+ pluginVersion: ${JSON.stringify(VERSION)},
launcherId,
sessionId,
transcriptPath: ready ? file : undefined,
@@ -658,6 +661,7 @@ export default function (amp: any) {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
engine: 'amp',
+ pluginVersion: ${JSON.stringify(VERSION)},
launcherId,
sessionId: threadId,
transcriptPath: file,
@@ -685,9 +689,15 @@ export default function (amp: any) {
* \`seed\` marks what already exists WITHOUT writing it, for a thread that is being resumed: those
* messages belong to earlier turns, and replaying them made a fresh turn open with an old answer in it.
*/
- const drain = async (ctx: any, seed = false) => {
+ const drain = async (ctx: any) => {
let messages: any[] = []
try { messages = await ctx.thread.messages({ from: 'end', limit: 20 }) } catch { return }
+ // The FIRST drain of this plugin instance only claims what it finds; it writes nothing. That covers
+ // both ways a plugin meets a thread that already has messages: a resumed thread, and a plugin reload
+ // (Amp loads a plugin ONCE per process, so reload is how a running pane picks up a new build). Without
+ // it, the next prompt replayed the whole recent history as if it had just happened.
+ const seed = !seeded
+ seeded = true
for (const message of messages) {
const blocks = Array.isArray(message.content) ? message.content : []
for (let i = 0; i < blocks.length; i++) {
@@ -719,8 +729,7 @@ export default function (amp: any) {
amp.on('session.start', async (event: any, ctx: any) => {
await register(event.thread.id)
- // A resumed thread arrives full of earlier turns. Claim them silently, once.
- if (!seeded) { seeded = true; await drain(ctx, true) }
+ await drain(ctx)
})
amp.on('agent.start', async (event: any, ctx: any) => {
@@ -754,7 +763,10 @@ export default function (amp: any) {
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() })
+ // \`message\` is the prompt that STARTED this turn, and agent.end carries it even when
+ // agent.start never fired (a prompt queued while Amp was connecting). Recording it here is what
+ // lets history still show what was asked — see the replay branch in the normalizer.
+ line({ t: 'turn_end', id: event.id, status: event.status, message: event.message, at: Date.now() })
})
}
`
@@ -776,7 +788,11 @@ export function installAmpPlugin(port: number): void {
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)')
+ // Amp loads a plugin ONCE per process, so a pane that is already open keeps running the old one —
+ // measured the hard way: an amp started at 11:49 went on writing tool-less transcripts for hours
+ // after the fix landed on disk. Say what to do about it rather than leaving it to be discovered.
+ console.log('[hooks] a NEW amp session picks this up automatically; for one already open, run')
+ console.log("[hooks] ctrl+o → 'plugins: reload' (or restart that pane)")
} catch (err) {
console.error('[hooks] failed to write Amp plugin:', err)
}