The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(provider): make the example recap a real per-turn recap
0xken15a4b110978bc5
diff --git a/provider/example-provider/README.md b/provider/example-provider/README.mdindex 9bfe32904..ab7c7abf2 100644--- a/provider/example-provider/README.md+++ b/provider/example-provider/README.md@@ -47,6 +47,8 @@ curl -N localhost:4502 \| `STATE_FILE` | `./sessions.json` || `WORKSPACE_ROOT` | `/tmp/example-provider-scratch` — where `autonomous.CreateAgent` puts a new agent's directory || `CLAUDE_PROJECTS_DIR` | `~/.claude/projects` |+| `CLAUDE_RECAP_MODEL` | `claude-haiku-4-5-20251001` — the per-turn recap is a one-line headline, not the work, so it gets a small model |+| `RECAP_DISABLED` | unset. `1` skips the recap model entirely and excerpts the turn instead |## How it works@@ -71,6 +73,23 @@ too** — it just does not stream live, since this app implements no `SubscribeTevents and JSONL lines carry the same Anthropic message shape, so writing two parsers is the reliableway to make the live view and the post-refresh view disagree.+**Recaps are generated per TURN**, after the stream closes, by a disposable one-shot `claude --print`+(`src/recap.ts`). Three details are load-bearing:++- **No `--resume`.** The summariser must never touch the live session, or the summary lands in the+ transcript and the next turn's history contains a summary of the previous one.+- **`recap` is what the turn ACCOMPLISHED, not what was asked.** Those are different sentences, and+ `metadata.title` — the first user message — is the wrong one. A device tile that echoes the user's+ own prompt back at them is worse than no tile.+- **The caps are re-applied after the model answers.** A model asked for 15 words will sometimes give+ 40, and `recapEntry.recap` is capped at 200 characters by the schema. Nothing ever appends an+ ellipsis: the tile renders on a small round display, where a line advertising its own truncation+ reads worse than one that simply ends.++A failed or cancelled turn gets no recap. If the one-shot fails, times out, or `RECAP_DISABLED=1`,+the turn's own opening sentence is excerpted instead — a recap is a nicety and must never be able to+retroactively fail a turn that succeeded.+## What it does not do- **No `INPUT_REQUIRED`.** With permissions skipped, Claude never asks, so HP-104 stays demonstrated@@ -84,7 +103,7 @@ way to make the live view and the post-refresh view disagree.## Verification```bash-npm test # 31 tests, deterministic — replays a RECORDED real turn+npm test # 43 tests, deterministic — replays a RECORDED real turn; never spawns a modelnpm run typecheck```@@ -130,5 +149,6 @@ All three are pinned by tests, and all three tests were mutation-checked.| `src/claude.ts` | spawn, stdin frame, stdout lines, process-group kill || `src/mapper.ts` | **the** Claude → A2A mapping, shared by the live and history paths || `src/jsonl.ts` | transcript discovery, reading and time-slicing |-| `src/sessions.ts` | `contextId ↔ claudeSessionId`, and task windows |+| `src/sessions.ts` | `contextId ↔ claudeSessionId`, task windows, and persisted per-turn recaps |+| `src/recap.ts` | the per-turn recap one-shot, its caps, and the no-model fallback || `src/server.ts` | JSON-RPC + SSE, with HP-xxx clause references inline |diff --git a/provider/example-provider/src/config.ts b/provider/example-provider/src/config.tsindex b796d83a7..079da5443 100644--- a/provider/example-provider/src/config.ts+++ b/provider/example-provider/src/config.ts@@ -8,6 +8,7 @@ import { execFileSync } from 'node:child_process'import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'import { homedir } from 'node:os'import { isAbsolute, resolve } from 'node:path'+import { DEFAULT_RECAP_MODEL } from './recap.js'export interface AgentEntry {id: string@@ -35,6 +36,10 @@ export interface Config {/** Where sessions.json lives. */stateFile: stringclaudeProjectsDir: string+ /** Model for the per-turn recap one-shot — a headline is not the work, so it gets a small model. */+ recapModel: string+ /** Skip the recap one-shot and excerpt the turn instead. Keeps the example cheap to run. */+ recapDisabled: boolean}/**@@ -127,5 +132,7 @@ export function loadConfig(): Config {port: Number(process.env.PORT ?? 4502),stateFile: process.env.STATE_FILE ?? resolve(process.cwd(), 'sessions.json'),claudeProjectsDir: process.env.CLAUDE_PROJECTS_DIR ?? `${homedir()}/.claude/projects`,+ recapModel: process.env.CLAUDE_RECAP_MODEL || DEFAULT_RECAP_MODEL,+ recapDisabled: process.env.RECAP_DISABLED === '1',}}diff --git a/provider/example-provider/src/recap.spec.ts b/provider/example-provider/src/recap.spec.tsnew file mode 100644index 000000000..a73e553e3--- /dev/null+++ b/provider/example-provider/src/recap.spec.ts@@ -0,0 +1,82 @@+/**+ * The recap contract, without spawning a model.+ *+ * `summariseTurn` is exercised only through its disabled path here — the package README is explicit+ * that this provider is not deterministic and belongs nowhere near CI, and a test that shells out to+ * `claude` would inherit exactly that problem.+ */+import { describe, expect, it } from 'vitest'+import { BODY_MAX_CHARS, RECAP_MAX_CHARS, excerptRecap, parseRecap, summariseTurn } from './recap.js'++describe('parseRecap', () => {+ it('splits the model’s two parts on the first blank line', () => {+ expect(parseRecap('Rebuilt the weekly pacing alert\n\nIt now runs at 08:00 and pages on 110%.')).toEqual({+ recap: 'Rebuilt the weekly pacing alert',+ body: 'It now runs at 08:00 and pages on 110%.',+ })+ })++ it('splits on the FIRST blank line, not the last', () => {+ // A body with its own paragraph breaks must not be mistaken for a second headline.+ expect(parseRecap('Headline\n\nOne.\n\nTwo.')!.body).toBe('One. Two.')+ })++ it('falls back to the headline when the model gives only one part', () => {+ expect(parseRecap('Just a headline')).toEqual({ recap: 'Just a headline', body: 'Just a headline' })+ })++ it('re-applies the caps — a model asked for 15 words will sometimes give 40', () => {+ const parsed = parseRecap(`${'word '.repeat(200)}\n\n${'body '.repeat(2000)}`)!+ expect(parsed.recap.length).toBeLessThanOrEqual(RECAP_MAX_CHARS)+ expect(parsed.body.length).toBeLessThanOrEqual(BODY_MAX_CHARS)+ })++ it('NEVER appends an ellipsis when it truncates', () => {+ // The device renders this on a small round display; a line advertising its own truncation reads+ // worse than one that simply ends.+ expect(parseRecap('x '.repeat(300))!.recap).not.toMatch(/…|\.\.\.$/)+ })++ it('returns null for an empty answer rather than an empty tile', () => {+ expect(parseRecap('')).toBeNull()+ expect(parseRecap(' \n\n ')).toBeNull()+ })+})++describe('excerptRecap — the no-model fallback', () => {+ it('takes the opening sentence as the headline', () => {+ expect(excerptRecap('Acme is at 118% of pacing. I rebuilt the alert too.')).toEqual({+ recap: 'Acme is at 118% of pacing.',+ body: 'Acme is at 118% of pacing. I rebuilt the alert too.',+ })+ })++ it('flattens newlines — the tile is one line', () => {+ expect(excerptRecap('Done\n\n - one\n - two')!.body).toBe('Done - one - two')+ })++ it('returns null for a turn that produced nothing', () => {+ expect(excerptRecap(' ')).toBeNull()+ })+})++describe('summariseTurn', () => {+ it('excerpts instead of spawning anything when disabled', async () => {+ const recap = await summariseTurn({+ claudeBin: '/nonexistent/claude', cwd: process.cwd(), turnText: 'Shipped it. Twice.', disabled: true,+ })+ expect(recap).toEqual({ recap: 'Shipped it.', body: 'Shipped it. Twice.' })+ })++ it('falls back rather than throwing when the binary cannot be spawned', async () => {+ // A recap must never be able to fail a turn that already succeeded.+ const recap = await summariseTurn({+ claudeBin: '/nonexistent/claude', cwd: process.cwd(), turnText: 'The answer is 42.',+ })+ expect(recap).toEqual({ recap: 'The answer is 42.', body: 'The answer is 42.' })+ })++ it('returns null for a silent turn', async () => {+ expect(await summariseTurn({ claudeBin: '/nonexistent/claude', cwd: process.cwd(), turnText: '' })).toBeNull()+ })+})diff --git a/provider/example-provider/src/recap.ts b/provider/example-provider/src/recap.tsnew file mode 100644index 000000000..7d3ca7c86--- /dev/null+++ b/provider/example-provider/src/recap.ts@@ -0,0 +1,150 @@+/**+ * Per-turn recap — the `session-recap` extension's actual content (HP-302).+ *+ * The schema calls `recap` a *"headline-style summary of what the turn accomplished"*, and that is a+ * different thing from the session title: the title is what the user ASKED, the recap is what the+ * agent DID. This provider used to return the title, which meant the device tile read the user's own+ * prompt back at them.+ *+ * So a real recap is generated, by a **disposable one-shot** `claude --print`:+ *+ * - no `--resume` — it must never touch the live session, or the summary itself lands in the+ * transcript and the next turn's history contains a summary of the previous one;+ * - a two-part answer, headline then blank line then body, which is the same contract the Autonomous+ * product uses internally;+ * - the caps are re-applied HERE, after the model returns, because a model asked for 15 words will+ * sometimes give you 40.+ *+ * If the one-shot fails, times out, or is switched off, the turn's own output is excerpted instead.+ * A recap is a nicety: it must never be able to fail a turn that already succeeded.+ */+import { spawn } from 'node:child_process'++/** `recapEntry.recap` is capped at 200 by the schema; the device renders it on one line. */+export const RECAP_MAX_CHARS = 200+/** `recapEntry.body` is capped at 2000. */+export const BODY_MAX_CHARS = 2000++/** Long enough for a small model on a big turn, short enough that nothing waits on it. */+const SUMMARY_TIMEOUT_MS = 30_000++/**+ * Pinned for the same reason `DEFAULT_MODEL` is: a provider owns its model choice. A small, fast+ * model is the right one here — this is a one-line headline, not the work.+ */+export const DEFAULT_RECAP_MODEL = 'claude-haiku-4-5-20251001'++const PROMPT = `Summarise the assistant's turn below in TWO parts.++Part 1 — one line, at most 15 words: a newspaper headline for what the assistant ACCOMPLISHED. Not+what it was asked. Front-load the outcome. No trailing ellipsis, ever. No markdown, no quotes.++Then ONE blank line.++Part 2 — at most 120 words: what happened, in plain prose. No markdown, no bullet points.++Write in the same language the turn is written in. Output the two parts and nothing else.++--- THE TURN ---+`++export interface Recap {+ recap: string+ body: string+}++export interface SummariseOptions {+ claudeBin: string+ /** The agent's directory. The one-shot runs here so the model sees the same project context. */+ cwd: string+ /** The assistant's output for this turn. */+ turnText: string+ model?: string+ /** Skip the model entirely and go straight to the excerpt. */+ disabled?: boolean+}++/**+ * A recap for one turn. Never rejects, and never returns an empty headline: callers get either a real+ * summary, an excerpt of the turn, or null when the turn genuinely said nothing.+ */+export async function summariseTurn(opts: SummariseOptions): Promise<Recap | null> {+ const fallback = excerptRecap(opts.turnText)+ if (opts.disabled || !flatten(opts.turnText)) return fallback+ try {+ const raw = await oneShot(opts)+ return parseRecap(raw) ?? fallback+ } catch {+ // Deliberately silent about the cause here — the caller logs it with the taskId attached.+ return fallback+ }+}++/** Split the model's two-part answer on the FIRST blank line, then re-apply the caps. */+export function parseRecap(raw: string): Recap | null {+ const text = raw.trim()+ if (!text) return null+ const split = text.indexOf('\n\n')+ const head = split === -1 ? text : text.slice(0, split)+ const rest = split === -1 ? '' : text.slice(split + 2)+ const recap = cap(flatten(head), RECAP_MAX_CHARS)+ if (!recap) return null+ return { recap, body: cap(flatten(rest), BODY_MAX_CHARS) || recap }+}++/**+ * The no-model fallback: the turn's opening sentence as the headline, the turn as the body.+ *+ * An excerpt, not an invention. For an assistant reply the first sentence is very often the answer+ * itself, which makes this a genuinely useful tile rather than a placeholder.+ */+export function excerptRecap(turnText: string): Recap | null {+ const body = cap(flatten(turnText), BODY_MAX_CHARS)+ if (!body) return null+ const recap = cap(firstSentence(body), RECAP_MAX_CHARS)+ return recap ? { recap, body } : null+}++function oneShot(opts: SummariseOptions): Promise<string> {+ return new Promise((resolve, reject) => {+ const child = spawn(+ opts.claudeBin,+ // No --resume, no tools, no permissions flag: this reads text and writes text.+ ['--model', opts.model ?? DEFAULT_RECAP_MODEL, '--print'],+ { cwd: opts.cwd, stdio: ['pipe', 'pipe', 'ignore'], env: { ...process.env } },+ )+ let out = ''+ const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error('recap timed out')) }, SUMMARY_TIMEOUT_MS)+ child.stdout?.on('data', (c: Buffer) => { out += c.toString() })+ child.on('error', (err) => { clearTimeout(timer); reject(err) })+ child.on('close', (code) => {+ clearTimeout(timer)+ if (code === 0) resolve(out)+ else reject(new Error(`claude exited ${code}`))+ })+ try {+ child.stdin?.end(`${PROMPT}${opts.turnText.slice(0, 50_000)}\n`)+ } catch (err) {+ clearTimeout(timer)+ reject(err)+ }+ })+}++/** Whitespace collapsed: the tile is one line, and newlines waste it. */+function flatten(value: string): string {+ return value.replace(/\s+/g, ' ').trim()+}++/** Hard cap at a word boundary where there is one, and NEVER with an ellipsis appended. */+function cap(text: string, max: number): string {+ if (text.length <= max) return text+ const cut = text.slice(0, max)+ const space = cut.lastIndexOf(' ')+ return (space > max * 0.6 ? cut.slice(0, space) : cut).trimEnd()+}++function firstSentence(text: string): string {+ const match = /[.!?](\s|$)/.exec(text)+ return match ? text.slice(0, match.index + 1) : text+}diff --git a/provider/example-provider/src/server.ts b/provider/example-provider/src/server.tsindex 9270fc836..624c0bd89 100644--- a/provider/example-provider/src/server.ts+++ b/provider/example-provider/src/server.ts@@ -14,7 +14,8 @@ import { buildAgentCard, EXT } from './agentCard.js'import { runTurn } from './claude.js'import { loadConfig, type AgentEntry, type Config } from './config.js'import { createAgent, deleteAgent, renameAgent, WorkspaceError } from './workspace.js'-import { epoch, listSessions, readTranscript, sliceByTime } from './jsonl.js'+import { epoch, readTranscript, sliceByTime } from './jsonl.js'+import { summariseTurn } from './recap.js'import { messageToParts, pairToolNames, sessionIdOf, streamLineToOutcome } from './mapper.js'import { SessionStore, type TaskRecord } from './sessions.js'import {@@ -270,6 +271,34 @@ async function sendStreamingMessage(res: ServerResponse, deps: Deps, params: Recfinal: true,})if (!res.destroyed) res.end()++ // HP-302 — summarise the turn AFTER closing the stream. Not awaited: the turn is over, and holding+ // the SSE response open for a summary would make every turn look slower than it was.+ // Only a turn that actually completed: summarising a failure produces a headline that reads like+ // an accomplishment.+ if (finalState === TaskState.COMPLETED) void recapTurn(deps, taskId, agent, collected)+}++/** Summarise one finished turn and persist it on the task, for `autonomous.GetRecap` to serve. */+async function recapTurn(deps: Deps, taskId: string, agent: AgentEntry, parts: Part[]): Promise<void> {+ // The assistant's own words only — thinking and tool output are not what the turn accomplished.+ const turnText = parts+ .filter((p) => p.metadata?.['autonomous.ai/kind'] === 'text_delta')+ .map((p) => p.text ?? '')+ .join('')+ try {+ const recap = await summariseTurn({+ claudeBin: deps.config.claudeBin,+ cwd: agent.cwd,+ turnText,+ model: deps.config.recapModel,+ disabled: deps.config.recapDisabled,+ })+ if (recap) deps.store.setRecap(taskId, recap.recap, recap.body)+ } catch (err) {+ // A recap is a nicety. It must never be able to retroactively fail a turn that succeeded.+ console.warn(`[example-provider] recap failed for ${taskId}:`, err instanceof Error ? err.message : String(err))+ }}// ── History (HP-200 … HP-202) ────────────────────────────────────────────────────────────────────@@ -432,22 +461,28 @@ function workspaceWrite(// ── Extension: session-recap (HP-302) ────────────────────────────────────────────────────────────/**- * Recent turns for the device's tiles, straight out of Claude's transcripts.+ * Recent turns for the device's tiles.+ *+ * Served from the task records, which is what makes these PER TURN — the unit HP-302 asks for. An+ * earlier version listed recent *sessions* and used each one's title, which was wrong twice over:+ * a session is not a turn, and a title is what the user ASKED rather than what the turn accomplished.*- * This is where reading the JSONL pays off twice: sessions started in a terminal show up here too,- * even though this provider streams nothing live for them.+ * `contextId` is the A2A context the client minted, never Claude's own session id. A client uses it+ * to reopen the conversation, so handing back an id we never issued would simply not resolve.*/function getRecap(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: string | number | null): void {const agent = agentById(deps, String(params.agentId ?? ''))if (!agent) { sendRpcError(res, id, RpcErrors.INVALID_PARAMS); return }const n = Math.max(1, Math.min(5, Number(params.n) || 2))- const entries = listSessions(deps.config.claudeProjectsDir, agent.cwd)- .slice(0, n)- .map((s) => ({- recap: s.title.slice(0, 200), // the device renders under a 200-char ceiling- contextId: s.sessionId,- timestamp: new Date(s.updatedAt).toISOString(),- }))+ // Empty until a turn has been summarised — which the schema calls correct. The device shows+ // nothing rather than resurrecting stale text.+ const entries = deps.store.recentRecaps(agent.id, n).map((t) => ({+ recap: t.recap!,+ body: t.body,+ contextId: t.contextId,+ taskId: t.taskId,+ timestamp: new Date(t.endedAt ?? t.startedAt).toISOString(),+ }))sendRpcResult(res, id, { agentId: agent.id, entries })}diff --git a/provider/example-provider/src/sessions.ts b/provider/example-provider/src/sessions.tsindex 9ca742bc4..7ed502e2e 100644--- a/provider/example-provider/src/sessions.ts+++ b/provider/example-provider/src/sessions.ts@@ -20,6 +20,14 @@ export interface TaskRecord {endedAt?: number/** First user text of the turn — the session title projection (spec §10.4). */title: string+ /**+ * Headline of what this turn ACCOMPLISHED (HP-302). Absent until the turn has been summarised, and+ * absent forever on a turn that failed — deliberately NOT the same thing as `title`, which is what+ * the user asked.+ */+ recap?: string+ /** The fuller summary behind the headline; `recapEntry.body` on the wire. */+ body?: string}export interface ContextRecord {@@ -119,4 +127,27 @@ export class SessionStore {contextsForAgent(agentId: string): ContextRecord[] {return Object.values(this.state.contexts).filter((c) => c.agentId === agentId)}++ /** Attach a summary to a finished turn. Persisted, because HP-302 says "persisted". */+ setRecap(taskId: string, recap: string, body: string): void {+ const task = this.state.tasks[taskId]+ if (!task || !recap) return+ task.recap = recap+ task.body = body+ this.save()+ }++ /**+ * The most recent SUMMARISED turns for one agent, newest first.+ *+ * Per TURN, not per session: HP-302 is "short persisted per-turn summaries", and a session can+ * hold dozens of turns. Turns still running, and turns that failed, carry no recap and are simply+ * not here — an empty array before anything has been summarised is the correct answer.+ */+ recentRecaps(agentId: string, n: number): TaskRecord[] {+ return Object.values(this.state.tasks)+ .filter((t) => t.agentId === agentId && !!t.recap)+ .sort((a, b) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt))+ .slice(0, n)+ }}diff --git a/provider/reference-provider/src/server.ts b/provider/reference-provider/src/server.tsindex ac98b8062..de7b5b81b 100644--- a/provider/reference-provider/src/server.ts+++ b/provider/reference-provider/src/server.ts@@ -140,6 +140,14 @@ const declaresExtension = (uri: string): boolean =>/*** HP-302 — `autonomous.GetRecap`. Headline-style summaries of recent turns, for the device's tiles.*+ * `recap` is what the turn ACCOMPLISHED, so it comes from the ASSISTANT's own words. It is emphatically+ * not `metadata.title`, which is the first user message — i.e. what was ASKED. An earlier version+ * returned the title, which made the device tile read the user's own prompt back at them.+ *+ * A real provider would summarise with a model. This one is scripted and must stay deterministic, so+ * it excerpts instead: headline = the reply's opening sentence, body = the reply. That is honest, and+ * it demonstrates the two-field shape a client renders (tile + tap-to-read).+ ** An empty array is the correct answer before anything has been summarised: the device shows nothing* rather than resurrecting stale text.*/@@ -152,16 +160,36 @@ function getRecap(res: ServerResponse, store: TaskStore, params: Record<string,const n = Math.max(1, Math.min(5, Number(params.n) || 2))const entries = store.list()- .filter((t) => isTerminal(t.status.state))+ .filter((t) => t.status.state === TaskState.COMPLETED) // a failed turn accomplished nothing+ .map((t) => ({ task: t, said: assistantTextOf(t) }))+ .filter((e) => !!e.said).slice(0, n)- .map((t) => ({- recap: (t.metadata?.title ?? 'Untitled').slice(0, 200),- contextId: t.contextId,- taskId: t.id,+ .map((e) => ({+ recap: firstSentence(e.said).slice(0, 200), // `recapEntry.recap` is capped at 200 by the schema+ body: e.said.slice(0, 2000),+ contextId: e.task.contextId,+ taskId: e.task.id,}))sendRpcResult(res, id, { agentId, entries })}+/** Everything the assistant said in a turn, flattened to the one line a tile renders. */+function assistantTextOf(task: Task): string {+ return task.history+ .filter((m) => m.role === 'ROLE_AGENT')+ .flatMap((m) => m.parts)+ .filter((p) => (p.metadata?.['autonomous.ai/kind'] ?? 'text_delta') === 'text_delta')+ .map((p) => p.text ?? '')+ .join('')+ .replace(/\s+/g, ' ')+ .trim()+}++function firstSentence(text: string): string {+ const match = /[.!?](\s|$)/.exec(text)+ return match ? text.slice(0, match.index + 1) : text+}+// ── SendStreamingMessage (HP-100 … HP-106) ───────────────────────────────────────────────────────async function sendStreamingMessage(res: ServerResponse, store: TaskStore, params: Record<string, unknown>): Promise<void> {