Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,12 @@ functions declared in the module's own file (`claude plugin validate` refuses `$
`bin/relay.mjs claude-code` with `$.process.spawn`, which prints `{ port, token }` once it listens on loopback; the
spawn's loop is the relay's life, so the relay ends with the module, and a relay that died is started again by the
next event. The module sends each event over `$.http.fetch` with that token, as the profile's host events, and
applies the answers: `$.session.append` for a strategy, `$.ui.toast` for a notice, `{ text, context }` for a
command, `$.prompt.submit` for `/evolver-evolve`, and the turn summary as `turn.complete`'s `{ text }`. Text
applies the answers: `$.session.append` for a strategy, `$.ui.toast` for a notice, `$.ui.status` for the recall's
status line under the prompt (recalling, then what it decided: injected, none fits, none relevant enough, the Proxy
did not answer, or arrived after the turn ended), `{ text, context }` for a command, `$.prompt.submit` for
`/evolver-evolve`, and the turn summary as `turn.complete`'s `{ text }`. The turn summary names each injected
strategy and its asset id, what the turn's last check says of its use (none ran: unverified), what EvoMap was told
(and whether the report carried evidence), and a saving only behind a passing check. Text
appended in `turn.start` never reaches the turn's first request, so a recall never waits there: the strategy is
appended when it lands, only while its turn is still open (and is then kept out of the session's later recalls), and
booked at the turn's next main-loop `turn.step` after the first; a turn that ends first books nothing. In the
Expand Down
2 changes: 1 addition & 1 deletion hosts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ a channel.
| Events | `events: { hostEvent: canonicalEvent }`, onto `sessionStart`, `prompt`, `toolResult`, `beforeEdit`, `turnEnd`, `sessionEnd`, `command`, `agentGene` | — (MCP: its seven tools) |
| Payload | `payload: { sessionId, turnId, prompt, projectDir, isIgnored, model, transcriptPath, gene, writtenFor }`, each `(payload, context)`; `context` has `env`, `transcriptSize()`, `transcriptSince(offset)`, and `turnStart` at a turn's end. `isIgnored` skips a subagent's event or any other that is no turn of the person's | Claude Code's field names |
| Session start | `sessionStart: 'event' \| 'owner-change' \| 'connection'` | `event` |
| Answer | `reply: { context, notice, empty, command, turnEnd, late?, lifetime: 'turn' \| 'call', strategyAt: 'prompt' \| 'tool-result', toolResultContext }`, each `(value, hostEvent, payload)`; `lifetime: 'call'` replays the turn's strategy before every model call; `late(answer, late)` lets a host that can add context to a running turn take a recall slower than the wait (`late` resolves to `{ text, show, join }`: `show()` while the turn is open, for a host that adds it before a model step carries it; `join()` books it once one does); `strategyAt: 'tool-result'`, for a host whose prompt hook cannot add context, holds the strategy recalled at the prompt for the open turn, unbooked, and `context(strategy, toolEvent)` answers the turn's first tool hook with it, under that tool event's name, booking it then; a turn with no tool call never gets it. Such a host takes no `owner-change` session start and no `late`; `toolResultContext: true` says `context(strategy, toolEvent)` reaches the model from any tool hook, which turns on the recall after a failed check (a `tool-result` host has it already) | `hookSpecificOutput.additionalContext`, `{}`, `strategyAt: 'prompt'`, `toolResultContext: false` |
| Answer | `reply: { context, notice, empty, command, turnEnd, late?, lifetime: 'turn' \| 'call', strategyAt: 'prompt' \| 'tool-result', toolResultContext }`, each `(value, hostEvent, payload)`; `lifetime: 'call'` replays the turn's strategy before every model call; `late(answer, late, hostEvent, payload, traced)` lets a host that can add context to a running turn take a recall slower than the wait (`late` resolves to `{ text, show, join }`: `show()` while the turn is open, for a host that adds it before a model step carries it; `join()` books it once one does; `traced`, absent for a turn nobody typed for, resolves to the recall's last trace, which Claude Code pins as its status line under the prompt); `strategyAt: 'tool-result'`, for a host whose prompt hook cannot add context, holds the strategy recalled at the prompt for the open turn, unbooked, and `context(strategy, toolEvent)` answers the turn's first tool hook with it, under that tool event's name, booking it then; a turn with no tool call never gets it. Such a host takes no `owner-change` session start and no `late`; `toolResultContext: true` says `context(strategy, toolEvent)` reaches the model from any tool hook, which turns on the recall after a failed check (a `tool-result` host has it already) | `hookSpecificOutput.additionalContext`, `{}`, `strategyAt: 'prompt'`, `toolResultContext: false` |
| Evidence | `evidence: { toolNote, editedFile \| editedFiles, turnStart?, turnRecord?, source }`: tool notes as hooks see them, or a turn record read from the host's transcript | required |
| Turn end | `turnEnd: { reason → 'answer' \| 'aborted' \| 'refusal' \| 'error' \| 'unknown', answer, unclosed: { settleMs, as } }` | every end is `answer`; a turn with no end closes as `error` at the next prompt |
| Commands | `commands: { entry: 'intercept' \| 'inline-script' \| 'prompt' \| 'tool' \| 'cli-only', parse, sessionOf?(env), scriptArgs?(text), scriptAnswer?(result, script), answerReachesModel }`; a script runs `bin/command.mjs <host> <command> [args…]`, from a host or a terminal; `answerReachesModel` defaults to true for `inline-script`, `prompt` and `tool` | `cli-only` |
Expand Down
30 changes: 22 additions & 8 deletions hosts/claude-code/dist/hooks/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ import type { EngineInterface, PluginOptions, Register } from 'claude-code'
// and runs the model completions the relay asks for, since only the module holds the session's model.

type Relay = { url: string; token: string }
type Answer = { append?: string; toast?: string; submit?: string; text?: string; context?: string[]; exitCode?: number; late?: string }
type Answer = { append?: string; toast?: string; submit?: string; text?: string; context?: string[]; exitCode?: number; late?: string; status?: string }
type CatalogCommand = { name: string; description: string; hint?: string }
type ModelRequest = { id: string; model: string; prompt: string }
type Landed = { id: string; text: string }
type LateAnswer = { id?: string; text?: string; status?: string }

const AGENT = 'claude-code'
const RELAY_START_MS = 15_000
Expand All @@ -23,7 +24,11 @@ const MODEL_MAX_TOKENS = 4_096
const MODEL_TIMEOUT_MS = 120_000
const MAX_PENDING_PROMPTS = 32
const UNKNOWN_ORIGIN = { kind: 'unknown' }
const RECALL_UNFINISHED_STATUS = 'evolver · recall did not finish for this prompt'

// The status line is one per plugin, so only the turn that runs now may write it: a recall that answers once a later
// turn has started describes a turn nobody is looking at.
let statusTurnId: string | null = null
let relay: Promise<Relay> | null = null
let current: Relay | null = null
let failedStarts = 0
Expand Down Expand Up @@ -184,12 +189,19 @@ async function startSession($: EngineInterface, options: PluginOptions): Promise

// A recall lands after `turn.start`, whose text never reaches the turn's first request: the strategy is added to the
// conversation when it lands, while its turn is open, and booked by the relay at the turn's next main-loop step after
// the first, the first that can carry it. A turn that ends first books nothing.
async function addWhenLanded($: EngineInterface, options: PluginOptions, turnId: string, id: string): Promise<void> {
const landed: Landed | null = await post($, options, '/late', { id })
if (!landed) return
await appendHidden($, landed.text)
carried.set(turnId, landed)
// the first, the first that can carry it. A turn that ends first books nothing. Whatever the recall decided, injected or
// not, replaces the plugin's status line under the prompt while its turn is the one running. A turn that showed it was
// recalling always settles: a recall the relay could not answer (it failed or restarted) says it did not finish.
async function addWhenLanded($: EngineInterface, options: PluginOptions, turnId: string, id: string, showsStatus: boolean): Promise<void> {
let answer: LateAnswer | null = null
try {
answer = await post($, options, '/late', { id, withStatus: true })
} finally {
if (showsStatus && turnId === statusTurnId) $.ui.status(answer?.status ?? RECALL_UNFINISHED_STATUS)
}
if (!answer?.id || !answer.text) return
await appendHidden($, answer.text)
carried.set(turnId, { id: answer.id, text: answer.text })
}

async function bookCarried($: EngineInterface, options: PluginOptions, turnId: string): Promise<void> {
Expand All @@ -200,9 +212,11 @@ async function bookCarried($: EngineInterface, options: PluginOptions, turnId: s
}

async function startTurn($: EngineInterface, options: PluginOptions, e: { text: string; turnId: string }, origin: unknown): Promise<void> {
statusTurnId = e.turnId
const answer = await raise($, options, 'turn.start', { turn_id: e.turnId, text: e.text, origin })
if (answer.status && e.turnId === statusTurnId) $.ui.status(answer.status)
if (answer.append) await appendHidden($, answer.append)
if (answer.late) void quietly(addWhenLanded($, options, e.turnId, answer.late))
if (answer.late) void quietly(addWhenLanded($, options, e.turnId, answer.late, Boolean(answer.status)))
}

function rememberOrigin(text: string, origin: unknown): void {
Expand Down
2 changes: 1 addition & 1 deletion hosts/claude-code/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default defineProfile({
const line = endedTurnSummaryOf(ended, payload);
return line ? { text: line } : {};
},
late: (answer, late) => ({ ...answer, late }),
late: (answer, late, hostEvent, payload, traced) => ({ ...answer, late, ...(traced && { traced }) }),
lifetime: 'turn',
toolResultContext: true,
},
Expand Down
2 changes: 1 addition & 1 deletion hosts/codex/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export default defineProfile({
command: (result) => ({ decision: 'block', reason: result.text }),
// Codex shows a Stop hook's systemMessage to the person only.
turnEnd: (ended, hostEvent) => {
const line = hostEvent === INTERRUPT ? null : endedTurnSummaryOf(ended, { reason: 'answer' });
const line = hostEvent === INTERRUPT ? null : endedTurnSummaryOf(ended);
return line ? { systemMessage: line } : {};
},
},
Expand Down
2 changes: 1 addition & 1 deletion hosts/grok/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default defineProfile({
// A blocked prompt reaches no model and opens no turn; grok shows the reason to the person.
command: (result) => ({ decision: 'block', reason: result.text }),
turnEnd: (ended, hostEvent) => {
const line = hostEvent === STOP ? endedTurnSummaryOf(ended, { reason: 'answer' }) : null;
const line = hostEvent === STOP ? endedTurnSummaryOf(ended) : null;
return line ? { systemMessage: line } : {};
},
},
Expand Down
2 changes: 1 addition & 1 deletion hosts/minimax/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default defineProfile({
commands: { entry: 'intercept', parse: promptCommandOf, background: isBackgroundCommand },
reply: {
command: result => ({ decision: 'block', reason: result.text, systemMessage: result.text }),
turnEnd: ended => { const line = endedTurnSummaryOf(ended, { reason: 'answer' }); return line ? { systemMessage: line } : {}; },
turnEnd: ended => { const line = endedTurnSummaryOf(ended); return line ? { systemMessage: line } : {}; },
},
evidence: { toolNote: toolNoteOf, editedFiles: editedFilesOf },
turnEnd: {
Expand Down
2 changes: 1 addition & 1 deletion hosts/qoder/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default defineProfile({
command: (result) => ({ decision: 'block', reason: result.text, systemMessage: result.text }),
// Qoder shows a Stop hook's systemMessage to the person only, and ignores what StopFailure and QueryEnd answer.
turnEnd: (ended, hostEvent) => {
const line = hostEvent === STOP ? endedTurnSummaryOf(ended, { reason: 'answer' }) : null;
const line = hostEvent === STOP ? endedTurnSummaryOf(ended) : null;
return line ? { systemMessage: line } : {};
},
},
Expand Down
4 changes: 2 additions & 2 deletions lib/agent/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,12 @@ const HANDLERS = {
const hostTurn = profile.payload.hostTurn(payload, context);
const holdForToolResult = profile.reply.strategyAt === STRATEGY_AT.TOOL_RESULT;
const lateAtToolResult = typeof profile.reply.lateAtToolResult === 'function';
const { turn, sessionEpoch, injection, late, deferred, skipped } = await promptSubmitted(ports, { sessionId, prompt, projectDir, turnId, turnStart, hostTurn, isCommand: Boolean(typed), waitMs: waitLeft(), keepLate, holdForToolResult, lateAtToolResult });
const { turn, sessionEpoch, injection, late, traced, deferred, skipped } = await promptSubmitted(ports, { sessionId, prompt, projectDir, turnId, turnStart, hostTurn, isCommand: Boolean(typed), waitMs: waitLeft(), keepLate, holdForToolResult, lateAtToolResult });
if (skipped) options.onError?.(skipped);
if (deferred) ports.scheduler.schedule([`recall:${JSON.stringify({ ...at, turn, sessionEpoch })}`]);
if (profile.turnEnd.statusRecord && turnId) await scheduleTurn(ports, at, { turn, turnId, sessionEpoch });
const answer = profile.reply.context(joined(notice, await checkpointOf(), injection), hostEvent, payload);
return late ? profile.reply.late(answer, late, hostEvent, payload) : answer;
return late ? profile.reply.late(answer, late, hostEvent, payload, traced) : answer;
},

async [EVENTS.TURN_START]({ profile, ports, hostEvent, payload, context, at }) {
Expand Down
16 changes: 11 additions & 5 deletions lib/app/prompt.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ async function recalled(ports, sessionId, { turn, prompt, projectDir, waitMs, ke
const { request: proxyFetch, signal, cancel } = recallRequestOf(ports.proxy, { timeoutMs });
const recipeCutoff = ports.clock.sleep(waitMs > 0 ? Math.max(0, waitMs - RECIPE_MARGIN_MS) : LATE_RECIPE_WAIT_MS, signal);
const onWithheld = rememberWithheld(ports, sessionId, turn);
const recall = recallStrategy(proxyFetch, promptTextOf(prompt), { context, projectDir, listedIds, onWithheld, closingOf: () => CLOSING, recipeCutoff });
const text = promptTextOf(prompt);
let lastTrace = null;
const onTrace = (trace) => { lastTrace = trace; };
const recall = recallStrategy(proxyFetch, text, { context, projectDir, listedIds, onWithheld, onTrace, closingOf: () => CLOSING, recipeCutoff });
const TIMED_OUT = Symbol('timed out');
const match = waitMs > 0 ? await Promise.race([recall, ports.clock.sleep(waitMs, signal).then(() => TIMED_OUT)]) : TIMED_OUT;
if (match !== TIMED_OUT || !keepLate) cancel();
Expand All @@ -150,7 +153,9 @@ async function recalled(ports, sessionId, { turn, prompt, projectDir, waitMs, ke
show: () => shown(ports, sessionId, { turn, ids: landed.ids }),
join: async () => (await booked(ports, sessionId, { turn, match: landed, onlyWhileOpen: true })) !== '',
} : null)).catch(() => null).finally(cancel);
return { injection: '', late };
// A turn nobody typed for (a task notification) recalls for nothing, which is no decision to show.
const traced = text ? late.then(() => lastTrace) : null;
return { injection: '', late, ...(traced && { traced }) };
}

// The commit a turn begins on is where a range of work turns starting with it takes its diff from, so work it commits
Expand All @@ -170,7 +175,8 @@ async function rememberTurnHead({ project, sessions }, sessionId, { turn, sessio
* it has answered. With `keepLate`, for a host that can add context to a running turn, a slower recall keeps going:
* `late` resolves to `{ text, show, join }`. `show()` answers whether the turn is still open and keeps the strategy
* out of the session's later recalls, for a host that adds it before a model step carries it; `join()` books it,
* only while the turn is still open, once a model step does. With `holdForToolResult`, for a host whose prompt hook
* only while the turn is still open, once a model step does; `traced` resolves, with it, to the recall's last trace
* (`recallStrategy`'s `onTrace`), or is absent for a turn nobody typed for. With `holdForToolResult`, for a host whose prompt hook
* cannot add context, a strategy that lands in time waits for the turn's first tool result instead (see
* `takeWaitingStrategy`). A plugin command's turn keeps the last real turn's reuses for the next prompt to label, is
* recalled for nothing and never joins the session's range of work turns. `skipped` is the error of a correction or
Expand All @@ -190,8 +196,8 @@ export async function promptSubmitted(ports, { sessionId, prompt, projectDir = n
const wantsRecall = !isCommand && ports.settings?.recall !== false;
const recall = wantsRecall ? recalled(ports, sessionId, { turn: opened.turn, prompt, projectDir, waitMs, keepLate, holdForToolResult, lateAtToolResult }) : { injection: '' };
const headRead = isCommand || !projectDir ? null : rememberTurnHead(ports, sessionId, { turn: opened.turn, sessionEpoch: opened.sessionEpoch, projectDir });
const [{ injection, late, deferred }] = await Promise.all([recall, headRead]);
return { turn: opened.turn, sessionEpoch: opened.sessionEpoch, injection, ...(late && { late }), ...(deferred && { deferred }), ...(skipped && { skipped }) };
const [{ injection, late, traced, deferred }] = await Promise.all([recall, headRead]);
return { turn: opened.turn, sessionEpoch: opened.sessionEpoch, injection, ...(late && { late }), ...(traced && { traced }), ...(deferred && { deferred }), ...(skipped && { skipped }) };
}

/**
Expand Down
Loading
Loading